1#![forbid(unsafe_code)]
23
24use crate::dialect::Dialect;
25use crate::message::{CausedBy, Message, WrapperType};
26use crate::protocol::{
27 verify_causal, CausalProtocol, CausalViolation, NodeRef, VerificationResult,
28};
29use crate::role::{parse_wrapper_cast, AgentKey, Cast, Endpoint, R6Violation, RoleAnnotation};
30use crate::sexpr::{Atom, SExpr};
31use crate::store::{ContentHash, MessageStore, ThreadId};
32use alloc::collections::{BTreeMap, BTreeSet};
33use alloc::format;
34use alloc::string::String;
35use alloc::vec::Vec;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40pub enum LocalStep {
41 Send,
43 Recv,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
50#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
51pub struct LocalProtocol {
52 pub steps: BTreeMap<String, LocalStep>,
55 #[cfg_attr(feature = "serde", serde(default))]
67 pub expect_envelopes: BTreeSet<String>,
68 pub protocol: Option<CausalProtocol>,
71}
72
73pub fn project(d: &Dialect, endpoint: &Endpoint, cast: Option<&Cast>) -> LocalProtocol {
86 let mut steps: BTreeMap<String, LocalStep> = BTreeMap::new();
87 for p in &d.performatives {
88 if let Some(ann) = &p.role {
89 if ann.from == endpoint.role {
90 steps.insert(p.name.clone(), LocalStep::Send);
91 } else if ann.to.contains(&endpoint.role) {
92 steps.insert(p.name.clone(), LocalStep::Recv);
93 }
94 }
95 }
96 let mut expect_envelopes: BTreeSet<String> = BTreeSet::new();
100 if let crate::role::CausalLocality::Derive(table) = &d.causal_locality {
101 for (perf, roles) in &table.0 {
103 if roles.contains(&endpoint.role) {
104 expect_envelopes.insert(perf.clone());
105 }
106 }
107 if let (Some(cast), Some(occupant)) = (cast, &endpoint.occupant) {
112 let occ = crate::r6::derive_occupant_envelope_routes(d, cast);
113 for (perf, keys) in &occ.0 {
114 if keys.contains(occupant) {
115 expect_envelopes.insert(perf.clone());
116 }
117 }
118 }
119 }
120 LocalProtocol {
121 steps,
122 expect_envelopes,
123 protocol: d.causal_protocol.clone(),
124 }
125}
126
127fn signer_of(msg: &Message) -> Option<&str> {
134 let mut cur = msg;
135 loop {
136 match cur {
137 Message::Wrapped {
138 wrapper: WrapperType::Signed,
139 params,
140 content,
141 } => {
142 if let Some(SExpr::Atom(Atom::Symbol(s))) = params.first() {
143 return Some(s.as_str());
144 }
145 cur = content;
146 }
147 Message::Wrapped { content, .. } => cur = content,
148 Message::Dialect { inner, .. } => cur = inner,
149 Message::Simple { .. } | Message::Meta { .. } => return None,
151 }
152 }
153}
154
155fn role_violation(reason: String) -> VerificationResult {
156 VerificationResult::Violation(CausalViolation::RoleConformance { reason })
157}
158
159fn expected_recipient_keys<'a>(ann: &RoleAnnotation, cast: &'a Cast) -> BTreeSet<&'a str> {
163 let mut keys: BTreeSet<&str> = BTreeSet::new();
164 for role in &ann.to {
165 if let Some(k) = cast.singleton.get(role) {
166 keys.insert(k.0.as_str());
167 }
168 if let Some(ks) = cast.indexed.get(role) {
169 keys.extend(ks.iter().map(|k| k.0.as_str()));
170 }
171 }
172 keys
173}
174
175pub fn verify_causal_for_role<S: MessageStore>(
180 msg: &Message,
181 endpoint: &Endpoint,
182 d: &Dialect,
183 cast: &Cast,
184 store: &S,
185 thread: &ThreadId,
186 root: &ContentHash,
187) -> VerificationResult {
188 let _ = endpoint; if let (Some(pinned), Some(installed)) = (cast.dialect_pin.as_deref(), d.hash.as_deref()) {
203 if pinned != installed {
204 return role_violation(format!(
205 "{}",
206 R6Violation::DialectPinMismatch {
207 pinned: String::from(pinned),
208 installed: String::from(installed),
209 }
210 ));
211 }
212 }
213
214 if msg.wrapper_type() == Some(WrapperType::WithRoles) {
217 return verify_cast_wrapper(msg, d, cast, store, thread, root);
218 }
219
220 let Some(simple) = msg.innermost_simple() else {
221 return VerificationResult::Valid;
223 };
224 let perf = match simple.performative() {
225 Some(p) => p.name(),
226 None => return VerificationResult::Valid,
227 };
228 let annotation = d.find_performative(perf).and_then(|p| p.role.as_ref());
229
230 let conformance = match annotation {
232 Some(ann) => check_conformance(msg, simple, ann, cast),
233 None => VerificationResult::Valid,
236 };
237 if let VerificationResult::Violation(_) = conformance {
238 return conformance;
239 }
240
241 let caused_by = simple.caused_by().cloned();
244 let rewritten = caused_by
245 .as_ref()
246 .map(|cb| rewrite_root_references(cb, root));
247 let r5 = match &d.causal_protocol {
248 Some(protocol) if crate::repeat::has_repeat(protocol) => crate::repeat::verify(
249 perf,
250 caused_by.as_ref(),
251 store,
252 protocol,
253 thread,
254 Some(root),
255 ),
256 Some(protocol) => verify_causal(perf, rewritten.as_ref(), store, protocol, thread),
257 None => VerificationResult::Valid,
258 };
259
260 let fanin = repeat_occupant_fanin(perf, caused_by.as_ref(), d, cast, store, thread, root);
262
263 conformance.meet(r5).meet(fanin)
264}
265
266fn verify_cast_wrapper<S: MessageStore>(
274 msg: &Message,
275 d: &Dialect,
276 cast: &Cast,
277 store: &S,
278 thread: &ThreadId,
279 root: &ContentHash,
280) -> VerificationResult {
281 let Message::Wrapped {
282 params, content, ..
283 } = msg
284 else {
285 unreachable!("guarded by wrapper_type");
286 };
287 let parsed = match parse_wrapper_cast(params, &d.roles) {
292 Ok(c) => c,
293 Err(v) => return role_violation(format!("{v}")),
294 };
295 if &parsed != cast {
296 return role_violation(String::from(
297 "with-roles wrapper does not match the thread's root cast (REQ-613)",
298 ));
299 }
300 if !matches!(
305 content.as_ref(),
306 Message::Wrapped {
307 wrapper: WrapperType::Signed,
308 ..
309 }
310 ) {
311 return role_violation(String::from(
312 "with-roles payload must be a signed message (CON-601)",
313 ));
314 }
315 if let Some(root_msg) = store.lookup_in_thread(root, thread) {
320 if root_msg != msg {
321 return role_violation(String::from(
322 "a second with-roles wrapper is not the thread root (REQ-613)",
323 ));
324 }
325 }
326 match content.innermost_simple().and_then(|m| m.caused_by()) {
327 Some(CausedBy::Begin) => VerificationResult::Valid,
328 _ => role_violation(String::from(
329 "with-roles wrapper must be the thread's causal root (REQ-613)",
330 )),
331 }
332}
333
334fn check_conformance(
337 outer: &Message,
338 simple: &Message,
339 ann: &RoleAnnotation,
340 cast: &Cast,
341) -> VerificationResult {
342 let Some(sender) = signer_of(outer) else {
346 return role_violation(String::from("role-annotated message carries no sender key"));
347 };
348 if !cast.admits(&ann.from, &AgentKey(String::from(sender))) {
349 return role_violation(format!(
350 "sender '{sender}' is not the cast's occupant of role '{}' (REQ-612)",
351 ann.from
352 ));
353 }
354 let expected = expected_recipient_keys(ann, cast);
356 let actual = simple.recipient_set();
357 if expected != actual {
358 return role_violation(format!(
359 "recipients {actual:?} do not match the cast keys {expected:?} for :to roles {:?} (REQ-615)",
360 ann.to
361 ));
362 }
363 VerificationResult::Valid
364}
365
366fn rewrite_root_references(cb: &CausedBy, root: &ContentHash) -> CausedBy {
375 match cb {
376 CausedBy::Single(h) if h == &root.0 => CausedBy::Begin,
377 other => other.clone(),
378 }
379}
380
381fn repeat_occupant_fanin<S: MessageStore>(
383 perf: &str,
384 caused_by: Option<&CausedBy>,
385 d: &Dialect,
386 cast: &Cast,
387 store: &S,
388 thread: &ThreadId,
389 root: &ContentHash,
390) -> VerificationResult {
391 let Some(cp) = d
392 .causal_protocol
393 .as_ref()
394 .filter(|p| crate::repeat::has_repeat(p))
395 else {
396 return occupant_fanin(perf, caused_by, d, cast, store, thread, None);
397 };
398 let hashes = match caused_by {
399 Some(CausedBy::Single(h)) => alloc::vec![h.clone()],
400 Some(CausedBy::Multiple(hs)) => hs.clone(),
401 _ => Vec::new(),
402 };
403 let resolution = crate::repeat::Resolution::new(store, cp, thread, Some(root), hashes);
404 let mut result = None;
405 for (name, step) in &cp.steps {
406 if crate::protocol::repeat_base_name(name) != perf
407 || !matches!(resolution.step(step, caused_by), VerificationResult::Valid)
408 {
409 continue;
410 }
411 let value = occupant_fanin(name, caused_by, d, cast, store, thread, Some(&resolution));
412 match value {
413 VerificationResult::Valid => return value,
414 VerificationResult::Unknown => result = Some(value),
415 _ if !matches!(result, Some(VerificationResult::Unknown)) => result = Some(value),
416 _ => {}
417 }
418 }
419 result.unwrap_or(VerificationResult::Valid)
421}
422
423fn occupant_fanin<S: MessageStore>(
430 perf: &str,
431 caused_by: Option<&CausedBy>,
432 d: &Dialect,
433 cast: &Cast,
434 store: &S,
435 thread: &ThreadId,
436 resolution: Option<&crate::repeat::Resolution<'_, S>>,
437) -> VerificationResult {
438 let Some(cp) = &d.causal_protocol else {
439 return VerificationResult::Valid;
440 };
441 let Some(step) = cp.steps.get(perf) else {
442 return VerificationResult::Valid;
443 };
444
445 let mut counted: Vec<(&str, &BTreeSet<AgentKey>)> = Vec::new();
447 for nr in &step.predecessors {
448 let NodeRef::All(preds) = nr else { continue };
449 for pred in preds {
450 let Some(p_ann) = d
451 .find_performative(crate::protocol::repeat_base_name(pred))
452 .and_then(|p| p.role.as_ref())
453 else {
454 continue;
455 };
456 if let Some(occupants) = cast.indexed.get(&p_ann.from) {
460 counted.push((pred.as_str(), occupants));
461 }
462 }
463 }
464 if counted.is_empty() {
465 return VerificationResult::Valid;
466 }
467
468 let CausedBy::Multiple(hs) = (match caused_by {
474 Some(cb) => cb,
475 None => return VerificationResult::Valid,
476 }) else {
477 return VerificationResult::Valid;
478 };
479 let hashes: Vec<&str> = hs.iter().map(String::as_str).collect();
480 let mut resolved: Vec<(&str, &Message)> = Vec::new();
481 for h in &hashes {
482 match store.lookup_in_thread(&ContentHash(String::from(*h)), thread) {
483 Some(m) => resolved.push((h, m)),
484 None => return VerificationResult::Unknown,
494 }
495 }
496
497 for (pred_type, occupants) in counted {
498 let mut senders: BTreeSet<&str> = BTreeSet::new();
499 for (hash, m) in &resolved {
500 let Some(simple) = m.innermost_simple() else {
501 continue;
502 };
503 if match resolution {
504 Some(r) => !matches!(r.at(hash, pred_type), VerificationResult::Valid),
505 None => simple.performative().map(|p| p.name()) != Some(pred_type),
506 } {
507 continue;
508 }
509 if let Some(k) = signer_of(m) {
510 if occupants.contains(&AgentKey(String::from(k))) {
512 senders.insert(k);
513 }
514 }
515 }
516 let missing: Vec<&str> = occupants
517 .iter()
518 .map(|k| k.0.as_str())
519 .filter(|k| !senders.contains(*k))
520 .collect();
521 if !missing.is_empty() {
522 return role_violation(format!(
523 "fan-in over '{pred_type}' lacks instances from sealed occupant(s) {missing:?} (REQ-618)"
524 ));
525 }
526 }
527 VerificationResult::Valid
528}
529
530#[cfg(test)]
531mod tests {
532 use super::*;
533 use crate::dialect::{Dialect, PerformativeDef, ResourceBounds};
534 use crate::protocol::StepDecl;
535 use crate::role::{parse_cast, parse_roles};
536 use crate::store::ThreadedMessageStore;
537 use alloc::string::ToString;
538 use alloc::vec;
539
540 fn perf(name: &str, from: &str, to: &[&str]) -> PerformativeDef {
541 PerformativeDef {
542 name: name.to_string(),
543 params: Vec::new(),
544 template: SExpr::Atom(Atom::Symbol("t".to_string())),
545 role: Some(RoleAnnotation {
546 from: from.to_string(),
547 to: to.iter().map(|s| s.to_string()).collect(),
548 }),
549 }
550 }
551
552 fn single(name: &str) -> NodeRef {
553 NodeRef::Single(name.to_string())
554 }
555
556 fn any(names: &[&str]) -> NodeRef {
557 NodeRef::Any(names.iter().map(|s| s.to_string()).collect())
558 }
559
560 fn all_of(names: &[&str]) -> NodeRef {
561 NodeRef::All(names.iter().map(|s| s.to_string()).collect())
562 }
563
564 fn step(name: &str, preds: Vec<NodeRef>, succs: Vec<NodeRef>) -> (String, StepDecl) {
565 (
566 name.to_string(),
567 StepDecl {
568 performative: name.to_string(),
569 predecessors: preds,
570 successors: succs,
571 },
572 )
573 }
574
575 fn dialect(
576 roles_src: &str,
577 perfs: Vec<PerformativeDef>,
578 steps: Vec<(String, StepDecl)>,
579 ) -> Dialect {
580 Dialect {
581 types: Default::default(),
582 roles: parse_roles(&roles_src.parse::<SExpr>().unwrap()).unwrap(),
583 state: None,
584 state_bounds: None,
585 causal_locality: Default::default(),
586 name: "test".to_string(),
587 extends: Vec::new(),
588 author: None,
589 performatives: perfs,
590 resources: ResourceBounds {
591 max_depth: 8,
592 max_expansion_size: 512,
593 },
594 examples: Vec::new(),
595 signature: None,
596 hash: None,
597 protocol: None,
598 causal_protocol: Some(CausalProtocol {
599 steps: steps.into_iter().collect(),
600 }),
601 shapes: Vec::new(),
602 }
603 }
604
605 fn oauth() -> Dialect {
607 dialect(
608 "(server client authoriser)",
609 vec![
610 perf("login", "server", &["client", "authoriser"]),
611 perf("abort", "server", &["client", "authoriser"]),
612 perf("passwd", "client", &["authoriser", "server"]),
613 perf("auth", "authoriser", &["server"]),
614 perf("quit", "client", &["authoriser"]),
615 ],
616 vec![
617 step("begin", vec![], vec![any(&["login", "abort"])]),
618 step("login", vec![single("begin")], vec![single("passwd")]),
619 step("abort", vec![single("begin")], vec![single("quit")]),
620 step("passwd", vec![single("login")], vec![single("auth")]),
621 step("auth", vec![single("passwd")], vec![]),
622 step("quit", vec![single("abort")], vec![]),
623 ],
624 )
625 }
626
627 fn oauth_cast(d: &Dialect) -> Cast {
628 parse_cast(
629 &"((server @srv) (client @cli) (authoriser @as))"
630 .parse::<SExpr>()
631 .unwrap(),
632 &d.roles,
633 )
634 .unwrap()
635 }
636
637 fn ep(role: &str) -> Endpoint {
638 Endpoint {
639 role: role.to_string(),
640 occupant: None,
641 }
642 }
643
644 fn msg(src: &str) -> Message {
645 Message::try_from(&src.parse::<SExpr>().unwrap()).unwrap()
646 }
647
648 fn tid() -> ThreadId {
649 ThreadId("conv".to_string())
650 }
651
652 fn put(store: &mut ThreadedMessageStore, h: &str, m: &Message) {
653 store.append(ContentHash(h.to_string()), tid(), m.clone());
654 }
655
656 fn oauth_h0() -> Message {
657 msg("(with-roles ((server @srv) (client @cli) (authoriser @as)) (signed @srv \"sig\" (hello :thread \"conv\" :caused-by begin)))")
658 }
659
660 #[test]
663 fn only_exact_single_root_reference_is_typed_as_begin() {
664 let root = ContentHash("root".into());
665 assert_eq!(
666 rewrite_root_references(&CausedBy::Single("root".into()), &root),
667 CausedBy::Begin
668 );
669 for reference in [
670 CausedBy::Begin,
671 CausedBy::Single("other".into()),
672 CausedBy::Multiple(vec!["root".into(), "other".into()]),
673 ] {
674 assert_eq!(rewrite_root_references(&reference, &root), reference);
675 }
676 }
677
678 #[test]
679 fn oauth_projections_match_the_paper() {
680 let d = oauth();
681 let server = project(&d, &ep("server"), None);
682 assert_eq!(server.steps.get("login"), Some(&LocalStep::Send));
683 assert_eq!(server.steps.get("abort"), Some(&LocalStep::Send));
684 assert_eq!(server.steps.get("passwd"), Some(&LocalStep::Recv));
685 assert_eq!(server.steps.get("auth"), Some(&LocalStep::Recv));
686 assert_eq!(server.steps.get("quit"), None, "bystander erased");
687
688 let client = project(&d, &ep("client"), None);
689 assert_eq!(client.steps.get("passwd"), Some(&LocalStep::Send));
690 assert_eq!(client.steps.get("quit"), Some(&LocalStep::Send));
691 assert_eq!(client.steps.get("login"), Some(&LocalStep::Recv));
692 assert_eq!(client.steps.get("auth"), None, "bystander erased");
693
694 let authoriser = project(&d, &ep("authoriser"), None);
695 assert_eq!(authoriser.steps.get("auth"), Some(&LocalStep::Send));
696 assert_eq!(authoriser.steps.get("passwd"), Some(&LocalStep::Recv));
697 assert_eq!(authoriser.steps.get("quit"), Some(&LocalStep::Recv));
698 }
699
700 #[test]
701 fn projection_keeps_raw_predecessor_clauses() {
702 let d = oauth();
703 for role in ["server", "client", "authoriser"] {
704 let local = project(&d, &ep(role), None);
705 assert_eq!(local.protocol, d.causal_protocol, "raw edges (REQ-610)");
706 }
707 }
708
709 #[test]
710 fn projection_is_deterministic() {
711 let d = oauth();
712 assert_eq!(
713 project(&d, &ep("client"), None),
714 project(&d, &ep("client"), None)
715 );
716 }
717
718 fn derived_oauth() -> Dialect {
724 let mut d = dialect(
725 "(server client authoriser)",
726 vec![
727 perf("login", "server", &["client"]),
728 perf("abort", "server", &["client"]),
729 perf("passwd", "client", &["authoriser"]),
730 perf("auth", "authoriser", &["server"]),
731 perf("quit", "client", &["authoriser"]),
732 ],
733 vec![
734 step("begin", vec![], vec![any(&["login", "abort"])]),
735 step("login", vec![single("begin")], vec![single("passwd")]),
736 step("abort", vec![single("begin")], vec![single("quit")]),
737 step("passwd", vec![single("login")], vec![single("auth")]),
738 step("auth", vec![single("passwd")], vec![]),
739 step("quit", vec![single("abort")], vec![]),
740 ],
741 );
742 d.causal_locality =
743 crate::role::CausalLocality::Derive(crate::r6::derive_envelope_routes(&d));
744 d
745 }
746
747 #[test]
748 fn reject_mode_projection_has_no_envelope_steps() {
749 let d = oauth();
752 for role in ["server", "client", "authoriser"] {
753 assert!(project(&d, &ep(role), None).expect_envelopes.is_empty());
754 }
755 }
756
757 #[test]
758 fn derived_projection_emits_expect_envelope_per_route() {
759 let d = derived_oauth();
760 let authoriser = project(&d, &ep("authoriser"), None);
762 let expected: BTreeSet<String> = ["login", "abort"].iter().map(|s| s.to_string()).collect();
763 assert_eq!(authoriser.expect_envelopes, expected);
764 let server = project(&d, &ep("server"), None);
765 let expected: BTreeSet<String> = ["passwd"].iter().map(|s| s.to_string()).collect();
766 assert_eq!(server.expect_envelopes, expected);
767 assert!(project(&d, &ep("client"), None).expect_envelopes.is_empty());
769 }
770
771 #[test]
772 fn expect_envelope_leaves_send_recv_steps_untouched() {
773 let d = derived_oauth();
776 let mut v1 = d.clone();
777 v1.causal_locality = crate::role::CausalLocality::Reject;
778 for role in ["server", "client", "authoriser"] {
779 assert_eq!(
780 project(&d, &ep(role), None).steps,
781 project(&v1, &ep(role), None).steps,
782 );
783 }
784 }
785
786 #[test]
787 fn per_occupant_expect_envelope_steps_come_from_the_sealed_cast() {
788 let mut d = dialect(
794 "(auctioneer (* bidder))",
795 vec![
796 perf("commit", "bidder", &["auctioneer"]),
797 perf("reveal", "bidder", &["auctioneer"]),
798 perf("declare-winner", "auctioneer", &["bidder"]),
799 ],
800 vec![
801 step("begin", vec![], vec![single("commit")]),
802 step("commit", vec![single("begin")], vec![single("reveal")]),
803 step("reveal", vec![single("commit")], vec![]),
804 step("declare-winner", vec![all_of(&["reveal"])], vec![]),
805 ],
806 );
807 d.causal_locality =
808 crate::role::CausalLocality::Derive(crate::r6::derive_envelope_routes(&d));
809 let cast = auction_cast(&d);
810
811 let b1 = Endpoint {
814 role: "bidder".to_string(),
815 occupant: Some(AgentKey("@b1".to_string())),
816 };
817 let local = project(&d, &b1, Some(&cast));
818 let expected: BTreeSet<String> =
819 ["commit", "reveal"].iter().map(|s| s.to_string()).collect();
820 assert_eq!(local.expect_envelopes, expected);
821 assert_eq!(local.steps.get("commit"), Some(&LocalStep::Send));
822 assert_eq!(local.steps.get("reveal"), Some(&LocalStep::Send));
823
824 assert!(project(&d, &b1, None).expect_envelopes.is_empty());
827 let auc = project(&d, &ep("auctioneer"), Some(&cast));
828 assert!(auc.expect_envelopes.is_empty());
829 }
830
831 #[test]
834 fn first_step_naming_root_hash_verifies() {
835 let d = oauth();
836 let cast = oauth_cast(&d);
837 let mut store = ThreadedMessageStore::new();
838 put(&mut store, "h0", &oauth_h0());
839 let h1 = msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
840 assert_eq!(
841 verify_causal_for_role(
842 &h1,
843 &ep("client"),
844 &d,
845 &cast,
846 &store,
847 &tid(),
848 &ContentHash("h0".to_string())
849 ),
850 VerificationResult::Valid
851 );
852 }
853
854 #[test]
857 fn non_nominee_cannot_squat_a_role() {
858 let d = oauth();
859 let cast = oauth_cast(&d);
860 let mut store = ThreadedMessageStore::new();
861 put(&mut store, "h0", &oauth_h0());
862 let evil = msg("(signed @evil \"sig\" (lang test (login (@as @cli) \"n\" :caused-by h0)))");
863 assert!(matches!(
864 verify_causal_for_role(
865 &evil,
866 &ep("client"),
867 &d,
868 &cast,
869 &store,
870 &tid(),
871 &ContentHash("h0".to_string())
872 ),
873 VerificationResult::Violation(CausalViolation::RoleConformance { .. })
874 ));
875 }
876
877 #[test]
878 fn narrowed_recipients_violate_conformance() {
879 let d = oauth();
880 let cast = oauth_cast(&d);
881 let mut store = ThreadedMessageStore::new();
882 put(&mut store, "h0", &oauth_h0());
883 let narrow = msg("(signed @srv \"sig\" (lang test (login @cli \"n\" :caused-by h0)))");
885 assert!(matches!(
886 verify_causal_for_role(
887 &narrow,
888 &ep("client"),
889 &d,
890 &cast,
891 &store,
892 &tid(),
893 &ContentHash("h0".to_string())
894 ),
895 VerificationResult::Violation(CausalViolation::RoleConformance { .. })
896 ));
897 }
898
899 #[test]
902 fn out_of_order_is_unknown_then_valid() {
903 let d = oauth();
904 let cast = oauth_cast(&d);
905 let mut store = ThreadedMessageStore::new();
906 put(&mut store, "h0", &oauth_h0());
907 let h1 = msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
908 let h2 =
909 msg("(signed @cli \"sig\" (lang test (passwd (@as @srv) \"cred\" :caused-by h1)))");
910 assert_eq!(
913 verify_causal_for_role(
914 &h2,
915 &ep("authoriser"),
916 &d,
917 &cast,
918 &store,
919 &tid(),
920 &ContentHash("h0".to_string())
921 ),
922 VerificationResult::Unknown
923 );
924 put(&mut store, "h1", &h1);
925 assert_eq!(
926 verify_causal_for_role(
927 &h2,
928 &ep("authoriser"),
929 &d,
930 &cast,
931 &store,
932 &tid(),
933 &ContentHash("h0".to_string())
934 ),
935 VerificationResult::Valid
936 );
937 }
938
939 #[test]
940 fn vacant_role_dependency_stays_unknown() {
941 let d = oauth();
942 let cast = oauth_cast(&d);
943 let store = ThreadedMessageStore::new();
944 let auth = msg("(signed @as \"sig\" (lang test (auth @srv \"tok\" :caused-by h-never)))");
945 assert_eq!(
946 verify_causal_for_role(
947 &auth,
948 &ep("server"),
949 &d,
950 &cast,
951 &store,
952 &tid(),
953 &ContentHash("h0".to_string())
954 ),
955 VerificationResult::Unknown
956 );
957 }
958
959 #[test]
962 fn foreign_cast_wrapper_is_a_violation() {
963 let d = oauth();
964 let cast = oauth_cast(&d);
965 let store = ThreadedMessageStore::new();
966 let second = msg("(with-roles ((server @evil) (client @cli) (authoriser @as)) (signed @evil \"sig\" (hello :caused-by begin)))");
967 assert!(matches!(
968 verify_causal_for_role(
969 &second,
970 &ep("client"),
971 &d,
972 &cast,
973 &store,
974 &tid(),
975 &ContentHash("h0".to_string())
976 ),
977 VerificationResult::Violation(CausalViolation::RoleConformance { .. })
978 ));
979 }
980
981 #[test]
982 fn non_root_wrapper_is_a_violation() {
983 let d = oauth();
984 let cast = oauth_cast(&d);
985 let store = ThreadedMessageStore::new();
986 let late = msg("(with-roles ((server @srv) (client @cli) (authoriser @as)) (signed @srv \"sig\" (hello :caused-by h0)))");
987 assert!(matches!(
988 verify_causal_for_role(
989 &late,
990 &ep("client"),
991 &d,
992 &cast,
993 &store,
994 &tid(),
995 &ContentHash("h0".to_string())
996 ),
997 VerificationResult::Violation(CausalViolation::RoleConformance { .. })
998 ));
999 }
1000
1001 #[test]
1004 fn unsigned_sender_field_cannot_occupy_a_role() {
1005 let d = oauth();
1008 let cast = oauth_cast(&d);
1009 let mut store = ThreadedMessageStore::new();
1010 put(&mut store, "h0", &oauth_h0());
1011 let forged = msg("(lang test (login (@as @cli) \"n\" :sender @srv :caused-by h0))");
1012 assert!(matches!(
1013 verify_causal_for_role(
1014 &forged,
1015 &ep("client"),
1016 &d,
1017 &cast,
1018 &store,
1019 &tid(),
1020 &ContentHash("h0".to_string())
1021 ),
1022 VerificationResult::Violation(CausalViolation::RoleConformance { .. })
1023 ));
1024 }
1025
1026 #[test]
1027 fn forged_second_root_wrapper_is_rejected() {
1028 let d = oauth();
1031 let cast = oauth_cast(&d);
1032 let mut store = ThreadedMessageStore::new();
1033 put(&mut store, "h0", &oauth_h0());
1034 let second = msg("(with-roles ((server @srv) (client @cli) (authoriser @as)) (signed @cli \"sig\" (hello :caused-by begin)))");
1035 put(&mut store, "h9", &second);
1036 assert!(matches!(
1038 verify_causal_for_role(
1039 &second,
1040 &ep("client"),
1041 &d,
1042 &cast,
1043 &store,
1044 &tid(),
1045 &ContentHash("h0".to_string())
1046 ),
1047 VerificationResult::Violation(CausalViolation::RoleConformance { .. })
1048 ));
1049 let reparented =
1053 msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n\" :caused-by h9)))");
1054 assert!(matches!(
1055 verify_causal_for_role(
1056 &reparented,
1057 &ep("client"),
1058 &d,
1059 &cast,
1060 &store,
1061 &tid(),
1062 &ContentHash("h0".to_string())
1063 ),
1064 VerificationResult::Violation(_)
1065 ));
1066 }
1067
1068 #[test]
1069 fn receive_only_role_needs_no_signature_to_be_addressed() {
1070 let d = oauth();
1074 let cast = oauth_cast(&d);
1075 let mut store = ThreadedMessageStore::new();
1076 put(&mut store, "h0", &oauth_h0());
1077 let login =
1078 msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
1079 assert_eq!(
1081 verify_causal_for_role(
1082 &login,
1083 &ep("client"),
1084 &d,
1085 &cast,
1086 &store,
1087 &tid(),
1088 &ContentHash("h0".to_string())
1089 ),
1090 VerificationResult::Valid
1091 );
1092 }
1093
1094 #[test]
1095 fn matching_root_wrapper_is_valid() {
1096 let d = oauth();
1097 let cast = oauth_cast(&d);
1098 let store = ThreadedMessageStore::new();
1099 assert_eq!(
1100 verify_causal_for_role(
1101 &oauth_h0(),
1102 &ep("client"),
1103 &d,
1104 &cast,
1105 &store,
1106 &tid(),
1107 &ContentHash("h0".to_string())
1108 ),
1109 VerificationResult::Valid
1110 );
1111 }
1112
1113 #[test]
1114 fn unsigned_root_payload_is_rejected() {
1115 let d = oauth();
1119 let cast = oauth_cast(&d);
1120 let store = ThreadedMessageStore::new();
1121 let unsigned = msg("(with-roles ((server @srv) (client @cli) (authoriser @as)) (hello :thread \"conv\" :caused-by begin))");
1122 assert!(matches!(
1123 verify_causal_for_role(
1124 &unsigned,
1125 &ep("client"),
1126 &d,
1127 &cast,
1128 &store,
1129 &tid(),
1130 &ContentHash("h0".to_string())
1131 ),
1132 VerificationResult::Violation(CausalViolation::RoleConformance { .. })
1133 ));
1134 }
1135
1136 #[test]
1137 fn root_wrapper_with_extra_params_is_rejected() {
1138 let d = oauth();
1140 let cast = oauth_cast(&d);
1141 let store = ThreadedMessageStore::new();
1142 let extra = msg("(with-roles ((server @srv) (client @cli) (authoriser @as)) junk (signed @srv \"sig\" (hello :caused-by begin)))");
1143 assert!(matches!(
1144 verify_causal_for_role(
1145 &extra,
1146 &ep("client"),
1147 &d,
1148 &cast,
1149 &store,
1150 &tid(),
1151 &ContentHash("h0".to_string())
1152 ),
1153 VerificationResult::Violation(CausalViolation::RoleConformance { .. })
1154 ));
1155 }
1156
1157 fn hashed_oauth() -> Dialect {
1162 let mut d = oauth();
1163 d.hash = Some(crate::canonical::dialect_hash(&d));
1164 d
1165 }
1166
1167 fn pinned_h0(pin: &str) -> Message {
1168 msg(&format!(
1169 "(with-roles ((server @srv) (client @cli) (authoriser @as)) :dialect {pin} (signed @srv \"sig\" (hello :thread \"conv\" :caused-by begin)))"
1170 ))
1171 }
1172
1173 fn pinned_cast(d: &Dialect, root: &Message) -> Cast {
1175 let Message::Wrapped { params, .. } = root else {
1176 panic!("root fixture is a wrapper");
1177 };
1178 parse_wrapper_cast(params, &d.roles).unwrap()
1179 }
1180
1181 #[test]
1182 fn pinned_root_matching_installed_hash_verifies() {
1183 let d = hashed_oauth();
1184 let pin = d.hash.clone().unwrap();
1185 let root = pinned_h0(&pin);
1186 let cast = pinned_cast(&d, &root);
1187 let mut store = ThreadedMessageStore::new();
1188 put(&mut store, "h0", &root);
1189 assert_eq!(
1191 verify_causal_for_role(
1192 &root,
1193 &ep("client"),
1194 &d,
1195 &cast,
1196 &store,
1197 &tid(),
1198 &ContentHash("h0".to_string())
1199 ),
1200 VerificationResult::Valid
1201 );
1202 let h1 = msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
1204 assert_eq!(
1205 verify_causal_for_role(
1206 &h1,
1207 &ep("client"),
1208 &d,
1209 &cast,
1210 &store,
1211 &tid(),
1212 &ContentHash("h0".to_string())
1213 ),
1214 VerificationResult::Valid
1215 );
1216 }
1217
1218 #[test]
1219 fn pin_mismatch_is_a_typed_violation_for_every_thread_message() {
1220 let d = hashed_oauth();
1224 let stale = format!("f1220{}", "0".repeat(64));
1225 let root = pinned_h0(&stale);
1226 let cast = pinned_cast(&d, &root);
1227 let mut store = ThreadedMessageStore::new();
1228 put(&mut store, "h0", &root);
1229 let h1 = msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
1230 for m in [&root, &h1] {
1231 match verify_causal_for_role(
1232 m,
1233 &ep("client"),
1234 &d,
1235 &cast,
1236 &store,
1237 &tid(),
1238 &ContentHash("h0".to_string()),
1239 ) {
1240 VerificationResult::Violation(CausalViolation::RoleConformance { reason }) => {
1241 assert!(
1242 reason.contains("REQ-628"),
1243 "expected the typed pin violation, got: {reason}"
1244 );
1245 }
1246 other => panic!("expected the REQ-628 violation, got {other:?}"),
1247 }
1248 }
1249 }
1250
1251 #[test]
1252 fn unpinned_root_still_verifies_during_transition() {
1253 let d = hashed_oauth();
1257 let cast = oauth_cast(&d);
1258 let mut store = ThreadedMessageStore::new();
1259 put(&mut store, "h0", &oauth_h0());
1260 assert_eq!(
1261 verify_causal_for_role(
1262 &oauth_h0(),
1263 &ep("client"),
1264 &d,
1265 &cast,
1266 &store,
1267 &tid(),
1268 &ContentHash("h0".to_string())
1269 ),
1270 VerificationResult::Valid
1271 );
1272 let h1 = msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
1273 assert_eq!(
1274 verify_causal_for_role(
1275 &h1,
1276 &ep("client"),
1277 &d,
1278 &cast,
1279 &store,
1280 &tid(),
1281 &ContentHash("h0".to_string())
1282 ),
1283 VerificationResult::Valid
1284 );
1285 }
1286
1287 #[test]
1288 fn malformed_pin_on_root_is_rejected() {
1289 let d = hashed_oauth();
1292 let cast = oauth_cast(&d);
1293 let store = ThreadedMessageStore::new();
1294 for bad in [
1295 "(with-roles ((server @srv) (client @cli) (authoriser @as)) :dialect f1220abc (signed @srv \"sig\" (hello :caused-by begin)))",
1296 "(with-roles ((server @srv) (client @cli) (authoriser @as)) :dialect md5:0000 (signed @srv \"sig\" (hello :caused-by begin)))",
1297 ] {
1298 assert!(matches!(
1299 verify_causal_for_role(
1300 &msg(bad),
1301 &ep("client"),
1302 &d,
1303 &cast,
1304 &store,
1305 &tid(),
1306 &ContentHash("h0".to_string())
1307 ),
1308 VerificationResult::Violation(CausalViolation::RoleConformance { .. })
1309 ));
1310 }
1311 }
1312
1313 fn auction() -> Dialect {
1316 dialect(
1317 "(auctioneer (* bidder))",
1318 vec![
1319 perf("commit", "bidder", &["auctioneer"]),
1320 perf("reveal", "bidder", &["auctioneer"]),
1321 perf("declare-winner", "auctioneer", &[]),
1322 ],
1323 vec![
1324 step("begin", vec![], vec![single("commit")]),
1325 step("commit", vec![single("begin")], vec![single("reveal")]),
1326 step("reveal", vec![single("commit")], vec![]),
1327 step("declare-winner", vec![all_of(&["reveal"])], vec![]),
1328 ],
1329 )
1330 }
1331
1332 fn auction_cast(d: &Dialect) -> Cast {
1333 parse_cast(
1334 &"((auctioneer @auc) (bidder @b1 @b2 @b3))"
1335 .parse::<SExpr>()
1336 .unwrap(),
1337 &d.roles,
1338 )
1339 .unwrap()
1340 }
1341
1342 fn auction_store() -> ThreadedMessageStore {
1343 let mut store = ThreadedMessageStore::new();
1344 put(&mut store, "h0", &msg("(with-roles ((auctioneer @auc) (bidder @b1 @b2 @b3)) (signed @auc \"sig\" (hello :thread \"conv\" :caused-by begin)))"));
1345 for (i, b) in ["@b1", "@b2", "@b3"].iter().enumerate() {
1346 let hc = alloc::format!("h{}", i + 1);
1347 let hr = alloc::format!("h{}", i + 4);
1348 put(
1349 &mut store,
1350 &hc,
1351 &msg(&alloc::format!(
1352 "(signed {b} \"sig\" (lang test (commit @auc \"c\" :caused-by h0)))"
1353 )),
1354 );
1355 put(
1356 &mut store,
1357 &hr,
1358 &msg(&alloc::format!(
1359 "(signed {b} \"sig\" (lang test (reveal @auc 42 :caused-by {hc})))"
1360 )),
1361 );
1362 }
1363 store
1364 }
1365
1366 #[test]
1367 fn fanin_unknown_until_all_reveals_then_valid() {
1368 let d = auction();
1369 let cast = auction_cast(&d);
1370 let mut store = ThreadedMessageStore::new();
1371 put(&mut store, "h0", &msg("(with-roles ((auctioneer @auc) (bidder @b1 @b2 @b3)) (signed @auc \"sig\" (hello :caused-by begin)))"));
1372 put(
1373 &mut store,
1374 "h1",
1375 &msg("(signed @b1 \"sig\" (lang test (commit @auc \"c\" :caused-by h0)))"),
1376 );
1377 put(
1378 &mut store,
1379 "h2",
1380 &msg("(signed @b2 \"sig\" (lang test (commit @auc \"c\" :caused-by h0)))"),
1381 );
1382 put(
1383 &mut store,
1384 "h4",
1385 &msg("(signed @b1 \"sig\" (lang test (reveal @auc 42 :caused-by h1)))"),
1386 );
1387 put(
1388 &mut store,
1389 "h5",
1390 &msg("(signed @b2 \"sig\" (lang test (reveal @auc 17 :caused-by h2)))"),
1391 );
1392 let h7 =
1393 msg("(signed @auc \"sig\" (lang test (declare-winner \"b3\" :caused-by (h4 h5 h6))))");
1394 assert_eq!(
1396 verify_causal_for_role(
1397 &h7,
1398 &ep("auctioneer"),
1399 &d,
1400 &cast,
1401 &store,
1402 &tid(),
1403 &ContentHash("h0".to_string())
1404 ),
1405 VerificationResult::Unknown
1406 );
1407 put(
1408 &mut store,
1409 "h3",
1410 &msg("(signed @b3 \"sig\" (lang test (commit @auc \"c\" :caused-by h0)))"),
1411 );
1412 put(
1413 &mut store,
1414 "h6",
1415 &msg("(signed @b3 \"sig\" (lang test (reveal @auc 55 :caused-by h3)))"),
1416 );
1417 assert_eq!(
1418 verify_causal_for_role(
1419 &h7,
1420 &ep("auctioneer"),
1421 &d,
1422 &cast,
1423 &store,
1424 &tid(),
1425 &ContentHash("h0".to_string())
1426 ),
1427 VerificationResult::Valid
1428 );
1429 }
1430
1431 #[test]
1432 fn resolved_fanin_missing_an_occupant_is_a_violation() {
1433 let d = auction();
1436 let cast = auction_cast(&d);
1437 let store = auction_store();
1438 let h7 =
1439 msg("(signed @auc \"sig\" (lang test (declare-winner \"b1\" :caused-by (h4 h5))))");
1440 assert!(matches!(
1441 verify_causal_for_role(
1442 &h7,
1443 &ep("auctioneer"),
1444 &d,
1445 &cast,
1446 &store,
1447 &tid(),
1448 &ContentHash("h0".to_string())
1449 ),
1450 VerificationResult::Violation(CausalViolation::RoleConformance { .. })
1451 ));
1452 }
1453
1454 #[test]
1455 fn non_member_instance_does_not_count_toward_coverage() {
1456 let d = auction();
1457 let cast = auction_cast(&d);
1458 let mut store = auction_store();
1459 put(
1461 &mut store,
1462 "hx",
1463 &msg("(signed @b4 \"sig\" (lang test (reveal @auc 99 :caused-by h3)))"),
1464 );
1465 let h7 =
1466 msg("(signed @auc \"sig\" (lang test (declare-winner \"b1\" :caused-by (h4 h5 hx))))");
1467 assert!(matches!(
1468 verify_causal_for_role(
1469 &h7,
1470 &ep("auctioneer"),
1471 &d,
1472 &cast,
1473 &store,
1474 &tid(),
1475 &ContentHash("h0".to_string())
1476 ),
1477 VerificationResult::Violation(CausalViolation::RoleConformance { .. })
1478 ));
1479 }
1480
1481 #[test]
1482 fn full_auction_trace_verifies_end_to_end() {
1483 let d = auction();
1484 let cast = auction_cast(&d);
1485 let store = auction_store();
1486 for (h, role) in [
1487 ("h1", "bidder"),
1488 ("h2", "bidder"),
1489 ("h3", "bidder"),
1490 ("h4", "bidder"),
1491 ("h5", "bidder"),
1492 ("h6", "bidder"),
1493 ] {
1494 let m = store
1495 .lookup_in_thread(&ContentHash(h.to_string()), &tid())
1496 .unwrap()
1497 .clone();
1498 assert_eq!(
1499 verify_causal_for_role(
1500 &m,
1501 &ep(role),
1502 &d,
1503 &cast,
1504 &store,
1505 &tid(),
1506 &ContentHash("h0".to_string())
1507 ),
1508 VerificationResult::Valid,
1509 "{h} should be Valid"
1510 );
1511 }
1512 let h7 =
1513 msg("(signed @auc \"sig\" (lang test (declare-winner \"b3\" :caused-by (h4 h5 h6))))");
1514 assert_eq!(
1515 verify_causal_for_role(
1516 &h7,
1517 &ep("auctioneer"),
1518 &d,
1519 &cast,
1520 &store,
1521 &tid(),
1522 &ContentHash("h0".to_string())
1523 ),
1524 VerificationResult::Valid
1525 );
1526 }
1527
1528 use crate::attest::{sign_attestation_v2, AttestationHeader};
1531 use crate::envelope::RedactedEnvelope;
1532 use crate::keyid::KeyId;
1533 use crate::r4::Signer;
1534
1535 struct TestSigner {
1538 secret: &'static str,
1539 }
1540
1541 impl Signer for TestSigner {
1542 fn sign(&self, data: &[u8]) -> Vec<u8> {
1543 use sha2::{Digest, Sha256};
1544 let mut h = Sha256::new();
1545 h.update(self.secret.as_bytes());
1546 h.update(data);
1547 h.finalize().to_vec()
1548 }
1549 fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
1550 self.sign(data) == sig
1551 }
1552 }
1553
1554 fn reveal_envelope(bidder: &str, content_hash: &str, commit_hash: &str) -> RedactedEnvelope {
1557 let mut to = BTreeSet::new();
1558 to.insert(KeyId::parse("@auc").unwrap());
1559 let header = AttestationHeader {
1560 content_hash: content_hash.to_string(),
1561 performative: String::from("reveal"),
1562 from: KeyId::parse(bidder).unwrap(),
1563 to,
1564 thread: String::from("conv"),
1565 caused_by: Some(crate::message::CausedBy::Single(String::from(commit_hash))),
1566 };
1567 let signer = TestSigner {
1568 secret: match bidder {
1569 "@b1" => "b1",
1570 "@b2" => "b2",
1571 _ => "b3",
1572 },
1573 };
1574 let signature = sign_attestation_v2(&signer, &header).unwrap();
1575 RedactedEnvelope { header, signature }
1576 }
1577
1578 #[test]
1584 fn test_703_envelope_only_members_leave_the_fanin_incomplete() {
1585 let d = auction();
1586 let cast = auction_cast(&d);
1587 let mut store = ThreadedMessageStore::new();
1589 put(&mut store, "h0", &msg("(with-roles ((auctioneer @auc) (bidder @b1 @b2 @b3)) (signed @auc \"sig\" (hello :thread \"conv\" :caused-by begin)))"));
1590 for (i, b) in ["@b1", "@b2", "@b3"].iter().enumerate() {
1591 let hc = alloc::format!("h{}", i + 1);
1592 put(
1593 &mut store,
1594 &hc,
1595 &msg(&alloc::format!(
1596 "(signed {b} \"sig\" (lang test (commit @auc \"c\" :caused-by h0)))"
1597 )),
1598 );
1599 let hr = alloc::format!("h{}", i + 4);
1600 let signer = TestSigner {
1601 secret: match *b {
1602 "@b1" => "b1",
1603 "@b2" => "b2",
1604 _ => "b3",
1605 },
1606 };
1607 store
1608 .append_envelope(reveal_envelope(b, &hr, &hc), &signer)
1609 .unwrap();
1610 }
1611
1612 let h7 =
1613 msg("(signed @auc \"sig\" (lang test (declare-winner \"b3\" :caused-by (h4 h5 h6))))");
1614
1615 let simple = h7.innermost_simple().unwrap();
1618 assert_eq!(
1619 crate::protocol::verify_causal(
1620 "declare-winner",
1621 simple.caused_by(),
1622 &store,
1623 d.causal_protocol.as_ref().unwrap(),
1624 &tid(),
1625 ),
1626 VerificationResult::Valid
1627 );
1628
1629 let decide = |store: &ThreadedMessageStore| {
1632 verify_causal_for_role(
1633 &h7,
1634 &ep("auctioneer"),
1635 &d,
1636 &cast,
1637 store,
1638 &tid(),
1639 &ContentHash("h0".to_string()),
1640 )
1641 };
1642 assert_eq!(decide(&store), VerificationResult::Unknown);
1643
1644 for (i, b) in ["@b1", "@b2", "@b3"].iter().enumerate() {
1646 put(
1647 &mut store,
1648 &alloc::format!("h{}", i + 4),
1649 &msg(&alloc::format!(
1650 "(signed {b} \"sig\" (lang test (reveal @auc 42 :caused-by h{})))",
1651 i + 1
1652 )),
1653 );
1654 }
1655 assert_eq!(decide(&store), VerificationResult::Valid);
1656 }
1657}