lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

receipt_public_snapshots.rs (21633B)


      1 //! Structural report consistency over actual retained public command facts.
      2 //! These transformations neither alter the journal nor grant dispatch rights.
      3 use super::*;
      4 use radroots_domain::TransactionId;
      5 use radroots_storage::command::{
      6     ArtifactSnapshot, BoundSigningPlan, CapturedArtifact, ChatInstallation, ClaimAttemptRequest,
      7     DeliveryAttempt, DeliveryAttemptRequest, DeliveryAttemptSummary, DeliveryIntent,
      8     ListingInstallation, OperationSnapshot, PublicPublicationWork, PublicationArtifact,
      9     RetainedOperation, SigningTarget,
     10 };
     11 
     12 async fn original_plan(ready: &Ready, id: u8) -> BoundSigningPlan {
     13     let snapshot = ready.snapshot(id).await;
     14     ready
     15         .store
     16         .signing_plan(
     17             ready.scope.binding().clone(),
     18             OperationId::from_bytes([id; 32]),
     19             snapshot.prepared().identity().command_digest(),
     20             copy(&ready.proof),
     21         )
     22         .await
     23         .unwrap()
     24         .unwrap()
     25 }
     26 
     27 async fn bare(ready: &Ready, id: u8) -> OperationSnapshot {
     28     let snapshot = ready.snapshot(id).await;
     29     OperationSnapshot::from_store_report(
     30         RetainedOperation::Planned(Box::new(original_plan(ready, id).await)),
     31         snapshot.artifacts().to_vec(),
     32         snapshot.observed_at(),
     33     )
     34     .unwrap()
     35 }
     36 
     37 async fn installed(ready: &Ready, id: u8) -> OperationSnapshot {
     38     let snapshot = ready.snapshot(id).await;
     39     bare(ready, id)
     40         .await
     41         .with_public_installation(
     42             snapshot.listing_installation(),
     43             snapshot.public_publications().to_vec(),
     44         )
     45         .unwrap()
     46 }
     47 
     48 async fn original_capture(ready: &Ready, id: u8) -> CapturedArtifact {
     49     let plan = original_plan(ready, id).await;
     50     ready
     51         .store
     52         .obtained_evidence(
     53             ClaimAttemptRequest::for_artifact(
     54                 ready.scope.binding().clone(),
     55                 OperationId::from_bytes([id; 32]),
     56                 plan.prepared().identity().command_digest(),
     57                 *plan.plan().digest(),
     58                 SigningTarget::PublicEvent,
     59             ),
     60             copy(&ready.proof),
     61         )
     62         .await
     63         .unwrap()
     64         .unwrap()
     65 }
     66 
     67 #[tokio::test]
     68 async fn public_reports_cannot_cross_actual_authenticated_workspaces_for_the_same_signer() {
     69     let relay = Relay::new().await;
     70     let first = Ready::new(&relay, StartMode::Online, PublicSigner::new(), true).await;
     71     let second = Ready::new(&relay, StartMode::Online, PublicSigner::new(), true).await;
     72     assert_ne!(first.input.workspace_id(), second.input.workspace_id());
     73     for ready in [&first, &second] {
     74         ready
     75             .client
     76             .listings()
     77             .publish(ready.context(224, now() + 120), input(224))
     78             .await
     79             .unwrap();
     80     }
     81     let original = first.snapshot(224).await;
     82     let foreign = second.snapshot(224).await;
     83     let work = original.public_publications()[0];
     84     let intent = original.delivery_attempts()[0].intent().clone();
     85     assert!(DeliveryAttemptRequest::new(second.scope.binding().clone(), work, intent).is_err());
     86     assert!(
     87         ListingInstallation::from_committed_store(
     88             &original_plan(&first, 224).await,
     89             foreign.public_publications()[0].evidence(),
     90             original.listing_installation().unwrap().transaction_id(),
     91             original.listing_installation().unwrap().installed_at(),
     92         )
     93         .is_err()
     94     );
     95     let captured = original_capture(&first, 224).await;
     96     let foreign_capture = original_capture(&second, 224).await;
     97     let foreign_attempt = second
     98         .store
     99         .signing_attempt(
    100             ClaimAttemptRequest::for_artifact(
    101                 second.scope.binding().clone(),
    102                 OperationId::from_bytes([224; 32]),
    103                 foreign.prepared().identity().command_digest(),
    104                 *foreign_capture.attempt().bound_plan().plan().digest(),
    105                 SigningTarget::PublicEvent,
    106             ),
    107             copy(&second.proof),
    108         )
    109         .await
    110         .unwrap()
    111         .unwrap();
    112     assert!(!captured.evidence().matches_attempt(&foreign_attempt));
    113     assert!(
    114         CapturedArtifact::from_committed_store(
    115             foreign_attempt,
    116             captured.evidence().retained_copy(),
    117             captured.receipt().transaction_id(),
    118         )
    119         .is_err()
    120     );
    121     assert_eq!(
    122         first.snapshot(224).await.checkpoint_digest(),
    123         original.checkpoint_digest()
    124     );
    125     assert_eq!(
    126         second.snapshot(224).await.checkpoint_digest(),
    127         foreign.checkpoint_digest()
    128     );
    129     assert_eq!(relay.count.load(Ordering::SeqCst), 2);
    130     for ready in [&first, &second] {
    131         assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1);
    132         assert_eq!(ready.signer.private_calls.load(Ordering::SeqCst), 0);
    133         ready.client.close().await.unwrap();
    134     }
    135     stop(relay).await;
    136 }
    137 
    138 #[tokio::test]
    139 async fn public_reports_require_original_plan_obtained_basis_and_atomic_installation_links() {
    140     let relay = Relay::new().await;
    141     let ready = Ready::new(&relay, StartMode::Online, PublicSigner::new(), true).await;
    142     for id in [220, 221] {
    143         ready
    144             .client
    145             .listings()
    146             .publish(ready.context(id, now() + 120), input(id))
    147             .await
    148             .unwrap();
    149     }
    150     let original = ready.snapshot(220).await;
    151     let other = ready.snapshot(221).await;
    152     let installation = original.listing_installation().unwrap();
    153     let work = original.public_publications()[0];
    154     let before = original.checkpoint_digest();
    155     assert!(
    156         bare(&ready, 220)
    157             .await
    158             .with_public_installation(None, vec![work])
    159             .is_err()
    160     );
    161     for works in [
    162         vec![],
    163         vec![work, work],
    164         other.public_publications().to_vec(),
    165     ] {
    166         assert!(
    167             bare(&ready, 220)
    168                 .await
    169                 .with_public_installation(Some(installation), works)
    170                 .is_err()
    171         );
    172     }
    173     assert!(
    174         bare(&ready, 220)
    175             .await
    176             .with_public_installation(other.listing_installation(), vec![work],)
    177             .is_err()
    178     );
    179 
    180     // Work may describe a later transaction, but cannot masquerade as the
    181     // initial atomic T2 pair required by this snapshot profile.
    182     for (transaction, time) in [
    183         (
    184             TransactionId::from_bytes([222; 32]),
    185             installation.installed_at(),
    186         ),
    187         (
    188             installation.transaction_id(),
    189             UnixSeconds::new(installation.installed_at().get() + 1).unwrap(),
    190         ),
    191     ] {
    192         let changed = PublicPublicationWork::from_committed_store(
    193             &original_plan(&ready, 220).await,
    194             installation,
    195             work.evidence(),
    196             transaction,
    197             time,
    198         )
    199         .unwrap();
    200         assert!(
    201             bare(&ready, 220)
    202                 .await
    203                 .with_public_installation(Some(installation), vec![changed])
    204                 .is_err()
    205         );
    206     }
    207     let artifact = original.artifacts()[0];
    208     let unknown = ArtifactSnapshot::from_store_report(
    209         SigningTarget::PublicEvent,
    210         artifact.expected_event(),
    211         artifact.claim(),
    212         None,
    213     );
    214     let incomplete = OperationSnapshot::from_store_report(
    215         RetainedOperation::Planned(Box::new(original_plan(&ready, 220).await)),
    216         vec![unknown],
    217         original.observed_at(),
    218     )
    219     .unwrap();
    220     assert!(
    221         incomplete
    222             .with_public_installation(Some(installation), vec![work])
    223             .is_err()
    224     );
    225     let preparation = ready
    226         .store
    227         .operation(
    228             ready.scope.binding().clone(),
    229             OperationId::from_bytes([220; 32]),
    230             None,
    231             copy(&ready.proof),
    232         )
    233         .await
    234         .unwrap()
    235         .unwrap();
    236     let unplanned = OperationSnapshot::from_store_report(
    237         RetainedOperation::Prepared(preparation),
    238         vec![ArtifactSnapshot::from_store_report(
    239             SigningTarget::PublicEvent,
    240             None,
    241             None,
    242             None,
    243         )],
    244         original.observed_at(),
    245     )
    246     .unwrap();
    247     assert!(
    248         unplanned
    249             .with_public_installation(Some(installation), vec![work])
    250             .is_err()
    251     );
    252 
    253     // An independently verified public signature supplies no private subject,
    254     // business seal or chat installation through any retained projection.
    255     assert!(artifact.recipient().is_err());
    256     assert!(artifact.claim().unwrap().recipient().is_err());
    257     assert!(artifact.obtained().unwrap().recipient().is_err());
    258     assert!(PublicationArtifact::Public(work).private().is_err());
    259     let plan = original_plan(&ready, 220).await;
    260     let selector = ClaimAttemptRequest::for_artifact(
    261         ready.scope.binding().clone(),
    262         OperationId::from_bytes([220; 32]),
    263         original.prepared().identity().command_digest(),
    264         *plan.plan().digest(),
    265         SigningTarget::PublicEvent,
    266     );
    267     assert!(selector.recipient().is_err());
    268     let attempt = ready
    269         .store
    270         .signing_attempt(selector, copy(&ready.proof))
    271         .await
    272         .unwrap()
    273         .unwrap();
    274     assert!(attempt.seal().is_err());
    275     assert!(
    276         ListingInstallation::from_committed_store(
    277             &plan,
    278             other.public_publications()[0].evidence(),
    279             installation.transaction_id(),
    280             installation.installed_at(),
    281         )
    282         .is_err()
    283     );
    284     let other_plan = original_plan(&ready, 221).await;
    285     let other_attempt = ready
    286         .store
    287         .signing_attempt(
    288             ClaimAttemptRequest::for_artifact(
    289                 ready.scope.binding().clone(),
    290                 OperationId::from_bytes([221; 32]),
    291                 other.prepared().identity().command_digest(),
    292                 *other_plan.plan().digest(),
    293                 SigningTarget::PublicEvent,
    294             ),
    295             copy(&ready.proof),
    296         )
    297         .await
    298         .unwrap()
    299         .unwrap();
    300     let captured = ready
    301         .store
    302         .obtained_evidence(
    303             ClaimAttemptRequest::for_artifact(
    304                 ready.scope.binding().clone(),
    305                 OperationId::from_bytes([220; 32]),
    306                 original.prepared().identity().command_digest(),
    307                 *plan.plan().digest(),
    308                 SigningTarget::PublicEvent,
    309             ),
    310             copy(&ready.proof),
    311         )
    312         .await
    313         .unwrap()
    314         .unwrap();
    315     assert!(
    316         CapturedArtifact::from_committed_store(
    317             other_attempt,
    318             captured.evidence().retained_copy(),
    319             captured.receipt().transaction_id(),
    320         )
    321         .is_err()
    322     );
    323     assert!(
    324         ListingInstallation::from_committed_store(
    325             &plan,
    326             work.evidence(),
    327             installation.transaction_id(),
    328             UnixSeconds::new(plan.bound_at().get() - 1).unwrap(),
    329         )
    330         .is_err()
    331     );
    332     assert!(
    333         ChatInstallation::from_committed_store(
    334             &plan,
    335             work.evidence(),
    336             installation.transaction_id(),
    337             installation.installed_at(),
    338         )
    339         .is_err()
    340     );
    341     let earlier = UnixSeconds::new(installation.installed_at().get() - 1).unwrap();
    342     assert!(
    343         PublicPublicationWork::from_committed_store(
    344             &plan,
    345             installation,
    346             work.evidence(),
    347             installation.transaction_id(),
    348             earlier,
    349         )
    350         .is_err()
    351     );
    352     assert!(
    353         installed(&ready, 220)
    354             .await
    355             .with_installation(None, vec![])
    356             .is_err()
    357     );
    358     assert_eq!(ready.snapshot(220).await.checkpoint_digest(), before);
    359     assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 2);
    360     assert_eq!(ready.signer.private_calls.load(Ordering::SeqCst), 0);
    361     assert_eq!(relay.count.load(Ordering::SeqCst), 2);
    362     ready.client.close().await.unwrap();
    363     stop(relay).await;
    364 }
    365 
    366 fn descriptor(
    367     original: &DeliveryAttempt,
    368     id: &str,
    369     transaction: TransactionId,
    370     ordinal: u8,
    371     policy: &SatisfactionPolicy,
    372 ) -> DeliveryAttemptSummary {
    373     let intent = DeliveryIntent::public(
    374         id,
    375         original.intent().event_id(),
    376         original.intent().targets(),
    377         policy,
    378         original.intent().deadline_unix_ms(),
    379     )
    380     .unwrap()
    381     .with_selection(&original.intent().selected_target_set().unwrap())
    382     .unwrap();
    383     let report = DeliveryAttempt::from_store_report(
    384         original.work(),
    385         intent,
    386         original.raw_json(),
    387         transaction,
    388         original.retained_at(),
    389         vec![ordinal],
    390     )
    391     .unwrap();
    392     DeliveryAttemptSummary::from_attempt(&report)
    393 }
    394 
    395 #[tokio::test]
    396 async fn public_delivery_reports_refuse_unbacked_duplicate_renumbered_or_redefined_history() {
    397     let relay = Relay::new().await;
    398     let ready = Ready::new(&relay, StartMode::Online, PublicSigner::new(), true).await;
    399     ready
    400         .client
    401         .listings()
    402         .publish(ready.context(222, now() + 120), input(222))
    403         .await
    404         .unwrap();
    405     let snapshot = ready.snapshot(222).await;
    406     let summary = &snapshot.delivery_attempts()[0];
    407     let original = ready
    408         .store
    409         .delivery_attempt(
    410             ready.scope.binding().clone(),
    411             OperationId::from_bytes([222; 32]),
    412             snapshot.prepared().identity().command_digest(),
    413             SigningTarget::PublicEvent,
    414             summary.intent().request_id().clone(),
    415             copy(&ready.proof),
    416         )
    417         .await
    418         .unwrap()
    419         .unwrap();
    420     let observations = snapshot.delivery_observations().to_vec();
    421     assert_eq!(observations.len(), 1);
    422     assert!(
    423         bare(&ready, 222)
    424             .await
    425             .publication_accepted(original.work())
    426             .is_err()
    427     );
    428 
    429     // Re-encoding even an authentic event cannot replace its original retained
    430     // bytes. Corrupted signed fields and an oversized carrier refuse too.
    431     let spaced = format!(" {}", original.raw_json());
    432     nostr::Event::from_json(&spaced).unwrap().verify().unwrap();
    433     let signed = nostr::Event::from_json(original.raw_json()).unwrap();
    434     let keys = route_key(1);
    435     assert_eq!(signed.pubkey, keys.public_key());
    436     for (kind, content) in [
    437         (nostr::Kind::TextNote, signed.content.clone()),
    438         (signed.kind, "Another authentic event".to_owned()),
    439     ] {
    440         let foreign = nostr::UnsignedEvent {
    441             id: None,
    442             pubkey: signed.pubkey,
    443             created_at: signed.created_at,
    444             kind,
    445             tags: signed.tags.clone(),
    446             content,
    447         }
    448         .sign_with_keys(&keys)
    449         .unwrap();
    450         foreign.verify().unwrap();
    451         assert!(
    452             DeliveryAttempt::from_store_report(
    453                 original.work(),
    454                 original.intent().clone(),
    455                 &foreign.as_json(),
    456                 original.transaction_id(),
    457                 original.retained_at(),
    458                 vec![1],
    459             )
    460             .is_err()
    461         );
    462     }
    463     let mut wrong_kind: serde_json::Value = serde_json::from_str(original.raw_json()).unwrap();
    464     wrong_kind["kind"] = json!(1);
    465     let mut wrong_id: serde_json::Value = serde_json::from_str(original.raw_json()).unwrap();
    466     wrong_id["id"] = json!("00".repeat(32));
    467     for raw in [
    468         spaced,
    469         wrong_kind.to_string(),
    470         wrong_id.to_string(),
    471         " ".repeat(65_537),
    472         "{".to_owned(),
    473     ] {
    474         assert!(
    475             DeliveryAttempt::from_store_report(
    476                 original.work(),
    477                 original.intent().clone(),
    478                 &raw,
    479                 original.transaction_id(),
    480                 original.retained_at(),
    481                 vec![1],
    482             )
    483             .is_err()
    484         );
    485     }
    486     let private_intent = DeliveryIntent::new(
    487         original.intent().request_id().as_str(),
    488         original.intent().event_id(),
    489         original.intent().targets(),
    490         original.intent().policy(),
    491         original.intent().deadline_unix_ms(),
    492     )
    493     .unwrap();
    494     assert!(
    495         DeliveryAttempt::from_store_report(
    496             original.work(),
    497             private_intent,
    498             original.raw_json(),
    499             original.transaction_id(),
    500             original.retained_at(),
    501             vec![1],
    502         )
    503         .is_err()
    504     );
    505     let id = if summary.intent().request_id().as_str() == "01".repeat(32) {
    506         "02".repeat(32)
    507     } else {
    508         "01".repeat(32)
    509     };
    510     let tx = TransactionId::from_bytes([223; 32]);
    511     assert_ne!(tx, summary.transaction_id());
    512     let second = descriptor(&original, &id, tx, 2, summary.intent().policy());
    513     let alternate = SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::any());
    514     let cases = [
    515         vec![summary.clone(), summary.clone()],
    516         vec![
    517             summary.clone(),
    518             descriptor(
    519                 &original,
    520                 &id,
    521                 summary.transaction_id(),
    522                 2,
    523                 summary.intent().policy(),
    524             ),
    525         ],
    526         vec![
    527             summary.clone(),
    528             descriptor(&original, &id, tx, 1, summary.intent().policy()),
    529         ],
    530         vec![second.clone()],
    531         vec![
    532             summary.clone(),
    533             descriptor(&original, &id, tx, 2, &alternate),
    534         ],
    535         vec![summary.clone(); 385],
    536     ];
    537     for attempts in cases {
    538         assert!(
    539             installed(&ready, 222)
    540                 .await
    541                 .with_delivery(attempts, observations.clone())
    542                 .is_err()
    543         );
    544     }
    545     assert!(
    546         bare(&ready, 222)
    547             .await
    548             .with_delivery(vec![summary.clone()], observations.clone())
    549             .is_err()
    550     );
    551     assert!(
    552         installed(&ready, 222)
    553             .await
    554             .with_delivery(vec![], observations.clone())
    555             .is_err()
    556     );
    557     assert!(
    558         installed(&ready, 222)
    559             .await
    560             .with_delivery(vec![summary.clone()], vec![observations[0].clone(); 2])
    561             .is_err()
    562     );
    563     assert!(
    564         installed(&ready, 222)
    565             .await
    566             .with_delivery(vec![summary.clone()], vec![observations[0].clone(); 2305])
    567             .is_err()
    568     );
    569     let renumbered = [
    570         descriptor(
    571             &original,
    572             summary.intent().request_id().as_str(),
    573             summary.transaction_id(),
    574             2,
    575             summary.intent().policy(),
    576         ),
    577         descriptor(&original, &id, tx, 1, summary.intent().policy()),
    578     ];
    579     assert!(
    580         installed(&ready, 222)
    581             .await
    582             .with_delivery(renumbered.into(), observations.clone())
    583             .is_err()
    584     );
    585     let valid = installed(&ready, 222)
    586         .await
    587         .with_delivery(vec![summary.clone(), second], observations)
    588         .unwrap();
    589     assert!(valid.publication_accepted(original.work()).unwrap());
    590     assert_eq!(
    591         ready.snapshot(222).await.checkpoint_digest(),
    592         snapshot.checkpoint_digest()
    593     );
    594     assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1);
    595     assert_eq!(relay.count.load(Ordering::SeqCst), 1);
    596     ready.client.close().await.unwrap();
    597     stop(relay).await;
    598 }
    599 
    600 #[tokio::test]
    601 async fn public_delivery_queries_require_exact_bounded_request_and_artifact_selectors() {
    602     use radroots_transport::sink::DeliveryRequestId;
    603     let relay = Relay::new().await;
    604     let ready = Ready::new(&relay, StartMode::Online, PublicSigner::new(), true).await;
    605     ready
    606         .client
    607         .listings()
    608         .publish(ready.context(223, now() + 120), input(223))
    609         .await
    610         .unwrap();
    611     let snapshot = ready.snapshot(223).await;
    612     let summary = &snapshot.delivery_attempts()[0];
    613     let operation = OperationId::from_bytes([223; 32]);
    614     let digest = snapshot.prepared().identity().command_digest();
    615     let query = |target, request| {
    616         ready.store.delivery_attempt(
    617             ready.scope.binding().clone(),
    618             operation,
    619             digest,
    620             target,
    621             request,
    622             copy(&ready.proof),
    623         )
    624     };
    625     let actual = query(
    626         SigningTarget::PublicEvent,
    627         summary.intent().request_id().clone(),
    628     )
    629     .await
    630     .unwrap()
    631     .unwrap();
    632     assert_eq!(actual.work(), summary.work());
    633     assert_eq!(actual.envelope_digest(), summary.envelope_digest());
    634     for id in ["short".to_owned(), "GG".repeat(32)] {
    635         assert!(matches!(
    636             query(
    637                 SigningTarget::PublicEvent,
    638                 DeliveryRequestId::parse(id).unwrap()
    639             )
    640             .await,
    641             Err(OperationError::InvalidCommand)
    642         ));
    643     }
    644     let missing = if summary.intent().request_id().as_str() == "00".repeat(32) {
    645         "11".repeat(32)
    646     } else {
    647         "00".repeat(32)
    648     };
    649     assert!(
    650         query(
    651             SigningTarget::PublicEvent,
    652             DeliveryRequestId::parse(missing).unwrap()
    653         )
    654         .await
    655         .unwrap()
    656         .is_none()
    657     );
    658     assert!(
    659         query(
    660             SigningTarget::BusinessSeal(key()),
    661             summary.intent().request_id().clone()
    662         )
    663         .await
    664         .unwrap()
    665         .is_none()
    666     );
    667     assert_eq!(
    668         ready.snapshot(223).await.checkpoint_digest(),
    669         snapshot.checkpoint_digest()
    670     );
    671     assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1);
    672     assert_eq!(ready.signer.private_calls.load(Ordering::SeqCst), 0);
    673     assert_eq!(relay.count.load(Ordering::SeqCst), 1);
    674     ready.client.close().await.unwrap();
    675     stop(relay).await;
    676 }