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