use std::collections::BTreeMap;
use serde_json::{json, Map, Value};
use crate::attenuation;
use crate::credentials;
use crate::delegation::{self, ChainOptions};
use crate::grant_chain::{self, py_repr, py_repr_str, truthy};
use crate::hybrid;
use crate::status_list;
use crate::time::parse_protocol_time_ns;
#[derive(Debug, Clone, Copy)]
pub struct FleetOptions<'a> {
pub trusted_roots: &'a BTreeMap<String, Vec<u8>>,
pub revoked: &'a [String],
pub now_iso: &'a str,
pub clock_skew_seconds: i64,
pub require_action: Option<&'a str>,
pub require_target: Option<&'a str>,
pub require_resource: Option<&'a str>,
pub check_status: bool,
pub status_lists: Option<&'a Map<String, Value>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct FleetResult {
pub ok: bool,
pub reason: Option<String>,
pub leaf: Option<Value>,
pub root_did: Option<String>,
}
impl FleetResult {
fn fail(reason: String) -> Self {
FleetResult {
ok: false,
reason: Some(reason),
leaf: None,
root_did: None,
}
}
pub fn to_json(&self) -> Value {
json!({
"ok": self.ok,
"reason": self.reason,
"leaf": self.leaf,
"rootDid": self.root_did,
})
}
}
fn issuer_of(cred: &Value) -> Option<String> {
let issuer = match cred.get("issuer") {
Some(Value::Array(items)) => items.first(),
Some(Value::Object(o)) => o.get("id"),
other => other,
};
issuer
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(String::from)
}
fn intent_of(cred: &Value) -> Option<&Map<String, Value>> {
cred.get("credentialSubject")
.and_then(|s| s.get("intent"))
.and_then(Value::as_object)
}
fn post_quantum_proof(cred: &Value) -> bool {
match cred.get("proof") {
Some(Value::Array(_)) => true,
Some(p) => {
p.get("cryptosuite").and_then(Value::as_str)
== Some(hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID)
}
None => false,
}
}
fn embedded_grants(cred: &Value) -> Vec<&Value> {
cred.get("credentialSubject")
.and_then(|s| s.get("delegationChain"))
.and_then(Value::as_array)
.map(|links| {
links
.iter()
.filter_map(|l| l.get("parentCredential").filter(|g| g.is_object()))
.collect()
})
.unwrap_or_default()
}
fn status_ok(cred: &Value, cred_key: &[u8], opts: &FleetOptions) -> bool {
let mut checked: Vec<(&Value, Option<Vec<u8>>)> = vec![(cred, Some(cred_key.to_vec()))];
for grant in embedded_grants(cred) {
let key = issuer_of(grant).and_then(|i| opts.trusted_roots.get(&i).cloned());
checked.push((grant, key));
}
for (c, key) in checked {
if c.get("credentialStatus").is_none() {
continue;
}
let Some(lists) = opts.status_lists else {
return false;
};
match status_list::check_credential_status(
c,
lists,
key.as_deref(),
None,
opts.now_iso,
opts.clock_skew_seconds,
) {
Ok(r) if r.ok => {}
_ => return false,
}
}
true
}
fn window_within(child: &Value, parent: &Value) -> bool {
let t = |c: &Value, k: &str| {
c.get(k)
.and_then(Value::as_str)
.and_then(|s| parse_protocol_time_ns(s).ok())
};
match (
t(child, "validFrom"),
t(child, "validUntil"),
t(parent, "validFrom"),
t(parent, "validUntil"),
) {
(Some(cf), Some(cu), Some(pf), Some(pu)) => cf >= pf && cu <= pu,
_ => false,
}
}
pub fn revocation_candidates(credentials: &[Value]) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let mut push = |s: Option<String>| {
if let Some(s) = s.filter(|s| !s.is_empty()) {
if !out.contains(&s) {
out.push(s);
}
}
};
for cred in credentials {
push(issuer_of(cred));
push(cred.get("id").and_then(Value::as_str).map(String::from));
}
for cred in credentials {
push(
intent_of(cred)
.and_then(|i| i.get("delegatee"))
.and_then(Value::as_str)
.map(String::from),
);
}
out
}
pub fn verify_delegated_chain(credentials: &[Value], opts: &FleetOptions) -> FleetResult {
if credentials.is_empty() {
return FleetResult::fail("empty chain".into());
}
for (index, cred) in credentials.iter().enumerate() {
if !cred.is_object() {
return FleetResult::fail(format!("credential {index} is not a JSON object"));
}
}
if let Some((index, code)) = grant_chain::presented_chain_problem(credentials) {
return FleetResult::fail(format!("credential {index}: {code}"));
}
let is_revoked = |id: &str| opts.revoked.iter().any(|r| r == id);
let root_dids: Vec<String> = opts.trusted_roots.keys().cloned().collect();
let chain_opts = ChainOptions {
trusted_roots: Some(&root_dids),
grant_keys: Some(opts.trusted_roots),
..Default::default()
};
let mut issuers: Vec<String> = Vec::with_capacity(credentials.len());
for (index, cred) in credentials.iter().enumerate() {
let Some(issuer) = issuer_of(cred) else {
return FleetResult::fail(format!("credential {index} has no issuer"));
};
let given = opts.trusted_roots.get(&issuer);
if index == 0 && given.is_none() {
return FleetResult::fail(format!(
"root issuer {} is not in trusted_roots",
py_repr_str(&issuer)
));
}
let key = match given {
Some(k) => Some(k.clone()),
None => crate::keys::did_key_to_ed25519(&issuer).ok(),
};
let failed = || FleetResult::fail(format!("credential {index} failed verification"));
let Some(key) = key else {
return failed();
};
let verdict = credentials::verify_with_keys(
cred,
&key,
None,
opts.now_iso,
opts.clock_skew_seconds,
&chain_opts,
);
match verdict {
Ok((r, _)) if r.is_valid() => {}
Ok((r, _)) => {
if given.is_some() && r.time_valid && !r.proof_valid && post_quantum_proof(cred) {
return FleetResult::fail(format!("credential {index} needs an ML-DSA-44 key"));
}
return failed();
}
Err(_) => return failed(),
}
if opts.check_status && !status_ok(cred, &key, opts) {
return failed();
}
if is_revoked(&issuer) {
return FleetResult::fail(format!(
"credential {index} issuer {} is revoked",
py_repr_str(&issuer)
));
}
if let Some(id) = cred.get("id").filter(|v| truthy(Some(v))) {
if id.as_str().is_some_and(is_revoked) {
let shown = id
.as_str()
.map(String::from)
.unwrap_or_else(|| id.to_string());
return FleetResult::fail(format!("credential {index} ({shown}) is revoked"));
}
}
issuers.push(issuer);
}
let mut effective = delegation::capability_view(&credentials[0], false);
for i in 0..credentials.len() - 1 {
let (parent, child) = (&credentials[i], &credentials[i + 1]);
let parent_intent = intent_of(parent);
let delegatee = parent_intent.and_then(|it| it.get("delegatee"));
if !truthy(delegatee) {
return FleetResult::fail(format!(
"link {i} (grant by {}) names no delegatee",
py_repr_str(&issuers[i])
));
}
if delegatee.and_then(Value::as_str).is_some_and(is_revoked) {
return FleetResult::fail(format!(
"link {i}: delegatee {} is revoked",
py_repr(delegatee)
));
}
if delegatee.and_then(Value::as_str) != Some(issuers[i + 1].as_str()) {
return FleetResult::fail(format!(
"link {i}: child issuer {} is not the delegatee {} the parent authorized",
py_repr_str(&issuers[i + 1]),
py_repr(delegatee)
));
}
let child_view = delegation::capability_view(child, false);
let dimension = attenuation::non_expansion(&effective, &child_view);
effective = attenuation::inherit(&effective, &child_view);
if let Err(dim) = dimension {
let name = dim.as_str();
let granted = parent_intent.and_then(|it| it.get(name));
let asked = intent_of(child).and_then(|it| it.get(name));
return FleetResult::fail(format!(
"link {i}: {name} {} is not within the granted {}",
py_repr(asked),
py_repr(granted)
));
}
if !window_within(child, parent) {
return FleetResult::fail(format!(
"link {i}: child validity is outside the grant window"
));
}
}
let leaf = &credentials[credentials.len() - 1];
let leaf_intent = intent_of(leaf);
for (field, expected) in [
("action", opts.require_action),
("target", opts.require_target),
("resource", opts.require_resource),
] {
let Some(expected) = expected else { continue };
if leaf_intent
.and_then(|it| it.get(field))
.and_then(Value::as_str)
!= Some(expected)
{
return FleetResult {
ok: false,
reason: Some(format!("leaf intent.{field} != {}", py_repr_str(expected))),
leaf: Some(leaf.clone()),
root_did: None,
};
}
}
FleetResult {
ok: true,
reason: None,
leaf: Some(leaf.clone()),
root_did: Some(issuers[0].clone()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::credentials::{sign_sub_grant, sign_vouch_credential, BuildCredentialOptions};
use crate::data_integrity::BuildProofOptions;
use crate::keys::Ed25519KeyPair;
const NOW: &str = "2026-11-10T12:00:00Z";
const FROM: &str = "2026-11-10T00:00:00Z";
const UNTIL: &str = "2026-11-11T00:00:00Z";
struct Who {
seed: [u8; 32],
did: String,
}
fn key_party(n: u8) -> Who {
let seed = [n; 32];
Who {
seed,
did: Ed25519KeyPair::from_seed(&seed).did_key(),
}
}
fn web_party(n: u8, host: &str) -> Who {
Who {
seed: [n; 32],
did: format!("did:web:{host}"),
}
}
fn public(w: &Who) -> Vec<u8> {
Ed25519KeyPair::from_seed(&w.seed).public_key().to_vec()
}
fn intent(action: &str, target: &str, resource: &str, extra: Value) -> Value {
let mut i = json!({"action": action, "target": target, "resource": resource});
for (k, v) in extra.as_object().unwrap() {
i[k] = v.clone();
}
i
}
fn opts(
who: &Who,
intent: Value,
id: &str,
window: (&str, &str),
chain: Option<Vec<Value>>,
) -> BuildCredentialOptions {
BuildCredentialOptions {
issuer_did: who.did.clone(),
credential_id: id.into(),
intent,
valid_from: window.0.into(),
valid_until: window.1.into(),
reputation_score: None,
delegation_chain: chain.map(Value::Array),
credential_status: None,
}
}
fn proof(who: &Who) -> BuildProofOptions {
BuildProofOptions::new(format!("{}#key-1", who.did), FROM)
}
fn sign(who: &Who, intent: Value, id: &str) -> Value {
sign_vouch_credential(
&opts(who, intent, id, (FROM, UNTIL), None),
&who.seed,
&proof(who),
)
.unwrap()
}
fn sign_window(who: &Who, intent: Value, id: &str, window: (&str, &str)) -> Value {
sign_vouch_credential(&opts(who, intent, id, window, None), &who.seed, &proof(who)).unwrap()
}
fn roots(ws: &[&Who]) -> BTreeMap<String, Vec<u8>> {
ws.iter().map(|w| (w.did.clone(), public(w))).collect()
}
fn check(
creds: &[Value],
roots: &BTreeMap<String, Vec<u8>>,
revoked: &[String],
) -> FleetResult {
verify_delegated_chain(
creds,
&FleetOptions {
trusted_roots: roots,
revoked,
now_iso: NOW,
clock_skew_seconds: 30,
require_action: None,
require_target: None,
require_resource: None,
check_status: true,
status_lists: None,
},
)
}
fn reason(r: FleetResult) -> String {
assert!(!r.ok);
r.reason.unwrap()
}
struct Fleet {
root: Who,
device: Who,
impostor: Who,
grant: Value,
}
fn fleet() -> Fleet {
let (root, device, impostor) =
(web_party(31, "root.example"), key_party(32), key_party(33));
let grant = sign(
&root,
intent(
"read",
"calendar",
"https://cal.example/team",
json!({"delegatee": device.did, "rate": {"limit": 10, "window": "PT1H"}}),
),
"urn:uuid:00000000-0000-4000-8000-000000000001",
);
Fleet {
root,
device,
impostor,
grant,
}
}
fn leaf_by(
f: &Fleet,
who: &Who,
action: &str,
target: &str,
resource: &str,
extra: Value,
) -> Value {
let _ = f;
sign(
who,
intent(action, target, resource, extra),
"urn:uuid:00000000-0000-4000-8000-000000000002",
)
}
#[test]
fn a_narrowing_chain_verifies_and_returns_the_leaf() {
let f = fleet();
let leaf = leaf_by(
&f,
&f.device,
"read",
"calendar",
"https://cal.example/team/1",
json!({}),
);
let r = check(&[f.grant.clone(), leaf.clone()], &roots(&[&f.root]), &[]);
assert!(r.ok, "{:?}", r.reason);
assert_eq!(r.root_did.as_deref(), Some("did:web:root.example"));
assert_eq!(r.leaf, Some(leaf));
assert_eq!(r.reason, None);
assert_eq!(r.to_json()["ok"], json!(true));
}
#[test]
fn widening_steps_are_refused_with_the_reference_text() {
let f = fleet();
let roots = roots(&[&f.root]);
let cases = [
(
leaf_by(&f, &f.device, "write", "calendar", "https://cal.example/team", json!({})),
"link 0: action 'write' is not within the granted 'read'",
),
(
leaf_by(&f, &f.device, "read", "mail", "https://cal.example/team", json!({})),
"link 0: target 'mail' is not within the granted 'calendar'",
),
(
leaf_by(&f, &f.device, "read", "calendar", "https://cal.example/other", json!({})),
"link 0: resource 'https://cal.example/other' is not within the granted 'https://cal.example/team'",
),
(
leaf_by(
&f,
&f.device,
"read",
"calendar",
"https://cal.example/team",
json!({"rate": {"limit": 100, "window": "PT1H"}}),
),
"link 0: rate {'limit': 100, 'window': 'PT1H'} is not within the granted {'limit': 10, 'window': 'PT1H'}",
),
(
leaf_by(
&f,
&f.device,
"read",
"calendar",
"https://cal.example/team",
json!({"rate": {"limit": 2.5e-05, "window": "PT1H"}}),
),
"link 0: rate {'limit': 2.5e-05, 'window': 'PT1H'} is not within the granted {'limit': 10, 'window': 'PT1H'}",
),
(
leaf_by(&f, &f.device, "read", "calendar", "https://cal.example/team", json!({"rate": null})),
"link 0: rate None is not within the granted {'limit': 10, 'window': 'PT1H'}",
),
(
leaf_by(&f, &f.device, "read", "calendar", "https://cal.example/../x", json!({})),
"link 0: resource 'https://cal.example/../x' is not within the granted 'https://cal.example/team'",
),
];
for (leaf, want) in cases {
assert_eq!(reason(check(&[f.grant.clone(), leaf], &roots, &[])), want);
}
let mut body = crate::credentials::build_vouch_credential(&opts(
&f.device,
intent("read", "calendar", "https://cal.example/team", json!({})),
"urn:uuid:00000000-0000-4000-8000-000000000003",
(FROM, UNTIL),
None,
))
.unwrap();
body["credentialSubject"]["intent"]["action"] = json!(["read", "delete"]);
let both_actions =
crate::data_integrity::sign(&body, &f.device.seed, &proof(&f.device)).unwrap();
assert_eq!(
reason(check(&[f.grant.clone(), both_actions], &roots, &[])),
"link 0: action ['read', 'delete'] is not within the granted 'read'"
);
}
#[test]
fn the_issuer_is_a_string_the_first_of_a_list_or_an_object_id() {
for (issuer, expected) in [
(json!("did:web:a"), Some("did:web:a")),
(json!(["did:web:a", "did:web:b"]), Some("did:web:a")),
(json!({"id": "did:web:a", "name": "x"}), Some("did:web:a")),
(json!([]), None),
(json!([{"id": "did:web:a"}]), None),
(json!([""]), None),
(json!([["did:web:a"]]), None),
(json!([5]), None),
(json!({"id": 5}), None),
(json!({"id": ""}), None),
(json!({"id": ["did:web:a"]}), None),
(json!({}), None),
(json!(""), None),
(json!(5), None),
(json!(true), None),
(Value::Null, None),
] {
let cred = json!({ "issuer": issuer });
assert_eq!(issuer_of(&cred).as_deref(), expected, "{issuer}");
}
assert_eq!(issuer_of(&json!({})), None);
let f = fleet();
let roots = roots(&[&f.root]);
let good = leaf_by(
&f,
&f.device,
"read",
"calendar",
"https://cal.example/team",
json!({}),
);
for issuer in [json!(5), json!({"id": 5}), json!([]), json!({}), json!("")] {
let mut grant = f.grant.clone();
grant["issuer"] = issuer.clone();
assert_eq!(
reason(check(&[grant, good.clone()], &roots, &[])),
"credential 0 has no issuer",
"{issuer}"
);
let mut leaf = good.clone();
leaf["issuer"] = issuer.clone();
assert_eq!(
reason(check(&[f.grant.clone(), leaf], &roots, &[])),
"credential 1 has no issuer",
"{issuer}"
);
}
}
#[test]
fn omitted_dimensions_are_inherited_down_the_chain() {
let f = fleet();
let helper = key_party(34);
let sub_intent = intent(
"read",
"calendar",
"https://cal.example/team",
json!({"delegatee": helper.did}),
);
let sub = sign_sub_grant(
&opts(
&f.device,
sub_intent,
"urn:uuid:00000000-0000-4000-8000-000000000004",
(FROM, UNTIL),
None,
),
&grant_chain::grant_digest(&f.grant).unwrap(),
&f.device.seed,
&proof(&f.device),
)
.unwrap();
let ok_leaf = sign(
&helper,
intent("read", "calendar", "https://cal.example/team", json!({})),
"urn:uuid:00000000-0000-4000-8000-000000000005",
);
let roots = roots(&[&f.root]);
let r = check(&[f.grant.clone(), sub.clone(), ok_leaf], &roots, &[]);
assert!(r.ok, "{:?}", r.reason);
let greedy = sign(
&helper,
intent(
"read",
"calendar",
"https://cal.example/team",
json!({"rate": {"limit": 11, "window": "PT1H"}}),
),
"urn:uuid:00000000-0000-4000-8000-000000000006",
);
assert_eq!(
reason(check(&[f.grant.clone(), sub.clone(), greedy], &roots, &[])),
"link 1: rate {'limit': 11, 'window': 'PT1H'} is not within the granted None"
);
let other = sign(
&f.root,
intent(
"read",
"calendar",
"https://cal.example/team",
json!({"delegatee": f.device.did}),
),
"urn:uuid:00000000-0000-4000-8000-000000000007",
);
let leaf = sign(
&helper,
intent("read", "calendar", "https://cal.example/team", json!({})),
"urn:uuid:00000000-0000-4000-8000-000000000008",
);
assert_eq!(
reason(check(&[other, sub, leaf], &roots, &[])),
"credential 1: delegation_parent_mismatch"
);
}
#[test]
fn the_walk_checks_delegatees_revocation_and_windows() {
let f = fleet();
let roots = roots(&[&f.root]);
let good = leaf_by(
&f,
&f.device,
"read",
"calendar",
"https://cal.example/team",
json!({}),
);
let by_impostor = leaf_by(
&f,
&f.impostor,
"read",
"calendar",
"https://cal.example/team",
json!({}),
);
assert_eq!(
reason(check(&[f.grant.clone(), by_impostor.clone()], &roots, &[])),
format!(
"link 0: child issuer '{}' is not the delegatee '{}' the parent authorized",
f.impostor.did, f.device.did
)
);
assert_eq!(
reason(check(
&[f.grant.clone(), good.clone()],
&roots,
std::slice::from_ref(&f.device.did)
)),
format!("credential 1 issuer '{}' is revoked", f.device.did)
);
let leaf_id = good["id"].as_str().unwrap().to_string();
assert_eq!(
reason(check(
&[f.grant.clone(), good.clone()],
&roots,
std::slice::from_ref(&leaf_id)
)),
format!("credential 1 ({leaf_id}) is revoked")
);
assert_eq!(
reason(check(
&[f.grant.clone(), by_impostor],
&roots,
std::slice::from_ref(&f.device.did)
)),
format!("link 0: delegatee '{}' is revoked", f.device.did)
);
assert_eq!(
reason(check(
&[f.grant.clone(), good.clone()],
&roots,
std::slice::from_ref(&f.root.did)
)),
"credential 0 issuer 'did:web:root.example' is revoked"
);
let late = sign_window(
&f.device,
intent("read", "calendar", "https://cal.example/team", json!({})),
"urn:uuid:00000000-0000-4000-8000-000000000009",
(FROM, "2026-11-12T00:00:00Z"),
);
let early = sign_window(
&f.device,
intent("read", "calendar", "https://cal.example/team", json!({})),
"urn:uuid:00000000-0000-4000-8000-000000000010",
("2026-11-09T00:00:00Z", UNTIL),
);
for leaf in [late, early] {
assert_eq!(
reason(check(&[f.grant.clone(), leaf], &roots, &[])),
"link 0: child validity is outside the grant window"
);
}
let no_delegatee = sign(
&f.root,
intent("read", "calendar", "https://cal.example/team", json!({})),
"urn:uuid:00000000-0000-4000-8000-000000000011",
);
assert_eq!(
reason(check(&[no_delegatee, good], &roots, &[])),
"link 0 (grant by 'did:web:root.example') names no delegatee"
);
}
#[test]
fn trust_identity_and_proofs_come_first() {
let f = fleet();
let roots = roots(&[&f.root]);
let good = leaf_by(
&f,
&f.device,
"read",
"calendar",
"https://cal.example/team",
json!({}),
);
assert_eq!(reason(check(&[], &roots, &[])), "empty chain");
assert_eq!(
reason(check(
&[f.grant.clone(), good.clone()],
&BTreeMap::new(),
&[]
)),
"root issuer 'did:web:root.example' is not in trusted_roots"
);
let mut wrong = BTreeMap::new();
wrong.insert(f.root.did.clone(), vec![7u8; 32]);
assert_eq!(
reason(check(&[f.grant.clone(), good.clone()], &wrong, &[])),
"credential 0 failed verification"
);
let mut no_issuer = good.clone();
no_issuer.as_object_mut().unwrap().remove("issuer");
assert_eq!(
reason(check(&[f.grant.clone(), no_issuer], &roots, &[])),
"credential 1 has no issuer"
);
let mut tampered = good.clone();
tampered["credentialSubject"]["intent"]["resource"] = json!("https://cal.example/team/2");
assert_eq!(
reason(check(&[f.grant.clone(), tampered], &roots, &[])),
"credential 1 failed verification"
);
let web_device = web_party(35, "device.example");
let web_grant = sign(
&f.root,
intent(
"read",
"calendar",
"https://cal.example/team",
json!({"delegatee": web_device.did}),
),
"urn:uuid:00000000-0000-4000-8000-000000000012",
);
let web_leaf = leaf_by(
&f,
&web_device,
"read",
"calendar",
"https://cal.example/team",
json!({}),
);
assert_eq!(
reason(check(&[web_grant.clone(), web_leaf.clone()], &roots, &[])),
"credential 1 failed verification"
);
let both = super::tests::roots(&[&f.root, &web_device]);
assert!(check(&[web_grant, web_leaf], &both, &[]).ok);
let sub = sign_sub_grant(
&opts(
&f.device,
intent(
"read",
"calendar",
"https://cal.example/team",
json!({"delegatee": f.impostor.did}),
),
"urn:uuid:00000000-0000-4000-8000-000000000013",
(FROM, UNTIL),
None,
),
&grant_chain::grant_digest(&f.grant).unwrap(),
&f.device.seed,
&proof(&f.device),
)
.unwrap();
assert_eq!(
reason(check(&[sub], &BTreeMap::new(), &[])),
"credential 0: delegation_parent_mismatch"
);
}
#[test]
fn shape_and_binding_come_before_any_key() {
let f = fleet();
let roots = roots(&[&f.root]);
let none = BTreeMap::new();
let good = leaf_by(
&f,
&f.device,
"read",
"calendar",
"https://cal.example/team",
json!({}),
);
for (position, value) in [
(0, json!(f.grant.to_string())),
(1, Value::Null),
(1, json!(["x"])),
(2, json!(7)),
] {
let mut creds = vec![f.grant.clone(), good.clone(), good.clone()];
creds[position] = value;
for r in [&roots, &none] {
assert_eq!(
reason(check(&creds, r, &[])),
format!("credential {position} is not a JSON object")
);
}
}
let named = json!({"issuer": f.device.did,
"credentialSubject": {"parentGrantDigest": "uEiA"}});
assert_eq!(
reason(check(&[named, json!("x")], &roots, &[])),
"credential 1 is not a JSON object"
);
let other = sign(
&f.impostor,
intent(
"read",
"calendar",
"https://cal.example/team",
json!({"delegatee": f.device.did}),
),
"urn:uuid:00000000-0000-4000-8000-000000000020",
);
let link = |grant: &Value| {
json!({"issuer": grant["issuer"], "subject": f.device.did,
"parentCredential": grant})
};
let nested = json!({"issuer": f.device.did, "credentialSubject": {
"intent": {"action": "read", "delegatee": f.impostor.did},
"delegationChain": [link(&other)]}});
assert_eq!(
reason(check(
&[f.grant.clone(), nested.clone(), good.clone()],
&none,
&[]
)),
"credential 1: delegation_parent_mismatch"
);
let elsewhere = json!({"issuer": f.device.did, "credentialSubject": {
"intent": {"action": "read"}, "delegationChain": [link(&other)]}});
assert_eq!(
reason(check(&[f.grant.clone(), elsewhere], &none, &[])),
"credential 1: delegation_parent_mismatch"
);
for subject in [
json!({"delegationChain": null}),
json!({"delegationChain": {}}),
json!({"parentGrantDigest": null}),
json!({"parentGrantDigest": grant_chain::grant_digest(&f.grant).unwrap(),
"delegationChain": [link(&f.grant)]}),
] {
let sub = json!({"issuer": f.device.did, "credentialSubject": subject});
assert_eq!(
reason(check(&[f.grant.clone(), sub, good.clone()], &none, &[])),
"credential 1: malformed_delegation"
);
}
}
#[test]
fn a_post_quantum_root_grant_needs_its_mldsa_key() {
let f = fleet();
let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
let body = crate::credentials::build_vouch_credential(&opts(
&f.root,
intent(
"read",
"calendar",
"https://cal.example/team",
json!({"delegatee": f.device.did}),
),
"urn:uuid:00000000-0000-4000-8000-000000000014",
(FROM, UNTIL),
None,
))
.unwrap();
let dual = hybrid::sign_dual(
&body,
&f.root.seed,
&ml,
&format!("{}#key-1", f.root.did),
&format!("{}#mldsa", f.root.did),
FROM,
)
.unwrap();
let good = leaf_by(
&f,
&f.device,
"read",
"calendar",
"https://cal.example/team",
json!({}),
);
assert_eq!(
reason(check(&[dual, good], &roots(&[&f.root]), &[])),
"credential 0 needs an ML-DSA-44 key"
);
}
#[test]
fn leaf_policy_and_status() {
let f = fleet();
let roots = roots(&[&f.root]);
let good = leaf_by(
&f,
&f.device,
"read",
"calendar",
"https://cal.example/team/1",
json!({}),
);
let creds = [f.grant.clone(), good.clone()];
let with = |action: Option<&str>, target: Option<&str>, resource: Option<&str>| {
verify_delegated_chain(
&creds,
&FleetOptions {
trusted_roots: &roots,
revoked: &[],
now_iso: NOW,
clock_skew_seconds: 30,
require_action: action,
require_target: target,
require_resource: resource,
check_status: true,
status_lists: None,
},
)
};
assert!(
with(
Some("read"),
Some("calendar"),
Some("https://cal.example/team/1")
)
.ok
);
for (r, want) in [
(
with(Some("write"), None, None),
"leaf intent.action != 'write'",
),
(
with(None, Some("mail"), None),
"leaf intent.target != 'mail'",
),
(
with(None, None, Some("https://cal.example/team")),
"leaf intent.resource != 'https://cal.example/team'",
),
] {
assert!(!r.ok);
assert_eq!(r.leaf.as_ref(), Some(&good));
assert_eq!(r.root_did, None);
assert_eq!(r.reason.as_deref(), Some(want));
}
let status = json!({"id": "https://status.example/1#5", "type": "BitstringStatusListEntry",
"statusPurpose": "revocation", "statusListIndex": "5",
"statusListCredential": "https://status.example/1"});
let mut o = opts(
&f.root,
intent(
"read",
"calendar",
"https://cal.example/team",
json!({"delegatee": f.device.did}),
),
"urn:uuid:00000000-0000-4000-8000-000000000015",
(FROM, UNTIL),
None,
);
o.credential_status = Some(status);
let with_status = sign_vouch_credential(&o, &f.root.seed, &proof(&f.root)).unwrap();
let creds = [with_status, good];
let base = FleetOptions {
trusted_roots: &roots,
revoked: &[],
now_iso: NOW,
clock_skew_seconds: 30,
require_action: None,
require_target: None,
require_resource: None,
check_status: true,
status_lists: None,
};
assert_eq!(
verify_delegated_chain(&creds, &base).reason.as_deref(),
Some("credential 0 failed verification")
);
let empty = Map::new();
let listed = FleetOptions {
status_lists: Some(&empty),
..base
};
assert_eq!(
verify_delegated_chain(&creds, &listed).reason.as_deref(),
Some("credential 0 failed verification")
);
let unchecked = FleetOptions {
check_status: false,
..base
};
assert!(verify_delegated_chain(&creds, &unchecked).ok);
}
#[test]
fn embedded_chains_start_at_the_fleet_roots() {
let f = fleet();
let leaf_intent = intent("read", "calendar", "https://cal.example/team", json!({}));
let links =
grant_chain::check_grant_chain(std::slice::from_ref(&f.grant), &leaf_intent).unwrap();
let leaf = sign_vouch_credential(
&opts(
&f.device,
leaf_intent,
"urn:uuid:00000000-0000-4000-8000-000000000016",
(FROM, UNTIL),
Some(links),
),
&f.device.seed,
&proof(&f.device),
)
.unwrap();
assert!(check(&[f.grant.clone(), leaf.clone()], &roots(&[&f.root]), &[]).ok);
let other = web_party(36, "other.example");
let mut two = roots(&[&f.root]);
two.insert(other.did.clone(), public(&other));
assert!(check(&[f.grant.clone(), leaf.clone()], &two, &[]).ok);
let mut wrong_key = roots(&[&f.root]);
wrong_key.insert(f.root.did.clone(), public(&other));
assert_eq!(
reason(check(&[f.grant.clone(), leaf], &wrong_key, &[])),
"credential 0 failed verification"
);
}
#[test]
fn revocation_candidates_cover_every_identifier_asked_about() {
let f = fleet();
let good = leaf_by(
&f,
&f.device,
"read",
"calendar",
"https://cal.example/team",
json!({}),
);
assert_eq!(
revocation_candidates(&[f.grant.clone(), good]),
vec![
"did:web:root.example".to_string(),
"urn:uuid:00000000-0000-4000-8000-000000000001".to_string(),
f.device.did.clone(),
"urn:uuid:00000000-0000-4000-8000-000000000002".to_string(),
]
);
assert!(
revocation_candidates(&[json!("x"), json!({"issuer": ["did:web:a"]})])
.contains(&"did:web:a".to_string())
);
}
}