lib

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

authored_signing.rs (20504B)


      1 use nostr::{EventBuilder, JsonUtil, Keys, Kind as NostrKind, SecretKey, Timestamp};
      2 use radroots_blossom::{
      3     Sha256 as BlossomSha256,
      4     authorization::{AuthoredUploadClaim, AuthorizationContent, ServerDomain},
      5 };
      6 use radroots_event::{
      7     GenericEventDraft,
      8     contract::AuthorRole,
      9     food::availability::{
     10         FoodAvailabilityDetails, FoodAvailabilityDetailsParts, FoodAvailabilityStatus, FoodContent,
     11         FoodCurrency, FoodIdentifier, FoodPrice, FoodPublishedAt, FoodText, FoodUnit,
     12     },
     13     wire::Nip01EventWire,
     14 };
     15 use radroots_event_codec::authoring::{AuthoredEventPlan, BlossomAuthorizationPlan};
     16 use radroots_identity::{AccountId, PublicKey};
     17 use radroots_protocol::runtime::v1::OperationId;
     18 use radroots_signing::{
     19     Actor, AuthoredArtifactId, CurrentAuthoringAuthority, CurrentAuthoringDecision, Error,
     20     SignReceipt, SignRequest, SigningIntentId, SigningOperationId, SigningPurpose,
     21     actor::ActorSource,
     22     authorization::ManagedSigningPolicy,
     23     error::Kind,
     24     recovery::{RecoveryDisposition, RemoteEffect, ReplayCapability, recovery_disposition},
     25     request::{CancellationPolicy, CancellationSignal, ProgressObserver, SignPolicy},
     26     status::{SignProgress, SignProgressStage},
     27 };
     28 
     29 const SECRET: &str = "7e0112ad58b2d2d13fb80532625195dc169b86d72b0e1db48347837a785cae90";
     30 const CREATED_AT: u64 = 1_700_000_000;
     31 const DEADLINE_MS: u64 = 1_700_000_100_000;
     32 
     33 #[derive(Clone, Copy)]
     34 struct FixedAuthority(CurrentAuthoringDecision);
     35 
     36 impl CurrentAuthoringAuthority for FixedAuthority {
     37     fn evaluate(&self, _plan: &AuthoredEventPlan) -> CurrentAuthoringDecision {
     38         self.0
     39     }
     40 }
     41 
     42 fn keys() -> Keys {
     43     Keys::new(SecretKey::from_hex(SECRET).expect("secret fixture"))
     44 }
     45 
     46 fn public_key() -> PublicKey {
     47     PublicKey::from_hex(&keys().public_key().to_hex()).expect("public key")
     48 }
     49 
     50 fn plan() -> AuthoredEventPlan {
     51     AuthoredEventPlan::from_generic(
     52         GenericEventDraft::new(
     53             "radroots.social.geochat.v1",
     54             20_000,
     55             CREATED_AT,
     56             Vec::new(),
     57             "exact signing plan",
     58             public_key().to_hex(),
     59         )
     60         .expect("generic draft"),
     61     )
     62     .expect("authored plan")
     63 }
     64 
     65 fn actor(source: ActorSource, roles: impl IntoIterator<Item = AuthorRole>) -> Actor {
     66     Actor::new(public_key(), source, roles).expect("actor")
     67 }
     68 
     69 fn intent(operation: u8, artifact: u8) -> SigningIntentId {
     70     SigningIntentId::new(
     71         SigningOperationId::new([operation; 16]).expect("operation ID"),
     72         AuthoredArtifactId::new([artifact; 16]).expect("artifact ID"),
     73     )
     74 }
     75 
     76 fn policy() -> SignPolicy {
     77     SignPolicy::new(DEADLINE_MS, CancellationPolicy::LocalCooperative).expect("policy")
     78 }
     79 
     80 fn request() -> SignRequest {
     81     SignRequest::new(
     82         OperationId::SyncPush,
     83         intent(1, 2),
     84         actor(ActorSource::ExplicitPublicKey, [AuthorRole::Any]),
     85         plan(),
     86         policy(),
     87     )
     88     .expect("request")
     89 }
     90 
     91 fn profile_edit_plan() -> AuthoredEventPlan {
     92     use radroots_event::profile::edit::{ProfileEdit, ProfileFieldChange};
     93     use radroots_event_codec::admission::profile::verify_and_admit_profile_event;
     94     let baseline = signed_event_with(
     95         &keys(),
     96         0,
     97         r#"{"name":"farm","website":"https://farm.example","custom":{"x":1}}"#,
     98         CREATED_AT,
     99         Vec::new(),
    100     );
    101     let baseline = verify_and_admit_profile_event(baseline.envelope().clone()).unwrap();
    102     AuthoredEventPlan::from_profile_edit(
    103         &baseline,
    104         &baseline,
    105         &ProfileEdit {
    106             display_name: ProfileFieldChange::Set("Updated farm".into()),
    107             ..Default::default()
    108         },
    109         CREATED_AT + 1,
    110         public_key().to_hex(),
    111     )
    112     .unwrap()
    113 }
    114 
    115 #[test]
    116 fn profile_complete_edit_managed_signing_admits_exact_current_operation_and_signature() {
    117     use radroots_signing::authorization::CurrentRegistryAuthority;
    118     let plan = profile_edit_plan();
    119     let request = SignRequest::new(
    120         OperationId::SyncPush,
    121         intent(41, 42),
    122         actor(ActorSource::ExplicitPublicKey, [AuthorRole::Any]),
    123         plan.clone(),
    124         policy(),
    125     )
    126     .expect("current complete-profile edit must enter managed signing");
    127     assert_eq!(
    128         CurrentRegistryAuthority.evaluate(&plan),
    129         CurrentAuthoringDecision::Allowed
    130     );
    131     assert_eq!(request.authored_plan(), Some(&plan));
    132     let signed = signed_event_with(
    133         &keys(),
    134         0,
    135         plan.body().content(),
    136         plan.created_at(),
    137         Vec::new(),
    138     );
    139     let receipt =
    140         SignReceipt::from_signed_event(&request, signed, CREATED_AT * 1000 + 2000).unwrap();
    141     assert_eq!(receipt.signed_event().id(), plan.expected_event_id());
    142     let fields: serde_json::Value = serde_json::from_str(receipt.signed_event().content()).unwrap();
    143     assert_eq!(fields["website"], "https://farm.example");
    144     assert_eq!(fields["custom"], serde_json::json!({"x":1}));
    145 }
    146 
    147 #[test]
    148 fn profile_complete_edit_managed_signing_preserves_host_denial_and_managed_actor_policy() {
    149     for decision in [
    150         CurrentAuthoringDecision::Blocked {
    151             code: "host_denied",
    152         },
    153         CurrentAuthoringDecision::Revoked {
    154             code: "host_revoked",
    155         },
    156     ] {
    157         let error = SignRequest::new_with_authority(
    158             OperationId::SyncPush,
    159             intent(41, 42),
    160             actor(ActorSource::ExplicitPublicKey, [AuthorRole::Any]),
    161             profile_edit_plan(),
    162             policy(),
    163             &FixedAuthority(decision),
    164         )
    165         .unwrap_err();
    166         assert_eq!(error.kind(), Kind::AuthorizationDenied);
    167     }
    168     let denied = SignRequest::new(
    169         OperationId::SyncPush,
    170         intent(41, 42),
    171         actor(ActorSource::ExplicitPublicKey, [AuthorRole::Any]),
    172         profile_edit_plan(),
    173         policy().with_managed_signing_policy(ManagedSigningPolicy::AccountBackedOnly),
    174     )
    175     .unwrap_err();
    176     assert_eq!(denied.kind(), Kind::AuthorizationDenied);
    177     let local = actor(
    178         ActorSource::LocalAccount(AccountId::from_hex(&public_key().to_hex()).unwrap()),
    179         [AuthorRole::Any],
    180     );
    181     assert!(
    182         SignRequest::new(
    183             OperationId::SyncPush,
    184             intent(41, 42),
    185             local,
    186             profile_edit_plan(),
    187             policy().with_managed_signing_policy(ManagedSigningPolicy::LocalAccountOnly)
    188         )
    189         .is_ok()
    190     );
    191 }
    192 
    193 fn blossom_plan() -> BlossomAuthorizationPlan {
    194     let claim = AuthoredUploadClaim::new(
    195         AuthorizationContent::parse("Upload exact image").expect("content"),
    196         ServerDomain::parse("media.example").expect("server"),
    197         BlossomSha256::digest(b"exact-image"),
    198         CREATED_AT,
    199         60,
    200     )
    201     .expect("upload claim");
    202     BlossomAuthorizationPlan::for_upload(&claim, public_key()).expect("authorization plan")
    203 }
    204 
    205 fn blossom_request() -> SignRequest {
    206     SignRequest::blossom_upload(
    207         OperationId::SyncPush,
    208         intent(9, 10),
    209         actor(ActorSource::ExplicitPublicKey, [AuthorRole::Any]),
    210         blossom_plan(),
    211         policy(),
    212     )
    213     .expect("Blossom request")
    214 }
    215 
    216 fn signed_event() -> radroots_event::SignedEvent {
    217     signed_event_with(
    218         &keys(),
    219         20_000,
    220         "exact signing plan",
    221         CREATED_AT,
    222         Vec::new(),
    223     )
    224 }
    225 
    226 fn signed_event_with(
    227     signer: &Keys,
    228     kind: u16,
    229     content: &str,
    230     created_at: u64,
    231     tags: Vec<nostr::Tag>,
    232 ) -> radroots_event::SignedEvent {
    233     let event = EventBuilder::new(NostrKind::Custom(kind), content)
    234         .tags(tags)
    235         .custom_created_at(Timestamp::from_secs(created_at))
    236         .sign_with_keys(signer)
    237         .expect("signed fixture");
    238     let raw = event.as_json();
    239     let wire = Nip01EventWire::parse_json(&raw).expect("wire");
    240     radroots_event::SignedEvent::from_wire_verified_id(wire, raw).expect("signed event")
    241 }
    242 
    243 #[test]
    244 fn authorization_decisions_are_current_and_explicit() {
    245     let base_actor = actor(ActorSource::ExplicitPublicKey, [AuthorRole::Any]);
    246     let base_plan = plan();
    247     for decision in [
    248         CurrentAuthoringDecision::Blocked { code: "blocked" },
    249         CurrentAuthoringDecision::Revoked { code: "revoked" },
    250     ] {
    251         let error = SignRequest::new_with_authority(
    252             OperationId::SyncPush,
    253             intent(1, 2),
    254             base_actor.clone(),
    255             base_plan.clone(),
    256             policy(),
    257             &FixedAuthority(decision),
    258         )
    259         .expect_err("denied decision");
    260         assert_eq!(error.kind(), Kind::AuthorizationDenied);
    261     }
    262 
    263     let deprecated = FixedAuthority(CurrentAuthoringDecision::AllowedDeprecated {
    264         warning_code: "deprecated",
    265     });
    266     assert_eq!(
    267         SignRequest::new_with_authority(
    268             OperationId::SyncPush,
    269             intent(1, 2),
    270             base_actor.clone(),
    271             base_plan.clone(),
    272             policy(),
    273             &deprecated,
    274         )
    275         .expect_err("deprecated requires opt in")
    276         .kind(),
    277         Kind::AuthorizationDenied
    278     );
    279     let allowed = SignRequest::new_with_authority(
    280         OperationId::SyncPush,
    281         intent(1, 2),
    282         base_actor,
    283         base_plan,
    284         policy().allowing_deprecated(),
    285         &deprecated,
    286     )
    287     .expect("explicitly allowed deprecated plan");
    288     assert!(matches!(
    289         allowed.authorization(),
    290         Some(CurrentAuthoringDecision::AllowedDeprecated { .. })
    291     ));
    292 }
    293 
    294 #[test]
    295 fn authorization_enforces_key_role_and_host_provenance() {
    296     let wrong_key =
    297         PublicKey::from_hex("e0266e3cfb0d2886f91c73f5f868f3b98273713e5fcd97c081663f5518a4b3af")
    298             .expect("other public key");
    299     let wrong_actor =
    300         Actor::new(wrong_key, ActorSource::ExplicitPublicKey, [AuthorRole::Any]).expect("actor");
    301     assert_eq!(
    302         SignRequest::new(
    303             OperationId::SyncPush,
    304             intent(1, 2),
    305             wrong_actor,
    306             plan(),
    307             policy(),
    308         )
    309         .expect_err("key drift")
    310         .kind(),
    311         Kind::AuthorizationDenied
    312     );
    313 
    314     let account = AccountId::from_hex(&public_key().to_hex()).expect("account ID");
    315     let local_actor = actor(ActorSource::LocalAccount(account), [AuthorRole::Any]);
    316     SignRequest::new(
    317         OperationId::SyncPush,
    318         intent(1, 2),
    319         local_actor,
    320         plan(),
    321         policy().with_managed_signing_policy(ManagedSigningPolicy::LocalAccountOnly),
    322     )
    323     .expect("local account is allowed");
    324     assert_eq!(
    325         SignRequest::new(
    326             OperationId::SyncPush,
    327             intent(1, 2),
    328             actor(ActorSource::ExplicitPublicKey, [AuthorRole::Any]),
    329             plan(),
    330             policy().with_managed_signing_policy(ManagedSigningPolicy::AccountBackedOnly),
    331         )
    332         .expect_err("unmanaged explicit key")
    333         .kind(),
    334         Kind::AuthorizationDenied
    335     );
    336 
    337     let food = FoodAvailabilityDetails::new(FoodAvailabilityDetailsParts {
    338         content: FoodContent::new("Carrots available.").unwrap(),
    339         identifier: FoodIdentifier::parse("carrots").unwrap(),
    340         title: FoodText::new("Carrots").unwrap(),
    341         summary: FoodText::new("Fresh bunches").unwrap(),
    342         published_at: FoodPublishedAt::new(CREATED_AT).unwrap(),
    343         location: FoodText::new("Saanich").unwrap(),
    344         price: FoodPrice::new("3", FoodCurrency::parse("CAD").unwrap(), FoodUnit::Pound).unwrap(),
    345         quantity: None,
    346         status: FoodAvailabilityStatus::Active,
    347         images: Vec::new(),
    348     })
    349     .unwrap();
    350     let seller_plan =
    351         AuthoredEventPlan::from_food_availability(&food, CREATED_AT, public_key().to_hex())
    352             .unwrap();
    353     assert_eq!(
    354         SignRequest::new(
    355             OperationId::SyncPush,
    356             intent(1, 3),
    357             actor(ActorSource::ExplicitPublicKey, [AuthorRole::Buyer]),
    358             seller_plan,
    359             policy(),
    360         )
    361         .expect_err("role drift")
    362         .kind(),
    363         Kind::AuthorizationDenied
    364     );
    365 }
    366 
    367 #[test]
    368 fn blossom_request_is_http_only_domain_separated_and_author_bound() {
    369     let request = blossom_request();
    370     assert_eq!(
    371         request.purpose(),
    372         SigningPurpose::BlossomUploadAuthorization
    373     );
    374     assert!(request.authored_plan().is_none());
    375     assert_eq!(request.blossom_authorization_plan(), Some(&blossom_plan()));
    376     assert_eq!(request.authorization(), None);
    377     assert_eq!(request.kind(), 24_242);
    378 
    379     let wrong_key =
    380         PublicKey::from_hex("e0266e3cfb0d2886f91c73f5f868f3b98273713e5fcd97c081663f5518a4b3af")
    381             .expect("other public key");
    382     let wrong_actor =
    383         Actor::new(wrong_key, ActorSource::ExplicitPublicKey, [AuthorRole::Any]).expect("actor");
    384     assert_eq!(
    385         SignRequest::blossom_upload(
    386             OperationId::SyncPush,
    387             intent(9, 10),
    388             wrong_actor,
    389             blossom_plan(),
    390             policy(),
    391         )
    392         .expect_err("author mismatch")
    393         .kind(),
    394         Kind::AuthorizationDenied
    395     );
    396 }
    397 
    398 #[test]
    399 fn blossom_receipt_rejects_mismatch_lateness_and_cancellation() {
    400     let request = blossom_request();
    401     let tags = request
    402         .tags()
    403         .iter()
    404         .cloned()
    405         .map(nostr::Tag::parse)
    406         .collect::<Result<Vec<_>, _>>()
    407         .expect("BUD-11 tags");
    408     let valid = signed_event_with(
    409         &keys(),
    410         24_242,
    411         request.content(),
    412         request.created_at(),
    413         tags.clone(),
    414     );
    415     SignReceipt::from_signed_event(&request, valid, DEADLINE_MS - 1)
    416         .expect("verified BUD-11 receipt");
    417 
    418     let mismatched = signed_event_with(
    419         &keys(),
    420         24_242,
    421         "Upload a different image",
    422         request.created_at(),
    423         tags,
    424     );
    425     assert_eq!(
    426         SignReceipt::from_signed_event(&request, mismatched, DEADLINE_MS - 1)
    427             .expect_err("mismatched output")
    428             .kind(),
    429         Kind::SignerOutputInvalid
    430     );
    431     assert_eq!(
    432         SignReceipt::from_signed_event(
    433             &request,
    434             signed_event_with(
    435                 &keys(),
    436                 24_242,
    437                 request.content(),
    438                 request.created_at(),
    439                 request
    440                     .tags()
    441                     .iter()
    442                     .cloned()
    443                     .map(nostr::Tag::parse)
    444                     .collect::<Result<Vec<_>, _>>()
    445                     .expect("BUD-11 tags"),
    446             ),
    447             DEADLINE_MS,
    448         )
    449         .expect_err("late output")
    450         .kind(),
    451         Kind::DeadlineExceeded
    452     );
    453 
    454     let signal = CancellationSignal::new();
    455     let cancelled = request.with_cancellation_signal(signal.clone());
    456     signal.cancel();
    457     assert_eq!(
    458         SignReceipt::from_signed_event(
    459             &cancelled,
    460             signed_event_with(
    461                 &keys(),
    462                 24_242,
    463                 cancelled.content(),
    464                 cancelled.created_at(),
    465                 cancelled
    466                     .tags()
    467                     .iter()
    468                     .cloned()
    469                     .map(nostr::Tag::parse)
    470                     .collect::<Result<Vec<_>, _>>()
    471                     .expect("BUD-11 tags"),
    472             ),
    473             DEADLINE_MS - 1,
    474         )
    475         .expect_err("cancelled output")
    476         .kind(),
    477         Kind::SignerCancelled
    478     );
    479 }
    480 
    481 #[test]
    482 fn request_identity_deadline_and_cancellation_are_exact() {
    483     let request = request();
    484     let replay = request.clone();
    485     assert_eq!(request.operation_kind(), OperationId::SyncPush);
    486     assert_eq!(request.intent_id(), intent(1, 2));
    487     assert_eq!(request.actor().public_key(), public_key());
    488     assert_eq!(request.plan_digest(), plan().digest());
    489     assert_eq!(request.policy(), policy());
    490     assert!(!request.cancellation_signal().is_cancelled());
    491     assert_eq!(request.signer_request_id(), replay.signer_request_id());
    492     let other_artifact = SignRequest::new(
    493         OperationId::SyncPush,
    494         intent(1, 3),
    495         actor(ActorSource::ExplicitPublicKey, [AuthorRole::Any]),
    496         plan(),
    497         policy(),
    498     )
    499     .unwrap();
    500     assert_ne!(
    501         request.signer_request_id(),
    502         other_artifact.signer_request_id()
    503     );
    504     assert!(request.ensure_active(DEADLINE_MS - 1).is_ok());
    505     assert_eq!(
    506         request.ensure_active(DEADLINE_MS).unwrap_err().kind(),
    507         Kind::DeadlineExceeded
    508     );
    509 
    510     let signal = CancellationSignal::new();
    511     let cancelled = request.clone().with_cancellation_signal(signal.clone());
    512     signal.cancel();
    513     assert_eq!(
    514         cancelled.ensure_active(DEADLINE_MS - 1).unwrap_err().kind(),
    515         Kind::SignerCancelled
    516     );
    517 
    518     struct Counter(std::sync::atomic::AtomicUsize);
    519     impl ProgressObserver for Counter {
    520         fn on_progress(&self, _progress: &SignProgress) {
    521             self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    522         }
    523     }
    524     let observer = std::sync::Arc::new(Counter(std::sync::atomic::AtomicUsize::new(0)));
    525     let observed = request.with_progress_observer(observer.clone());
    526     observed.report_progress(&SignProgress::stage(SignProgressStage::Validating).unwrap());
    527     assert_eq!(observer.0.load(std::sync::atomic::Ordering::Relaxed), 1);
    528 }
    529 
    530 #[test]
    531 fn receipt_requires_exact_fields_and_a_valid_schnorr_signature() {
    532     let request = request();
    533     let receipt = SignReceipt::from_signed_event(&request, signed_event(), DEADLINE_MS - 1)
    534         .expect("verified receipt");
    535     assert_eq!(receipt.intent_id(), request.intent_id());
    536     assert_eq!(receipt.signer_request_id(), request.signer_request_id());
    537     assert_eq!(receipt.operation_kind(), OperationId::SyncPush);
    538     assert_eq!(receipt.completed_at_unix_ms(), DEADLINE_MS - 1);
    539     assert_eq!(receipt.signed_event().id(), signed_event().id());
    540 
    541     let other_keys = Keys::generate();
    542     let mismatches = [
    543         signed_event_with(
    544             &other_keys,
    545             20_000,
    546             "exact signing plan",
    547             CREATED_AT,
    548             Vec::new(),
    549         ),
    550         signed_event_with(
    551             &keys(),
    552             20_000,
    553             "exact signing plan",
    554             CREATED_AT + 1,
    555             Vec::new(),
    556         ),
    557         signed_event_with(
    558             &keys(),
    559             20_001,
    560             "exact signing plan",
    561             CREATED_AT,
    562             Vec::new(),
    563         ),
    564         signed_event_with(
    565             &keys(),
    566             20_000,
    567             "exact signing plan",
    568             CREATED_AT,
    569             vec![nostr::Tag::parse(["t", "mismatch"]).expect("tag")],
    570         ),
    571         signed_event_with(&keys(), 20_000, "different content", CREATED_AT, Vec::new()),
    572     ];
    573     for mismatch in mismatches {
    574         assert_eq!(
    575             SignReceipt::from_signed_event(&request, mismatch, DEADLINE_MS - 1)
    576                 .expect_err("mismatched exact plan must fail")
    577                 .kind(),
    578             Kind::SignerOutputInvalid
    579         );
    580     }
    581 
    582     let invalid = invalid_signature_event();
    583     assert_eq!(
    584         SignReceipt::from_signed_event(&request, invalid, DEADLINE_MS - 1)
    585             .expect_err("invalid signature")
    586             .kind(),
    587         Kind::SignerOutputInvalid
    588     );
    589 }
    590 
    591 #[test]
    592 fn uncertain_remote_effects_never_become_unsafe_automatic_retries() {
    593     let uncertain = Error::new(Kind::SignerTimeout).with_possible_remote_effect();
    594     assert_eq!(uncertain.remote_effect(), RemoteEffect::MayHaveOccurred);
    595     assert_eq!(
    596         recovery_disposition(
    597             ReplayCapability::ExactReplayByRequestId,
    598             uncertain.remote_effect(),
    599             uncertain.retryable(),
    600         ),
    601         RecoveryDisposition::RetryExactRequest
    602     );
    603     assert_eq!(
    604         recovery_disposition(
    605             ReplayCapability::NonReplayable,
    606             uncertain.remote_effect(),
    607             uncertain.retryable(),
    608         ),
    609         RecoveryDisposition::Indeterminate
    610     );
    611     assert_eq!(
    612         recovery_disposition(ReplayCapability::LocalReplaySafe, RemoteEffect::None, true,),
    613         RecoveryDisposition::RetryLocal
    614     );
    615 }
    616 
    617 #[path = "authored_signing/evidence.rs"]
    618 mod evidence;
    619 
    620 fn invalid_signature_event() -> radroots_event::SignedEvent {
    621     let valid = signed_event();
    622     let mut wire = valid.wire().clone();
    623     wire.sig = "f".repeat(128);
    624     let mut raw: serde_json::Value = serde_json::from_str(valid.raw_json()).expect("raw event");
    625     raw["sig"] = serde_json::Value::String(wire.sig.clone());
    626     radroots_event::SignedEvent::from_wire_verified_id(
    627         wire,
    628         serde_json::to_string(&raw).expect("hostile raw event"),
    629     )
    630     .expect("ID-valid event with hostile signature")
    631 }