1use 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#[cfg(feature = "axum")]
19pub mod middleware;
20
21mod 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
62pub const PCACTN_WIRE_VERSION: i64 = 2;
64pub const MAX_CHAIN_DEPTH: usize = 16;
65pub const MAX_CAVEATS_PER_HOP: usize = 256;
67pub const MAX_CAVEATS_PER_CHAIN: usize = 1024;
68pub const CAVEAT_LIMIT_REASON: &str = "chain exceeds caveat limit (max 256 per hop, 1024 per chain)";
70pub const MAX_ARTIFACT_BYTES: usize = 524_288;
72pub const ARTIFACT_SIZE_REASON: &str = "artifact exceeds size limit (max 524288 bytes)";
74
75pub 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
103pub 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 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; }
125 if let Some(n) = len {
126 if bytes.len() != n {
127 return None;
128 }
129 }
130 Some(bytes)
131}
132
133#[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
149fn 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 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
185fn 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 format!("{}", f)
221}
222
223pub fn canonicalize(v: &Value) -> String {
228 let mut s = String::new();
229 let _ = ser(&mut s, v, false, 1);
230 s
231}
232
233pub 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 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
315pub fn hash_canonical(v: &Value) -> String {
318 b64_encode(&sha(canonicalize(v).as_bytes()))
319}
320
321pub fn hash_canonical_strict(v: &Value) -> Option<String> {
327 canonicalize_strict(v).ok().map(|c| b64_encode(&sha(c.as_bytes())))
328}
329
330fn 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
335pub fn strict_parse(text: &str) -> Result<Value, String> {
342 strict_parse_depth(text, MAX_JSON_DEPTH)
343}
344
345pub 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 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; 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 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
618fn 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
651pub 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
660fn 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
680pub 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
724pub 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
763fn 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; }
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; }
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; }
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
812pub const ML_DSA_65_PUBLIC_KEY_BYTES: usize = 1952;
831pub const ML_DSA_65_SIGNATURE_BYTES: usize = 3309;
832
833pub const UNSUPPORTED_SUITE_REASON: &str = "unsupported_suite";
835
836pub 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
854pub fn supported_suites() -> Vec<&'static str> {
856 REGISTERED_SUITES.iter().copied().filter(|a| sig_suite(a).is_some()).collect()
857}
858
859fn 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#[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 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 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#[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 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 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 sig_bytes: usize,
937 needs_pq_pk: bool,
939 needs_pq_sig: bool,
941 pq: Option<Pq>,
943 nested: bool,
945}
946
947fn 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
972fn 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
987fn 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
992fn 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 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
1041fn 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
1056fn validate_signature_wire(p: &Map<String, Value>) -> Result<(), String> {
1059 validate_suite_fields(p, true)
1060}
1061
1062fn 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 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 } 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
1108fn 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); }
1143 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
1159pub 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
1172mod pinned {
1176 use super::{holder_pq_commitment, Value};
1177 use std::collections::HashMap;
1178
1179 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 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 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
1233pub fn cap_hash(c: &Value) -> String {
1237 hash_canonical(c)
1238}
1239
1240fn 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
1259fn 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
1282fn 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
1297fn 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
1308fn 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
1324fn 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 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 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
1378fn 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
1393pub 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
1402fn 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
1407fn 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
1412fn 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), };
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 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
1447pub 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
1526const 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 "alg", "pq_pk", "pq_sig",
1537 "intent",
1539 "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
1568pub 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 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 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 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 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 validate_share_signature_wire(s).map_err(|e| format!("threshold.shares[{i}]: {e}"))?;
1788 }
1789 }
1790 Ok(())
1791}
1792
1793pub 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
1809fn signer_set_hash(signer_set: &[Value]) -> Option<Vec<u8>> {
1813 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
1842const PQ_PK_LENGTHS: [usize; 7] = [1952, 2592, 32, 64, 897, 1793, 97484];
1845const SIGNER_ROLES: [&str; 3] = ["agent", "guardian", "principal"];
1846
1847fn 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; }
1873 continue;
1874 }
1875 if reg.iter().any(|r| r.1 == pk) {
1876 return None; }
1878 reg.push((role, pk, pq));
1879 }
1880 Some(reg)
1881}
1882
1883pub fn signer_set_hash_b64u(signer_set: &[Value]) -> Option<String> {
1885 signer_set_hash(signer_set).map(|h| b64_encode(&h))
1886}
1887
1888pub 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 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 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; }
1934 let pk = match share.get("publicKey").and_then(Value::as_str) {
1935 Some(p) => p,
1936 None => return false,
1937 };
1938 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 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 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 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 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
1988pub 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
1994pub 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
1999pub fn verify_pcactn_json_with(text: &str, grant: &Value, now: i64, audience: &str, opts: &VerifyOptions<'_>) -> Verdict {
2001 if text.len() > MAX_ARTIFACT_BYTES {
2002 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
2011pub 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
2018pub 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#[derive(Debug, Clone, Copy, Default)]
2027pub struct VerifyOptions<'a> {
2028 pub allowed: Option<&'a [String]>,
2030 pub intent: Option<&'a IntentPolicy>,
2032 pub intent_v2: Option<&'a IntentV2Context>,
2034}
2035
2036pub 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 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 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 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 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()) } else if !same_strict_hash(&chain[0], grant) {
2109 Err("chain root is not the grant".into())
2110 } else {
2111 verify_chain_policy(chain, grant.get("issuer").and_then(Value::as_str), allowed, None, Some(grant))
2113 }
2114 });
2115
2116 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 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 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 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 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 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
2198const 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;
2206pub 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#[derive(Debug, Clone, Default, PartialEq)]
2214pub struct IntentPolicy {
2215 pub require: bool,
2217 pub min_fidelity_ppm: Option<f64>,
2219 pub max_residual_risk_ppm: Option<f64>,
2221}
2222
2223impl IntentPolicy {
2224 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 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 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
2252pub 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
2262pub 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
2272pub 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
2311fn 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"))?; 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 Some(f) => f.fract() == 0.0 && !f.is_sign_negative() && f <= MAX_SAFE as f64,
2326 }
2327}
2328
2329fn 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2378pub enum PcaHeaderError {
2379 Empty,
2381 NotBase64url,
2383 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
2399pub 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
2413const ENVELOPE_CAVEAT: &str = "envelope";
2422const REVERSIBILITY_ORDER: [&str; 3] = ["reversible", "rate_limited", "irreversible"];
2423
2424pub 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
2444pub 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
2472fn 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_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;