Skip to main content

ratify_protocol/
verify.rs

1//! Verify — the core verifier. Mirrors the Go reference verify.go exactly.
2
3#[cfg(not(feature = "std"))]
4use alloc::{boxed::Box, format, string::String, string::ToString, vec::Vec};
5
6use alloc::collections::BTreeMap;
7
8use crate::challenge_store::UNKNOWN_CHALLENGE;
9use crate::constraints::evaluate_constraints;
10
11use crate::crypto::{
12    transaction_receipt_sign_bytes, verify_both, verify_challenge_signature_with_stream,
13    verify_delegation_signature_e, verify_session_token_e,
14};
15use crate::scope::{intersect_scopes, validate_scopes, SCOPE_IDENTITY_DELEGATE};
16use crate::types::{
17    DelegationCert, HybridPublicKey, HybridSignature, IdentityStatus, ProofBundle, SessionToken,
18    StreamContext, TransactionReceipt, TransactionReceiptResult, VerifyOptions, VerifyResult,
19    CHALLENGE_WINDOW_SECONDS, ED25519_PUBLIC_KEY_SIZE, MAX_CONSTRAINTS_PER_CERT,
20    MAX_DELEGATION_CHAIN_DEPTH, MAX_IDENTIFIER_LENGTH_BYTES, MAX_SCOPES_PER_CERT,
21    MAX_SCOPE_LENGTH_BYTES, MLDSA65_PUBLIC_KEY_SIZE, PROTOCOL_VERSION,
22};
23
24/// `verify_bundle` is the entry point. Audit hook (SPEC §17.3) wraps the
25/// inner verifier so it fires on every call — success AND failure — and its
26/// errors are swallowed so auditing never alters the verdict.
27pub fn verify_bundle(bundle: &ProofBundle, opts: &VerifyOptions) -> VerifyResult {
28    let res = verify_bundle_inner(bundle, opts);
29    if let Some(audit) = &opts.audit {
30        audit.log_verification(&res, bundle);
31    }
32    res
33}
34
35fn verify_bundle_inner(bundle: &ProofBundle, opts: &VerifyOptions) -> VerifyResult {
36    let now = opts.now.unwrap_or_else(|| {
37        #[cfg(feature = "std")]
38        {
39            use std::time::{SystemTime, UNIX_EPOCH};
40            SystemTime::now()
41                .duration_since(UNIX_EPOCH)
42                .unwrap_or_default()
43                .as_secs() as i64
44        }
45        #[cfg(not(feature = "std"))]
46        {
47            // Without std, callers MUST supply opts.now.
48            panic!("verify_bundle: opts.now must be set when std feature is disabled")
49        }
50    });
51
52    // --- Structure ---
53    if bundle.delegations.is_empty() {
54        return invalid(
55            "no_delegations",
56            "proof bundle contains no delegation certificates",
57        );
58    }
59    if bundle.delegations.len() > MAX_DELEGATION_CHAIN_DEPTH {
60        return invalid("chain_too_deep", "delegation chain exceeds maximum depth");
61    }
62    if bundle.challenge.is_empty() {
63        return invalid("no_challenge", "proof bundle contains no challenge");
64    }
65    // Input bounds (SPEC §5.1). Wire codecs enforce these during decode; the
66    // verifier re-enforces them so bundles constructed in-process are held to
67    // the same bounds. Violations are structural: `invalid`, no new status.
68    for (i, cert) in bundle.delegations.iter().enumerate() {
69        if cert.scope.len() > MAX_SCOPES_PER_CERT {
70            return invalid(
71                "invalid",
72                &format!(
73                    "cert {} carries {} scopes, exceeding MAX_SCOPES_PER_CERT ({})",
74                    i,
75                    cert.scope.len(),
76                    MAX_SCOPES_PER_CERT
77                ),
78            );
79        }
80        if cert.constraints.len() > MAX_CONSTRAINTS_PER_CERT {
81            return invalid(
82                "invalid",
83                &format!(
84                    "cert {} carries {} constraints, exceeding MAX_CONSTRAINTS_PER_CERT ({})",
85                    i,
86                    cert.constraints.len(),
87                    MAX_CONSTRAINTS_PER_CERT
88                ),
89            );
90        }
91        for s in &cert.scope {
92            if s.len() > MAX_SCOPE_LENGTH_BYTES {
93                return invalid(
94                    "invalid",
95                    &format!(
96                        "cert {} carries a scope of {} bytes, exceeding MAX_SCOPE_LENGTH_BYTES ({})",
97                        i,
98                        s.len(),
99                        MAX_SCOPE_LENGTH_BYTES
100                    ),
101                );
102            }
103        }
104        for (j, c) in cert.constraints.iter().enumerate() {
105            if c.resource_id.len() > MAX_IDENTIFIER_LENGTH_BYTES {
106                return invalid(
107                    "invalid",
108                    &format!(
109                        "cert {} constraint {} resource_id is {} bytes, exceeding MAX_IDENTIFIER_LENGTH_BYTES ({})",
110                        i,
111                        j,
112                        c.resource_id.len(),
113                        MAX_IDENTIFIER_LENGTH_BYTES
114                    ),
115                );
116            }
117        }
118    }
119    if !bundle.session_context.is_empty() && bundle.session_context.len() != 32 {
120        return invalid(
121            "invalid_session_context",
122            &format!(
123                "session_context must be 32 bytes, got {}",
124                bundle.session_context.len()
125            ),
126        );
127    }
128    if !opts.session_context.is_empty() && opts.session_context.len() != 32 {
129        return invalid(
130            "invalid_session_context",
131            &format!(
132                "verify option session_context must be 32 bytes, got {}",
133                opts.session_context.len()
134            ),
135        );
136    }
137    if !opts.session_context.is_empty() {
138        if bundle.session_context.is_empty() {
139            return invalid(
140                "missing_session_context",
141                "verifier requires a session-bound challenge but bundle has no session_context",
142            );
143        }
144        if bundle.session_context != opts.session_context {
145            return invalid(
146                "session_context_mismatch",
147                "bundle session_context does not match verifier context",
148            );
149        }
150    } else if !bundle.session_context.is_empty() {
151        return invalid(
152            "session_context_unverifiable",
153            "bundle has session_context but verifier did not provide one",
154        );
155    }
156
157    // --- Single-use challenge: locate WITHOUT consuming (SPEC §10) ---
158    // An unknown, expired, already-consumed, or wrongly-bound challenge is
159    // rejected before any signature work; the record is not touched, so a
160    // forged presentation cannot burn a legitimate challenge. The store's
161    // error is discarded: the public result always carries the canonical
162    // UNKNOWN_CHALLENGE text so no store failure mode is distinguishable.
163    if let Some(store) = &opts.challenge_store {
164        if store
165            .validate(&bundle.challenge, &opts.session_context, now)
166            .is_err()
167        {
168            return invalid("unknown_challenge", UNKNOWN_CHALLENGE);
169        }
170    }
171
172    // --- v1.1 stream binding checks (SPEC §5.8, §6.4.2) ---
173    if !bundle.stream_id.is_empty() && bundle.stream_id.len() != 32 {
174        return invalid(
175            "invalid_stream_id",
176            &format!("stream_id must be 32 bytes, got {}", bundle.stream_id.len()),
177        );
178    }
179    if bundle.stream_id.is_empty() && bundle.stream_seq != 0 {
180        return invalid("invalid_stream_seq", "stream_seq set without stream_id");
181    }
182    if !bundle.stream_id.is_empty() && bundle.stream_seq < 1 {
183        return invalid(
184            "invalid_stream_seq",
185            &format!("stream_seq must be >=1, got {}", bundle.stream_seq),
186        );
187    }
188    if let Some(stream) = &opts.stream {
189        if stream.stream_id.len() != 32 {
190            return invalid(
191                "invalid_stream_id",
192                &format!(
193                    "verify option stream_id must be 32 bytes, got {}",
194                    stream.stream_id.len()
195                ),
196            );
197        }
198        if bundle.stream_id.is_empty() {
199            return invalid(
200                "missing_stream_context",
201                "verifier requires a stream-bound challenge but bundle has no stream_id",
202            );
203        }
204        if bundle.stream_id != stream.stream_id {
205            return invalid(
206                "stream_id_mismatch",
207                "bundle stream_id does not match verifier stream context",
208            );
209        }
210        let expected = stream.last_seen_seq + 1;
211        if bundle.stream_seq <= stream.last_seen_seq {
212            return invalid(
213                "stream_seq_replay",
214                &format!(
215                    "stream_seq {} already seen (last={})",
216                    bundle.stream_seq, stream.last_seen_seq
217                ),
218            );
219        }
220        if bundle.stream_seq != expected {
221            return invalid(
222                "stream_seq_skip",
223                &format!(
224                    "stream_seq {} skips expected {}",
225                    bundle.stream_seq, expected
226                ),
227            );
228        }
229    } else if !bundle.stream_id.is_empty() {
230        return invalid(
231            "stream_context_unverifiable",
232            "bundle has stream_id but verifier did not provide a stream context",
233        );
234    }
235
236    if let Some(err) = validate_hybrid_pubkey_lens(&bundle.agent_pub_key, "agent") {
237        return invalid("invalid_agent_key", &err);
238    }
239
240    let first_cert = &bundle.delegations[0];
241    let human_id = bundle.delegations.last().unwrap().issuer_id.clone();
242
243    if !hybrid_pub_key_equal(&bundle.agent_pub_key, &first_cert.subject_pub_key) {
244        return invalid(
245            "key_mismatch",
246            "agent public key does not match delegation subject",
247        );
248    }
249    if bundle.agent_id != first_cert.subject_id {
250        return invalid(
251            "id_mismatch",
252            "agent ID does not match delegation subject ID",
253        );
254    }
255
256    #[allow(deprecated)]
257    let legacy_revoke = opts.is_revoked.as_ref();
258    if opts.force_revocation_check && legacy_revoke.is_none() && opts.revocation.is_none() {
259        return invalid(
260            "force_revocation_no_callback",
261            "force_revocation_check is true but neither is_revoked nor revocation provider is set",
262        );
263    }
264
265    // --- Per-cert ---
266    for (i, cert) in bundle.delegations.iter().enumerate() {
267        if cert.version != PROTOCOL_VERSION {
268            return invalid(
269                "version_mismatch",
270                &format!("cert {} has unsupported version {}", i, cert.version),
271            );
272        }
273        // Scope vocabulary validation (SPEC §9): every granted scope must be
274        // canonical, a wildcard, or a custom: extension. Checked before any
275        // scope arithmetic so invalid vocabulary can never reach the
276        // effective-scope intersection.
277        if let Some(scope_err) = validate_scopes(&cert.scope) {
278            return fail_with_status("invalid_scope", &format!("cert {}: {}", i, scope_err));
279        }
280        if now > cert.expires_at {
281            return expired(&human_id, &bundle.agent_id);
282        }
283        if now < cert.issued_at {
284            return invalid("not_yet_valid", &format!("cert {} is not yet valid", i));
285        }
286        // Revocation: provider (SPEC §17.1) takes precedence over legacy closure.
287        if let Some(provider) = &opts.revocation {
288            match provider.is_revoked(&cert.cert_id) {
289                Err(e) => {
290                    return invalid(
291                        "revocation_error",
292                        &format!("cert {}: revocation lookup failed: {}", i, e),
293                    )
294                }
295                Ok(true) => return revoked(&human_id, &bundle.agent_id),
296                Ok(false) => {}
297            }
298        } else if let Some(check) = legacy_revoke {
299            if check(&cert.cert_id) {
300                return revoked(&human_id, &bundle.agent_id);
301            }
302        }
303        if let Err(sig_err) = verify_delegation_signature_e(cert) {
304            return invalid("bad_signature", &format!("cert {}: {}", i, sig_err));
305        }
306        // Constraint evaluation — each cert's first-class constraints must all
307        // pass against the caller-supplied VerifierContext. Fail-closed.
308        // With a challenge store in play, constraint evaluation is deferred
309        // until after the challenge is consumed (SPEC §10): a
310        // cryptographically valid presentation spends its challenge even
311        // when a constraint subsequently denies it, so denial outcomes
312        // cannot be probed with one liveness proof.
313        if opts.challenge_store.is_none() {
314            if let Some(failure) = evaluate_cert_constraints(cert, i, opts, now) {
315                return failure;
316            }
317        }
318        // Chain linkage
319        if i + 1 < bundle.delegations.len() {
320            let next = &bundle.delegations[i + 1];
321            if cert.issuer_id != next.subject_id {
322                return invalid(
323                    "broken_chain",
324                    &format!("cert {} issuer does not match cert {} subject", i, i + 1),
325                );
326            }
327            if !hybrid_pub_key_equal(&cert.issuer_pub_key, &next.subject_pub_key) {
328                return invalid(
329                    "broken_chain_keys",
330                    &format!(
331                        "cert {} issuer key does not match cert {} subject key",
332                        i,
333                        i + 1
334                    ),
335                );
336            }
337            // Sub-delegation gate: parent cert must have granted identity:delegate.
338            if !next.scope.iter().any(|s| s == SCOPE_IDENTITY_DELEGATE) {
339                return fail_with_status(
340                    "delegation_not_authorized",
341                    &format!(
342                        "cert {} issued by a subject whose parent cert {} did not grant \"{}\"",
343                        i,
344                        i + 1,
345                        SCOPE_IDENTITY_DELEGATE
346                    ),
347                );
348            }
349        }
350    }
351
352    // --- Liveness ---
353    let challenge_age = now - bundle.challenge_at;
354    if !(0..=CHALLENGE_WINDOW_SECONDS).contains(&challenge_age) {
355        return invalid(
356            "stale_challenge",
357            &format!(
358                "challenge is {} seconds old (max {})",
359                challenge_age, CHALLENGE_WINDOW_SECONDS
360            ),
361        );
362    }
363    if let Err(err) = verify_challenge_signature_with_stream(
364        &bundle.challenge,
365        bundle.challenge_at,
366        &bundle.session_context,
367        &bundle.stream_id,
368        bundle.stream_seq,
369        &bundle.challenge_sig,
370        &bundle.agent_pub_key,
371    ) {
372        return invalid(
373            "bad_challenge_sig",
374            &format!("challenge signature verification failed: {}", err),
375        );
376    }
377
378    // --- Single-use challenge: atomic consume (SPEC §10) ---
379    // Structure, chain, and challenge signature have all verified, so this
380    // presentation is cryptographically the agent's. Consume the challenge
381    // now — before authorization evaluation — so a later replay of the
382    // same challenge fails even if this presentation is subsequently
383    // denied.
384    if let Some(store) = &opts.challenge_store {
385        if store
386            .consume(&bundle.challenge, &opts.session_context, now)
387            .is_err()
388        {
389            return invalid("unknown_challenge", UNKNOWN_CHALLENGE);
390        }
391        // Deferred constraint evaluation (skipped in the per-cert loop
392        // above when a store is present).
393        for (i, cert) in bundle.delegations.iter().enumerate() {
394            if let Some(failure) = evaluate_cert_constraints(cert, i, opts, now) {
395                return failure;
396            }
397        }
398    }
399
400    // --- Effective scope ---
401    let scope_refs: Vec<&[String]> = bundle
402        .delegations
403        .iter()
404        .map(|c| c.scope.as_slice())
405        .collect();
406    let effective = intersect_scopes(&scope_refs);
407
408    if !opts.required_scope.is_empty() && !effective.iter().any(|s| s == &opts.required_scope) {
409        return fail_with_status(
410            "scope_denied",
411            &format!(
412                "required scope \"{}\" not in effective delegation scope",
413                opts.required_scope
414            ),
415        );
416    }
417
418    let mut result = VerifyResult {
419        valid: true,
420        identity_status: IdentityStatus::AuthorizedAgent,
421        human_id: human_id.clone(),
422        agent_id: bundle.agent_id.clone(),
423        agent_name: String::new(),
424        agent_type: String::new(),
425        granted_scope: effective,
426        error_reason: String::new(),
427        anchor: None,
428    };
429
430    // --- Anchor resolution (SPEC §17.8) ---
431    // Best-effort: populate anchor on the success result so downstream
432    // AuditProviders observe an identity-bound receipt. Resolver errors are
433    // non-fatal.
434    if let Some(resolver) = &opts.anchor_resolver {
435        if let Ok(Some(anchor)) = resolver.resolve_anchor(&human_id) {
436            result.anchor = Some(anchor);
437        }
438    }
439
440    // --- Advanced Policy Gating (SPEC §17.2 / §17.6) ---
441    //
442    // Fast path: if a PolicyVerdict is supplied AND verifies cleanly, skip
443    // the live Policy provider entirely.
444    if let (Some(verdict), Some(secret)) = (&opts.policy_verdict, &opts.policy_secret) {
445        if !opts.required_scope.is_empty() {
446            match crate::receipts::verifier_context_hash(&opts.context) {
447                Err(e) => {
448                    return invalid(
449                        "policy_error",
450                        &format!("verifier context hash failed: {}", e),
451                    );
452                }
453                Ok(ctx_hash) => {
454                    let v_err = crate::receipts::verify_policy_verdict(
455                        verdict,
456                        secret,
457                        &bundle.agent_id,
458                        &opts.required_scope,
459                        &ctx_hash,
460                        now,
461                    );
462                    match v_err {
463                        Ok(()) => return result,
464                        Err(e) if e.starts_with("policy_verdict_denied") => {
465                            return fail_with_status(
466                                "scope_denied",
467                                "policy verdict (cached) denied access",
468                            );
469                        }
470                        Err(_) => {
471                            // stale verdict — fall through to live policy
472                        }
473                    }
474                }
475            }
476        }
477    }
478
479    if let Some(policy) = &opts.policy {
480        match policy.evaluate_policy(bundle, &opts.context) {
481            Err(e) => {
482                return invalid(
483                    "policy_error",
484                    &format!("advanced policy evaluation failed: {}", e),
485                )
486            }
487            Ok(false) => {
488                return fail_with_status(
489                    "scope_denied",
490                    "advanced policy evaluation denied access",
491                )
492            }
493            Ok(true) => {}
494        }
495    }
496
497    result
498}
499
500// ----------------------------------------------------------------------
501
502fn hybrid_pub_key_equal(a: &HybridPublicKey, b: &HybridPublicKey) -> bool {
503    a.ed25519 == b.ed25519 && a.ml_dsa_65 == b.ml_dsa_65
504}
505
506fn validate_hybrid_pubkey_lens(pub_key: &HybridPublicKey, label: &str) -> Option<String> {
507    if pub_key.ed25519.len() != ED25519_PUBLIC_KEY_SIZE {
508        return Some(format!(
509            "{} Ed25519 public key has wrong length: {}",
510            label,
511            pub_key.ed25519.len()
512        ));
513    }
514    if pub_key.ml_dsa_65.len() != MLDSA65_PUBLIC_KEY_SIZE {
515        return Some(format!(
516            "{} ML-DSA-65 public key has wrong length: {}",
517            label,
518            pub_key.ml_dsa_65.len()
519        ));
520    }
521    None
522}
523
524/// Run one cert's constraint evaluation and map a failure to its identity
525/// status; None means the constraints passed.
526fn evaluate_cert_constraints(
527    cert: &DelegationCert,
528    i: usize,
529    opts: &VerifyOptions,
530    now: i64,
531) -> Option<VerifyResult> {
532    let constraint_err =
533        evaluate_constraints(cert, &opts.context, now, opts.constraint_evaluators.as_ref()).err()?;
534    // Route constraint failures to the specific identity_status so audit
535    // layers can distinguish unverifiable / unknown / denied.
536    // Matches Go/TS/Python.
537    let status = if constraint_err.contains("constraint_unverifiable") {
538        "constraint_unverifiable"
539    } else if constraint_err.contains("constraint_unknown") {
540        "constraint_unknown"
541    } else {
542        "constraint_denied"
543    };
544    Some(fail_with_status(
545        status,
546        &format!("cert {}: {}", i, constraint_err),
547    ))
548}
549
550fn invalid(reason: &str, msg: &str) -> VerifyResult {
551    VerifyResult {
552        valid: false,
553        identity_status: IdentityStatus::Invalid,
554        human_id: String::new(),
555        agent_id: String::new(),
556        agent_name: String::new(),
557        agent_type: String::new(),
558        granted_scope: Vec::new(),
559        error_reason: format!("{}: {}", reason, msg),
560        anchor: None,
561    }
562}
563
564/// fail_with_status is used when the failure maps to its own identity_status
565/// (scope_denied, constraint_denied, constraint_unverifiable,
566/// delegation_not_authorized). Unknown `status` strings fall back to Invalid
567/// — the wire form for error_reason still reflects the intended status so
568/// audits aren't lossy.
569fn fail_with_status(status: &str, msg: &str) -> VerifyResult {
570    let st = IdentityStatus::from_wire(status).unwrap_or(IdentityStatus::Invalid);
571    VerifyResult {
572        valid: false,
573        identity_status: st,
574        human_id: String::new(),
575        agent_id: String::new(),
576        agent_name: String::new(),
577        agent_type: String::new(),
578        granted_scope: Vec::new(),
579        error_reason: format!("{}: {}", status, msg),
580        anchor: None,
581    }
582}
583
584fn expired(human_id: &str, agent_id: &str) -> VerifyResult {
585    VerifyResult {
586        valid: false,
587        identity_status: IdentityStatus::Expired,
588        human_id: human_id.to_string(),
589        agent_id: agent_id.to_string(),
590        agent_name: String::new(),
591        agent_type: String::new(),
592        granted_scope: Vec::new(),
593        error_reason: "delegation certificate has expired".to_string(),
594        anchor: None,
595    }
596}
597
598fn revoked(human_id: &str, agent_id: &str) -> VerifyResult {
599    VerifyResult {
600        valid: false,
601        identity_status: IdentityStatus::Revoked,
602        human_id: human_id.to_string(),
603        agent_id: agent_id.to_string(),
604        agent_name: String::new(),
605        agent_type: String::new(),
606        granted_scope: Vec::new(),
607        error_reason: "delegation certificate has been revoked".to_string(),
608        anchor: None,
609    }
610}
611
612// ----------------------------------------------------------------------
613// v1.1 transaction receipt verification
614// ----------------------------------------------------------------------
615
616/// Verify a TransactionReceipt: envelope checks, per-party bundle
617/// verification, and party signature verification over the canonical signable.
618pub fn verify_transaction_receipt(
619    receipt: &TransactionReceipt,
620    now: i64,
621) -> TransactionReceiptResult {
622    if receipt.version != PROTOCOL_VERSION {
623        return receipt_fail(&format!(
624            "version_mismatch: unsupported version {}",
625            receipt.version
626        ));
627    }
628    if receipt.transaction_id.is_empty() {
629        return receipt_fail("missing_transaction_id: transaction_id must not be empty");
630    }
631    if receipt.terms_schema_uri.is_empty() {
632        return receipt_fail("missing_terms_schema_uri: terms_schema_uri must not be empty");
633    }
634    if receipt.terms_canonical_json.is_empty() {
635        return receipt_fail(
636            "missing_terms_canonical_json: terms_canonical_json must not be empty",
637        );
638    }
639    if receipt.parties.is_empty() {
640        return receipt_fail("no_parties: receipt must list at least one party");
641    }
642
643    // Party IDs must be unique.
644    let mut party_idx: BTreeMap<&str, usize> = BTreeMap::new();
645    for (i, p) in receipt.parties.iter().enumerate() {
646        if p.party_id.is_empty() {
647            return receipt_fail(&format!("empty_party_id: party {} has no party_id", i));
648        }
649        if party_idx.contains_key(p.party_id.as_str()) {
650            return receipt_fail(&format!(
651                "duplicate_party_id: {:?} listed more than once",
652                p.party_id
653            ));
654        }
655        party_idx.insert(&p.party_id, i);
656    }
657
658    // Each listed party must have exactly one signature; every signature's
659    // party_id must refer to a listed party.
660    let mut sig_by_party: BTreeMap<&str, usize> = BTreeMap::new();
661    for (i, s) in receipt.party_signatures.iter().enumerate() {
662        if !party_idx.contains_key(s.party_id.as_str()) {
663            return receipt_fail(&format!(
664                "unknown_party_signature: signature {} references unknown party_id {:?}",
665                i, s.party_id
666            ));
667        }
668        if sig_by_party.contains_key(s.party_id.as_str()) {
669            return receipt_fail(&format!(
670                "duplicate_party_signature: party {:?} has multiple signatures",
671                s.party_id
672            ));
673        }
674        sig_by_party.insert(&s.party_id, i);
675    }
676    for p in &receipt.parties {
677        if !sig_by_party.contains_key(p.party_id.as_str()) {
678            return receipt_fail(&format!(
679                "missing_party_signature: party {:?} has no signature",
680                p.party_id
681            ));
682        }
683    }
684
685    // Canonical signable bytes.
686    let signable = transaction_receipt_sign_bytes(receipt);
687
688    let mut party_results = Vec::with_capacity(receipt.parties.len());
689    for p in &receipt.parties {
690        // Proof bundle's agent_id / agent_pub_key MUST match the party's.
691        if p.proof_bundle.agent_id != p.agent_id {
692            return receipt_fail_with_results(
693                &format!(
694                    "party_agent_id_mismatch: party {:?} proof_bundle.agent_id={:?} != party.agent_id={:?}",
695                    p.party_id, p.proof_bundle.agent_id, p.agent_id
696                ),
697                party_results,
698            );
699        }
700        if !hybrid_pub_key_equal(&p.proof_bundle.agent_pub_key, &p.agent_pub_key) {
701            return receipt_fail_with_results(
702                &format!(
703                    "party_agent_key_mismatch: party {:?} proof_bundle.agent_pub_key != party.agent_pub_key",
704                    p.party_id
705                ),
706                party_results,
707            );
708        }
709
710        // Bundle verification.
711        let bundle_opts = VerifyOptions {
712            now: Some(now),
713            ..VerifyOptions::default()
714        };
715        let r = verify_bundle(&p.proof_bundle, &bundle_opts);
716        party_results.push(r.clone());
717        if !r.valid {
718            return receipt_fail_with_results(
719                &format!(
720                    "party_bundle_invalid: party {:?} status={} reason={}",
721                    p.party_id,
722                    r.identity_status.as_str(),
723                    r.error_reason
724                ),
725                party_results,
726            );
727        }
728
729        // Party signature check over the atomic signable.
730        let sig_idx = sig_by_party[p.party_id.as_str()];
731        let sig = &receipt.party_signatures[sig_idx].signature;
732        if let Err(e) = verify_both(&signable, sig, &p.agent_pub_key) {
733            return receipt_fail_with_results(
734                &format!("party_signature_invalid: party {:?}: {}", p.party_id, e),
735                party_results,
736            );
737        }
738    }
739
740    TransactionReceiptResult {
741        valid: true,
742        error_reason: String::new(),
743        party_results,
744    }
745}
746
747fn receipt_fail(reason: &str) -> TransactionReceiptResult {
748    TransactionReceiptResult {
749        valid: false,
750        error_reason: reason.to_string(),
751        party_results: Vec::new(),
752    }
753}
754
755fn receipt_fail_with_results(
756    reason: &str,
757    party_results: Vec<VerifyResult>,
758) -> TransactionReceiptResult {
759    TransactionReceiptResult {
760        valid: false,
761        error_reason: reason.to_string(),
762        party_results,
763    }
764}
765
766// ----------------------------------------------------------------------
767// v1.1 session cert cache (ROADMAP 2.3) streamed-turn verification
768// ----------------------------------------------------------------------
769
770/// The presentation-side inputs of one streamed turn: the fresh challenge
771/// the agent signed and the bindings it signed it under (SPEC §6.4.2).
772/// Presented values, distinct from the verifier-side expectations carried
773/// in [`VerifyOptions`].
774#[derive(Debug, Clone)]
775pub struct StreamedTurn {
776    pub challenge: Vec<u8>,
777    pub challenge_at: i64,
778    pub challenge_sig: HybridSignature,
779    /// Presented session binding (empty = unbound; otherwise 32 bytes).
780    pub session_context: Vec<u8>,
781    /// Presented stream binding (empty = unbound; otherwise 32 bytes with
782    /// `stream_seq >= 1`).
783    pub stream_id: Vec<u8>,
784    pub stream_seq: i64,
785}
786
787/// The verifier-side controls that apply to a streamed-turn presentation
788/// (SPEC §5.13). Deliberately NOT the full [`VerifyOptions`]: a streamed
789/// turn re-verifies liveness and bindings, not the chain, so revocation,
790/// policy, constraint, audit, and anchor options have no field here and
791/// can never be passed and silently ignored. Callers who need fresh
792/// revocation or policy semantics — including high-value operations the
793/// spec directs to `force_revocation_check` — MUST run full
794/// `verify_bundle` instead.
795#[derive(Default)]
796pub struct StreamedVerifyOptions<'a> {
797    /// Must be present in `token.granted_scope` for the turn to be valid;
798    /// empty skips the check. The token stores the verified chain's
799    /// effective scope lex-sorted for exactly this check.
800    pub required_scope: String,
801    /// Makes the per-turn challenge single-use: consulted (without
802    /// consuming) after the session token's HMAC authenticates the
803    /// presentation and before the per-turn hybrid challenge signature is
804    /// verified; atomically consumed after that signature verifies —
805    /// before the scope check. Store failures normalize to the canonical
806    /// unknown_challenge result.
807    pub challenge_store: Option<Box<dyn crate::challenge_store::ChallengeStore + 'a>>,
808    /// Verifier-side session binding; when set, the turn's presented
809    /// session_context must match byte-for-byte.
810    pub session_context: Vec<u8>,
811    /// Verifier-side stream state (stream_id match; stream_seq must be
812    /// exactly last_seen_seq+1, else stream_seq_replay /
813    /// stream_seq_skip).
814    ///
815    /// This is a caller-owned SNAPSHOT: the verifier only reads it and
816    /// never advances it. Two concurrent turns carrying distinct valid
817    /// challenges and the same stream_seq will BOTH verify against the
818    /// same snapshot. Concurrency-safe sequence enforcement is the
819    /// caller's responsibility: atomically compare-and-advance your
820    /// tracked last-seen sequence to `turn.stream_seq` when (and only
821    /// when) verification succeeds, and build the snapshot from that
822    /// tracked state.
823    pub stream: Option<StreamContext>,
824    /// Clock override (unix seconds); `None` uses the system clock (std
825    /// builds only — no_std callers MUST set it).
826    pub now: Option<i64>,
827}
828
829/// Options-object form of the streamed fast path (SPEC §5.13): verifies
830/// one turn against a previously issued SessionToken and enforces the
831/// verifier-side controls in [`StreamedVerifyOptions`] — required scope
832/// against the token's cached effective scope, single-use challenges, and
833/// session/stream binding checks.
834pub fn verify_streamed_turn_with_options(
835    token: &SessionToken,
836    session_secret: &[u8],
837    turn: &StreamedTurn,
838    opts: &StreamedVerifyOptions,
839) -> VerifyResult {
840    let now = opts.now.unwrap_or_else(|| {
841        #[cfg(feature = "std")]
842        {
843            use std::time::{SystemTime, UNIX_EPOCH};
844            SystemTime::now()
845                .duration_since(UNIX_EPOCH)
846                .unwrap_or_default()
847                .as_secs() as i64
848        }
849        #[cfg(not(feature = "std"))]
850        {
851            // Without std, callers MUST supply opts.now.
852            panic!("verify_streamed_turn_with_options: opts.now must be set when std feature is disabled")
853        }
854    });
855
856    // --- Token authenticity and validity window ---
857    // Deliberately FIRST, before the challenge store is consulted: the
858    // HMAC is a cheap authenticated pre-check that stops unauthenticated
859    // callers from probing the challenge store. This is the documented
860    // SPEC §5.13 order — it differs from §10, where no equivalent cheap
861    // authenticator exists ahead of the store lookup.
862    if let Err(e) = verify_session_token_e(token, session_secret, now) {
863        return invalid("session_token_invalid", &e);
864    }
865
866    // --- Basic structure ---
867    if turn.challenge.is_empty() {
868        return invalid("no_challenge", "streamed turn contains no challenge");
869    }
870
871    // --- Session context validation (mirrors SPEC §10 step 2) ---
872    if !turn.session_context.is_empty() && turn.session_context.len() != 32 {
873        return invalid(
874            "invalid_session_context",
875            &format!(
876                "session_context must be 32 bytes, got {}",
877                turn.session_context.len()
878            ),
879        );
880    }
881    if !opts.session_context.is_empty() && opts.session_context.len() != 32 {
882        return invalid(
883            "invalid_session_context",
884            &format!(
885                "verify option session_context must be 32 bytes, got {}",
886                opts.session_context.len()
887            ),
888        );
889    }
890    if !opts.session_context.is_empty() {
891        if turn.session_context.is_empty() {
892            return invalid(
893                "missing_session_context",
894                "verifier requires a session-bound challenge but turn has no session_context",
895            );
896        }
897        if turn.session_context != opts.session_context {
898            return invalid(
899                "session_context_mismatch",
900                "turn session_context does not match verifier context",
901            );
902        }
903    } else if !turn.session_context.is_empty() {
904        return invalid(
905            "session_context_unverifiable",
906            "turn has session_context but verifier did not provide one",
907        );
908    }
909
910    // --- Single-use challenge: locate WITHOUT consuming ---
911    // Before the per-turn hybrid challenge signature is verified, so a
912    // forged turn cannot burn a pending challenge and unknown challenges
913    // are rejected before the expensive signature check.
914    if let Some(store) = &opts.challenge_store {
915        if store
916            .validate(&turn.challenge, &opts.session_context, now)
917            .is_err()
918        {
919            return invalid("unknown_challenge", UNKNOWN_CHALLENGE);
920        }
921    }
922
923    // --- Stream binding validation (mirrors SPEC §10 step 3) ---
924    if !turn.stream_id.is_empty() && turn.stream_id.len() != 32 {
925        return invalid(
926            "invalid_stream_id",
927            &format!("stream_id must be 32 bytes, got {}", turn.stream_id.len()),
928        );
929    }
930    if turn.stream_id.is_empty() && turn.stream_seq != 0 {
931        return invalid("invalid_stream_seq", "stream_seq set without stream_id");
932    }
933    if !turn.stream_id.is_empty() && turn.stream_seq < 1 {
934        return invalid(
935            "invalid_stream_seq",
936            &format!("stream_seq must be >=1, got {}", turn.stream_seq),
937        );
938    }
939    if let Some(stream) = &opts.stream {
940        if stream.stream_id.len() != 32 {
941            return invalid(
942                "invalid_stream_id",
943                &format!(
944                    "verify option stream_id must be 32 bytes, got {}",
945                    stream.stream_id.len()
946                ),
947            );
948        }
949        if turn.stream_id.is_empty() {
950            return invalid(
951                "missing_stream_context",
952                "verifier requires a stream-bound challenge but turn has no stream_id",
953            );
954        }
955        if turn.stream_id != stream.stream_id {
956            return invalid(
957                "stream_id_mismatch",
958                "turn stream_id does not match verifier stream context",
959            );
960        }
961        let expected = stream.last_seen_seq + 1;
962        if turn.stream_seq <= stream.last_seen_seq {
963            return invalid(
964                "stream_seq_replay",
965                &format!(
966                    "stream_seq {} already seen (last={})",
967                    turn.stream_seq, stream.last_seen_seq
968                ),
969            );
970        }
971        if turn.stream_seq != expected {
972            return invalid(
973                "stream_seq_skip",
974                &format!("stream_seq {} skips expected {}", turn.stream_seq, expected),
975            );
976        }
977    } else if !turn.stream_id.is_empty() {
978        return invalid(
979            "stream_context_unverifiable",
980            "turn has stream_id but verifier did not provide a stream context",
981        );
982    }
983
984    // --- Liveness (challenge freshness + hybrid signature) ---
985    let challenge_age = now - turn.challenge_at;
986    if !(0..=CHALLENGE_WINDOW_SECONDS).contains(&challenge_age) {
987        return invalid(
988            "stale_challenge",
989            &format!(
990                "challenge is {} seconds old (max {})",
991                challenge_age, CHALLENGE_WINDOW_SECONDS
992            ),
993        );
994    }
995    if let Err(err) = verify_challenge_signature_with_stream(
996        &turn.challenge,
997        turn.challenge_at,
998        &turn.session_context,
999        &turn.stream_id,
1000        turn.stream_seq,
1001        &turn.challenge_sig,
1002        &token.agent_pub_key,
1003    ) {
1004        return invalid(
1005            "bad_challenge_sig",
1006            &format!("challenge signature verification failed: {}", err),
1007        );
1008    }
1009
1010    // --- Single-use challenge: atomic consume ---
1011    // The signature has verified. Consume before the scope check so a
1012    // denied caller cannot probe authorization with one liveness proof.
1013    if let Some(store) = &opts.challenge_store {
1014        if store
1015            .consume(&turn.challenge, &opts.session_context, now)
1016            .is_err()
1017        {
1018            return invalid("unknown_challenge", UNKNOWN_CHALLENGE);
1019        }
1020    }
1021
1022    // --- Required scope against the token's cached effective scope ---
1023    if !opts.required_scope.is_empty()
1024        && !token
1025            .granted_scope
1026            .iter()
1027            .any(|s| s == &opts.required_scope)
1028    {
1029        return fail_with_status(
1030            "scope_denied",
1031            &format!(
1032                "required scope \"{}\" not in session token granted scope",
1033                opts.required_scope
1034            ),
1035        );
1036    }
1037
1038    VerifyResult {
1039        valid: true,
1040        identity_status: IdentityStatus::AuthorizedAgent,
1041        human_id: token.human_id.clone(),
1042        agent_id: token.agent_id.clone(),
1043        agent_name: String::new(),
1044        agent_type: String::new(),
1045        granted_scope: token.granted_scope.clone(),
1046        error_reason: String::new(),
1047        anchor: None,
1048    }
1049}
1050
1051/// Fast-path verifier for streamed turns that present a SessionToken in
1052/// place of the full cert chain. Checks HMAC, validity window, challenge
1053/// freshness, and hybrid challenge signature against token.agent_pub_key.
1054/// The chain is NOT re-verified — that's the point of the token.
1055///
1056/// Presentation checks only — this form cannot enforce a required scope,
1057/// single-use challenges, or verifier-side session/stream checks, so a
1058/// token holder passes it for any protected action.
1059#[deprecated(
1060    since = "1.0.0-alpha.15",
1061    note = "presentation checks only — cannot enforce scope, single-use, or verifier-side bindings; use verify_streamed_turn_with_options"
1062)]
1063#[allow(clippy::too_many_arguments)]
1064pub fn verify_streamed_turn(
1065    token: &SessionToken,
1066    session_secret: &[u8],
1067    challenge: &[u8],
1068    challenge_at: i64,
1069    challenge_sig: &HybridSignature,
1070    session_context: &[u8],
1071    stream_id: &[u8],
1072    stream_seq: i64,
1073    now: i64,
1074) -> VerifyResult {
1075    if let Err(e) = verify_session_token_e(token, session_secret, now) {
1076        return invalid("session_token_invalid", &e);
1077    }
1078    if challenge.is_empty() {
1079        return invalid("no_challenge", "streamed turn contains no challenge");
1080    }
1081    if !session_context.is_empty() && session_context.len() != 32 {
1082        return invalid(
1083            "invalid_session_context",
1084            &format!(
1085                "session_context must be 32 bytes, got {}",
1086                session_context.len()
1087            ),
1088        );
1089    }
1090    if !stream_id.is_empty() && stream_id.len() != 32 {
1091        return invalid(
1092            "invalid_stream_id",
1093            &format!("stream_id must be 32 bytes, got {}", stream_id.len()),
1094        );
1095    }
1096    if !stream_id.is_empty() && stream_seq < 1 {
1097        return invalid(
1098            "invalid_stream_seq",
1099            &format!("stream_seq must be >=1, got {}", stream_seq),
1100        );
1101    }
1102    let challenge_age = now - challenge_at;
1103    if !(0..=CHALLENGE_WINDOW_SECONDS).contains(&challenge_age) {
1104        return invalid(
1105            "stale_challenge",
1106            &format!(
1107                "challenge is {} seconds old (max {})",
1108                challenge_age, CHALLENGE_WINDOW_SECONDS
1109            ),
1110        );
1111    }
1112    if let Err(err) = verify_challenge_signature_with_stream(
1113        challenge,
1114        challenge_at,
1115        session_context,
1116        stream_id,
1117        stream_seq,
1118        challenge_sig,
1119        &token.agent_pub_key,
1120    ) {
1121        return invalid(
1122            "bad_challenge_sig",
1123            &format!("challenge signature verification failed: {}", err),
1124        );
1125    }
1126    VerifyResult {
1127        valid: true,
1128        identity_status: IdentityStatus::AuthorizedAgent,
1129        human_id: token.human_id.clone(),
1130        agent_id: token.agent_id.clone(),
1131        agent_name: String::new(),
1132        agent_type: String::new(),
1133        granted_scope: token.granted_scope.clone(),
1134        error_reason: String::new(),
1135        anchor: None,
1136    }
1137}