Skip to main content

atlas_pca/
lib.rs

1//! Reference verifier for the CORE PCActn checks (wire format v2): wire, version, audience, validity,
2//! capability chain, grant_ref binding, Merkle plan inclusion, strict Ed25519 leaf signature, counter. Byte-matches
3//! `@atlasauth/pca` (the shared conformance corpus defines the normative rules).
4
5use base64::engine::general_purpose::URL_SAFE_NO_PAD;
6use base64::Engine;
7use curve25519_dalek::edwards::CompressedEdwardsY as CompressedEdwards;
8use curve25519_dalek::scalar::Scalar;
9use ed25519_dalek::{Signature, VerifyingKey};
10use serde_json::{Map, Number, Value};
11use sha2::{Digest, Sha256};
12use std::collections::BTreeMap;
13use std::fmt::Write;
14
15pub use serde_json;
16
17/// Ergonomic tower / axum middleware built on top of this verifier (feature `axum`).
18#[cfg(feature = "axum")]
19pub mod middleware;
20
21// Intent Layer v2 (rules 13-18 and the V5 `layers` check).
22mod action_schema;
23mod intent_acc;
24mod intent_map;
25mod intent_strict;
26mod intent_revocation;
27mod intent_session;
28mod intent_suite;
29mod intent_v2;
30mod intent_wb;
31mod predicates;
32mod safe_regex;
33#[cfg(test)]
34mod k042_support;
35
36pub use action_schema::{action_schema_digest, action_schema_shape_error, conform_action, verify_action_schema, ConformResult};
37pub use intent_acc::{
38    acc_receipt_digest, pcactn_reservation_digest, sequencer_key_set_digest, DEFAULT_MAX_KEYSET_AGE_MS, DEFAULT_MAX_RECEIPT_AGE_MS, MAX_RECEIPT_LIFETIME_MS, RECEIPT_SKEW_MS,
39};
40pub use intent_map::{decide_map_disclosure, map_commit_of_leaves, MapDecision};
41pub use intent_revocation::{
42    check_session_revocation, delta_revocation_id, map_revocation_id, profile_revocation_id, revocation_epoch_shape_error, revset_root,
43    session_revocation_id, session_revocation_scope,
44};
45pub use intent_session::{
46    intent_session_caveat_error, session_root_digest, session_root_shape_error, validate_intent_session_wire, verify_session_root, verify_session_root_pinned, MAP_FORM_COMMIT,
47    MAX_SESSION_SEQ,
48};
49pub use intent_v2::{decide_intent_v2, intent_v2_active, intent_v2_context_error, IntentV2Check, IntentV2Context, IntentV2Decision};
50pub use intent_wb::{
51    decide_classifier_dimensions, decide_intent_wb, decide_intent_world, decide_param_provenance, decide_read_purpose, intent_wb_active, ClassifierDecision, IntentWbResult,
52    IntentWorldDecision, ProvenanceDecision, WbCheck,
53};
54
55const SIG_DOMAIN: &[u8] = b"atlas-pca/actn/v2\x00";
56const CAP_DOMAIN: &[u8] = b"atlas-pca/cap/v1\x00";
57const SHARE_DOMAIN_PREFIX: &[u8] = b"atlas-pca/share/";
58const SIGNERSET_DOMAIN: &[u8] = b"atlas-pca/signerset/v1\x00";
59const SHARE_SUITE_TAG: &[u8] = b"\x00atlas-pca/share-suite/v1\x00";
60const DEFAULT_REV: &str = "reversible";
61
62/// Wire format version this verifier accepts.
63pub const PCACTN_WIRE_VERSION: i64 = 2;
64pub const MAX_CHAIN_DEPTH: usize = 16;
65/// Shared hard caveat caps (all PCA verifiers): per-hop cumulative list, and the sum over every hop of a chain.
66pub const MAX_CAVEATS_PER_HOP: usize = 256;
67pub const MAX_CAVEATS_PER_CHAIN: usize = 1024;
68/// Shared reason string for the caveat caps (identical across all PCA verifiers).
69pub const CAVEAT_LIMIT_REASON: &str = "chain exceeds caveat limit (max 256 per hop, 1024 per chain)";
70/// Shared raw wire-size cap of a PCActn JSON document (UTF-8 bytes), checked before any parsing.
71pub const MAX_ARTIFACT_BYTES: usize = 524_288;
72/// Shared reason string for the raw-size cap (identical across all PCA verifiers).
73pub const ARTIFACT_SIZE_REASON: &str = "artifact exceeds size limit (max 524288 bytes)";
74
75/// True when the chain breaks the caveat caps; reads raw list sizes only, so it runs before any hashing/signature work.
76pub fn caveat_limit_exceeded(chain: &[Value]) -> bool {
77    let mut total = 0usize;
78    for c in chain {
79        let n = c.get("caveats").and_then(Value::as_array).map_or(0, Vec::len);
80        if n > MAX_CAVEATS_PER_HOP {
81            return true;
82        }
83        total += n;
84        if total > MAX_CAVEATS_PER_CHAIN {
85            return true;
86        }
87    }
88    false
89}
90pub const MAX_JSON_DEPTH: usize = 32;
91pub const MAX_JSON_CHARS: usize = 1 << 20;
92pub const MAX_DECIMAL_DIGITS: usize = 15;
93pub const MAX_LIFETIME_MS: i64 = 3_600_000;
94pub const MAX_SKEW_MS: i64 = 60_000;
95const MAX_SAFE: i64 = 9_007_199_254_740_991;
96const MAX_AUD_LEN: usize = 256;
97const MAX_NONCE_LEN: usize = 128;
98
99fn b64_encode(b: &[u8]) -> String {
100    URL_SAFE_NO_PAD.encode(b)
101}
102
103/// STRICT base64url (RFC 4648 section 5, no padding): only `[A-Za-z0-9_-]`, no whitespace, `len % 4 != 1`,
104/// zero trailing bits (re-encoding must reproduce the input). When `len` is given the DECODED length must
105/// equal it. Returns `None` on ANY deviation.
106pub fn decode_b64u_strict(s: &str, len: Option<usize>) -> Option<Vec<u8>> {
107    let b = s.as_bytes();
108    if !b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-' || *c == b'_') {
109        return None;
110    }
111    if b.len() % 4 == 1 {
112        return None;
113    }
114    if let Some(n) = len {
115        // checked: a caller-supplied n > usize::MAX/4 must fail closed, not panic (debug) or wrap (release)
116        match n.checked_mul(4) {
117            Some(m) if b.len() == m.div_ceil(3) => {}
118            _ => return None,
119        }
120    }
121    let bytes = URL_SAFE_NO_PAD.decode(b).ok()?;
122    if b64_encode(&bytes) != s {
123        return None; // non-canonical trailing bits
124    }
125    if let Some(n) = len {
126        if bytes.len() != n {
127            return None;
128        }
129    }
130    Some(bytes)
131}
132
133/// Verdict for the core checks. `checks[name]` is true when it passed. A wire failure is terminal and is
134/// the ONLY entry (`{wire: false}`); otherwise all of wire, version, audience, validity, chain,
135/// plan_inclusion, leaf_signature, counter are present.
136#[derive(Debug, Clone)]
137pub struct Verdict {
138    pub allow: bool,
139    pub checks: BTreeMap<String, bool>,
140    pub reason: String,
141}
142
143fn wire_fail(why: impl Into<String>) -> Verdict {
144    let mut checks = BTreeMap::new();
145    checks.insert("wire".to_string(), false);
146    Verdict { allow: false, checks, reason: format!("wire: {}", why.into()) }
147}
148
149// ---- numbers ---------------------------------------------------------------------------
150
151/// Strict-profile check of one JSON number (see README section 3). `None` when acceptable.
152fn number_error(n: &Number) -> Option<String> {
153    if let Some(i) = n.as_i64() {
154        return if i.unsigned_abs() > MAX_SAFE as u64 {
155            Some("integer outside the safe range (|n| > 2^53-1)".into())
156        } else {
157            None
158        };
159    }
160    if let Some(u) = n.as_u64() {
161        return if u > MAX_SAFE as u64 { Some("integer outside the safe range (|n| > 2^53-1)".into()) } else { None };
162    }
163    let f = match n.as_f64() {
164        Some(f) if f.is_finite() => f,
165        _ => return Some("non-finite number".into()),
166    };
167    if f == 0.0 && f.is_sign_negative() {
168        return Some("negative zero".into());
169    }
170    if f.fract() == 0.0 {
171        return if f.abs() > MAX_SAFE as f64 { Some("integer outside the safe range (|n| > 2^53-1)".into()) } else { None };
172    }
173    if f.abs() < 1e-6 {
174        return Some("non-integer magnitude below 1e-6 (needs an exponent form; not representable in the canonical decimal form)".into());
175    }
176    // Rust's Display for f64 is the shortest round-trip decimal and never uses an exponent.
177    let s = format!("{}", f.abs());
178    let digits: String = s.chars().filter(|c| *c != '.').collect();
179    if digits.trim_start_matches('0').len() > MAX_DECIMAL_DIGITS {
180        return Some("non-integer number has more than 15 significant digits".into());
181    }
182    None
183}
184
185/// A value that is a strictly-valid number AND integer-valued.
186fn safe_int(v: &Value) -> Option<i64> {
187    let n = match v {
188        Value::Number(n) => n,
189        _ => return None,
190    };
191    if number_error(n).is_some() {
192        return None;
193    }
194    if let Some(i) = n.as_i64() {
195        return Some(i);
196    }
197    if let Some(u) = n.as_u64() {
198        return i64::try_from(u).ok();
199    }
200    let f = n.as_f64()?;
201    if f.fract() == 0.0 {
202        Some(f as i64)
203    } else {
204        None
205    }
206}
207
208fn fmt_number(n: &Number) -> String {
209    if let Some(i) = n.as_i64() {
210        return i.to_string();
211    }
212    if let Some(u) = n.as_u64() {
213        return u.to_string();
214    }
215    let f = n.as_f64().unwrap_or(0.0);
216    if f == 0.0 {
217        return "0".to_string();
218    }
219    // Rust's Display for f64 is shortest round-trip and never uses exponent notation.
220    format!("{}", f)
221}
222
223// ---- canonicalization ------------------------------------------------------------------
224
225/// LENIENT canonical JSON (capability content addressing, Merkle leaves): keys sorted BYTEWISE over UTF-8,
226/// compact, escape only `"` `\` and < U+0020, shortest round-trip numbers, `-0` -> `0`.
227pub fn canonicalize(v: &Value) -> String {
228    let mut s = String::new();
229    let _ = ser(&mut s, v, false, 1);
230    s
231}
232
233/// STRICT canonical form of a signed PCActn body (wire v2): as [`canonicalize`] plus integer-valued numbers
234/// must be safe integers (no `-0`), non-integers plain decimal <= 15 significant digits and >= 1e-6, and
235/// nesting depth <= 32. Errs on any violation.
236pub fn canonicalize_strict(v: &Value) -> Result<String, String> {
237    let mut s = String::new();
238    ser(&mut s, v, true, 1)?;
239    Ok(s)
240}
241
242fn js_string(out: &mut String, s: &str) {
243    out.push('"');
244    for c in s.chars() {
245        match c {
246            '"' => out.push_str("\\\""),
247            '\\' => out.push_str("\\\\"),
248            '\u{8}' => out.push_str("\\b"),
249            '\u{c}' => out.push_str("\\f"),
250            '\n' => out.push_str("\\n"),
251            '\r' => out.push_str("\\r"),
252            '\t' => out.push_str("\\t"),
253            c if (c as u32) < 0x20 => {
254                let _ = write!(out, "\\u{:04x}", c as u32);
255            }
256            c => out.push(c),
257        }
258    }
259    out.push('"');
260}
261
262fn ser(out: &mut String, v: &Value, strict: bool, depth: usize) -> Result<(), String> {
263    match v {
264        Value::Null => out.push_str("null"),
265        Value::Bool(true) => out.push_str("true"),
266        Value::Bool(false) => out.push_str("false"),
267        Value::String(s) => js_string(out, s),
268        Value::Number(n) => {
269            if strict {
270                if let Some(e) = number_error(n) {
271                    return Err(format!("canonicalize: {e}"));
272                }
273            }
274            out.push_str(&fmt_number(n));
275        }
276        Value::Array(a) => {
277            if strict && depth > MAX_JSON_DEPTH {
278                return Err("canonicalize: nesting too deep".into());
279            }
280            out.push('[');
281            for (i, x) in a.iter().enumerate() {
282                if i > 0 {
283                    out.push(',');
284                }
285                ser(out, x, strict, depth + 1)?;
286            }
287            out.push(']');
288        }
289        Value::Object(m) => {
290            if strict && depth > MAX_JSON_DEPTH {
291                return Err("canonicalize: nesting too deep".into());
292            }
293            // String ordering is bytewise over UTF-8 (== code point order).
294            let mut keys: Vec<&String> = m.keys().collect();
295            keys.sort();
296            out.push('{');
297            for (i, k) in keys.iter().enumerate() {
298                if i > 0 {
299                    out.push(',');
300                }
301                js_string(out, k);
302                out.push(':');
303                ser(out, &m[k.as_str()], strict, depth + 1)?;
304            }
305            out.push('}');
306        }
307    }
308    Ok(())
309}
310
311fn sha(b: &[u8]) -> Vec<u8> {
312    Sha256::digest(b).to_vec()
313}
314
315/// base64url-nopad(sha256(canonical(v))) (lenient canonical form). Content addressing only: the verifiers never
316/// use it for a protocol digest (see [`hash_canonical_strict`]).
317pub fn hash_canonical(v: &Value) -> String {
318    b64_encode(&sha(canonicalize(v).as_bytes()))
319}
320
321/// base64url-nopad(sha256(STRICT canonical(v))), like the reference `hashCanonical` (hash.ts `canonicalBytes` is
322/// `canonicalizeStrict`): depth <= [`MAX_JSON_DEPTH`], safe integers only, plain-decimal non-integers. `None` on an
323/// out-of-profile value. Every protocol digest the verifiers compute (capability / grant hash, hop body digest,
324/// caveat comparison, Merkle leaf) goes through it: a lenient digest would accept a correctly signed out-of-profile hop
325/// that the reference refuses, and would recurse without bound on a deep caller-built value.
326pub fn hash_canonical_strict(v: &Value) -> Option<String> {
327    canonicalize_strict(v).ok().map(|c| b64_encode(&sha(c.as_bytes())))
328}
329
330/// `a` and `b` have the same strict digest; `false` when either is out of profile (never equal-by-both-failing).
331fn same_strict_hash(a: &Value, b: &Value) -> bool {
332    matches!((hash_canonical_strict(a), hash_canonical_strict(b)), (Some(x), Some(y)) if x == y)
333}
334
335// ---- strict JSON parser ----------------------------------------------------------------
336
337/// STRICT JSON profile for signed bytes (README section 2): hand-written RFC 8259 parser rejecting comments,
338/// trailing commas, a BOM, non-JSON whitespace, duplicate keys (post-unescape), lone surrogates (raw or
339/// escaped), raw control chars in strings, unknown escapes, nesting > 32, input > 2^20 UTF-8 bytes, and any
340/// number not in the canonical wire form. Returns any JSON value (the PCActn check requires an object).
341pub fn strict_parse(text: &str) -> Result<Value, String> {
342    strict_parse_depth(text, MAX_JSON_DEPTH)
343}
344
345/// R6-01: [`strict_parse`] for an untrusted transport envelope that WRAPS a PCActn one level deep (the middleware body
346/// `{"pcactn": ...}`): the same strict profile (duplicate keys refused at ANY depth, strict numbers, no lone surrogates,
347/// size cap) with the depth cap `MAX_JSON_DEPTH` applied to the WHOLE envelope, as the reference does (require-pca.ts
348/// `defaultExtract` strict-parses the body text): the wrapped PCActn therefore gets one level less than in header mode.
349pub fn strict_parse_envelope(text: &str) -> Result<Value, String> {
350    strict_parse_depth(text, MAX_JSON_DEPTH)
351}
352
353fn strict_parse_depth(text: &str, max_depth: usize) -> Result<Value, String> {
354    if text.len() > MAX_JSON_CHARS {
355        return Err("strict JSON: input too large".into());
356    }
357    let mut p = Parser { b: text.as_bytes(), i: 0, max_depth };
358    let v = p.value(1)?;
359    p.ws();
360    if p.i < p.b.len() {
361        return Err(p.err("trailing characters after the JSON value"));
362    }
363    Ok(v)
364}
365
366struct Parser<'a> {
367    b: &'a [u8],
368    i: usize,
369    max_depth: usize,
370}
371
372impl<'a> Parser<'a> {
373    fn err(&self, m: &str) -> String {
374        format!("strict JSON: {m} (at offset {})", self.i)
375    }
376
377    fn peek(&self) -> Option<u8> {
378        self.b.get(self.i).copied()
379    }
380
381    fn ws(&mut self) {
382        while let Some(c) = self.peek() {
383            if c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' {
384                self.i += 1;
385            } else {
386                break;
387            }
388        }
389    }
390
391    /// `self.i` points at the `u`; reads 4 hex digits and leaves `self.i` on the last one.
392    fn hex4(&mut self) -> Result<u32, String> {
393        let s = self.b.get(self.i + 1..self.i + 5).ok_or_else(|| self.err("bad \\u escape"))?;
394        if !s.iter().all(|c| c.is_ascii_hexdigit()) {
395            return Err(self.err("bad \\u escape"));
396        }
397        let h = std::str::from_utf8(s).map_err(|_| self.err("bad \\u escape"))?;
398        let v = u32::from_str_radix(h, 16).map_err(|_| self.err("bad \\u escape"))?;
399        self.i += 4;
400        Ok(v)
401    }
402
403    fn string(&mut self) -> Result<String, String> {
404        self.i += 1; // opening quote
405        let mut out: Vec<u8> = Vec::new();
406        loop {
407            let c = match self.peek() {
408                Some(c) => c,
409                None => return Err(self.err("unterminated string")),
410            };
411            match c {
412                b'"' => {
413                    self.i += 1;
414                    break;
415                }
416                0..=0x1f => return Err(self.err("raw control character in string")),
417                b'\\' => {
418                    self.i += 1;
419                    let e = match self.peek() {
420                        Some(e) => e,
421                        None => return Err(self.err("unterminated string")),
422                    };
423                    match e {
424                        b'"' => out.push(b'"'),
425                        b'\\' => out.push(b'\\'),
426                        b'/' => out.push(b'/'),
427                        b'b' => out.push(0x08),
428                        b'f' => out.push(0x0c),
429                        b'n' => out.push(b'\n'),
430                        b'r' => out.push(b'\r'),
431                        b't' => out.push(b'\t'),
432                        b'u' => {
433                            let hi = self.hex4()?;
434                            let cp = if (0xD800..=0xDBFF).contains(&hi) {
435                                if self.b.get(self.i + 1) == Some(&b'\\') && self.b.get(self.i + 2) == Some(&b'u') {
436                                    self.i += 2;
437                                    let lo = self.hex4()?;
438                                    if !(0xDC00..=0xDFFF).contains(&lo) {
439                                        return Err(self.err("lone surrogate in string"));
440                                    }
441                                    0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00)
442                                } else {
443                                    return Err(self.err("lone surrogate in string"));
444                                }
445                            } else if (0xDC00..=0xDFFF).contains(&hi) {
446                                return Err(self.err("lone surrogate in string"));
447                            } else {
448                                hi
449                            };
450                            let ch = char::from_u32(cp).ok_or_else(|| self.err("bad code point"))?;
451                            let mut buf = [0u8; 4];
452                            out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
453                        }
454                        _ => return Err(self.err("unknown escape")),
455                    }
456                    self.i += 1;
457                }
458                _ => {
459                    out.push(c);
460                    self.i += 1;
461                }
462            }
463        }
464        String::from_utf8(out).map_err(|_| self.err("invalid UTF-8"))
465    }
466
467    fn number(&mut self) -> Result<Value, String> {
468        let start = self.i;
469        if self.peek() == Some(b'-') {
470            self.i += 1;
471        }
472        match self.peek() {
473            Some(b'0') => self.i += 1,
474            Some(b'1'..=b'9') => {
475                while matches!(self.peek(), Some(b'0'..=b'9')) {
476                    self.i += 1;
477                }
478            }
479            _ => return Err(self.err("bad number")),
480        }
481        let mut frac = false;
482        if self.peek() == Some(b'.') {
483            self.i += 1;
484            if !matches!(self.peek(), Some(b'0'..=b'9')) {
485                return Err(self.err("bad number"));
486            }
487            while matches!(self.peek(), Some(b'0'..=b'9')) {
488                self.i += 1;
489            }
490            frac = true;
491        }
492        if matches!(self.peek(), Some(b'e') | Some(b'E')) {
493            return Err(self.err("exponent form is not allowed (use a plain decimal)"));
494        }
495        let lex = std::str::from_utf8(&self.b[start..self.i]).map_err(|_| self.err("bad number"))?;
496        if lex == "-0" {
497            return Err(self.err("negative zero is not allowed"));
498        }
499        // a leading zero followed by a digit ("01") leaves a digit behind: rejected by the caller's
500        // structural check ("expected , or }"), exactly like the reference parser.
501        if frac {
502            if lex.ends_with('0') {
503                return Err(self.err("trailing fractional zero is not canonical"));
504            }
505            let digits: String = lex.chars().filter(|c| *c != '-' && *c != '.').collect();
506            if digits.trim_start_matches('0').len() > MAX_DECIMAL_DIGITS {
507                return Err(self.err("more than 15 significant digits"));
508            }
509            let v: f64 = lex.parse().map_err(|_| self.err("bad number"))?;
510            if v != 0.0 && v.abs() < 1e-6 {
511                return Err(self.err("non-integer magnitude below 1e-6 is not allowed"));
512            }
513            let n = Number::from_f64(v).ok_or_else(|| self.err("bad number"))?;
514            Ok(Value::Number(n))
515        } else {
516            let abs = lex.trim_start_matches('-');
517            if abs.len() > 16 {
518                return Err(self.err("integer outside the safe range"));
519            }
520            let mag: i64 = abs.parse().map_err(|_| self.err("bad number"))?;
521            if mag > MAX_SAFE {
522                return Err(self.err("integer outside the safe range"));
523            }
524            Ok(Value::Number(Number::from(if lex.starts_with('-') { -mag } else { mag })))
525        }
526    }
527
528    fn value(&mut self, depth: usize) -> Result<Value, String> {
529        self.ws();
530        let ch = match self.peek() {
531            Some(c) => c,
532            None => return Err(self.err("unexpected end of input")),
533        };
534        match ch {
535            b'{' => {
536                if depth > self.max_depth {
537                    return Err(self.err("nesting too deep"));
538                }
539                self.i += 1;
540                let mut o = Map::new();
541                self.ws();
542                if self.peek() == Some(b'}') {
543                    self.i += 1;
544                    return Ok(Value::Object(o));
545                }
546                loop {
547                    self.ws();
548                    if self.peek() != Some(b'"') {
549                        return Err(self.err("expected a string key"));
550                    }
551                    let k = self.string()?;
552                    if o.contains_key(&k) {
553                        return Err(self.err("duplicate key"));
554                    }
555                    self.ws();
556                    if self.peek() != Some(b':') {
557                        return Err(self.err("expected \":\""));
558                    }
559                    self.i += 1;
560                    let v = self.value(depth + 1)?;
561                    o.insert(k, v);
562                    self.ws();
563                    match self.peek() {
564                        Some(b',') => self.i += 1,
565                        Some(b'}') => {
566                            self.i += 1;
567                            return Ok(Value::Object(o));
568                        }
569                        _ => return Err(self.err("expected \",\" or \"}\"")),
570                    }
571                }
572            }
573            b'[' => {
574                if depth > self.max_depth {
575                    return Err(self.err("nesting too deep"));
576                }
577                self.i += 1;
578                let mut a = Vec::new();
579                self.ws();
580                if self.peek() == Some(b']') {
581                    self.i += 1;
582                    return Ok(Value::Array(a));
583                }
584                loop {
585                    a.push(self.value(depth + 1)?);
586                    self.ws();
587                    match self.peek() {
588                        Some(b',') => self.i += 1,
589                        Some(b']') => {
590                            self.i += 1;
591                            return Ok(Value::Array(a));
592                        }
593                        _ => return Err(self.err("expected \",\" or \"]\"")),
594                    }
595                }
596            }
597            b'"' => Ok(Value::String(self.string()?)),
598            b'-' | b'0'..=b'9' => self.number(),
599            _ => {
600                let rest = &self.b[self.i..];
601                if rest.starts_with(b"true") {
602                    self.i += 4;
603                    Ok(Value::Bool(true))
604                } else if rest.starts_with(b"false") {
605                    self.i += 5;
606                    Ok(Value::Bool(false))
607                } else if rest.starts_with(b"null") {
608                    self.i += 4;
609                    Ok(Value::Null)
610                } else {
611                    Err(self.err("unexpected token"))
612                }
613            }
614        }
615    }
616}
617
618// ---- Merkle ----------------------------------------------------------------------------
619
620/// Merkle leaf hash over the STRICT canonical form (like the reference); `None` on an out-of-profile leaf.
621fn leaf_hash(leaf: &Value) -> Option<Vec<u8>> {
622    let mut m = vec![0x00u8];
623    m.extend_from_slice(canonicalize_strict(leaf).ok()?.as_bytes());
624    Some(sha(&m))
625}
626
627fn node_hash(l: &[u8], r: &[u8]) -> Vec<u8> {
628    let mut m = Vec::with_capacity(1 + l.len() + r.len());
629    m.push(0x01);
630    m.extend_from_slice(l);
631    m.extend_from_slice(r);
632    sha(&m)
633}
634
635fn split(n: u64) -> u64 {
636    let mut k = 1u64;
637    while k * 2 < n {
638        k *= 2;
639    }
640    k
641}
642
643fn build(hs: &[Vec<u8>]) -> Vec<u8> {
644    if hs.len() == 1 {
645        return hs[0].clone();
646    }
647    let k = split(hs.len() as u64) as usize;
648    node_hash(&build(&hs[..k]), &build(&hs[k..]))
649}
650
651/// RFC-6962-shaped Merkle root (split at the largest power of two < n).
652pub fn merkle_root(leaves: &[Value]) -> Result<String, String> {
653    if leaves.is_empty() {
654        return Err("empty leaf set".into());
655    }
656    let hs: Vec<Vec<u8>> = leaves.iter().map(leaf_hash).collect::<Option<_>>().ok_or("leaf is outside the strict JSON profile")?;
657    Ok(b64_encode(&build(&hs)))
658}
659
660/// Sibling sides (leaf -> root) for leaf `index` in a tree of `size` leaves (RFC 6962 split).
661fn path_shape(index: u64, size: u64) -> Vec<u8> {
662    let mut out = Vec::new();
663    let mut idx = index;
664    let mut n = size;
665    while n > 1 {
666        let k = split(n);
667        if idx < k {
668            out.push(b'R');
669            n = k;
670        } else {
671            out.push(b'L');
672            idx -= k;
673            n -= k;
674        }
675    }
676    out.reverse();
677    out
678}
679
680/// Never panics; malformed proofs return false. `index`/`size` are bound to the path shape
681/// (`size >= 1`, `0 <= index < size`, path length and every side recomputed from them).
682pub fn verify_inclusion(root: &str, proof: Option<&Map<String, Value>>, leaf: &Value) -> bool {
683    let proof = match proof {
684        Some(p) => p,
685        None => return false,
686    };
687    let path = match proof.get("path").and_then(Value::as_array) {
688        Some(p) => p,
689        None => return false,
690    };
691    let (index, size) = match (proof.get("index").and_then(safe_int), proof.get("size").and_then(safe_int)) {
692        (Some(i), Some(s)) => (i, s),
693        _ => return false,
694    };
695    if size < 1 || index < 0 || index >= size {
696        return false;
697    }
698    let shape = path_shape(index as u64, size as u64);
699    if shape.len() != path.len() {
700        return false;
701    }
702    let mut h = match leaf_hash(leaf) {
703        Some(h) => h,
704        None => return false,
705    };
706    for (i, s) in path.iter().enumerate() {
707        let step = match s.as_object() {
708            Some(s) => s,
709            None => return false,
710        };
711        let side = step.get("side").and_then(Value::as_str).unwrap_or("");
712        if side.as_bytes() != [shape[i]] {
713            return false;
714        }
715        let sib = match step.get("hash").and_then(Value::as_str).and_then(|x| decode_b64u_strict(x, Some(32))) {
716            Some(b) => b,
717            None => return false,
718        };
719        h = if side == "L" { node_hash(&sib, &h) } else { node_hash(&h, &sib) };
720    }
721    b64_encode(&h) == root
722}
723
724/// hashCanonical(params ?? {}).
725pub fn params_digest(params: Option<&Value>) -> String {
726    match params {
727        Some(p) if !p.is_null() => hash_canonical(p),
728        _ => hash_canonical(&Value::Object(Map::new())),
729    }
730}
731
732fn conditions_digest_default() -> String {
733    let mut m = Map::new();
734    m.insert("pre".into(), Value::Null);
735    m.insert("post".into(), Value::Null);
736    hash_canonical(&Value::Object(m))
737}
738
739fn plan_leaf(node_id: Option<&Value>, action: Option<&Map<String, Value>>, cond: &str) -> Option<Value> {
740    let node_id = match node_id {
741        Some(v) if !v.is_null() => v.clone(),
742        _ => return None,
743    };
744    let get = |k: &str| action.and_then(|a| a.get(k)).cloned().unwrap_or(Value::Null);
745    let pd = match get("params_digest") {
746        Value::Null => Value::String(params_digest(None)),
747        v => v,
748    };
749    let rc = match get("reversibility_class") {
750        Value::Null => Value::String(DEFAULT_REV.into()),
751        v => v,
752    };
753    let mut m = Map::new();
754    m.insert("node_id".into(), node_id);
755    m.insert("verb".into(), get("verb"));
756    m.insert("resource".into(), get("resource"));
757    m.insert("params_digest".into(), pd);
758    m.insert("reversibility_class".into(), rc);
759    m.insert("conditions".into(), Value::String(cond.to_string()));
760    Some(Value::Object(m))
761}
762
763// ---- keys ------------------------------------------------------------------------------
764
765/// STRICT RFC 8032 verification: exact lengths, canonical base64url, canonical point encodings (y < p),
766/// canonical S (S < L), rejects small-order AND mixed-order (torsion) public key and R, then
767/// `verify_strict` (cofactorless equation, also rejecting weak keys).
768fn verify_b64u(pubkey: &str, msg: &[u8], sig: &str) -> bool {
769    let pk = match decode_b64u_strict(pubkey, Some(32)).and_then(|b| <[u8; 32]>::try_from(b).ok()) {
770        Some(a) => a,
771        None => return false,
772    };
773    let sg = match decode_b64u_strict(sig, Some(64)).and_then(|b| <[u8; 64]>::try_from(b).ok()) {
774        Some(a) => a,
775        None => return false,
776    };
777    verify_ed25519_strict(&pk, msg, &sg)
778}
779
780fn verify_ed25519_strict(pk: &[u8; 32], msg: &[u8], sg: &[u8; 64]) -> bool {
781    let a = match CompressedEdwards(*pk).decompress() {
782        Some(p) => p,
783        None => return false,
784    };
785    if a.compress().to_bytes() != *pk {
786        return false; // non-canonical encoding of A
787    }
788    let mut rb = [0u8; 32];
789    rb.copy_from_slice(&sg[..32]);
790    let r = match CompressedEdwards(rb).decompress() {
791        Some(p) => p,
792        None => return false,
793    };
794    if r.compress().to_bytes() != rb {
795        return false; // non-canonical encoding of R
796    }
797    if a.is_small_order() || r.is_small_order() || !a.is_torsion_free() || !r.is_torsion_free() {
798        return false;
799    }
800    let mut sb = [0u8; 32];
801    sb.copy_from_slice(&sg[32..]);
802    if !bool::from(Scalar::from_canonical_bytes(sb).is_some()) {
803        return false; // S >= L
804    }
805    let vk = match VerifyingKey::from_bytes(pk) {
806        Ok(v) => v,
807        Err(_) => return false,
808    };
809    vk.verify_strict(msg, &Signature::from_bytes(sg)).is_ok()
810}
811
812// ---- B4 post-quantum crypto-agility (FIPS 204 / 205 / 206) ----------------------------
813//
814// An ADDITIVE, backward-compatible algorithm-agility slot for the PCActn leaf signature, mirroring
815// `@atlasauth/pca` (packages/pca/src/pq.ts). Absent `alg` (or `alg == "ed25519"`) is BYTE-IDENTICAL to the pre-B4 wire.
816// Suite capability (packages/pca/conformance/SUITES.md): this crate implements every registered suite Rust has a vetted,
817// pure-Rust primitive for (pure mode, EMPTY context, = @noble/post-quantum):
818//   - ML-DSA-65 / ML-DSA-87 (FIPS 204, `fips204`), SLH-DSA-SHA2-128f / -256s (FIPS 205, `fips205`): pure suites
819//     (`sig` = the PQ signature under the resolved `pq_pk`) and `hybrid-ed25519-*` (Ed25519 `sig` under the holder,
820//     checked FIRST, AND the PQ `pq_sig`, same message); `hybrid-nested-ed25519-ml-dsa-65` (SUF-CMA: the PQ half signs
821//     msg || the 64 Ed25519 signature bytes).
822//   - FN-DSA-512 / -1024 (FIPS 206, `fn-dsa-vrfy`, the crate the TS reference wraps; DOMAIN_NONE + HASH_ID_RAW): pure.
823//   - LESS (`less-cat1`, `hybrid-ed25519-less-cat1`; a NIST round-2 candidate, not a standard) only with the cargo feature
824//     `less`: the patched reference C (sdks/pca-less-c, less-252-45) through FFI; the signature is variable-length
825//     (1,153..1,329 bytes in steps of 16). Without the feature both fail closed with `unsupported_suite: <alg>`.
826// An unregistered alg keeps `unknown signature alg`.
827// `alg` and `pq_pk` are SIGNED; `sig` and `pq_sig` are the signatures, stripped from the signed body.
828
829/// ML-DSA-65 (FIPS-204, category 3) encoded sizes, in bytes.
830pub const ML_DSA_65_PUBLIC_KEY_BYTES: usize = 1952;
831pub const ML_DSA_65_SIGNATURE_BYTES: usize = 3309;
832
833/// The reason token of a REGISTERED suite this verifier does not implement (the full reason is `unsupported_suite: <alg>`).
834pub const UNSUPPORTED_SUITE_REASON: &str = "unsupported_suite";
835
836/// The closed TS suite registry (`SIG_SUITES` in packages/pca/src/pq.ts), in registry order.
837pub const REGISTERED_SUITES: &[&str] = &[
838    "ed25519",
839    "ml-dsa-65",
840    "hybrid-ed25519-ml-dsa-65",
841    "hybrid-nested-ed25519-ml-dsa-65",
842    "slh-dsa-sha2-128f",
843    "hybrid-ed25519-slh-dsa-sha2-128f",
844    "ml-dsa-87",
845    "hybrid-ed25519-ml-dsa-87",
846    "slh-dsa-sha2-256s",
847    "hybrid-ed25519-slh-dsa-sha2-256s",
848    "fn-dsa-512",
849    "fn-dsa-1024",
850    "less-cat1",
851    "hybrid-ed25519-less-cat1",
852];
853
854/// The capability manifest: the registered suites this crate implements, in registry order.
855pub fn supported_suites() -> Vec<&'static str> {
856    REGISTERED_SUITES.iter().copied().filter(|a| sig_suite(a).is_some()).collect()
857}
858
859/// `unsupported_suite: <alg>` for a registered suite this crate does not implement, else `unknown signature alg`.
860fn suite_refusal(alg: Option<&Value>) -> String {
861    match alg {
862        Some(Value::String(s)) if REGISTERED_SUITES.contains(&s.as_str()) => format!("{UNSUPPORTED_SUITE_REASON}: {s}"),
863        _ => format!("unknown signature alg '{}'", alg.map(Value::to_string).unwrap_or_default()),
864    }
865}
866
867/// The post-quantum primitive of a suite.
868#[derive(Clone, Copy, PartialEq, Eq, Debug)]
869enum Pq {
870    MlDsa65,
871    MlDsa87,
872    Slh128f,
873    Slh256s,
874    FnDsa512,
875    FnDsa1024,
876    #[cfg(feature = "less")]
877    LessCat1,
878}
879
880impl Pq {
881    /// (public key bytes, signature bytes).
882    fn lens(self) -> (usize, usize) {
883        match self {
884            Pq::MlDsa65 => (ML_DSA_65_PUBLIC_KEY_BYTES, ML_DSA_65_SIGNATURE_BYTES),
885            Pq::MlDsa87 => (fips204::ml_dsa_87::PK_LEN, fips204::ml_dsa_87::SIG_LEN),
886            Pq::Slh128f => (fips205::slh_dsa_sha2_128f::PK_LEN, fips205::slh_dsa_sha2_128f::SIG_LEN),
887            Pq::Slh256s => (fips205::slh_dsa_sha2_256s::PK_LEN, fips205::slh_dsa_sha2_256s::SIG_LEN),
888            Pq::FnDsa512 => (897, 666),
889            Pq::FnDsa1024 => (1793, 1280),
890            #[cfg(feature = "less")]
891            Pq::LessCat1 => (less::PUBLIC_KEY_BYTES, less::SIGNATURE_MAX_BYTES),
892        }
893    }
894
895    /// Whether `n` is a signature length of this primitive: exactly the fixed length, or (LESS) any length the parameter
896    /// set produces (1,153..1,329 in steps of 16).
897    fn sig_len_ok(self, n: usize) -> bool {
898        match self {
899            #[cfg(feature = "less")]
900            Pq::LessCat1 => less::sig_len_ok(n),
901            _ => n == self.lens().1,
902        }
903    }
904}
905
906/// LESS (less-252-45) through the patched reference C in sdks/pca-less-c (feature `less`, compiled by build.rs).
907#[cfg(feature = "less")]
908mod less {
909    pub(super) const PUBLIC_KEY_BYTES: usize = 97484;
910    pub(super) const SIGNATURE_MIN_BYTES: usize = 1153;
911    pub(super) const SIGNATURE_MAX_BYTES: usize = 1329;
912    const SIGNATURE_STEP_BYTES: usize = 16;
913
914    extern "C" {
915        fn atlas_less_cat1_verify(pk: *const u8, pk_len: usize, msg: *const u8, msg_len: usize, sig: *const u8, sig_len: usize) -> core::ffi::c_int;
916    }
917
918    pub(super) fn sig_len_ok(n: usize) -> bool {
919        (SIGNATURE_MIN_BYTES..=SIGNATURE_MAX_BYTES).contains(&n) && (SIGNATURE_MAX_BYTES - n).is_multiple_of(SIGNATURE_STEP_BYTES)
920    }
921
922    /// The detached signature opens under `pk` and yields exactly `msg`. Total.
923    pub(super) fn verify(pk: &[u8], msg: &[u8], sig: &[u8]) -> bool {
924        if pk.len() != PUBLIC_KEY_BYTES || !sig_len_ok(sig.len()) {
925            return false;
926        }
927        // SAFETY: every pointer is valid for the length passed with it for the whole call; the C side reads only within
928        // those lengths (it verifies on its own thread with its own stack and joins it before returning) and writes none.
929        unsafe { atlas_less_cat1_verify(pk.as_ptr(), pk.len(), msg.as_ptr(), msg.len(), sig.as_ptr(), sig.len()) == 1 }
930    }
931}
932
933struct SigSuite {
934    alg: &'static str,
935    /// Decoded byte length REQUIRED in the primary `sig` field for this suite.
936    sig_bytes: usize,
937    /// A `pq_pk` (the PQ public key of `pq`) field is REQUIRED (and forbidden otherwise).
938    needs_pq_pk: bool,
939    /// A `pq_sig` field is REQUIRED — the PQ sig separate from `sig` (hybrid). Forbidden otherwise.
940    needs_pq_sig: bool,
941    /// The PQ primitive (None for ed25519).
942    pq: Option<Pq>,
943    /// SUF-CMA nested hybrid: the PQ half signs msg || the Ed25519 signature bytes.
944    nested: bool,
945}
946
947/// The suites this crate implements (a subset of [`REGISTERED_SUITES`]).
948fn sig_suite(name: &str) -> Option<SigSuite> {
949    let pure = |alg, p: Pq| SigSuite { alg, sig_bytes: p.lens().1, needs_pq_pk: true, needs_pq_sig: false, pq: Some(p), nested: false };
950    let hybrid = |alg, p, nested| SigSuite { alg, sig_bytes: 64, needs_pq_pk: true, needs_pq_sig: true, pq: Some(p), nested };
951    Some(match name {
952        "ed25519" => SigSuite { alg: "ed25519", sig_bytes: 64, needs_pq_pk: false, needs_pq_sig: false, pq: None, nested: false },
953        "ml-dsa-65" => pure("ml-dsa-65", Pq::MlDsa65),
954        "hybrid-ed25519-ml-dsa-65" => hybrid("hybrid-ed25519-ml-dsa-65", Pq::MlDsa65, false),
955        "hybrid-nested-ed25519-ml-dsa-65" => hybrid("hybrid-nested-ed25519-ml-dsa-65", Pq::MlDsa65, true),
956        "slh-dsa-sha2-128f" => pure("slh-dsa-sha2-128f", Pq::Slh128f),
957        "hybrid-ed25519-slh-dsa-sha2-128f" => hybrid("hybrid-ed25519-slh-dsa-sha2-128f", Pq::Slh128f, false),
958        "ml-dsa-87" => pure("ml-dsa-87", Pq::MlDsa87),
959        "hybrid-ed25519-ml-dsa-87" => hybrid("hybrid-ed25519-ml-dsa-87", Pq::MlDsa87, false),
960        "slh-dsa-sha2-256s" => pure("slh-dsa-sha2-256s", Pq::Slh256s),
961        "hybrid-ed25519-slh-dsa-sha2-256s" => hybrid("hybrid-ed25519-slh-dsa-sha2-256s", Pq::Slh256s, false),
962        "fn-dsa-512" => pure("fn-dsa-512", Pq::FnDsa512),
963        "fn-dsa-1024" => pure("fn-dsa-1024", Pq::FnDsa1024),
964        #[cfg(feature = "less")]
965        "less-cat1" => pure("less-cat1", Pq::LessCat1),
966        #[cfg(feature = "less")]
967        "hybrid-ed25519-less-cat1" => hybrid("hybrid-ed25519-less-cat1", Pq::LessCat1, false),
968        _ => return None,
969    })
970}
971
972/// Resolve the suite for a PCActn `alg`: absent => ed25519; an implemented name => that suite; anything else
973/// (unregistered or unimplemented name, non-string, null) => `None` (FAIL-CLOSED: the caller rejects it, reporting
974/// [`suite_refusal`]).
975fn resolve_sig_alg(alg: Option<&Value>) -> Option<SigSuite> {
976    match alg {
977        None => sig_suite("ed25519"),
978        Some(Value::String(s)) => sig_suite(s),
979        Some(_) => None,
980    }
981}
982
983fn b64_len(v: Option<&Value>, n: usize) -> bool {
984    v.and_then(Value::as_str).is_some_and(|s| decode_b64u_strict(s, Some(n)).is_some())
985}
986
987/// Canonical base64url whose decoded length is a signature length of `pq` (fixed, or LESS's variable range).
988fn b64_sig_len(v: Option<&Value>, pq: Pq) -> bool {
989    v.and_then(Value::as_str).and_then(|s| decode_b64u_strict(s, None)).is_some_and(|b| pq.sig_len_ok(b.len()))
990}
991
992/// Exact-length PQ verification over raw bytes (pure, empty context / FN-DSA DOMAIN_NONE + HASH_ID_RAW). Total.
993fn pq_verify(pq: Pq, pk: &[u8], msg: &[u8], sig: &[u8]) -> bool {
994    let (pk_len, _) = pq.lens();
995    if pk.len() != pk_len || !pq.sig_len_ok(sig.len()) {
996        return false;
997    }
998    // fips204 takes the key array by value, fips205 by reference (`$($r)?` = `&`).
999    macro_rules! fips {
1000        ($m:path $(, $r:tt)?) => {{
1001            use $m as m;
1002            let (Ok(pk), Ok(sig)) = (<[u8; m::PK_LEN]>::try_from(pk), <[u8; m::SIG_LEN]>::try_from(sig)) else { return false };
1003            match m::PublicKey::try_from_bytes($($r)? pk) {
1004                Ok(vk) => vk.verify(msg, &sig, &[]),
1005                Err(_) => false,
1006            }
1007        }};
1008    }
1009    match pq {
1010        Pq::MlDsa65 => {
1011            use fips204::traits::{SerDes, Verifier};
1012            fips!(fips204::ml_dsa_65)
1013        }
1014        Pq::MlDsa87 => {
1015            use fips204::traits::{SerDes, Verifier};
1016            fips!(fips204::ml_dsa_87)
1017        }
1018        Pq::Slh128f => {
1019            use fips205::traits::{SerDes, Verifier};
1020            fips!(fips205::slh_dsa_sha2_128f, &)
1021        }
1022        Pq::Slh256s => {
1023            use fips205::traits::{SerDes, Verifier};
1024            fips!(fips205::slh_dsa_sha2_256s, &)
1025        }
1026        Pq::FnDsa512 => {
1027            use fn_dsa_vrfy::VerifyingKey;
1028            fn_dsa_vrfy::VerifyingKey512::decode(pk)
1029                .is_some_and(|vk| vk.verify(sig, &fn_dsa_vrfy::DOMAIN_NONE, &fn_dsa_vrfy::HASH_ID_RAW, msg))
1030        }
1031        Pq::FnDsa1024 => {
1032            use fn_dsa_vrfy::VerifyingKey;
1033            fn_dsa_vrfy::VerifyingKey1024::decode(pk)
1034                .is_some_and(|vk| vk.verify(sig, &fn_dsa_vrfy::DOMAIN_NONE, &fn_dsa_vrfy::HASH_ID_RAW, msg))
1035        }
1036        #[cfg(feature = "less")]
1037        Pq::LessCat1 => less::verify(pk, msg, sig),
1038    }
1039}
1040
1041/// `pq_verify` over a base64url key and signature; false on any decoding error.
1042/// Private on purpose: the only callers take a [`pinned::PinnedPq`].
1043fn pq_verify_b64u(pq: Pq, pk_b64u: &str, msg: &[u8], sig_b64u: Option<&Value>) -> bool {
1044    let (pk_len, _) = pq.lens();
1045    let pk = match decode_b64u_strict(pk_b64u, Some(pk_len)) {
1046        Some(b) => b,
1047        None => return false,
1048    };
1049    let sg = match sig_b64u.and_then(Value::as_str).and_then(|s| decode_b64u_strict(s, None)) {
1050        Some(b) if pq.sig_len_ok(b.len()) => b,
1051        _ => return false,
1052    };
1053    pq_verify(pq, &pk, msg, &sg)
1054}
1055
1056/// Validate `alg`/`sig`/`pq_pk`/`pq_sig` per suite. `Ok(())` when well-formed, else a short reason.
1057/// Strict + fail-closed: unknown alg, wrong sizes, or a field not used by the suite being present all fail.
1058fn validate_signature_wire(p: &Map<String, Value>) -> Result<(), String> {
1059    validate_suite_fields(p, true)
1060}
1061
1062/// 0.4.1: a threshold share's signature fields, validated PER SUITE exactly like the leaf's (`alg` absent = ed25519 with a
1063/// 64-byte `sig` and no `pq_sig`; ml-dsa-65 a 3309-byte `sig`; the hybrid a 64-byte `sig` plus a 3309-byte `pq_sig`), EXCEPT
1064/// that a share's `pq_pk` is not judged here: it is an optional echo checked against the signer set by the threshold check.
1065fn validate_share_signature_wire(s: &Map<String, Value>) -> Result<(), String> {
1066    validate_suite_fields(s, false)
1067}
1068
1069fn validate_suite_fields(p: &Map<String, Value>, check_pq_pk: bool) -> Result<(), String> {
1070    let alg = p.get("alg");
1071    if let Some(a) = alg {
1072        if !a.is_string() {
1073            return Err("'alg' must be a string".into());
1074        }
1075    }
1076    let suite = match resolve_sig_alg(alg) {
1077        Some(s) => s,
1078        None => return Err(suite_refusal(alg)),
1079    };
1080    let (pk_len, pq_sig_len) = suite.pq.map_or((0, 0), Pq::lens);
1081    // the PQ signature is `sig` for a pure suite and `pq_sig` for a hybrid; its length rule is the primitive's
1082    let sig_ok = match suite.pq {
1083        Some(pq) if !suite.needs_pq_sig => b64_sig_len(p.get("sig"), pq),
1084        _ => b64_len(p.get("sig"), suite.sig_bytes),
1085    };
1086    if !sig_ok {
1087        return Err(format!("'sig' is not canonical base64url ({} bytes) for alg '{}'", suite.sig_bytes, suite.alg));
1088    }
1089    if !check_pq_pk {
1090        // share: `pq_pk` is an optional echo, judged by verify_threshold_share against the signer set
1091    } else if suite.needs_pq_pk {
1092        if !b64_len(p.get("pq_pk"), pk_len) {
1093            return Err(format!("'pq_pk' is not canonical base64url ({pk_len} bytes)"));
1094        }
1095    } else if p.get("pq_pk").is_some() {
1096        return Err(format!("'pq_pk' must be absent for alg '{}'", suite.alg));
1097    }
1098    if suite.needs_pq_sig {
1099        if !suite.pq.is_some_and(|pq| b64_sig_len(p.get("pq_sig"), pq)) {
1100            return Err(format!("'pq_sig' is not canonical base64url ({pq_sig_len} bytes)"));
1101        }
1102    } else if p.get("pq_sig").is_some() {
1103        return Err(format!("'pq_sig' must be absent for alg '{}'", suite.alg));
1104    }
1105    Ok(())
1106}
1107
1108/// Verify the leaf signature under the PCActn's suite. FAIL-CLOSED: unknown alg, a missing component, or any
1109/// invalid component returns false.
1110///   - ed25519:   Ed25519 `sig` under `holder`.
1111///   - ml-dsa-65: ML-DSA-65 `sig` under `pq_pk`.
1112///   - hybrid:    Ed25519 `sig` under `holder` AND ML-DSA-65 `pq_sig` under `pq_pk`; BOTH must verify.
1113///
1114/// The PQ half verifies ONLY under `pq` (a [`pinned::PinnedPq`], minted solely by [`pinned::resolve_pq_key`] or the
1115/// explicitly named caller-vouched constructor), never under a `pq_pk` read off the artifact being verified (R3-01 / R4-01).
1116fn verify_suite(
1117    alg: Option<&Value>,
1118    holder: &str,
1119    pq: Option<&pinned::PinnedPq>,
1120    msg: &[u8],
1121    sig: Option<&Value>,
1122    pq_sig: Option<&Value>,
1123) -> bool {
1124    let suite = match resolve_sig_alg(alg) {
1125        Some(s) => s,
1126        None => return false,
1127    };
1128    let sig_str = match sig.and_then(Value::as_str) {
1129        Some(s) => s,
1130        None => return false,
1131    };
1132    let prim = match suite.pq {
1133        None => return verify_b64u(holder, msg, sig_str),
1134        Some(p) => p,
1135    };
1136    let key = match pq {
1137        Some(k) => k.key(),
1138        None => return false,
1139    };
1140    if !suite.needs_pq_sig {
1141        return pq_verify_b64u(prim, key, msg, sig); // pure PQ: `sig` is the PQ signature
1142    }
1143    // hybrid: the cheap Ed25519 half first (R6-API-04), then the PQ `pq_sig` (nested: over msg || Ed25519 sig bytes)
1144    if !verify_b64u(holder, msg, sig_str) {
1145        return false;
1146    }
1147    if suite.nested {
1148        let ed_sig = match decode_b64u_strict(sig_str, Some(64)) {
1149            Some(b) => b,
1150            None => return false,
1151        };
1152        let mut nested = msg.to_vec();
1153        nested.extend_from_slice(&ed_sig);
1154        return pq_verify_b64u(prim, key, &nested, pq_sig);
1155    }
1156    pq_verify_b64u(prim, key, msg, pq_sig)
1157}
1158
1159/// Verify a signed artifact (`alg` / `sig` / `pq_pk` / `pq_sig`, `alg` absent = ed25519) over `msg` under its suite: the
1160/// wire shape per suite, then the ONE suite dispatch with the Ed25519 half under `ed_pub` and the PQ half under the
1161/// artifact's OWN `pq_pk` (CALLER-VOUCHED: only for keys the caller authorised elsewhere, e.g. the `pq_artifact`
1162/// conformance primitives). False for an unsupported / unknown suite or any failure. Total.
1163pub fn verify_artifact_suite(artifact: &Value, ed_pub: &str, msg: &[u8]) -> bool {
1164    let Some(a) = artifact.as_object() else { return false };
1165    if validate_signature_wire(a).is_err() {
1166        return false;
1167    }
1168    let pq = a.get("pq_pk").and_then(Value::as_str).and_then(pinned::PinnedPq::caller_vouched);
1169    verify_suite(a.get("alg"), ed_pub, pq.as_ref(), msg, a.get("sig"), a.get("pq_sig"))
1170}
1171
1172/// The single key-resolution choke point (R3-01 / R4-01). `PinnedPq` has a private field and no public constructor,
1173/// so code outside this module can obtain one only from [`resolve_pq_key`] (verifier-side authority) or the explicitly
1174/// named [`PinnedPq::caller_vouched`].
1175mod pinned {
1176    use super::{holder_pq_commitment, Value};
1177    use std::collections::HashMap;
1178
1179    /// An opaque PQ verification key.
1180    pub(super) struct PinnedPq {
1181        key: String,
1182    }
1183
1184    impl PinnedPq {
1185        pub(super) fn key(&self) -> &str {
1186            &self.key
1187        }
1188
1189        /// The caller asserts the key is authorised by some other mechanism. Named loudly on purpose.
1190        pub(super) fn caller_vouched(pk: &str) -> Option<PinnedPq> {
1191            if pk.is_empty() {
1192                None
1193            } else {
1194                Some(PinnedPq { key: pk.to_string() })
1195            }
1196        }
1197    }
1198
1199    /// Mirrors `resolvePqVerifyKey` in packages/pca/src/pq.ts. Returns the key to verify under, or `None` (REFUSE)
1200    /// when no verifier-side authority vouches for the artifact's `pq_pk`:
1201    ///   1. `trusted_pk`: a key the verifier itself holds (the stored grant). Used as is.
1202    ///   2. `pq_pins[identity]` (own entry only): the artifact's `pq_pk` MUST equal the pin; a differing pin refuses.
1203    ///   3. `holder_pq`: the artifact's `pq_pk` must hash to the signer's committed `holder_pq` (F-2).
1204    /// Natives have no `allowUnboundPq`: an artifact's own key is never enough.
1205    pub(super) fn resolve_pq_key(
1206        identity: Option<&str>,
1207        artifact_pk: Option<&Value>,
1208        holder_pq: Option<&Value>,
1209        pq_pins: Option<&HashMap<String, String>>,
1210        trusted_pk: Option<&str>,
1211    ) -> Option<PinnedPq> {
1212        if let Some(t) = trusted_pk {
1213            if !t.is_empty() {
1214                return Some(PinnedPq { key: t.to_string() });
1215            }
1216        }
1217        let pk = match artifact_pk {
1218            Some(Value::String(s)) if !s.is_empty() => s.as_str(),
1219            _ => return None,
1220        };
1221        if let (Some(pins), Some(id)) = (pq_pins, identity) {
1222            if let Some(pinned) = pins.get(id) {
1223                return if pinned == pk { Some(PinnedPq { key: pk.to_string() }) } else { None };
1224            }
1225        }
1226        match holder_pq {
1227            Some(Value::String(c)) if holder_pq_commitment(pk) == *c => Some(PinnedPq { key: pk.to_string() }),
1228            _ => None,
1229        }
1230    }
1231}
1232
1233// ---- capability chain ------------------------------------------------------------------
1234
1235/// Hash of the full capability, including its signature.
1236pub fn cap_hash(c: &Value) -> String {
1237    hash_canonical(c)
1238}
1239
1240/// `true` when `v`, sitting at container depth `at` (the hop object itself is depth 1, its fields' values depth 2),
1241/// nests deeper than [`MAX_JSON_DEPTH`]. ITERATIVE and stops at the first container past the cap, so a caller-built value
1242/// of any depth is measured without recursion (a recursive clone / serialisation of it would overflow the stack).
1243fn deeper_than_cap(v: &Value, at: usize) -> bool {
1244    let mut st: Vec<(&Value, usize)> = vec![(v, at)];
1245    while let Some((x, d)) = st.pop() {
1246        let kids: Box<dyn Iterator<Item = &Value>> = match x {
1247            Value::Array(a) => Box::new(a.iter()),
1248            Value::Object(m) => Box::new(m.values()),
1249            _ => continue,
1250        };
1251        if d > MAX_JSON_DEPTH {
1252            return true;
1253        }
1254        st.extend(kids.map(|k| (k, d + 1)));
1255    }
1256    false
1257}
1258
1259/// The hop BODY (the fields `signable_hop_body` copies) is out of the strict depth profile: the reference cannot hash it
1260/// (`hop N: malformed body`). Checked before the body is cloned.
1261fn body_too_deep(c: &Map<String, Value>) -> bool {
1262    ["issuer", "holder", "caveats", "parent", "holder_pq", "alg", "pq_pk"]
1263        .iter()
1264        .any(|k| c.get(*k).is_some_and(|v| deeper_than_cap(v, 2)))
1265}
1266
1267fn body_of(c: &Map<String, Value>) -> Value {
1268    let g = |k: &str| c.get(k).cloned().unwrap_or(Value::Null);
1269    let mut m = Map::new();
1270    m.insert("issuer".into(), g("issuer"));
1271    m.insert("holder".into(), g("holder"));
1272    m.insert("caveats".into(), g("caveats"));
1273    m.insert("parent".into(), g("parent"));
1274    if let Some(hp) = c.get("holder_pq") {
1275        m.insert("holder_pq".into(), hp.clone());
1276    }
1277    Value::Object(m)
1278}
1279
1280const HOLDER_PQ_DOMAIN: &[u8] = b"atlas-pca/holder-pq/v1\0";
1281
1282/// Mirrors holderPqCommitment in capability.ts: b64u(sha256(domain || utf8(pq_pk string))).
1283fn holder_pq_commitment(pq_pk: &str) -> String {
1284    let mut m = HOLDER_PQ_DOMAIN.to_vec();
1285    m.extend_from_slice(pq_pk.as_bytes());
1286    b64_encode(&sha(&m))
1287}
1288
1289fn alg_name(alg: Option<&Value>) -> String {
1290    match alg {
1291        None => "ed25519".to_string(),
1292        Some(Value::String(s)) => s.clone(),
1293        Some(_) => "\u{0}non-string".to_string(),
1294    }
1295}
1296
1297/// Mirrors suitePolicyError: `None` policy allows everything; a present (even empty) list enforces.
1298fn suite_allowed(alg: Option<&Value>, allowed: Option<&[String]>) -> bool {
1299    match allowed {
1300        None => true,
1301        Some(l) => {
1302            let n = alg_name(alg);
1303            l.iter().any(|a| *a == n)
1304        }
1305    }
1306}
1307
1308/// Mirrors pqBindingError (always strict, no allowUnboundPq): a suite carrying a PQ key is accepted only if
1309/// `pq_pk` hashes to the signer's committed `holder_pq`.
1310fn pq_binding_ok(alg: Option<&Value>, pq_pk: Option<&Value>, committed: Option<&Value>) -> bool {
1311    match resolve_sig_alg(alg) {
1312        Some(su) if su.needs_pq_pk => matches!(
1313            (pq_pk, committed),
1314            (Some(Value::String(pk)), Some(Value::String(c))) if holder_pq_commitment(pk) == *c
1315        ),
1316        _ => true,
1317    }
1318}
1319
1320fn str_of<'a>(c: &'a Map<String, Value>, k: &str) -> &'a str {
1321    c.get(k).and_then(Value::as_str).unwrap_or("")
1322}
1323
1324/// body_of + the suite fields (`alg`, `pq_pk`) bound in for a non-default suite (so a downgrade or ML-DSA
1325/// key-swap breaks the hop digest), byte-identical to body_of for ed25519. Mirrors signableBody in
1326/// capability.ts. Returns `Err(reason)` for an unknown `alg` (fail-closed).
1327fn signable_hop_body(c: &Map<String, Value>) -> Result<Value, String> {
1328    let suite = match resolve_sig_alg(c.get("alg")) {
1329        Some(s) => s,
1330        None => return Err(suite_refusal(c.get("alg"))),
1331    };
1332    let mut body = body_of(c);
1333    if suite.alg != "ed25519" {
1334        if let Value::Object(ref mut m) = body {
1335            m.insert("alg".into(), Value::String(suite.alg.to_string()));
1336            if suite.needs_pq_pk {
1337                if let Some(pk @ Value::String(_)) = c.get("pq_pk") {
1338                    m.insert("pq_pk".into(), pk.clone());
1339                }
1340            }
1341        }
1342    }
1343    Ok(body)
1344}
1345
1346fn check_sig(c: &Map<String, Value>, signer: &str, label: &str, pq: Option<&pinned::PinnedPq>) -> Option<String> {
1347    // Unknown suite => fail-closed (before any hashing), mirroring capability.ts checkSig.
1348    if resolve_sig_alg(c.get("alg")).is_some() && body_too_deep(c) {
1349        return Some(format!("{label}: malformed body"));
1350    }
1351    let body = match signable_hop_body(c) {
1352        Ok(b) => b,
1353        Err(e) => return Some(format!("{label}: {e}")),
1354    };
1355    let digest = match hash_canonical_strict(&body) {
1356        Some(d) => d,
1357        None => return Some(format!("{label}: malformed body")),
1358    };
1359    let bd = str_of(c, "body_digest");
1360    let id = str_of(c, "id");
1361    if digest != bd || id != bd {
1362        return Some(format!("{label}: body digest mismatch"));
1363    }
1364    let msg = decode_b64u_strict(bd, Some(32)).map(|d| {
1365        let mut m = CAP_DOMAIN.to_vec();
1366        m.extend_from_slice(&d);
1367        m
1368    });
1369    // Suite-agile hop verification: ed25519 == verify_b64u(signer, msg, sig); hybrid requires BOTH the
1370    // Ed25519 `sig` (under `signer`) AND the ML-DSA `pq_sig` (under `pq_pk`); pure ml-dsa-65 verifies `sig`
1371    // under the RESOLVED `pq` key (never the hop's own `pq_pk`). verify_suite dispatches on the hop's `alg`.
1372    match msg {
1373        Some(msg) if verify_suite(c.get("alg"), signer, pq, &msg, c.get("sig"), c.get("pq_sig")) => None,
1374        _ => Some(format!("{label}: bad signature (not signed by expected key)")),
1375    }
1376}
1377
1378/// Mirrors `wellTyped` in capability.ts: id/issuer/holder/body_digest/sig are strings; alg/pq_pk/pq_sig/holder_pq/parent are
1379/// absent or strings (JSON null is NOT absent); caveats is an array of objects each carrying a string `type`. A correctly
1380/// SIGNED but ill-typed hop is refused like in the reference (R6-05).
1381fn hop_well_typed(c: &Value) -> bool {
1382    let o = match c.as_object() {
1383        Some(o) => o,
1384        None => return false,
1385    };
1386    ["id", "issuer", "holder", "body_digest", "sig"].iter().all(|k| is_str(o.get(*k)))
1387        && ["alg", "pq_pk", "pq_sig", "holder_pq", "parent"].iter().all(|k| o.get(*k).map_or(true, Value::is_string))
1388        && o.get("caveats").and_then(Value::as_array).is_some_and(|cv| {
1389            cv.iter().all(|x| x.as_object().is_some_and(|d| is_str(d.get("type"))))
1390        })
1391}
1392
1393/// Mirrors verifyChain in capability.ts. `Ok(())` when valid, else `Err(reason)`. The 16-hop cap is
1394/// enforced before any signature work.
1395///
1396/// No PQ authority is supplied, so a non-ed25519 (pure `ml-dsa-65` or hybrid) ROOT is always refused (R4-01); use
1397/// [`verify_chain_policy`] with `pq_pins` / `trusted_root` to accept one.
1398pub fn verify_chain(chain: &[Value], expected_root_issuer: Option<&str>) -> Result<(), String> {
1399    verify_chain_policy(chain, expected_root_issuer, None, None, None)
1400}
1401
1402/// Reason a stored-grant root is refused because a supplied pin for its issuer disagrees (0.4.2, fail closed).
1403fn root_pq_pin_mismatch_reason(alg: &str) -> String {
1404    format!("hop 0: root suite '{alg}': the server-side PQ pin for the root issuer (policy.pqPins) does not match the stored grant's pq_pk (fail closed)")
1405}
1406
1407/// Reason a non-ed25519 root is refused without verifier-side PQ authority (R4-01); exact text is conformance-checked.
1408fn root_pq_pin_reason(alg: &str) -> String {
1409    format!("hop 0: root suite '{alg}' needs a PQ key pinned for the root issuer (policy.pqPins) or the verifier's stored grant (policy.trustedRoot); the root's own pq_pk proves nothing about who issued it (R3-01)")
1410}
1411
1412/// Mirrors `rootPq` in capability.ts. The root has no parent holding a `holder_pq` commitment, so a PQ-carrying root's key
1413/// must come from a verifier-side authority: the verifier's stored copy of this very grant (`trusted_root`, same content
1414/// hash) or a pin for `root.issuer`. `Ok(None)` for an ed25519 root (no PQ key needed).
1415fn resolve_root_pq(
1416    root: &Map<String, Value>,
1417    root_val: &Value,
1418    pq_pins: Option<&std::collections::HashMap<String, String>>,
1419    trusted_root: Option<&Value>,
1420) -> Result<Option<pinned::PinnedPq>, String> {
1421    let suite = match resolve_sig_alg(root.get("alg")) {
1422        Some(s) => s,
1423        None => return Ok(None), // unknown suite: check_sig refuses it
1424    };
1425    if !suite.needs_pq_pk {
1426        return Ok(None);
1427    }
1428    let pk = root.get("pq_pk");
1429    let trusted: Option<&str> = match (trusted_root, pk) {
1430        (Some(t), Some(Value::String(s))) if same_strict_hash(t, root_val) => Some(s.as_str()),
1431        _ => None,
1432    };
1433    // 0.4.2 fail closed: with the stored grant AND a pin for the issuer, both must agree (the grant never overrides a pin).
1434    if let (Some(t), Some(pins), Some(iss)) = (trusted, pq_pins, root.get("issuer").and_then(Value::as_str)) {
1435        if let Some(pin) = pins.get(iss) {
1436            if pin != t {
1437                return Err(root_pq_pin_mismatch_reason(suite.alg));
1438            }
1439        }
1440    }
1441    match pinned::resolve_pq_key(root.get("issuer").and_then(Value::as_str), pk, None, pq_pins, trusted) {
1442        Some(k) => Ok(Some(k)),
1443        None => Err(root_pq_pin_reason(suite.alg)),
1444    }
1445}
1446
1447/// [`verify_chain`] with an optional allowed-suites policy (`None` = none; `Some(&[])` refuses every suite) and the
1448/// verifier-side PQ authority for a non-ed25519 ROOT (R4-01): `pq_pins` maps the root issuer (Ed25519, base64url) to its
1449/// ML-DSA public key (a pin that differs from the root's `pq_pk` is a refusal); `trusted_root` is the verifier's own stored
1450/// root capability (accepted when its content hash equals the presented root's). Ed25519 roots need neither.
1451pub fn verify_chain_policy(
1452    chain: &[Value],
1453    expected_root_issuer: Option<&str>,
1454    allowed: Option<&[String]>,
1455    pq_pins: Option<&std::collections::HashMap<String, String>>,
1456    trusted_root: Option<&Value>,
1457) -> Result<(), String> {
1458    if chain.is_empty() {
1459        return Err("empty chain".into());
1460    }
1461    if chain.len() > MAX_CHAIN_DEPTH {
1462        return Err(format!("chain too long (max {MAX_CHAIN_DEPTH} hops)"));
1463    }
1464    if caveat_limit_exceeded(chain) {
1465        return Err(CAVEAT_LIMIT_REASON.into());
1466    }
1467    for (i, c) in chain.iter().enumerate() {
1468        if !hop_well_typed(c) {
1469            return Err(format!("hop {i}: malformed capability"));
1470        }
1471    }
1472    let root = chain[0].as_object().ok_or("hop 0: malformed")?;
1473    if root.contains_key("parent") {
1474        return Err("hop 0: root must not have a parent".into());
1475    }
1476    if let Some(exp) = expected_root_issuer {
1477        if root.get("issuer").and_then(Value::as_str) != Some(exp) {
1478            return Err("hop 0: root issuer is not the expected principal".into());
1479        }
1480    }
1481    if !suite_allowed(root.get("alg"), allowed) {
1482        return Err(format!("hop 0: signature suite '{}' is not allowed by this verifier's suite policy", alg_name(root.get("alg"))));
1483    }
1484    let root_pq = resolve_root_pq(root, &chain[0], pq_pins, trusted_root)?;
1485    if let Some(e) = check_sig(root, str_of(root, "issuer"), "hop 0", root_pq.as_ref()) {
1486        return Err(e);
1487    }
1488    for i in 1..chain.len() {
1489        let label = format!("hop {i}");
1490        let (parent, c) = match (chain[i - 1].as_object(), chain[i].as_object()) {
1491            (Some(p), Some(c)) => (p, c),
1492            _ => return Err(format!("{label}: malformed")),
1493        };
1494        let ph = hash_canonical_strict(&chain[i - 1]);
1495        if ph.is_none() || c.get("parent").and_then(Value::as_str) != ph.as_deref() {
1496            return Err(format!("{label}: broken parent link"));
1497        }
1498        if c.get("issuer") != parent.get("holder") {
1499            return Err(format!("{label}: issuer is not the parent's bound holder"));
1500        }
1501        if !suite_allowed(c.get("alg"), allowed) {
1502            return Err(format!("{label}: signature suite '{}' is not allowed by this verifier's suite policy", alg_name(c.get("alg"))));
1503        }
1504        if !pq_binding_ok(c.get("alg"), c.get("pq_pk"), parent.get("holder_pq")) {
1505            return Err(format!("{label}: pq_pk does not match the signer's committed holder_pq (F-2)"));
1506        }
1507        let hop_pq = pinned::resolve_pq_key(parent.get("holder").and_then(Value::as_str), c.get("pq_pk"), parent.get("holder_pq"), None, None);
1508        if let Some(e) = check_sig(c, str_of(parent, "holder"), &label, hop_pq.as_ref()) {
1509            return Err(e);
1510        }
1511        let empty = Vec::new();
1512        let pc = parent.get("caveats").and_then(Value::as_array).unwrap_or(&empty);
1513        let cc = c.get("caveats").and_then(Value::as_array).unwrap_or(&empty);
1514        if cc.len() < pc.len() {
1515            return Err(format!("{label}: drops parent caveat(s)"));
1516        }
1517        for j in 0..pc.len() {
1518            if !same_strict_hash(&cc[j], &pc[j]) {
1519                return Err(format!("{label}: caveat {j} altered or reordered"));
1520            }
1521        }
1522    }
1523    Ok(())
1524}
1525
1526// ---- wire format v2 --------------------------------------------------------------------
1527
1528const REQUIRED_FIELDS: [&str; 14] = [
1529    "ver", "action", "grant_ref", "cap_chain", "plan", "attestation", "provenance", "freshness", "counter",
1530    "risk_claim", "aud", "iat", "exp", "sig",
1531];
1532const OPTIONAL_FIELDS: [&str; 14] = [
1533    "nonce", "caution", "rationale_commitment", "progress_step", "prohibition_evidence", "tool_binding",
1534    "threshold", "zk_compliance", "bond_ref",
1535    // B4 crypto-agility (additive): absent `alg` == "ed25519" and validates exactly as pre-B4.
1536    "alg", "pq_pk", "pq_sig",
1537    // Intent Layer M2 (additive, SIGNED): the `envelope.intent` binding (see [`IntentPolicy`]).
1538    "intent",
1539    // Intent Layer v2 (additive, SIGNED): the session member (rule 13; see [`validate_intent_session_wire`]).
1540    "intent_session",
1541];
1542
1543fn b32(v: Option<&Value>) -> bool {
1544    v.and_then(Value::as_str).is_some_and(|s| decode_b64u_strict(s, Some(32)).is_some())
1545}
1546
1547fn is_str(v: Option<&Value>) -> bool {
1548    matches!(v, Some(Value::String(_)))
1549}
1550
1551fn is_int(v: Option<&Value>) -> bool {
1552    v.and_then(safe_int).is_some()
1553}
1554
1555fn closed(o: &Map<String, Value>, allowed: &[&str], label: &str) -> Result<(), String> {
1556    for k in o.keys() {
1557        if !allowed.contains(&k.as_str()) {
1558            return Err(format!("unknown field '{label}{k}'"));
1559        }
1560    }
1561    Ok(())
1562}
1563
1564fn obj<'a>(v: Option<&'a Value>, what: &str) -> Result<&'a Map<String, Value>, String> {
1565    v.and_then(Value::as_object).ok_or_else(|| format!("'{what}' must be an object"))
1566}
1567
1568/// Validate the wire form (README section 1/3/5): closed field sets, presence, JSON types, safe integers,
1569/// canonical fixed-length base64url, and that the whole signed body admits the strict canonical encoding.
1570/// `Ok(())` when well-formed, else a short reason.
1571pub fn validate_wire(pcactn: &Value) -> Result<(), String> {
1572    let p = pcactn.as_object().ok_or("PCActn is not an object")?;
1573    for k in p.keys() {
1574        if !REQUIRED_FIELDS.contains(&k.as_str()) && !OPTIONAL_FIELDS.contains(&k.as_str()) {
1575            return Err(format!("unknown field '{k}'"));
1576        }
1577    }
1578    for k in REQUIRED_FIELDS {
1579        if !p.contains_key(k) {
1580            return Err(format!("missing field '{k}'"));
1581        }
1582    }
1583    // every signed byte must be strict-canonical-encodable (`sig`, `threshold`, `pq_sig` are unsigned)
1584    let mut body = Map::new();
1585    for (k, v) in p {
1586        if k != "sig" && k != "threshold" && k != "pq_sig" {
1587            body.insert(k.clone(), v.clone());
1588        }
1589    }
1590    canonicalize_strict(&Value::Object(body))?;
1591
1592    for k in ["ver", "counter", "iat", "exp"] {
1593        if !is_int(p.get(k)) {
1594            return Err(format!("'{k}' must be a safe integer"));
1595        }
1596    }
1597    match p.get("aud").and_then(Value::as_str) {
1598        Some(a) if !a.is_empty() && a.len() <= MAX_AUD_LEN => {}
1599        _ => return Err("'aud' must be a non-empty string".into()),
1600    }
1601    if let Some(n) = p.get("nonce") {
1602        match n.as_str() {
1603            Some(s) if !s.is_empty() && s.len() <= MAX_NONCE_LEN => {}
1604            _ => return Err("'nonce' must be a non-empty string".into()),
1605        }
1606    }
1607    // B4 crypto-agility: the signature fields (`alg`, `sig`, `pq_pk`, `pq_sig`) are validated per suite.
1608    // With no `alg` this asserts exactly `sig` is 64-byte canonical b64u and `pq_pk`/`pq_sig` are absent —
1609    // i.e. BYTE-IDENTICAL wire behaviour to the pre-B4 reference. Unknown `alg` fails closed.
1610    validate_signature_wire(p)?;
1611    if !b32(p.get("grant_ref")) {
1612        return Err("'grant_ref' is not canonical base64url (32 bytes)".into());
1613    }
1614
1615    let a = obj(p.get("action"), "action")?;
1616    closed(a, &["verb", "resource", "params_digest", "reversibility_class"], "action.")?;
1617    if !is_str(a.get("verb")) || !is_str(a.get("resource")) || !is_str(a.get("reversibility_class")) {
1618        return Err("action.verb/resource/reversibility_class must be strings".into());
1619    }
1620    if !b32(a.get("params_digest")) {
1621        return Err("'action.params_digest' is not canonical base64url (32 bytes)".into());
1622    }
1623
1624    let pl = obj(p.get("plan"), "plan")?;
1625    closed(pl, &["root", "inclusion_proof", "node_id", "conditions_digest"], "plan.")?;
1626    if !b32(pl.get("root")) {
1627        return Err("'plan.root' is not canonical base64url (32 bytes)".into());
1628    }
1629    if !is_str(pl.get("node_id")) {
1630        return Err("'plan.node_id' must be a string".into());
1631    }
1632    if let Some(cd) = pl.get("conditions_digest") {
1633        if !b32(Some(cd)) {
1634            return Err("'plan.conditions_digest' must be a canonical base64url string (32 bytes)".into());
1635        }
1636    }
1637    let ip = obj(pl.get("inclusion_proof"), "plan.inclusion_proof")?;
1638    closed(ip, &["index", "size", "path"], "plan.inclusion_proof.")?;
1639    if !is_int(ip.get("index")) {
1640        return Err("'plan.inclusion_proof.index' must be a safe integer".into());
1641    }
1642    if !is_int(ip.get("size")) {
1643        return Err("'plan.inclusion_proof.size' must be a safe integer".into());
1644    }
1645    let path = ip
1646        .get("path")
1647        .and_then(Value::as_array)
1648        .ok_or("'plan.inclusion_proof.path' must be an array")?;
1649    for (i, st) in path.iter().enumerate() {
1650        let st = st.as_object().ok_or_else(|| format!("proof step {i} must be an object"))?;
1651        for k in st.keys() {
1652            if k != "side" && k != "hash" {
1653                return Err(format!("unknown field 'path[{i}].{k}'"));
1654            }
1655        }
1656        match st.get("side").and_then(Value::as_str) {
1657            Some("L") | Some("R") => {}
1658            _ => return Err(format!("proof step {i}: side must be 'L' or 'R'")),
1659        }
1660        if !b32(st.get("hash")) {
1661            return Err(format!("proof step {i}: hash is not canonical base64url (32 bytes)"));
1662        }
1663    }
1664
1665    let chain = p.get("cap_chain").and_then(Value::as_array).ok_or("'cap_chain' must be an array")?;
1666    for (i, c) in chain.iter().enumerate() {
1667        let c = c.as_object().ok_or_else(|| format!("cap_chain[{i}] must be an object"))?;
1668        closed(
1669            c,
1670            &["id", "issuer", "holder", "body_digest", "caveats", "sig", "parent", "alg", "pq_pk", "pq_sig", "holder_pq"],
1671            &format!("cap_chain[{i}]."),
1672        )?;
1673        for k in ["id", "issuer", "holder", "body_digest"] {
1674            if !b32(c.get(k)) {
1675                return Err(format!("cap_chain[{i}].{k} is not canonical base64url (32 bytes)"));
1676            }
1677        }
1678        // B4 crypto-agility: validate the hop's `alg`/`sig`/`pq_pk`/`pq_sig` per suite, exactly as the leaf.
1679        // Absent `alg` asserts a 64-byte `sig` and that `pq_pk`/`pq_sig` are absent (byte-identical pre-B4 hop).
1680        if let Err(e) = validate_signature_wire(c) {
1681            return Err(format!("cap_chain[{i}]: {e}"));
1682        }
1683        if let Some(par) = c.get("parent") {
1684            if !b32(Some(par)) {
1685                return Err(format!("cap_chain[{i}].parent is not canonical base64url (32 bytes)"));
1686            }
1687        }
1688        if let Some(hp) = c.get("holder_pq") {
1689            if !b32(Some(hp)) {
1690                return Err(format!("cap_chain[{i}].holder_pq is not canonical base64url (32 bytes)"));
1691            }
1692        }
1693        let ok = c.get("caveats").and_then(Value::as_array).is_some_and(|cv| {
1694            cv.iter().all(|x| x.as_object().is_some_and(|o| is_str(o.get("type"))))
1695        });
1696        if !ok {
1697            return Err(format!("cap_chain[{i}].caveats must be an array of {{type,...}} objects"));
1698        }
1699    }
1700
1701    let at = p.get("attestation").and_then(Value::as_object);
1702    match at {
1703        Some(at) if is_int(at.get("epoch")) => {
1704            if !(is_str(at.get("quote_digest"))
1705                && is_str(at.get("model_id"))
1706                && is_str(at.get("measurement"))
1707                && is_str(at.get("operator")))
1708            {
1709                return Err("attestation string fields must be strings".into());
1710            }
1711        }
1712        _ => return Err("'attestation' must be an object with an integer 'epoch'".into()),
1713    }
1714    let pv = p.get("provenance").and_then(Value::as_object);
1715    let pv_ok = pv.is_some_and(|pv| {
1716        is_str(pv.get("causal_hash"))
1717            && matches!(pv.get("taint_level"), Some(Value::Number(_)))
1718            && pv
1719                .get("trusted_refs")
1720                .and_then(Value::as_array)
1721                .is_some_and(|r| r.iter().all(Value::is_string))
1722    });
1723    if !pv_ok {
1724        return Err("'provenance' is malformed".into());
1725    }
1726    let fr_ok = p.get("freshness").and_then(Value::as_object).is_some_and(|fr| {
1727        is_int(fr.get("epoch")) && is_str(fr.get("beacon_ref")) && is_str(fr.get("accumulator_witness"))
1728    });
1729    if !fr_ok {
1730        return Err("'freshness' is malformed".into());
1731    }
1732    let rc_ok = p.get("risk_claim").and_then(Value::as_object).is_some_and(|rc| {
1733        matches!(rc.get("r"), Some(Value::Number(_))) && matches!(rc.get("inputs"), Some(Value::Object(_)))
1734    });
1735    if !rc_ok {
1736        return Err("'risk_claim' is malformed".into());
1737    }
1738
1739    // optional signed slots
1740    if let Some(c) = p.get("caution") {
1741        match c.as_f64() {
1742            Some(f) if c.is_number() && (0.0..=1.0).contains(&f) => {}
1743            _ => return Err("'caution' must be a number in [0,1]".into()),
1744        }
1745    }
1746    if let Some(v) = p.get("rationale_commitment") {
1747        if !b32(Some(v)) {
1748            return Err("'rationale_commitment' is not canonical base64url (32 bytes)".into());
1749        }
1750    }
1751    if let Some(v) = p.get("tool_binding") {
1752        if !b32(Some(v)) {
1753            return Err("'tool_binding' is not canonical base64url (32 bytes)".into());
1754        }
1755    }
1756    if let Some(v) = p.get("progress_step") {
1757        if !v.is_object() {
1758            return Err("'progress_step' must be an object".into());
1759        }
1760    }
1761    if let Some(v) = p.get("intent") {
1762        validate_intent_wire(v)?;
1763    }
1764    if let Some(v) = p.get("intent_session") {
1765        validate_intent_session_wire(v)?;
1766    }
1767    if let Some(v) = p.get("prohibition_evidence") {
1768        if !v.is_object() && !v.is_array() {
1769            return Err("'prohibition_evidence' must be an object or array".into());
1770        }
1771    }
1772    if let Some(th) = p.get("threshold") {
1773        let shares = th
1774            .as_object()
1775            .and_then(|t| t.get("shares"))
1776            .and_then(Value::as_array)
1777            .ok_or("'threshold' must be {shares:[...]}")?;
1778        for (i, s) in shares.iter().enumerate() {
1779            let s = match s.as_object() {
1780                Some(s) if is_str(s.get("role")) => s,
1781                _ => return Err(format!("threshold.shares[{i}] is malformed")),
1782            };
1783            if !b32(s.get("publicKey")) {
1784                return Err(format!("threshold.shares[{i}].publicKey is not canonical base64url (32 bytes)"));
1785            }
1786            // 0.4.1: per suite (it used to be a fixed 64 bytes, so a pure post-quantum share could never be carried).
1787            validate_share_signature_wire(s).map_err(|e| format!("threshold.shares[{i}]: {e}"))?;
1788        }
1789    }
1790    Ok(())
1791}
1792
1793// ---- PCActn ----------------------------------------------------------------------------
1794
1795/// SIG_DOMAIN || sha256(strictCanonical(pcactn without `sig`, `threshold`, `pq_sig`)).
1796pub fn threshold_message(p: &Map<String, Value>) -> Result<Vec<u8>, String> {
1797    let mut body = Map::new();
1798    for (k, v) in p {
1799        if k != "sig" && k != "threshold" && k != "pq_sig" {
1800            body.insert(k.clone(), v.clone());
1801        }
1802    }
1803    let canon = canonicalize_strict(&Value::Object(body))?;
1804    let mut m = SIG_DOMAIN.to_vec();
1805    m.extend_from_slice(&sha(canon.as_bytes()));
1806    Ok(m)
1807}
1808
1809/// Recompute the signer-set hash committed by a threshold share (v2.1):
1810/// `sha256("atlas-pca/signerset/v1\0" || canonical(sort_by(role, publicKey)[{publicKey, role}]))`.
1811/// FAIL-CLOSED: `None` on any malformed entry.
1812fn signer_set_hash(signer_set: &[Value]) -> Option<Vec<u8>> {
1813    // `pq_pk` is carried ONLY when registered (additive: ed25519-only sets hash as before).
1814    let mut entries: Vec<(&str, &str, Option<&str>)> = Vec::with_capacity(signer_set.len());
1815    for e in signer_set {
1816        let o = e.as_object()?;
1817        let role = o.get("role")?.as_str()?;
1818        let pk = o.get("publicKey")?.as_str()?;
1819        entries.push((role, pk, o.get("pq_pk").and_then(Value::as_str)));
1820    }
1821    entries.sort_by(|a, b| a.0.cmp(b.0).then(a.1.cmp(b.1)));
1822    let arr = Value::Array(
1823        entries
1824            .iter()
1825            .map(|(role, pk, pq)| {
1826                let mut m = Map::new();
1827                if let Some(pq) = pq {
1828                    m.insert("pq_pk".into(), Value::String((*pq).to_string()));
1829                }
1830                m.insert("publicKey".into(), Value::String((*pk).to_string()));
1831                m.insert("role".into(), Value::String((*role).to_string()));
1832                Value::Object(m)
1833            })
1834            .collect(),
1835    );
1836    let canon = canonicalize_strict(&arr).ok()?;
1837    let mut m = SIGNERSET_DOMAIN.to_vec();
1838    m.extend_from_slice(canon.as_bytes());
1839    Some(sha(&m))
1840}
1841
1842/// Registered PQ public-key lengths of every suite (ml-dsa-65/87, slh-dsa-128f/256s, fn-dsa-512/1024, less-cat1), whether
1843/// or not this crate implements the suite: a signer set is validated exactly like the reference.
1844const PQ_PK_LENGTHS: [usize; 7] = [1952, 2592, 32, 64, 897, 1793, 97484];
1845const SIGNER_ROLES: [&str; 3] = ["agent", "guardian", "principal"];
1846
1847/// R6-03: validate the WHOLE signer set like the reference (`decideThreshold` BuildReg): every entry an object with a known
1848/// role (case-sensitive) and a canonical 32-byte `publicKey`; a present `pq_pk` (JSON null is present) is canonical
1849/// base64url of a registered PQ key length; one key per role; one role per key; a duplicate (role, key) only with the same
1850/// `pq_pk`. Returns `(role, publicKey, pq_pk)` rows (one per role), or `None` when the set is malformed.
1851fn validate_signer_set(signer_set: &[Value]) -> Option<Vec<(&str, &str, Option<&str>)>> {
1852    let mut reg: Vec<(&str, &str, Option<&str>)> = Vec::new();
1853    for e in signer_set {
1854        let o = e.as_object()?;
1855        let role = o.get("role")?.as_str().filter(|r| SIGNER_ROLES.contains(r))?;
1856        let pk = o.get("publicKey")?.as_str()?;
1857        decode_b64u_strict(pk, Some(32))?;
1858        let pq = match o.get("pq_pk") {
1859            None => None,
1860            Some(v) => {
1861                let ps = v.as_str()?;
1862                let b = decode_b64u_strict(ps, None)?;
1863                if !PQ_PK_LENGTHS.contains(&b.len()) {
1864                    return None;
1865                }
1866                Some(ps)
1867            }
1868        };
1869        if let Some(prev) = reg.iter().find(|r| r.0 == role) {
1870            if prev.1 != pk || prev.2 != pq {
1871                return None; // two keys for one role, or a conflicting pq_pk on a duplicate (role, key)
1872            }
1873            continue;
1874        }
1875        if reg.iter().any(|r| r.1 == pk) {
1876            return None; // one key under two roles
1877        }
1878        reg.push((role, pk, pq));
1879    }
1880    Some(reg)
1881}
1882
1883/// The signer-set hash as base64url: `None` on a set with a non-object entry or a non-string role / publicKey.
1884pub fn signer_set_hash_b64u(signer_set: &[Value]) -> Option<String> {
1885    signer_set_hash(signer_set).map(|h| b64_encode(&h))
1886}
1887
1888/// Verify a single threshold share under the v2.1 agent-leaf share binding. FAIL-CLOSED: returns `false`
1889/// on any malformed input (never panics). The share signature MUST verify over the bound message
1890/// `"atlas-pca/share/<role>\0" || sha256(thresholdMessage) || signerSetHash || t(1 byte)` under
1891/// `share.publicKey` (or `share.pq_pk` per `share.alg`, routed through the same suite seam as the leaf).
1892/// Consequently the PRE-v2.1 bare agent share (a `sig` over the bare threshold message) and a cross-signer-set
1893/// replay (a share bound to a DIFFERENT signer set) both fail — the clean break the v2.1 binding mandates.
1894/// `entry` is a `{ role, t, signer_set, threshold_message, share{publicKey, sig, alg?, pq_pk?, pq_sig?} }`
1895/// object (the `primitives.threshold_share[]` shape).
1896pub fn verify_threshold_share(entry: &Value) -> bool {
1897    let o = match entry.as_object() {
1898        Some(o) => o,
1899        None => return false,
1900    };
1901    let role = match o.get("role").and_then(Value::as_str) {
1902        Some(r) => r,
1903        None => return false,
1904    };
1905    // R6-04: t is exactly 1, 2 or 3 (the reference refuses every other value).
1906    let t = match o.get("t").and_then(safe_int) {
1907        Some(t) if (1..=3).contains(&t) => t as u8,
1908        _ => return false,
1909    };
1910    let signer_set = match o.get("signer_set").and_then(Value::as_array) {
1911        Some(s) => s,
1912        None => return false,
1913    };
1914    let tm = match o.get("threshold_message").and_then(Value::as_str).and_then(|s| decode_b64u_strict(s, None)) {
1915        Some(b) => b,
1916        None => return false,
1917    };
1918    // R6-03: the WHOLE set is validated before the share is looked at.
1919    let reg = match validate_signer_set(signer_set) {
1920        Some(r) => r,
1921        None => return false,
1922    };
1923    let ssh = match signer_set_hash(signer_set) {
1924        Some(h) => h,
1925        None => return false,
1926    };
1927    let share = match o.get("share").and_then(Value::as_object) {
1928        Some(s) => s,
1929        None => return false,
1930    };
1931    if share.get("role").and_then(Value::as_str) != Some(role) {
1932        return false; // share.role is required and must name the verified role
1933    }
1934    let pk = match share.get("publicKey").and_then(Value::as_str) {
1935        Some(p) => p,
1936        None => return false,
1937    };
1938    // R5-A1: the share must be for the ONE key the verifier's signer set registers for `role`; the share's own
1939    // publicKey / pq_pk never vouch for themselves.
1940    let (reg_pq, role_has_pq) = match reg.iter().find(|r| r.0 == role) {
1941        Some(r) if r.1 == pk => (r.2, r.2.is_some()),
1942        _ => return false,
1943    };
1944    let suite = match resolve_sig_alg(share.get("alg")) {
1945        Some(s) => s,
1946        None => return false,
1947    };
1948    // A share that NAMES a pq_pk must name exactly its role's registered one (any suite; a role registering none has
1949    // nothing it could equal). The key used is always the registered one.
1950    if let Some(sp) = share.get("pq_pk") {
1951        match (sp.as_str(), reg_pq) {
1952            (Some(s), Some(rq)) if s == rq => {}
1953            _ => return false,
1954        }
1955    }
1956    // R6-02: a role that registers a pq_pk REQUIRES a PQ (pure or hybrid) share; an ed25519-only share for it is
1957    // refused (otherwise an Ed25519 break would still forge the role).
1958    if role_has_pq && suite.alg == "ed25519" {
1959        return false;
1960    }
1961    let mut tag: Vec<u8> = Vec::new();
1962    let mut vouched = None;
1963    if suite.alg != "ed25519" {
1964        // PQ key = the signer set's registered pq_pk, never the share's own.
1965        let rq = match reg_pq {
1966            Some(q) => q,
1967            None => return false,
1968        };
1969        vouched = pinned::PinnedPq::caller_vouched(rq);
1970        if vouched.is_none() {
1971            return false;
1972        }
1973        tag.extend_from_slice(SHARE_SUITE_TAG);
1974        tag.extend_from_slice(suite.alg.as_bytes());
1975    }
1976    // Bound share message: domain(role) || sha256(thresholdMessage) || signerSetHash || t [|| suite tag].
1977    let mut msg = Vec::with_capacity(SHARE_DOMAIN_PREFIX.len() + role.len() + 1 + 32 + ssh.len() + 1 + tag.len());
1978    msg.extend_from_slice(SHARE_DOMAIN_PREFIX);
1979    msg.extend_from_slice(role.as_bytes());
1980    msg.push(0);
1981    msg.extend_from_slice(&sha(&tm));
1982    msg.extend_from_slice(&ssh);
1983    msg.push(t);
1984    msg.extend_from_slice(&tag);
1985    verify_suite(share.get("alg"), pk, vouched.as_ref(), &msg, share.get("sig"), share.get("pq_sig"))
1986}
1987
1988/// Verify a RAW PCActn text: strict-parse it first (a parse failure is a `wire` failure), then
1989/// [`verify_pcactn_core`].
1990pub fn verify_pcactn_json(text: &str, grant: &Value, now: i64, audience: &str) -> Verdict {
1991    verify_pcactn_json_policy(text, grant, now, audience, None)
1992}
1993
1994/// [`verify_pcactn_json`] with an optional allowed-suites policy.
1995pub fn verify_pcactn_json_policy(text: &str, grant: &Value, now: i64, audience: &str, allowed: Option<&[String]>) -> Verdict {
1996    verify_pcactn_json_with(text, grant, now, audience, &VerifyOptions { allowed, ..VerifyOptions::default() })
1997}
1998
1999/// [`verify_pcactn_json`] with explicit [`VerifyOptions`].
2000pub fn verify_pcactn_json_with(text: &str, grant: &Value, now: i64, audience: &str, opts: &VerifyOptions<'_>) -> Verdict {
2001    if text.len() > MAX_ARTIFACT_BYTES {
2002        // FIRST: before any parsing (str::len is UTF-8 bytes)
2003        return wire_fail(ARTIFACT_SIZE_REASON.to_string());
2004    }
2005    match strict_parse(text) {
2006        Ok(v) => verify_pcactn_core_with(&v, grant, now, audience, opts),
2007        Err(e) => wire_fail(e),
2008    }
2009}
2010
2011/// Checks, in the normative order: wire (terminal), version, audience, validity, chain, plan_inclusion,
2012/// leaf_signature, counter (then `intent` when the PCActn carries it). `now` is epoch milliseconds; `audience` is this verifier's own audience id.
2013/// Later-milestone checks (attestation, threshold, revocation, ...) are out of scope.
2014pub fn verify_pcactn_core(pcactn: &Value, grant: &Value, now: i64, audience: &str) -> Verdict {
2015    verify_pcactn_core_policy(pcactn, grant, now, audience, None)
2016}
2017
2018/// [`verify_pcactn_core`] with an optional allowed-suites policy (`None` = none; `Some(&[])` refuses every
2019/// hop and leaf suite; absent `alg` == "ed25519"). Hybrid / pure-PQ keys are always required to be bound
2020/// to the signer's `holder_pq` (no unbound escape hatch).
2021pub fn verify_pcactn_core_policy(pcactn: &Value, grant: &Value, now: i64, audience: &str, allowed: Option<&[String]>) -> Verdict {
2022    verify_pcactn_core_with(pcactn, grant, now, audience, &VerifyOptions { allowed, ..VerifyOptions::default() })
2023}
2024
2025/// Optional verifier policies of [`verify_pcactn_core_with`] (`VerifyOptions::default()` == [`verify_pcactn_core`]).
2026#[derive(Debug, Clone, Copy, Default)]
2027pub struct VerifyOptions<'a> {
2028    /// Allowed signature suites (`None` = no restriction; `Some(&[])` refuses every hop and leaf suite).
2029    pub allowed: Option<&'a [String]>,
2030    /// Intent Layer M2 policy (`None` = none). See [`IntentPolicy`].
2031    pub intent: Option<&'a IntentPolicy>,
2032    /// Intent Layer v2 verifier state + policy (`None` = none). See [`IntentV2Context`].
2033    pub intent_v2: Option<&'a IntentV2Context>,
2034}
2035
2036/// [`verify_pcactn_core`] with explicit [`VerifyOptions`]. The `intent` check runs after `counter` and is reported
2037/// iff the PCActn carries `intent` or `opts.intent` is active; otherwise the verdict is the pre-M2 one.
2038pub fn verify_pcactn_core_with(pcactn: &Value, grant: &Value, now: i64, audience: &str, opts: &VerifyOptions<'_>) -> Verdict {
2039    let allowed = opts.allowed;
2040    if let Err(why) = validate_wire(pcactn) {
2041        return wire_fail(why);
2042    }
2043    let p = match pcactn.as_object() {
2044        Some(p) => p,
2045        None => return wire_fail("PCActn is not an object"),
2046    };
2047
2048    let mut checks: BTreeMap<String, bool> = BTreeMap::new();
2049    let mut reason = String::new();
2050    let mut record = |name: &str, res: Result<(), String>| match res {
2051        Ok(()) => {
2052            checks.insert(name.into(), true);
2053        }
2054        Err(why) => {
2055            checks.insert(name.into(), false);
2056            if reason.is_empty() {
2057                reason = format!("{name}: {why}");
2058            }
2059        }
2060    };
2061    record("wire", Ok(()));
2062
2063    // version
2064    let ver = p.get("ver").and_then(safe_int);
2065    record(
2066        "version",
2067        if ver == Some(PCACTN_WIRE_VERSION) { Ok(()) } else { Err("unsupported ver".into()) },
2068    );
2069
2070    // audience
2071    record(
2072        "audience",
2073        if p.get("aud").and_then(Value::as_str) == Some(audience) {
2074            Ok(())
2075        } else {
2076            Err("aud does not match this resource server / instance".into())
2077        },
2078    );
2079
2080    // validity
2081    let iat = p.get("iat").and_then(safe_int).unwrap_or(0);
2082    let exp = p.get("exp").and_then(safe_int).unwrap_or(0);
2083    record(
2084        "validity",
2085        if exp <= iat {
2086            Err("exp must be greater than iat".into())
2087        } else if exp - iat > MAX_LIFETIME_MS {
2088            Err(format!("lifetime exceeds {MAX_LIFETIME_MS} ms"))
2089        } else if iat > now.saturating_add(MAX_SKEW_MS) {
2090            Err("iat is in the future (clock skew)".into())
2091        } else if now > exp {
2092            Err("the PCActn has expired".into())
2093        } else {
2094            Ok(())
2095        },
2096    );
2097
2098    // capability chain, root == grant (16-hop cap is checked before any signature work)
2099    let empty_vec = Vec::new();
2100    let chain = p.get("cap_chain").and_then(Value::as_array).unwrap_or(&empty_vec);
2101    record("chain", {
2102        if chain.is_empty() {
2103            Err("empty chain".into())
2104        } else if chain.len() > MAX_CHAIN_DEPTH {
2105            Err(format!("chain too long (max {MAX_CHAIN_DEPTH} hops)"))
2106        } else if caveat_limit_exceeded(chain) {
2107            Err(CAVEAT_LIMIT_REASON.into()) // before any hashing or signature work
2108        } else if !same_strict_hash(&chain[0], grant) {
2109            Err("chain root is not the grant".into())
2110        } else {
2111            // chain[0] == grant was checked above, so the grant is the verifier's stored root
2112            verify_chain_policy(chain, grant.get("issuer").and_then(Value::as_str), allowed, None, Some(grant))
2113        }
2114    });
2115
2116    // grant_ref_bound (normative): the signed grant_ref MUST be a non-empty string byte-equal to the id of the
2117    // ROOT capability of the presented chain (cap_chain[0].id). Independent of the chain verdict; fail-closed on
2118    // an empty / malformed chain. Replay state is keyed on grant_ref, so it must not be attacker-chosen.
2119    let gref = p.get("grant_ref").and_then(Value::as_str);
2120    let root_id = chain.first().and_then(|c| c.get("id")).and_then(Value::as_str);
2121    record(
2122        "grant_ref_bound",
2123        match (gref, root_id) {
2124            (Some(g), Some(r)) if !g.is_empty() && g == r => Ok(()),
2125            _ => Err("grant_ref is not the id of the root capability in cap_chain".into()),
2126        },
2127    );
2128
2129    // plan inclusion (leaf recomputed from the action itself)
2130    let empty_map = Map::new();
2131    let plan = p.get("plan").and_then(Value::as_object).unwrap_or(&empty_map);
2132    let action = p.get("action").and_then(Value::as_object);
2133    let cond = plan
2134        .get("conditions_digest")
2135        .and_then(Value::as_str)
2136        .map(str::to_string)
2137        .unwrap_or_else(conditions_digest_default);
2138    let root = plan.get("root").and_then(Value::as_str).unwrap_or("");
2139    let proof = plan.get("inclusion_proof").and_then(Value::as_object);
2140    let ok = plan_leaf(plan.get("node_id"), action, &cond)
2141        .map(|leaf| verify_inclusion(root, proof, &leaf))
2142        .unwrap_or(false);
2143    record(
2144        "plan_inclusion",
2145        if ok { Ok(()) } else { Err("action is not a node of the committed plan".into()) },
2146    );
2147
2148    // leaf signature under the PCActn's B4 suite (ed25519 / ml-dsa-65 / hybrid) over the v2 signed message
2149    let leaf_msg = "signature does not verify under the leaf holder key";
2150    let sig_ok = chain.last().is_some_and(|leaf_cap| {
2151        let holder = leaf_cap.get("holder").and_then(Value::as_str).unwrap_or("");
2152        if !suite_allowed(p.get("alg"), allowed) || !pq_binding_ok(p.get("alg"), p.get("pq_pk"), leaf_cap.get("holder_pq")) {
2153            return false;
2154        }
2155        match threshold_message(p) {
2156            Ok(msg) => verify_suite(
2157                p.get("alg"),
2158                holder,
2159                pinned::resolve_pq_key(Some(holder), p.get("pq_pk"), leaf_cap.get("holder_pq"), None, None).as_ref(),
2160                &msg,
2161                p.get("sig"),
2162                p.get("pq_sig"),
2163            ),
2164            Err(_) => false,
2165        }
2166    });
2167    record("leaf_signature", if sig_ok { Ok(()) } else { Err(leaf_msg.into()) });
2168
2169    // counter: safe integer >= 0 (monotonicity vs. stored state is the resource server's job)
2170    record(
2171        "counter",
2172        match p.get("counter").and_then(safe_int) {
2173            Some(i) if i >= 0 => Ok(()),
2174            _ => Err("missing or not a non-negative safe integer".into()),
2175        },
2176    );
2177
2178    // Intent Layer M2: `intent` (reported iff the PCActn carries `intent` or the policy is active). Rule 13 amends the
2179    // goal: with a (wire-valid) `intent_session` it is "pca-intent:v2:" + session + ":" + map_digest, and rule 19 makes
2180    // it "pca-intent:v2c:" + session + ":" + map_commit when `intent_session.map_form` is "commit".
2181    let session = p.get("intent_session").and_then(|is| {
2182        let sess = is.get("session").and_then(Value::as_str)?;
2183        Some((sess, is.get("map_form").is_some()))
2184    });
2185    if let Some(res) = decide_intent(p.get("intent"), grant, opts.intent, session) {
2186        record("intent", res);
2187    }
2188    // Intent Layer v2: schema, intent_session, layers, accumulators, facts, provenance, classes (each reported only
2189    // when the PCActn carries `intent_session` or a v2 policy is active; see [`decide_intent_v2`]).
2190    for c in decide_intent_v2(pcactn, grant, opts.intent_v2, now).checks {
2191        record(c.name, if c.ok { Ok(()) } else { Err(c.reason) });
2192    }
2193
2194    let allow = checks.values().all(|v| *v);
2195    Verdict { allow, checks, reason }
2196}
2197
2198// ---- Intent Layer M2: envelope.intent -----------------------------------------------------
2199// Normative rules: packages/pca/src/intent-binding.ts and conformance/README.md "12. Intent binding".
2200
2201const INTENT_GOAL_PREFIX: &str = "pca-intent:v1:";
2202const INTENT_GOAL_V2_PREFIX: &str = "pca-intent:v2:";
2203const INTENT_GOAL_V2C_PREFIX: &str = "pca-intent:v2c:";
2204const INTENT_GOAL_COMMIT_DOMAIN: &str = "atlas-pca/goal/v1\0";
2205const PPM_ONE: i64 = 1_000_000;
2206/// UTF-8 byte cap of `intent.goal_salt`.
2207pub const MAX_INTENT_GOAL_SALT_LEN: usize = 128;
2208const ENVELOPE_INTENT_FIELDS: [&str; 5] = ["ref", "map_digest", "goal_salt", "fidelity_ppm", "residual_risk_ppm"];
2209
2210/// Verifier-side intent policy (Intent Layer M2). ACTIVE iff `require` is true or either threshold is `Some` (even
2211/// an invalid one); an active policy runs the `intent` check even for a PCActn without the slot and fails it closed.
2212/// A set threshold that is not a non-negative safe integer is a misconfiguration and fails the check.
2213#[derive(Debug, Clone, Default, PartialEq)]
2214pub struct IntentPolicy {
2215    /// Require every PCActn to carry a bound `intent`.
2216    pub require: bool,
2217    /// Deny when the claimed `fidelity_ppm` is below this. Setting it implies `require`.
2218    pub min_fidelity_ppm: Option<f64>,
2219    /// Deny when the claimed `residual_risk_ppm` is above this. Setting it implies `require`.
2220    pub max_residual_risk_ppm: Option<f64>,
2221}
2222
2223impl IntentPolicy {
2224    /// True iff the policy is active.
2225    pub fn is_active(&self) -> bool {
2226        self.require || self.min_fidelity_ppm.is_some() || self.max_residual_risk_ppm.is_some()
2227    }
2228
2229    /// Lenient construction from a JSON object `{require?, min_fidelity_ppm?, max_residual_risk_ppm?}`: a threshold
2230    /// keeps its NUMERIC VALUE whatever its lexical form (`950000.0`, `1e6` are valid integers; `-0` is -0.0), so the
2231    /// check accepts exactly the non-negative safe integers and fails closed on anything else (negative, fractional,
2232    /// -0, > 2^53-1). A present non-numeric threshold (null, bool, string, ...) becomes NaN (misconfigured). `None`
2233    /// when `v` is not an object.
2234    pub fn from_json(v: &Value) -> Option<IntentPolicy> {
2235        let o = v.as_object()?;
2236        let num = |k: &str| o.get(k).map(|x| x.as_f64().unwrap_or(f64::NAN));
2237        Some(IntentPolicy {
2238            require: o.get("require").and_then(Value::as_bool) == Some(true),
2239            min_fidelity_ppm: num("min_fidelity_ppm"),
2240            max_residual_risk_ppm: num("max_residual_risk_ppm"),
2241        })
2242    }
2243
2244    /// Parse raw policy JSON text (any JSON number form) and apply [`IntentPolicy::from_json`]. An unparseable text or
2245    /// a non-object is an error.
2246    pub fn from_json_text(text: &str) -> Result<IntentPolicy, String> {
2247        let v: Value = serde_json::from_str(text).map_err(|e| format!("intent policy: {e}"))?;
2248        IntentPolicy::from_json(&v).ok_or_else(|| "intent policy: not a JSON object".to_string())
2249    }
2250}
2251
2252/// The goal commitment a root grant minted for this IntentStatement and Intent Map carries:
2253/// `hash_canonical_strict({d: "atlas-pca/goal/v1\0", goal: "pca-intent:v1:" + ref + ":" + map_digest, salt})`.
2254pub fn intent_goal_commit(r#ref: &str, map_digest: &str, goal_salt: &str) -> Option<String> {
2255    hash_canonical_strict(&serde_json::json!({
2256        "d": INTENT_GOAL_COMMIT_DOMAIN,
2257        "goal": format!("{INTENT_GOAL_PREFIX}{}:{}", r#ref, map_digest),
2258        "salt": goal_salt,
2259    }))
2260}
2261
2262/// The goal commitment of an Intent Layer v2 session grant (rule 13 amends rule 12 step 2):
2263/// `hash_canonical_strict({d: "atlas-pca/goal/v1\0", goal: "pca-intent:v2:" + session + ":" + map_digest, salt})`.
2264pub fn intent_goal_commit_v2(session: &str, map_digest: &str, goal_salt: &str) -> Option<String> {
2265    hash_canonical_strict(&serde_json::json!({
2266        "d": INTENT_GOAL_COMMIT_DOMAIN,
2267        "goal": format!("{INTENT_GOAL_V2_PREFIX}{}:{}", session, map_digest),
2268        "salt": goal_salt,
2269    }))
2270}
2271
2272/// The goal commitment of a session grant over a COMMITTED map (rule 19 amends rule 12 step 2):
2273/// `hash_canonical_strict({d: "atlas-pca/goal/v1\0", goal: "pca-intent:v2c:" + session + ":" + map_commit, salt})`.
2274pub fn intent_goal_commit_v2c(session: &str, map_commit: &str, goal_salt: &str) -> Option<String> {
2275    hash_canonical_strict(&serde_json::json!({
2276        "d": INTENT_GOAL_COMMIT_DOMAIN,
2277        "goal": format!("{INTENT_GOAL_V2C_PREFIX}{}:{}", session, map_commit),
2278        "salt": goal_salt,
2279    }))
2280}
2281
2282fn validate_intent_wire(v: &Value) -> Result<(), String> {
2283    let o = v.as_object().ok_or("'intent' must be an object")?;
2284    closed(o, &ENVELOPE_INTENT_FIELDS, "intent.")?;
2285    for k in ENVELOPE_INTENT_FIELDS {
2286        if !o.contains_key(k) {
2287            return Err(format!("missing field 'intent.{k}'"));
2288        }
2289    }
2290    if !b32(o.get("ref")) {
2291        return Err("'intent.ref' is not canonical base64url (32 bytes)".into());
2292    }
2293    if !b32(o.get("map_digest")) {
2294        return Err("'intent.map_digest' is not canonical base64url (32 bytes)".into());
2295    }
2296    match o.get("goal_salt").and_then(Value::as_str) {
2297        Some(s) if !s.is_empty() && s.len() <= MAX_INTENT_GOAL_SALT_LEN => {}
2298        _ => return Err("'intent.goal_salt' must be a non-empty string (<= 128 UTF-8 bytes)".into()),
2299    }
2300    match o.get("fidelity_ppm").and_then(safe_int) {
2301        Some(f) if (0..=PPM_ONE).contains(&f) => {}
2302        _ => return Err("'intent.fidelity_ppm' must be a safe integer in [0, 1000000]".into()),
2303    }
2304    match o.get("residual_risk_ppm").and_then(safe_int) {
2305        Some(r) if r >= 0 => {}
2306        _ => return Err("'intent.residual_risk_ppm' must be a non-negative safe integer".into()),
2307    }
2308    Ok(())
2309}
2310
2311/// The FIRST `envelope` caveat of the verifier's root grant: its string `goal_commit`.
2312fn root_goal_commit(grant: &Value) -> Option<&str> {
2313    let env = grant
2314        .get("caveats")?
2315        .as_array()?
2316        .iter()
2317        .find(|c| c.get("type").and_then(Value::as_str) == Some("envelope"))?; // non-objects have no `type`
2318    env.get("goal_commit").and_then(Value::as_str)
2319}
2320
2321fn ok_threshold(x: Option<f64>) -> bool {
2322    match x {
2323        None => true,
2324        // NaN and +/-Inf have a NaN fract(), so no separate finiteness test is needed
2325        Some(f) => f.fract() == 0.0 && !f.is_sign_negative() && f <= MAX_SAFE as f64,
2326    }
2327}
2328
2329/// The `intent` check on a wire-valid PCActn (rules 0-4). `None` = not reported. `session` is the wire-valid
2330/// `intent_session.session` with whether it carries `map_form` (the v2 / v2c goal), else `None` (the v1 goal). Never panics.
2331fn decide_intent(intent: Option<&Value>, grant: &Value, policy: Option<&IntentPolicy>, session: Option<(&str, bool)>) -> Option<Result<(), String>> {
2332    let active = policy.is_some_and(IntentPolicy::is_active);
2333    if intent.is_none() && !active {
2334        return None;
2335    }
2336    if let Some(pol) = policy {
2337        // an inactive policy has no thresholds, so this only bites when active
2338        if !ok_threshold(pol.min_fidelity_ppm) || !ok_threshold(pol.max_residual_risk_ppm) {
2339            return Some(Err("intent policy misconfigured: thresholds must be non-negative safe integers (fail closed)".into()));
2340        }
2341    }
2342    let Some(i) = intent else {
2343        return Some(Err("this verifier requires an intent binding but the PCActn carries none".into()));
2344    };
2345    let Some(commit) = root_goal_commit(grant) else {
2346        return Some(Err("the root grant carries no envelope goal commitment to bind the intent to".into()));
2347    };
2348    let r = i.get("ref").and_then(Value::as_str).unwrap_or("");
2349    let md = i.get("map_digest").and_then(Value::as_str).unwrap_or("");
2350    let salt = i.get("goal_salt").and_then(Value::as_str).unwrap_or("");
2351    let opened = match session {
2352        Some((sess, false)) => intent_goal_commit_v2(sess, md, salt),
2353        Some((sess, true)) => intent_goal_commit_v2c(sess, md, salt),
2354        None => intent_goal_commit(r, md, salt),
2355    };
2356    if opened.as_deref() != Some(commit) {
2357        return Some(Err("intent ref / map_digest / goal_salt do not open the root grant's goal commitment".into()));
2358    }
2359    let fid = i.get("fidelity_ppm").and_then(safe_int).unwrap_or(-1);
2360    let res = i.get("residual_risk_ppm").and_then(safe_int).unwrap_or(i64::MAX);
2361    if let Some(min) = policy.and_then(|p| p.min_fidelity_ppm) {
2362        if (fid as f64) < min {
2363            return Some(Err(format!("intent fidelity {fid} ppm is below the policy minimum {min}")));
2364        }
2365    }
2366    if let Some(max) = policy.and_then(|p| p.max_residual_risk_ppm) {
2367        if (res as f64) > max {
2368            return Some(Err(format!("intent residual risk {res} ppm exceeds the policy maximum {max}")));
2369        }
2370    }
2371    Some(Ok(()))
2372}
2373
2374// ---- PCA-Action header (0.4.1) -----------------------------------------------------------
2375
2376/// Why [`decode_pca_header`] refused a `PCA-Action` header value.
2377#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2378pub enum PcaHeaderError {
2379    /// The value is empty.
2380    Empty,
2381    /// The value is not strict unpadded base64url.
2382    NotBase64url,
2383    /// The decoded bytes are not valid UTF-8.
2384    NotUtf8,
2385}
2386
2387impl std::fmt::Display for PcaHeaderError {
2388    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2389        f.write_str(match self {
2390            PcaHeaderError::Empty => "PCA-Action header is empty",
2391            PcaHeaderError::NotBase64url => "PCA-Action header is not strict unpadded base64url",
2392            PcaHeaderError::NotUtf8 => "PCA-Action header does not decode to UTF-8 text",
2393        })
2394    }
2395}
2396
2397impl std::error::Error for PcaHeaderError {}
2398
2399/// Decode a `PCA-Action` header value to the encoded PCActn JSON text (pass it to [`strict_parse`]).
2400///
2401/// STRICT (0.4.1), exactly the profile's base64url rule ([`decode_b64u_strict`] with no fixed length): RFC 4648 section 5
2402/// alphabet only (`A-Z a-z 0-9 - _`), no `=` padding, no whitespace anywhere (nothing is trimmed), `len % 4 != 1`, zero
2403/// unused trailing bits; then strict UTF-8 (invalid, overlong, surrogate and truncated sequences are refused; a leading
2404/// BOM is kept, and the strict JSON parser refuses it). Nothing is normalized, so one PCActn has one header spelling.
2405pub fn decode_pca_header(value: &str) -> Result<String, PcaHeaderError> {
2406    if value.is_empty() {
2407        return Err(PcaHeaderError::Empty);
2408    }
2409    let bytes = decode_b64u_strict(value, None).ok_or(PcaHeaderError::NotBase64url)?;
2410    String::from_utf8(bytes).map_err(|_| PcaHeaderError::NotUtf8)
2411}
2412
2413// ---- policy-layer caveat helpers (0.4.1) -------------------------------------------------
2414//
2415// The core verifier (the nine checks above, and the axum middleware) treats caveats as OPAQUE: it checks that they are
2416// carried, signed and only ever appended, but it does not evaluate them. A resource server enforcing a grant's caveats
2417// calls `evaluate_caveats(&policy_caveats(&grant, &chain), &ctx)` with its own action. 0.4.1 (security, mirrors the
2418// TypeScript policy layer): the caveats on the ROOT grant outside the envelope are part of that list, so they are enforced
2419// exactly like the caveats delegation hops append.
2420
2421const ENVELOPE_CAVEAT: &str = "envelope";
2422const REVERSIBILITY_ORDER: [&str; 3] = ["reversible", "rate_limited", "irreversible"];
2423
2424/// Every caveat the policy layer evaluates for an action under `grant` delegated along `chain` (root first): the grant's
2425/// caveats with its FIRST `envelope` caveat removed (order kept; that one is the policy container read separately), then
2426/// the caveats the hops appended (`leaf.caveats` beyond the grant's, leaf = the last chain element). Nothing is appended
2427/// when `chain` is not a non-empty array or either caveat list is not an array. A non-array grant list is returned as is
2428/// (`Null` when absent), and [`evaluate_caveats`] refuses it (fail closed). Total.
2429pub fn policy_caveats(grant: &Value, chain: &Value) -> Value {
2430    let cs = match grant.get("caveats").and_then(Value::as_array) {
2431        Some(cs) => cs,
2432        None => return grant.get("caveats").cloned().unwrap_or(Value::Null),
2433    };
2434    let mut out: Vec<Value> = cs.clone();
2435    if let Some(i) = cs.iter().position(|c| c.get("type").and_then(Value::as_str) == Some(ENVELOPE_CAVEAT)) {
2436        out.remove(i);
2437    }
2438    if let Some(leaf_cs) = chain.as_array().and_then(|c| c.last()).and_then(|l| l.get("caveats")).and_then(Value::as_array) {
2439        out.extend(leaf_cs.get(cs.len()..).unwrap_or(&[]).iter().cloned());
2440    }
2441    Value::Array(out)
2442}
2443
2444/// Evaluate a caveat list against a policy context; `(ok, failed)` where `ok` iff every caveat is satisfied and `failed`
2445/// lists the unsatisfied caveats' `type` (`"<malformed>"` when it is not a string) in order. A non-array list is
2446/// `(false, ["<malformed caveats>"])`. Total: never panics.
2447///
2448/// `ctx` is a JSON object: `now` (epoch ms), optional `delegation_depth`, `blast_radius`, `reversibility_class`,
2449/// `recent_action_times` (epoch ms), and `action` `{verb, resource, reversibility_class?, params}`. A field the caveat
2450/// needs that is absent (or of the wrong type) leaves it unsatisfied. Implemented types (anything else, including
2451/// `envelope`, `note`, `resource_prefix`, `predicates`, `tool_schema`, is unsatisfied: fail closed):
2452///   * `max_spend {usd}`: `usd` finite >= 0; `action.params` is an object with an own finite `amount`, `0 <= amount <= usd`;
2453///     a `currency` in params, when present, is exactly `"usd"` or `"USD"`. Does not need `now`.
2454///   * the rest need a finite `now`: `expires {at}` (now < at), `not_before {at}` (now >= at), `rate {max, per_secs}`
2455///     (admitted times in `(now - per_secs*1000, now]` fewer than `max`), `max_blast_radius {max}`,
2456///     `reversibility_max {class}` (reads `ctx.reversibility_class`), `delegation_depth {max}`, `budget_alloc {limit}`
2457///     (limit finite >= 0; metered elsewhere).
2458pub fn evaluate_caveats(caveats: &Value, ctx: &Value) -> (bool, Vec<String>) {
2459    let list = match caveats.as_array() {
2460        Some(l) => l,
2461        None => return (false, vec!["<malformed caveats>".to_string()]),
2462    };
2463    let mut failed = Vec::new();
2464    for cv in list {
2465        if !caveat_satisfied(cv, ctx) {
2466            failed.push(cv.get("type").and_then(Value::as_str).unwrap_or("<malformed>").to_string());
2467        }
2468    }
2469    (failed.is_empty(), failed)
2470}
2471
2472/// A finite JSON number (never a bool or a string).
2473fn fin(v: Option<&Value>) -> Option<f64> {
2474    match v {
2475        Some(Value::Number(n)) => n.as_f64().filter(|x| x.is_finite()),
2476        _ => None,
2477    }
2478}
2479
2480fn caveat_satisfied(cv: &Value, ctx: &Value) -> bool {
2481    let (c, x) = match (cv.as_object(), ctx.as_object()) {
2482        (Some(c), Some(x)) => (c, x),
2483        _ => return false,
2484    };
2485    let ty = match c.get("type") {
2486        Some(Value::String(t)) => t.as_str(),
2487        _ => return false,
2488    };
2489    if ty == "max_spend" {
2490        let lim = match fin(c.get("usd")) {
2491            Some(l) if l >= 0.0 => l,
2492            _ => return false,
2493        };
2494        let params = match x.get("action").and_then(Value::as_object).and_then(|a| a.get("params")).and_then(Value::as_object) {
2495            Some(p) => p,
2496            None => return false,
2497        };
2498        let amount = match fin(params.get("amount")) {
2499            Some(a) if a >= 0.0 => a,
2500            _ => return false,
2501        };
2502        if let Some(cur) = params.get("currency") {
2503            if cur.as_str() != Some("usd") && cur.as_str() != Some("USD") {
2504                return false;
2505            }
2506        }
2507        return amount <= lim;
2508    }
2509    let now = match fin(x.get("now")) {
2510        Some(n) => n,
2511        None => return false,
2512    };
2513    match ty {
2514        "expires" => fin(c.get("at")).is_some_and(|at| now < at),
2515        "not_before" => fin(c.get("at")).is_some_and(|at| now >= at),
2516        "rate" => {
2517            let (max, per) = match (fin(c.get("max")), fin(c.get("per_secs"))) {
2518                (Some(m), Some(p)) if p > 0.0 => (m, p),
2519                _ => return false,
2520            };
2521            let times = match x.get("recent_action_times").and_then(Value::as_array) {
2522                Some(t) => t,
2523                None => return false,
2524            };
2525            let lo = now - per * 1000.0;
2526            let n = times.iter().filter_map(|t| fin(Some(t))).filter(|t| *t > lo && *t <= now).count();
2527            (n as f64) < max
2528        }
2529        "max_blast_radius" => match (fin(c.get("max")), fin(x.get("blast_radius"))) {
2530            (Some(m), Some(b)) => b <= m,
2531            _ => false,
2532        },
2533        "reversibility_max" => {
2534            let (lim, cur) = match (c.get("class").and_then(Value::as_str), x.get("reversibility_class").and_then(Value::as_str)) {
2535                (Some(l), Some(c)) => (l, c),
2536                _ => return false,
2537            };
2538            match (REVERSIBILITY_ORDER.iter().position(|r| *r == lim), REVERSIBILITY_ORDER.iter().position(|r| *r == cur)) {
2539                (Some(l), Some(c)) => c <= l,
2540                _ => false,
2541            }
2542        }
2543        "delegation_depth" => match (fin(c.get("max")), fin(x.get("delegation_depth"))) {
2544            (Some(m), Some(d)) => d <= m,
2545            _ => false,
2546        },
2547        "budget_alloc" => fin(c.get("limit")).is_some_and(|l| l >= 0.0),
2548        // Intent Layer v2 session binding (rule 13): no per-action constraint; satisfied iff well-formed.
2549        "intent_session" => intent_session_caveat_error(Some(cv)).is_none(),
2550        _ => false,
2551    }
2552}
2553
2554#[cfg(test)]
2555#[path = "k042_lib_test.rs"]
2556mod k042_test;