lib

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

command.rs (18045B)


      1 #![cfg(feature = "commands")]
      2 
      3 use radroots_domain::{
      4     ActorRef, ActorRole, Approval, AuthorityRef, CommandContextData, CorrelationId, ExecutorId,
      5     Generation, GrantId, MessageId, OperationId, PublicKey, RouteDigest, SourceId, ThreadId,
      6     UnixSeconds, WorkspaceId,
      7 };
      8 use radroots_protocol::command::{
      9     CHAT_MAX_BYTES, COMMAND_MAX_BYTES, CapturedChatCommand, ChatKind, CommandError, InquireInput,
     10     ListingRevisionRef, ReplyInput,
     11 };
     12 use serde::Deserialize;
     13 use serde_json::{Value, json};
     14 
     15 fn alice() -> PublicKey {
     16     PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap()
     17 }
     18 fn bob() -> PublicKey {
     19     PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5").unwrap()
     20 }
     21 fn context(correlation: Option<&str>, approval: Option<Approval>) -> CommandContextData {
     22     CommandContextData::new(
     23         OperationId::from_bytes([1; 32]),
     24         ActorRef::new(
     25             alice(),
     26             ActorRole::Buyer,
     27             None,
     28             Some(GrantId::from_bytes([2; 32])),
     29         ),
     30         WorkspaceId::from_bytes([3; 32]),
     31         AuthorityRef::new(
     32             ExecutorId::from_bytes([4; 32]),
     33             Generation::new(9_007_199_254_740_993).unwrap(),
     34         ),
     35         RouteDigest::from_bytes([5; 32]),
     36         approval,
     37         None,
     38         UnixSeconds::new(200).unwrap(),
     39         correlation.map(|v| CorrelationId::new(v).unwrap()),
     40     )
     41     .unwrap()
     42 }
     43 fn inquiry(
     44     correlation: Option<&str>,
     45     approval: Option<Approval>,
     46     text: &str,
     47 ) -> CapturedChatCommand {
     48     CapturedChatCommand::inquire(
     49         context(correlation, approval),
     50         InquireInput::new(ThreadId::from_bytes([6; 32]), bob(), None, text).unwrap(),
     51     )
     52     .unwrap()
     53 }
     54 
     55 #[test]
     56 fn profile_keys_require_canonical_spelling_at_all_chat_command_entry_points() {
     57     use radroots_protocol::command::CapturedCommand;
     58     let mut base: Value =
     59         serde_json::from_slice(inquiry(None, None, "private").protected_wire()).unwrap();
     60     base["context"]["actor"]["organization"] = json!(alice().to_hex());
     61     base["input"]["source"] = json!({"coordinate":{"kind":30402,"author":alice().to_hex(),"d":"01".repeat(16)},"event_id":"03".repeat(32)});
     62     assert!(CapturedChatCommand::parse(&serde_json::to_vec(&base).unwrap()).is_ok());
     63     for path in [
     64         "/context/actor/participant",
     65         "/context/actor/organization",
     66         "/input/peer",
     67         "/input/source/coordinate/author",
     68     ] {
     69         let mut altered = base.clone();
     70         let uppercase = altered
     71             .pointer(path)
     72             .unwrap()
     73             .as_str()
     74             .unwrap()
     75             .to_ascii_uppercase();
     76         *altered.pointer_mut(path).unwrap() = json!(uppercase);
     77         let wire = serde_json::to_vec(&altered).unwrap();
     78         assert!(CapturedChatCommand::parse(&wire).is_err(), "{path}");
     79         assert!(CapturedCommand::parse(&wire).is_err(), "dispatcher {path}");
     80     }
     81     let mut reply: Value = serde_json::from_slice(
     82         CapturedChatCommand::reply(
     83             context(None, None),
     84             ReplyInput::new(
     85                 ThreadId::from_bytes([6; 32]),
     86                 bob(),
     87                 MessageId::from_bytes([7; 32]),
     88                 "private",
     89             )
     90             .unwrap(),
     91         )
     92         .unwrap()
     93         .protected_wire(),
     94     )
     95     .unwrap();
     96     reply["input"]["peer"] = json!(bob().to_hex().to_ascii_uppercase());
     97     let wire = serde_json::to_vec(&reply).unwrap();
     98     assert!(CapturedChatCommand::parse(&wire).is_err());
     99     assert!(CapturedCommand::parse(&wire).is_err());
    100 }
    101 
    102 #[test]
    103 fn closed_commands_require_objects_at_every_context_and_inquiry_boundary() {
    104     use radroots_protocol::command::CapturedCommand;
    105 
    106     let mut base: Value =
    107         serde_json::from_slice(inquiry(None, None, "private").protected_wire()).unwrap();
    108     base["context"]["approval"] = json!({
    109         "intent_digest":"08".repeat(32),"scope":"inbox.inquire","expires_at":"190"
    110     });
    111     base["context"]["expected"] = json!({
    112         "order_id":"09".repeat(32),"agreement":"0a".repeat(32),
    113         "seller_sequence":"4","buyer_head":"0b".repeat(32),
    114         "checkpoint":{"digest":"0c".repeat(32),"sequence":"4",
    115             "coverage":"partial","missing":["0d".repeat(32)]}
    116     });
    117     base["input"]["source"] = json!({
    118         "coordinate":{"kind":30402,"author":bob().to_hex(),"d":"55".repeat(16)},
    119         "event_id":"0e".repeat(32)
    120     });
    121     let wire = serde_json::to_vec(&base).unwrap();
    122     CapturedChatCommand::parse(&wire).unwrap();
    123     CapturedCommand::parse(&wire).unwrap();
    124     let mut accepted = Vec::new();
    125     for (pointer, keys) in [
    126         ("", &["type", "context", "input"][..]),
    127         (
    128             "/context",
    129             &[
    130                 "operation_id",
    131                 "actor",
    132                 "workspace_id",
    133                 "authority",
    134                 "route_digest",
    135                 "approval",
    136                 "expected",
    137                 "not_after",
    138                 "correlation_id",
    139             ][..],
    140         ),
    141         (
    142             "/context/actor",
    143             &["participant", "role", "organization", "grant_id"][..],
    144         ),
    145         ("/context/authority", &["executor_id", "generation"][..]),
    146         (
    147             "/context/approval",
    148             &["intent_digest", "scope", "expires_at"][..],
    149         ),
    150         (
    151             "/context/expected",
    152             &[
    153                 "order_id",
    154                 "agreement",
    155                 "seller_sequence",
    156                 "buyer_head",
    157                 "checkpoint",
    158             ][..],
    159         ),
    160         (
    161             "/context/expected/checkpoint",
    162             &["digest", "sequence", "coverage", "missing"][..],
    163         ),
    164         ("/input", &["thread_id", "peer", "source", "text"][..]),
    165         ("/input/source", &["coordinate", "event_id"][..]),
    166         ("/input/source/coordinate", &["kind", "author", "d"][..]),
    167     ] {
    168         let mut value = base.clone();
    169         let array = Value::Array(
    170             keys.iter()
    171                 .map(|key| value.pointer(pointer).unwrap()[key].clone())
    172                 .collect(),
    173         );
    174         *value.pointer_mut(pointer).unwrap() = array;
    175         let raw = serde_json::to_vec(&value).unwrap();
    176         if CapturedChatCommand::parse(&raw).is_ok() {
    177             accepted.push(format!("chat:{pointer}"));
    178         }
    179         if CapturedCommand::parse(&raw).is_ok() {
    180             accepted.push(format!("dispatch:{pointer}"));
    181         }
    182     }
    183     assert!(
    184         accepted.is_empty(),
    185         "object fields accepted positional arrays: {accepted:?}"
    186     );
    187 }
    188 
    189 #[test]
    190 fn closed_reply_input_requires_an_object_without_changing_its_canonical_bytes() {
    191     use radroots_protocol::command::CapturedCommand;
    192 
    193     let reply = CapturedChatCommand::reply(
    194         context(None, None),
    195         ReplyInput::new(
    196             ThreadId::from_bytes([6; 32]),
    197             bob(),
    198             MessageId::from_bytes([11; 32]),
    199             "reply",
    200         )
    201         .unwrap(),
    202     )
    203     .unwrap();
    204     let mut value: Value = serde_json::from_slice(reply.protected_wire()).unwrap();
    205     let parsed = CapturedChatCommand::parse(reply.protected_wire()).unwrap();
    206     assert_eq!(parsed.protected_wire(), reply.protected_wire());
    207     assert_eq!(parsed.digest(), reply.digest());
    208     value["input"] = Value::Array(
    209         ["thread_id", "peer", "parent", "text"]
    210             .iter()
    211             .map(|key| value["input"][key].clone())
    212             .collect(),
    213     );
    214     let raw = serde_json::to_vec(&value).unwrap();
    215     assert!(matches!(
    216         CapturedChatCommand::parse(&raw),
    217         Err(CommandError::InvalidInput)
    218     ));
    219     assert!(matches!(
    220         CapturedCommand::parse(&raw),
    221         Err(CommandError::InvalidInput)
    222     ));
    223 }
    224 #[derive(Deserialize)]
    225 struct Vectors {
    226     vectors: Vec<Vector>,
    227 }
    228 #[derive(Deserialize)]
    229 struct Vector {
    230     name: String,
    231     wire: String,
    232     command_digest: String,
    233     approval_intent_digest: String,
    234 }
    235 
    236 #[test]
    237 fn independent_ecmascript_vectors_match_exact_bytes_and_both_hash_domains() {
    238     let vectors: Vectors =
    239         serde_json::from_str(include_str!("fixtures/chat_commands.v1.json")).unwrap();
    240     assert_eq!(vectors.vectors.len(), 3);
    241     for vector in vectors.vectors {
    242         let command = CapturedChatCommand::parse(vector.wire.as_bytes()).unwrap();
    243         assert_eq!(
    244             command.protected_wire(),
    245             vector.wire.as_bytes(),
    246             "{}",
    247             vector.name
    248         );
    249         assert_eq!(
    250             command.digest().to_string(),
    251             vector.command_digest,
    252             "{}",
    253             vector.name
    254         );
    255         assert_eq!(
    256             command.approval_intent_digest().to_string(),
    257             vector.approval_intent_digest,
    258             "{}",
    259             vector.name
    260         );
    261         assert_eq!(
    262             command.context().authority().generation().get(),
    263             9_007_199_254_740_993
    264         );
    265         assert_eq!(command.peer(), bob());
    266         assert_eq!(command.thread_id(), ThreadId::from_bytes([6; 32]));
    267         match command.kind() {
    268             ChatKind::Inquire => assert_eq!(command.parent(), None),
    269             ChatKind::Reply => assert_eq!(command.parent(), Some(MessageId::from_bytes([11; 32]))),
    270         }
    271         if let Some(source) = command.source() {
    272             assert_eq!(source.author(), bob());
    273             assert_eq!(source.d(), "55".repeat(16));
    274             assert_eq!(source.event_id(), SourceId::from_bytes([10; 32]));
    275         }
    276     }
    277 }
    278 
    279 #[test]
    280 fn correlation_is_diagnostic_and_approval_is_bound_only_to_the_final_command() {
    281     let original = inquiry(Some("original"), None, "private");
    282     let other = inquiry(Some("other"), None, "private");
    283     let absent = inquiry(None, None, "private");
    284     assert_ne!(original.protected_wire(), other.protected_wire());
    285     assert_eq!(original.digest(), other.digest());
    286     assert_eq!(original.digest(), absent.digest());
    287     let approval = Approval::new(
    288         original.approval_intent_digest(),
    289         "inbox.inquire",
    290         UnixSeconds::new(190).unwrap(),
    291     )
    292     .unwrap();
    293     let approved = inquiry(Some("other"), Some(approval), "private");
    294     assert_eq!(
    295         original.approval_intent_digest(),
    296         approved.approval_intent_digest()
    297     );
    298     assert_ne!(original.digest(), approved.digest());
    299     assert_eq!(
    300         CapturedChatCommand::parse(approved.protected_wire())
    301             .unwrap()
    302             .digest(),
    303         approved.digest()
    304     );
    305     assert!(!format!("{approved:?}").contains("private"));
    306     assert_eq!(format!("{approved:?}"), "CapturedChatCommand(<redacted>)");
    307 }
    308 
    309 #[test]
    310 fn each_semantic_change_changes_the_command_commitment_without_unicode_normalization() {
    311     let original = inquiry(None, None, "Å");
    312     let decomposed = inquiry(None, None, "A\u{030a}");
    313     assert_ne!(original.digest(), decomposed.digest());
    314     let base: Value = serde_json::from_slice(original.protected_wire()).unwrap();
    315     for (pointer, replacement) in [
    316         ("/context/operation_id", json!("10".repeat(32))),
    317         ("/context/actor/role", json!("seller")),
    318         ("/context/actor/participant", json!(bob().to_hex())),
    319         ("/context/actor/organization", json!(bob().to_hex())),
    320         ("/context/actor/grant_id", json!("11".repeat(32))),
    321         ("/context/workspace_id", json!("12".repeat(32))),
    322         ("/context/authority/executor_id", json!("13".repeat(32))),
    323         ("/context/authority/generation", json!("2")),
    324         ("/context/route_digest", json!("14".repeat(32))),
    325         ("/context/not_after", json!("201")),
    326         ("/input/thread_id", json!("15".repeat(32))),
    327         ("/input/peer", json!(alice().to_hex())),
    328         ("/input/text", json!("different")),
    329     ] {
    330         let mut changed = base.clone();
    331         *changed.pointer_mut(pointer).unwrap() = replacement;
    332         let changed = CapturedChatCommand::parse(&serde_json::to_vec(&changed).unwrap()).unwrap();
    333         assert_ne!(changed.digest(), original.digest(), "{pointer}");
    334     }
    335     let source =
    336         ListingRevisionRef::new(bob(), &"55".repeat(16), SourceId::from_bytes([10; 32])).unwrap();
    337     let sourced = CapturedChatCommand::inquire(
    338         context(None, None),
    339         InquireInput::new(ThreadId::from_bytes([6; 32]), bob(), Some(source), "Å").unwrap(),
    340     )
    341     .unwrap();
    342     assert_ne!(sourced.digest(), original.digest());
    343     let reply = CapturedChatCommand::reply(
    344         context(None, None),
    345         ReplyInput::new(
    346             ThreadId::from_bytes([6; 32]),
    347             bob(),
    348             MessageId::from_bytes([11; 32]),
    349             "reply",
    350         )
    351         .unwrap(),
    352     )
    353     .unwrap();
    354     assert_eq!(
    355         CapturedChatCommand::parse(reply.protected_wire())
    356             .unwrap()
    357             .digest(),
    358         reply.digest()
    359     );
    360 }
    361 
    362 #[test]
    363 fn closed_json_requires_explicit_null_and_rejects_duplicates_aliases_unknowns_and_bad_sources() {
    364     let command = inquiry(None, None, "private");
    365     let wire = std::str::from_utf8(command.protected_wire()).unwrap();
    366     let duplicate = wire.replacen(
    367         "\"type\":\"inbox.inquire\"",
    368         "\"type\":\"inbox.inquire\",\"t\\u0079pe\":\"inbox.inquire\"",
    369         1,
    370     );
    371     assert!(matches!(
    372         CapturedChatCommand::parse(duplicate.as_bytes()),
    373         Err(CommandError::InvalidInput)
    374     ));
    375     let duplicate = wire.replacen(
    376         "\"text\":\"private\"",
    377         "\"text\":\"private\",\"te\\u0078t\":\"other\"",
    378         1,
    379     );
    380     assert!(matches!(
    381         CapturedChatCommand::parse(duplicate.as_bytes()),
    382         Err(CommandError::InvalidInput)
    383     ));
    384     let base: Value = serde_json::from_slice(command.protected_wire()).unwrap();
    385     for pointer in [
    386         "/context/correlation_id",
    387         "/context/approval",
    388         "/context/expected",
    389         "/input/source",
    390     ] {
    391         let mut value = base.clone();
    392         let (parent, key) = pointer.rsplit_once('/').unwrap();
    393         value
    394             .pointer_mut(parent)
    395             .unwrap()
    396             .as_object_mut()
    397             .unwrap()
    398             .remove(key);
    399         assert!(
    400             matches!(
    401                 CapturedChatCommand::parse(&serde_json::to_vec(&value).unwrap()),
    402                 Err(CommandError::InvalidInput)
    403             ),
    404             "{pointer}"
    405         );
    406     }
    407     let mut extra = base.clone();
    408     extra["extra"] = json!(true);
    409     assert!(matches!(
    410         CapturedChatCommand::parse(&serde_json::to_vec(&extra).unwrap()),
    411         Err(CommandError::InvalidInput)
    412     ));
    413     let mut extra = base.clone();
    414     extra["input"]["extra"] = json!(true);
    415     assert!(matches!(
    416         CapturedChatCommand::parse(&serde_json::to_vec(&extra).unwrap()),
    417         Err(CommandError::InvalidInput)
    418     ));
    419     let mut unsupported = base.clone();
    420     unsupported["type"] = json!("orders.accept");
    421     assert!(matches!(
    422         CapturedChatCommand::parse(&serde_json::to_vec(&unsupported).unwrap()),
    423         Err(CommandError::UnsupportedCommand)
    424     ));
    425     unsupported["type"] = json!("x".repeat(81));
    426     assert!(matches!(
    427         CapturedChatCommand::parse(&serde_json::to_vec(&unsupported).unwrap()),
    428         Err(CommandError::LimitExceeded)
    429     ));
    430     for d in ["f".repeat(31), "F".repeat(32), "é".repeat(16)] {
    431         assert!(matches!(
    432             ListingRevisionRef::new(bob(), &d, SourceId::from_bytes([10; 32])),
    433             Err(CommandError::InvalidInput)
    434         ));
    435     }
    436     let mut source = base;
    437     source["input"]["source"] = json!({"coordinate":{"kind":30403,"author":bob().to_hex(),"d":"55".repeat(16)},"event_id":"0a".repeat(32)});
    438     assert!(matches!(
    439         CapturedChatCommand::parse(&serde_json::to_vec(&source).unwrap()),
    440         Err(CommandError::InvalidInput)
    441     ));
    442     assert!(
    443         !format!(
    444             "{} {:?}",
    445             CommandError::InvalidInput,
    446             CommandError::LimitExceeded
    447         )
    448         .contains("private")
    449     );
    450 }
    451 
    452 #[test]
    453 fn byte_and_depth_budgets_are_enforced_before_untrusted_json_materialization() {
    454     let full = "é".repeat(CHAT_MAX_BYTES / 2);
    455     let command = inquiry(None, None, &full);
    456     assert_eq!(
    457         CapturedChatCommand::parse(command.protected_wire())
    458             .unwrap()
    459             .text(),
    460         full
    461     );
    462     assert!(matches!(
    463         InquireInput::new(
    464             ThreadId::from_bytes([6; 32]),
    465             bob(),
    466             None,
    467             &(full.clone() + "é")
    468         ),
    469         Err(CommandError::LimitExceeded)
    470     ));
    471     assert!(matches!(
    472         ReplyInput::new(
    473             ThreadId::from_bytes([6; 32]),
    474             bob(),
    475             MessageId::from_bytes([11; 32]),
    476             &"x".repeat(CHAT_MAX_BYTES + 1)
    477         ),
    478         Err(CommandError::LimitExceeded)
    479     ));
    480     assert_eq!(inquiry(None, None, "").text(), "");
    481     let mut raw = command.protected_wire().to_vec();
    482     raw.resize(COMMAND_MAX_BYTES + 1, b' ');
    483     assert!(matches!(
    484         CapturedChatCommand::parse(&raw),
    485         Err(CommandError::LimitExceeded)
    486     ));
    487     for (depth, expected) in [
    488         (16, CommandError::InvalidInput),
    489         (17, CommandError::LimitExceeded),
    490     ] {
    491         let nested = format!("{}0{}", "[".repeat(depth), "]".repeat(depth));
    492         assert!(
    493             matches!(CapturedChatCommand::parse(nested.as_bytes()), Err(error) if error == expected)
    494         );
    495     }
    496     let bracket_text = "[ { \\\" ] }";
    497     let command = inquiry(None, None, bracket_text);
    498     assert_eq!(
    499         CapturedChatCommand::parse(command.protected_wire())
    500             .unwrap()
    501             .text(),
    502         bracket_text
    503     );
    504     for raw in [b"}".as_slice(), b"{", b"\"unterminated", b"\xff"] {
    505         assert!(matches!(
    506             CapturedChatCommand::parse(raw),
    507             Err(CommandError::InvalidInput)
    508         ));
    509     }
    510     let mut too_long: Value = serde_json::from_slice(command.protected_wire()).unwrap();
    511     too_long["input"]["text"] = json!("x".repeat(CHAT_MAX_BYTES + 1));
    512     assert!(matches!(
    513         CapturedChatCommand::parse(&serde_json::to_vec(&too_long).unwrap()),
    514         Err(CommandError::LimitExceeded)
    515     ));
    516 }