#![forbid(unsafe_code)]
use crate::dialect::Dialect;
use crate::message::{CausedBy, Message, WrapperType};
use crate::protocol::{
verify_causal, CausalProtocol, CausalViolation, NodeRef, VerificationResult,
};
use crate::role::{parse_wrapper_cast, AgentKey, Cast, Endpoint, R6Violation, RoleAnnotation};
use crate::sexpr::{Atom, SExpr};
use crate::store::{ContentHash, MessageStore, ThreadId};
use alloc::collections::{BTreeMap, BTreeSet};
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LocalStep {
Send,
Recv,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LocalProtocol {
pub steps: BTreeMap<String, LocalStep>,
#[cfg_attr(feature = "serde", serde(default))]
pub expect_envelopes: BTreeSet<String>,
pub protocol: Option<CausalProtocol>,
}
pub fn project(d: &Dialect, endpoint: &Endpoint, cast: Option<&Cast>) -> LocalProtocol {
let mut steps: BTreeMap<String, LocalStep> = BTreeMap::new();
for p in &d.performatives {
if let Some(ann) = &p.role {
if ann.from == endpoint.role {
steps.insert(p.name.clone(), LocalStep::Send);
} else if ann.to.contains(&endpoint.role) {
steps.insert(p.name.clone(), LocalStep::Recv);
}
}
}
let mut expect_envelopes: BTreeSet<String> = BTreeSet::new();
if let crate::role::CausalLocality::Derive(table) = &d.causal_locality {
for (perf, roles) in &table.0 {
if roles.contains(&endpoint.role) {
expect_envelopes.insert(perf.clone());
}
}
if let (Some(cast), Some(occupant)) = (cast, &endpoint.occupant) {
let occ = crate::r6::derive_occupant_envelope_routes(d, cast);
for (perf, keys) in &occ.0 {
if keys.contains(occupant) {
expect_envelopes.insert(perf.clone());
}
}
}
}
LocalProtocol {
steps,
expect_envelopes,
protocol: d.causal_protocol.clone(),
}
}
fn signer_of(msg: &Message) -> Option<&str> {
let mut cur = msg;
loop {
match cur {
Message::Wrapped {
wrapper: WrapperType::Signed,
params,
content,
} => {
if let Some(SExpr::Atom(Atom::Symbol(s))) = params.first() {
return Some(s.as_str());
}
cur = content;
}
Message::Wrapped { content, .. } => cur = content,
Message::Dialect { inner, .. } => cur = inner,
Message::Simple { .. } | Message::Meta { .. } => return None,
}
}
}
fn role_violation(reason: String) -> VerificationResult {
VerificationResult::Violation(CausalViolation::RoleConformance { reason })
}
fn expected_recipient_keys<'a>(ann: &RoleAnnotation, cast: &'a Cast) -> BTreeSet<&'a str> {
let mut keys: BTreeSet<&str> = BTreeSet::new();
for role in &ann.to {
if let Some(k) = cast.singleton.get(role) {
keys.insert(k.0.as_str());
}
if let Some(ks) = cast.indexed.get(role) {
keys.extend(ks.iter().map(|k| k.0.as_str()));
}
}
keys
}
pub fn verify_causal_for_role<S: MessageStore>(
msg: &Message,
endpoint: &Endpoint,
d: &Dialect,
cast: &Cast,
store: &S,
thread: &ThreadId,
root: &ContentHash,
) -> VerificationResult {
let _ = endpoint;
if let (Some(pinned), Some(installed)) = (cast.dialect_pin.as_deref(), d.hash.as_deref()) {
if pinned != installed {
return role_violation(format!(
"{}",
R6Violation::DialectPinMismatch {
pinned: String::from(pinned),
installed: String::from(installed),
}
));
}
}
if msg.wrapper_type() == Some(WrapperType::WithRoles) {
return verify_cast_wrapper(msg, d, cast, store, thread, root);
}
let Some(simple) = msg.innermost_simple() else {
return VerificationResult::Valid;
};
let perf = match simple.performative() {
Some(p) => p.name(),
None => return VerificationResult::Valid,
};
let annotation = d.find_performative(perf).and_then(|p| p.role.as_ref());
let conformance = match annotation {
Some(ann) => check_conformance(msg, simple, ann, cast),
None => VerificationResult::Valid,
};
if let VerificationResult::Violation(_) = conformance {
return conformance;
}
let caused_by = simple.caused_by().cloned();
let rewritten = caused_by
.as_ref()
.map(|cb| rewrite_root_references(cb, root));
let r5 = match &d.causal_protocol {
Some(protocol) if crate::repeat::has_repeat(protocol) => crate::repeat::verify(
perf,
caused_by.as_ref(),
store,
protocol,
thread,
Some(root),
),
Some(protocol) => verify_causal(perf, rewritten.as_ref(), store, protocol, thread),
None => VerificationResult::Valid,
};
let fanin = repeat_occupant_fanin(perf, caused_by.as_ref(), d, cast, store, thread, root);
conformance.meet(r5).meet(fanin)
}
fn verify_cast_wrapper<S: MessageStore>(
msg: &Message,
d: &Dialect,
cast: &Cast,
store: &S,
thread: &ThreadId,
root: &ContentHash,
) -> VerificationResult {
let Message::Wrapped {
params, content, ..
} = msg
else {
unreachable!("guarded by wrapper_type");
};
let parsed = match parse_wrapper_cast(params, &d.roles) {
Ok(c) => c,
Err(v) => return role_violation(format!("{v}")),
};
if &parsed != cast {
return role_violation(String::from(
"with-roles wrapper does not match the thread's root cast (REQ-613)",
));
}
if !matches!(
content.as_ref(),
Message::Wrapped {
wrapper: WrapperType::Signed,
..
}
) {
return role_violation(String::from(
"with-roles payload must be a signed message (CON-601)",
));
}
if let Some(root_msg) = store.lookup_in_thread(root, thread) {
if root_msg != msg {
return role_violation(String::from(
"a second with-roles wrapper is not the thread root (REQ-613)",
));
}
}
match content.innermost_simple().and_then(|m| m.caused_by()) {
Some(CausedBy::Begin) => VerificationResult::Valid,
_ => role_violation(String::from(
"with-roles wrapper must be the thread's causal root (REQ-613)",
)),
}
}
fn check_conformance(
outer: &Message,
simple: &Message,
ann: &RoleAnnotation,
cast: &Cast,
) -> VerificationResult {
let Some(sender) = signer_of(outer) else {
return role_violation(String::from("role-annotated message carries no sender key"));
};
if !cast.admits(&ann.from, &AgentKey(String::from(sender))) {
return role_violation(format!(
"sender '{sender}' is not the cast's occupant of role '{}' (REQ-612)",
ann.from
));
}
let expected = expected_recipient_keys(ann, cast);
let actual = simple.recipient_set();
if expected != actual {
return role_violation(format!(
"recipients {actual:?} do not match the cast keys {expected:?} for :to roles {:?} (REQ-615)",
ann.to
));
}
VerificationResult::Valid
}
fn rewrite_root_references(cb: &CausedBy, root: &ContentHash) -> CausedBy {
match cb {
CausedBy::Single(h) if h == &root.0 => CausedBy::Begin,
other => other.clone(),
}
}
fn repeat_occupant_fanin<S: MessageStore>(
perf: &str,
caused_by: Option<&CausedBy>,
d: &Dialect,
cast: &Cast,
store: &S,
thread: &ThreadId,
root: &ContentHash,
) -> VerificationResult {
let Some(cp) = d
.causal_protocol
.as_ref()
.filter(|p| crate::repeat::has_repeat(p))
else {
return occupant_fanin(perf, caused_by, d, cast, store, thread, None);
};
let hashes = match caused_by {
Some(CausedBy::Single(h)) => alloc::vec![h.clone()],
Some(CausedBy::Multiple(hs)) => hs.clone(),
_ => Vec::new(),
};
let resolution = crate::repeat::Resolution::new(store, cp, thread, Some(root), hashes);
let mut result = None;
for (name, step) in &cp.steps {
if crate::protocol::repeat_base_name(name) != perf
|| !matches!(resolution.step(step, caused_by), VerificationResult::Valid)
{
continue;
}
let value = occupant_fanin(name, caused_by, d, cast, store, thread, Some(&resolution));
match value {
VerificationResult::Valid => return value,
VerificationResult::Unknown => result = Some(value),
_ if !matches!(result, Some(VerificationResult::Unknown)) => result = Some(value),
_ => {}
}
}
result.unwrap_or(VerificationResult::Valid)
}
fn occupant_fanin<S: MessageStore>(
perf: &str,
caused_by: Option<&CausedBy>,
d: &Dialect,
cast: &Cast,
store: &S,
thread: &ThreadId,
resolution: Option<&crate::repeat::Resolution<'_, S>>,
) -> VerificationResult {
let Some(cp) = &d.causal_protocol else {
return VerificationResult::Valid;
};
let Some(step) = cp.steps.get(perf) else {
return VerificationResult::Valid;
};
let mut counted: Vec<(&str, &BTreeSet<AgentKey>)> = Vec::new();
for nr in &step.predecessors {
let NodeRef::All(preds) = nr else { continue };
for pred in preds {
let Some(p_ann) = d
.find_performative(crate::protocol::repeat_base_name(pred))
.and_then(|p| p.role.as_ref())
else {
continue;
};
if let Some(occupants) = cast.indexed.get(&p_ann.from) {
counted.push((pred.as_str(), occupants));
}
}
}
if counted.is_empty() {
return VerificationResult::Valid;
}
let CausedBy::Multiple(hs) = (match caused_by {
Some(cb) => cb,
None => return VerificationResult::Valid,
}) else {
return VerificationResult::Valid;
};
let hashes: Vec<&str> = hs.iter().map(String::as_str).collect();
let mut resolved: Vec<(&str, &Message)> = Vec::new();
for h in &hashes {
match store.lookup_in_thread(&ContentHash(String::from(*h)), thread) {
Some(m) => resolved.push((h, m)),
None => return VerificationResult::Unknown,
}
}
for (pred_type, occupants) in counted {
let mut senders: BTreeSet<&str> = BTreeSet::new();
for (hash, m) in &resolved {
let Some(simple) = m.innermost_simple() else {
continue;
};
if match resolution {
Some(r) => !matches!(r.at(hash, pred_type), VerificationResult::Valid),
None => simple.performative().map(|p| p.name()) != Some(pred_type),
} {
continue;
}
if let Some(k) = signer_of(m) {
if occupants.contains(&AgentKey(String::from(k))) {
senders.insert(k);
}
}
}
let missing: Vec<&str> = occupants
.iter()
.map(|k| k.0.as_str())
.filter(|k| !senders.contains(*k))
.collect();
if !missing.is_empty() {
return role_violation(format!(
"fan-in over '{pred_type}' lacks instances from sealed occupant(s) {missing:?} (REQ-618)"
));
}
}
VerificationResult::Valid
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dialect::{Dialect, PerformativeDef, ResourceBounds};
use crate::protocol::StepDecl;
use crate::role::{parse_cast, parse_roles};
use crate::store::ThreadedMessageStore;
use alloc::string::ToString;
use alloc::vec;
fn perf(name: &str, from: &str, to: &[&str]) -> PerformativeDef {
PerformativeDef {
name: name.to_string(),
params: Vec::new(),
template: SExpr::Atom(Atom::Symbol("t".to_string())),
role: Some(RoleAnnotation {
from: from.to_string(),
to: to.iter().map(|s| s.to_string()).collect(),
}),
}
}
fn single(name: &str) -> NodeRef {
NodeRef::Single(name.to_string())
}
fn any(names: &[&str]) -> NodeRef {
NodeRef::Any(names.iter().map(|s| s.to_string()).collect())
}
fn all_of(names: &[&str]) -> NodeRef {
NodeRef::All(names.iter().map(|s| s.to_string()).collect())
}
fn step(name: &str, preds: Vec<NodeRef>, succs: Vec<NodeRef>) -> (String, StepDecl) {
(
name.to_string(),
StepDecl {
performative: name.to_string(),
predecessors: preds,
successors: succs,
},
)
}
fn dialect(
roles_src: &str,
perfs: Vec<PerformativeDef>,
steps: Vec<(String, StepDecl)>,
) -> Dialect {
Dialect {
types: Default::default(),
roles: parse_roles(&roles_src.parse::<SExpr>().unwrap()).unwrap(),
state: None,
state_bounds: None,
causal_locality: Default::default(),
name: "test".to_string(),
extends: Vec::new(),
author: None,
performatives: perfs,
resources: ResourceBounds {
max_depth: 8,
max_expansion_size: 512,
},
examples: Vec::new(),
signature: None,
hash: None,
protocol: None,
causal_protocol: Some(CausalProtocol {
steps: steps.into_iter().collect(),
}),
shapes: Vec::new(),
}
}
fn oauth() -> Dialect {
dialect(
"(server client authoriser)",
vec![
perf("login", "server", &["client", "authoriser"]),
perf("abort", "server", &["client", "authoriser"]),
perf("passwd", "client", &["authoriser", "server"]),
perf("auth", "authoriser", &["server"]),
perf("quit", "client", &["authoriser"]),
],
vec![
step("begin", vec![], vec![any(&["login", "abort"])]),
step("login", vec![single("begin")], vec![single("passwd")]),
step("abort", vec![single("begin")], vec![single("quit")]),
step("passwd", vec![single("login")], vec![single("auth")]),
step("auth", vec![single("passwd")], vec![]),
step("quit", vec![single("abort")], vec![]),
],
)
}
fn oauth_cast(d: &Dialect) -> Cast {
parse_cast(
&"((server @srv) (client @cli) (authoriser @as))"
.parse::<SExpr>()
.unwrap(),
&d.roles,
)
.unwrap()
}
fn ep(role: &str) -> Endpoint {
Endpoint {
role: role.to_string(),
occupant: None,
}
}
fn msg(src: &str) -> Message {
Message::try_from(&src.parse::<SExpr>().unwrap()).unwrap()
}
fn tid() -> ThreadId {
ThreadId("conv".to_string())
}
fn put(store: &mut ThreadedMessageStore, h: &str, m: &Message) {
store.append(ContentHash(h.to_string()), tid(), m.clone());
}
fn oauth_h0() -> Message {
msg("(with-roles ((server @srv) (client @cli) (authoriser @as)) (signed @srv \"sig\" (hello :thread \"conv\" :caused-by begin)))")
}
#[test]
fn only_exact_single_root_reference_is_typed_as_begin() {
let root = ContentHash("root".into());
assert_eq!(
rewrite_root_references(&CausedBy::Single("root".into()), &root),
CausedBy::Begin
);
for reference in [
CausedBy::Begin,
CausedBy::Single("other".into()),
CausedBy::Multiple(vec!["root".into(), "other".into()]),
] {
assert_eq!(rewrite_root_references(&reference, &root), reference);
}
}
#[test]
fn oauth_projections_match_the_paper() {
let d = oauth();
let server = project(&d, &ep("server"), None);
assert_eq!(server.steps.get("login"), Some(&LocalStep::Send));
assert_eq!(server.steps.get("abort"), Some(&LocalStep::Send));
assert_eq!(server.steps.get("passwd"), Some(&LocalStep::Recv));
assert_eq!(server.steps.get("auth"), Some(&LocalStep::Recv));
assert_eq!(server.steps.get("quit"), None, "bystander erased");
let client = project(&d, &ep("client"), None);
assert_eq!(client.steps.get("passwd"), Some(&LocalStep::Send));
assert_eq!(client.steps.get("quit"), Some(&LocalStep::Send));
assert_eq!(client.steps.get("login"), Some(&LocalStep::Recv));
assert_eq!(client.steps.get("auth"), None, "bystander erased");
let authoriser = project(&d, &ep("authoriser"), None);
assert_eq!(authoriser.steps.get("auth"), Some(&LocalStep::Send));
assert_eq!(authoriser.steps.get("passwd"), Some(&LocalStep::Recv));
assert_eq!(authoriser.steps.get("quit"), Some(&LocalStep::Recv));
}
#[test]
fn projection_keeps_raw_predecessor_clauses() {
let d = oauth();
for role in ["server", "client", "authoriser"] {
let local = project(&d, &ep(role), None);
assert_eq!(local.protocol, d.causal_protocol, "raw edges (REQ-610)");
}
}
#[test]
fn projection_is_deterministic() {
let d = oauth();
assert_eq!(
project(&d, &ep("client"), None),
project(&d, &ep("client"), None)
);
}
fn derived_oauth() -> Dialect {
let mut d = dialect(
"(server client authoriser)",
vec![
perf("login", "server", &["client"]),
perf("abort", "server", &["client"]),
perf("passwd", "client", &["authoriser"]),
perf("auth", "authoriser", &["server"]),
perf("quit", "client", &["authoriser"]),
],
vec![
step("begin", vec![], vec![any(&["login", "abort"])]),
step("login", vec![single("begin")], vec![single("passwd")]),
step("abort", vec![single("begin")], vec![single("quit")]),
step("passwd", vec![single("login")], vec![single("auth")]),
step("auth", vec![single("passwd")], vec![]),
step("quit", vec![single("abort")], vec![]),
],
);
d.causal_locality =
crate::role::CausalLocality::Derive(crate::r6::derive_envelope_routes(&d));
d
}
#[test]
fn reject_mode_projection_has_no_envelope_steps() {
let d = oauth();
for role in ["server", "client", "authoriser"] {
assert!(project(&d, &ep(role), None).expect_envelopes.is_empty());
}
}
#[test]
fn derived_projection_emits_expect_envelope_per_route() {
let d = derived_oauth();
let authoriser = project(&d, &ep("authoriser"), None);
let expected: BTreeSet<String> = ["login", "abort"].iter().map(|s| s.to_string()).collect();
assert_eq!(authoriser.expect_envelopes, expected);
let server = project(&d, &ep("server"), None);
let expected: BTreeSet<String> = ["passwd"].iter().map(|s| s.to_string()).collect();
assert_eq!(server.expect_envelopes, expected);
assert!(project(&d, &ep("client"), None).expect_envelopes.is_empty());
}
#[test]
fn expect_envelope_leaves_send_recv_steps_untouched() {
let d = derived_oauth();
let mut v1 = d.clone();
v1.causal_locality = crate::role::CausalLocality::Reject;
for role in ["server", "client", "authoriser"] {
assert_eq!(
project(&d, &ep(role), None).steps,
project(&v1, &ep(role), None).steps,
);
}
}
#[test]
fn per_occupant_expect_envelope_steps_come_from_the_sealed_cast() {
let mut d = dialect(
"(auctioneer (* bidder))",
vec![
perf("commit", "bidder", &["auctioneer"]),
perf("reveal", "bidder", &["auctioneer"]),
perf("declare-winner", "auctioneer", &["bidder"]),
],
vec![
step("begin", vec![], vec![single("commit")]),
step("commit", vec![single("begin")], vec![single("reveal")]),
step("reveal", vec![single("commit")], vec![]),
step("declare-winner", vec![all_of(&["reveal"])], vec![]),
],
);
d.causal_locality =
crate::role::CausalLocality::Derive(crate::r6::derive_envelope_routes(&d));
let cast = auction_cast(&d);
let b1 = Endpoint {
role: "bidder".to_string(),
occupant: Some(AgentKey("@b1".to_string())),
};
let local = project(&d, &b1, Some(&cast));
let expected: BTreeSet<String> =
["commit", "reveal"].iter().map(|s| s.to_string()).collect();
assert_eq!(local.expect_envelopes, expected);
assert_eq!(local.steps.get("commit"), Some(&LocalStep::Send));
assert_eq!(local.steps.get("reveal"), Some(&LocalStep::Send));
assert!(project(&d, &b1, None).expect_envelopes.is_empty());
let auc = project(&d, &ep("auctioneer"), Some(&cast));
assert!(auc.expect_envelopes.is_empty());
}
#[test]
fn first_step_naming_root_hash_verifies() {
let d = oauth();
let cast = oauth_cast(&d);
let mut store = ThreadedMessageStore::new();
put(&mut store, "h0", &oauth_h0());
let h1 = msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
assert_eq!(
verify_causal_for_role(
&h1,
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Valid
);
}
#[test]
fn non_nominee_cannot_squat_a_role() {
let d = oauth();
let cast = oauth_cast(&d);
let mut store = ThreadedMessageStore::new();
put(&mut store, "h0", &oauth_h0());
let evil = msg("(signed @evil \"sig\" (lang test (login (@as @cli) \"n\" :caused-by h0)))");
assert!(matches!(
verify_causal_for_role(
&evil,
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Violation(CausalViolation::RoleConformance { .. })
));
}
#[test]
fn narrowed_recipients_violate_conformance() {
let d = oauth();
let cast = oauth_cast(&d);
let mut store = ThreadedMessageStore::new();
put(&mut store, "h0", &oauth_h0());
let narrow = msg("(signed @srv \"sig\" (lang test (login @cli \"n\" :caused-by h0)))");
assert!(matches!(
verify_causal_for_role(
&narrow,
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Violation(CausalViolation::RoleConformance { .. })
));
}
#[test]
fn out_of_order_is_unknown_then_valid() {
let d = oauth();
let cast = oauth_cast(&d);
let mut store = ThreadedMessageStore::new();
put(&mut store, "h0", &oauth_h0());
let h1 = msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
let h2 =
msg("(signed @cli \"sig\" (lang test (passwd (@as @srv) \"cred\" :caused-by h1)))");
assert_eq!(
verify_causal_for_role(
&h2,
&ep("authoriser"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Unknown
);
put(&mut store, "h1", &h1);
assert_eq!(
verify_causal_for_role(
&h2,
&ep("authoriser"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Valid
);
}
#[test]
fn vacant_role_dependency_stays_unknown() {
let d = oauth();
let cast = oauth_cast(&d);
let store = ThreadedMessageStore::new();
let auth = msg("(signed @as \"sig\" (lang test (auth @srv \"tok\" :caused-by h-never)))");
assert_eq!(
verify_causal_for_role(
&auth,
&ep("server"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Unknown
);
}
#[test]
fn foreign_cast_wrapper_is_a_violation() {
let d = oauth();
let cast = oauth_cast(&d);
let store = ThreadedMessageStore::new();
let second = msg("(with-roles ((server @evil) (client @cli) (authoriser @as)) (signed @evil \"sig\" (hello :caused-by begin)))");
assert!(matches!(
verify_causal_for_role(
&second,
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Violation(CausalViolation::RoleConformance { .. })
));
}
#[test]
fn non_root_wrapper_is_a_violation() {
let d = oauth();
let cast = oauth_cast(&d);
let store = ThreadedMessageStore::new();
let late = msg("(with-roles ((server @srv) (client @cli) (authoriser @as)) (signed @srv \"sig\" (hello :caused-by h0)))");
assert!(matches!(
verify_causal_for_role(
&late,
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Violation(CausalViolation::RoleConformance { .. })
));
}
#[test]
fn unsigned_sender_field_cannot_occupy_a_role() {
let d = oauth();
let cast = oauth_cast(&d);
let mut store = ThreadedMessageStore::new();
put(&mut store, "h0", &oauth_h0());
let forged = msg("(lang test (login (@as @cli) \"n\" :sender @srv :caused-by h0))");
assert!(matches!(
verify_causal_for_role(
&forged,
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Violation(CausalViolation::RoleConformance { .. })
));
}
#[test]
fn forged_second_root_wrapper_is_rejected() {
let d = oauth();
let cast = oauth_cast(&d);
let mut store = ThreadedMessageStore::new();
put(&mut store, "h0", &oauth_h0());
let second = msg("(with-roles ((server @srv) (client @cli) (authoriser @as)) (signed @cli \"sig\" (hello :caused-by begin)))");
put(&mut store, "h9", &second);
assert!(matches!(
verify_causal_for_role(
&second,
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Violation(CausalViolation::RoleConformance { .. })
));
let reparented =
msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n\" :caused-by h9)))");
assert!(matches!(
verify_causal_for_role(
&reparented,
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Violation(_)
));
}
#[test]
fn receive_only_role_needs_no_signature_to_be_addressed() {
let d = oauth();
let cast = oauth_cast(&d);
let mut store = ThreadedMessageStore::new();
put(&mut store, "h0", &oauth_h0());
let login =
msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
assert_eq!(
verify_causal_for_role(
&login,
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Valid
);
}
#[test]
fn matching_root_wrapper_is_valid() {
let d = oauth();
let cast = oauth_cast(&d);
let store = ThreadedMessageStore::new();
assert_eq!(
verify_causal_for_role(
&oauth_h0(),
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Valid
);
}
#[test]
fn unsigned_root_payload_is_rejected() {
let d = oauth();
let cast = oauth_cast(&d);
let store = ThreadedMessageStore::new();
let unsigned = msg("(with-roles ((server @srv) (client @cli) (authoriser @as)) (hello :thread \"conv\" :caused-by begin))");
assert!(matches!(
verify_causal_for_role(
&unsigned,
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Violation(CausalViolation::RoleConformance { .. })
));
}
#[test]
fn root_wrapper_with_extra_params_is_rejected() {
let d = oauth();
let cast = oauth_cast(&d);
let store = ThreadedMessageStore::new();
let extra = msg("(with-roles ((server @srv) (client @cli) (authoriser @as)) junk (signed @srv \"sig\" (hello :caused-by begin)))");
assert!(matches!(
verify_causal_for_role(
&extra,
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Violation(CausalViolation::RoleConformance { .. })
));
}
fn hashed_oauth() -> Dialect {
let mut d = oauth();
d.hash = Some(crate::canonical::dialect_hash(&d));
d
}
fn pinned_h0(pin: &str) -> Message {
msg(&format!(
"(with-roles ((server @srv) (client @cli) (authoriser @as)) :dialect {pin} (signed @srv \"sig\" (hello :thread \"conv\" :caused-by begin)))"
))
}
fn pinned_cast(d: &Dialect, root: &Message) -> Cast {
let Message::Wrapped { params, .. } = root else {
panic!("root fixture is a wrapper");
};
parse_wrapper_cast(params, &d.roles).unwrap()
}
#[test]
fn pinned_root_matching_installed_hash_verifies() {
let d = hashed_oauth();
let pin = d.hash.clone().unwrap();
let root = pinned_h0(&pin);
let cast = pinned_cast(&d, &root);
let mut store = ThreadedMessageStore::new();
put(&mut store, "h0", &root);
assert_eq!(
verify_causal_for_role(
&root,
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Valid
);
let h1 = msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
assert_eq!(
verify_causal_for_role(
&h1,
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Valid
);
}
#[test]
fn pin_mismatch_is_a_typed_violation_for_every_thread_message() {
let d = hashed_oauth();
let stale = format!("f1220{}", "0".repeat(64));
let root = pinned_h0(&stale);
let cast = pinned_cast(&d, &root);
let mut store = ThreadedMessageStore::new();
put(&mut store, "h0", &root);
let h1 = msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
for m in [&root, &h1] {
match verify_causal_for_role(
m,
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string()),
) {
VerificationResult::Violation(CausalViolation::RoleConformance { reason }) => {
assert!(
reason.contains("REQ-628"),
"expected the typed pin violation, got: {reason}"
);
}
other => panic!("expected the REQ-628 violation, got {other:?}"),
}
}
}
#[test]
fn unpinned_root_still_verifies_during_transition() {
let d = hashed_oauth();
let cast = oauth_cast(&d);
let mut store = ThreadedMessageStore::new();
put(&mut store, "h0", &oauth_h0());
assert_eq!(
verify_causal_for_role(
&oauth_h0(),
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Valid
);
let h1 = msg("(signed @srv \"sig\" (lang test (login (@as @cli) \"n-42\" :caused-by h0)))");
assert_eq!(
verify_causal_for_role(
&h1,
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Valid
);
}
#[test]
fn malformed_pin_on_root_is_rejected() {
let d = hashed_oauth();
let cast = oauth_cast(&d);
let store = ThreadedMessageStore::new();
for bad in [
"(with-roles ((server @srv) (client @cli) (authoriser @as)) :dialect f1220abc (signed @srv \"sig\" (hello :caused-by begin)))",
"(with-roles ((server @srv) (client @cli) (authoriser @as)) :dialect md5:0000 (signed @srv \"sig\" (hello :caused-by begin)))",
] {
assert!(matches!(
verify_causal_for_role(
&msg(bad),
&ep("client"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Violation(CausalViolation::RoleConformance { .. })
));
}
}
fn auction() -> Dialect {
dialect(
"(auctioneer (* bidder))",
vec![
perf("commit", "bidder", &["auctioneer"]),
perf("reveal", "bidder", &["auctioneer"]),
perf("declare-winner", "auctioneer", &[]),
],
vec![
step("begin", vec![], vec![single("commit")]),
step("commit", vec![single("begin")], vec![single("reveal")]),
step("reveal", vec![single("commit")], vec![]),
step("declare-winner", vec![all_of(&["reveal"])], vec![]),
],
)
}
fn auction_cast(d: &Dialect) -> Cast {
parse_cast(
&"((auctioneer @auc) (bidder @b1 @b2 @b3))"
.parse::<SExpr>()
.unwrap(),
&d.roles,
)
.unwrap()
}
fn auction_store() -> ThreadedMessageStore {
let mut store = ThreadedMessageStore::new();
put(&mut store, "h0", &msg("(with-roles ((auctioneer @auc) (bidder @b1 @b2 @b3)) (signed @auc \"sig\" (hello :thread \"conv\" :caused-by begin)))"));
for (i, b) in ["@b1", "@b2", "@b3"].iter().enumerate() {
let hc = alloc::format!("h{}", i + 1);
let hr = alloc::format!("h{}", i + 4);
put(
&mut store,
&hc,
&msg(&alloc::format!(
"(signed {b} \"sig\" (lang test (commit @auc \"c\" :caused-by h0)))"
)),
);
put(
&mut store,
&hr,
&msg(&alloc::format!(
"(signed {b} \"sig\" (lang test (reveal @auc 42 :caused-by {hc})))"
)),
);
}
store
}
#[test]
fn fanin_unknown_until_all_reveals_then_valid() {
let d = auction();
let cast = auction_cast(&d);
let mut store = ThreadedMessageStore::new();
put(&mut store, "h0", &msg("(with-roles ((auctioneer @auc) (bidder @b1 @b2 @b3)) (signed @auc \"sig\" (hello :caused-by begin)))"));
put(
&mut store,
"h1",
&msg("(signed @b1 \"sig\" (lang test (commit @auc \"c\" :caused-by h0)))"),
);
put(
&mut store,
"h2",
&msg("(signed @b2 \"sig\" (lang test (commit @auc \"c\" :caused-by h0)))"),
);
put(
&mut store,
"h4",
&msg("(signed @b1 \"sig\" (lang test (reveal @auc 42 :caused-by h1)))"),
);
put(
&mut store,
"h5",
&msg("(signed @b2 \"sig\" (lang test (reveal @auc 17 :caused-by h2)))"),
);
let h7 =
msg("(signed @auc \"sig\" (lang test (declare-winner \"b3\" :caused-by (h4 h5 h6))))");
assert_eq!(
verify_causal_for_role(
&h7,
&ep("auctioneer"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Unknown
);
put(
&mut store,
"h3",
&msg("(signed @b3 \"sig\" (lang test (commit @auc \"c\" :caused-by h0)))"),
);
put(
&mut store,
"h6",
&msg("(signed @b3 \"sig\" (lang test (reveal @auc 55 :caused-by h3)))"),
);
assert_eq!(
verify_causal_for_role(
&h7,
&ep("auctioneer"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Valid
);
}
#[test]
fn resolved_fanin_missing_an_occupant_is_a_violation() {
let d = auction();
let cast = auction_cast(&d);
let store = auction_store();
let h7 =
msg("(signed @auc \"sig\" (lang test (declare-winner \"b1\" :caused-by (h4 h5))))");
assert!(matches!(
verify_causal_for_role(
&h7,
&ep("auctioneer"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Violation(CausalViolation::RoleConformance { .. })
));
}
#[test]
fn non_member_instance_does_not_count_toward_coverage() {
let d = auction();
let cast = auction_cast(&d);
let mut store = auction_store();
put(
&mut store,
"hx",
&msg("(signed @b4 \"sig\" (lang test (reveal @auc 99 :caused-by h3)))"),
);
let h7 =
msg("(signed @auc \"sig\" (lang test (declare-winner \"b1\" :caused-by (h4 h5 hx))))");
assert!(matches!(
verify_causal_for_role(
&h7,
&ep("auctioneer"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Violation(CausalViolation::RoleConformance { .. })
));
}
#[test]
fn full_auction_trace_verifies_end_to_end() {
let d = auction();
let cast = auction_cast(&d);
let store = auction_store();
for (h, role) in [
("h1", "bidder"),
("h2", "bidder"),
("h3", "bidder"),
("h4", "bidder"),
("h5", "bidder"),
("h6", "bidder"),
] {
let m = store
.lookup_in_thread(&ContentHash(h.to_string()), &tid())
.unwrap()
.clone();
assert_eq!(
verify_causal_for_role(
&m,
&ep(role),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Valid,
"{h} should be Valid"
);
}
let h7 =
msg("(signed @auc \"sig\" (lang test (declare-winner \"b3\" :caused-by (h4 h5 h6))))");
assert_eq!(
verify_causal_for_role(
&h7,
&ep("auctioneer"),
&d,
&cast,
&store,
&tid(),
&ContentHash("h0".to_string())
),
VerificationResult::Valid
);
}
use crate::attest::{sign_attestation_v2, AttestationHeader};
use crate::envelope::RedactedEnvelope;
use crate::keyid::KeyId;
use crate::r4::Signer;
struct TestSigner {
secret: &'static str,
}
impl Signer for TestSigner {
fn sign(&self, data: &[u8]) -> Vec<u8> {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
h.update(self.secret.as_bytes());
h.update(data);
h.finalize().to_vec()
}
fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
self.sign(data) == sig
}
}
fn reveal_envelope(bidder: &str, content_hash: &str, commit_hash: &str) -> RedactedEnvelope {
let mut to = BTreeSet::new();
to.insert(KeyId::parse("@auc").unwrap());
let header = AttestationHeader {
content_hash: content_hash.to_string(),
performative: String::from("reveal"),
from: KeyId::parse(bidder).unwrap(),
to,
thread: String::from("conv"),
caused_by: Some(crate::message::CausedBy::Single(String::from(commit_hash))),
};
let signer = TestSigner {
secret: match bidder {
"@b1" => "b1",
"@b2" => "b2",
_ => "b3",
},
};
let signature = sign_attestation_v2(&signer, &header).unwrap();
RedactedEnvelope { header, signature }
}
#[test]
fn test_703_envelope_only_members_leave_the_fanin_incomplete() {
let d = auction();
let cast = auction_cast(&d);
let mut store = ThreadedMessageStore::new();
put(&mut store, "h0", &msg("(with-roles ((auctioneer @auc) (bidder @b1 @b2 @b3)) (signed @auc \"sig\" (hello :thread \"conv\" :caused-by begin)))"));
for (i, b) in ["@b1", "@b2", "@b3"].iter().enumerate() {
let hc = alloc::format!("h{}", i + 1);
put(
&mut store,
&hc,
&msg(&alloc::format!(
"(signed {b} \"sig\" (lang test (commit @auc \"c\" :caused-by h0)))"
)),
);
let hr = alloc::format!("h{}", i + 4);
let signer = TestSigner {
secret: match *b {
"@b1" => "b1",
"@b2" => "b2",
_ => "b3",
},
};
store
.append_envelope(reveal_envelope(b, &hr, &hc), &signer)
.unwrap();
}
let h7 =
msg("(signed @auc \"sig\" (lang test (declare-winner \"b3\" :caused-by (h4 h5 h6))))");
let simple = h7.innermost_simple().unwrap();
assert_eq!(
crate::protocol::verify_causal(
"declare-winner",
simple.caused_by(),
&store,
d.causal_protocol.as_ref().unwrap(),
&tid(),
),
VerificationResult::Valid
);
let decide = |store: &ThreadedMessageStore| {
verify_causal_for_role(
&h7,
&ep("auctioneer"),
&d,
&cast,
store,
&tid(),
&ContentHash("h0".to_string()),
)
};
assert_eq!(decide(&store), VerificationResult::Unknown);
for (i, b) in ["@b1", "@b2", "@b3"].iter().enumerate() {
put(
&mut store,
&alloc::format!("h{}", i + 4),
&msg(&alloc::format!(
"(signed {b} \"sig\" (lang test (reveal @auc 42 :caused-by h{})))",
i + 1
)),
);
}
assert_eq!(decide(&store), VerificationResult::Valid);
}
}