Skip to main content

ratify_protocol/v2/
context_policy.rs

1//! Verifier-owned context policy (SPEC-v2 §6.7). Mirrors Go
2//! `context_policy_v2.go`.
3
4use super::crypto::{sha384, valid_prefixed_digest};
5use super::errors::{err, V2ErrorClass, V2Result};
6use super::json::{canonical, CJ};
7use super::wire::ProofBundleV2;
8
9const VERIFY_SESSION_CONTEXT_PROFILE_V2: &str = "ratify.verify.session-context/v1";
10
11const VERIFY_SESSION_CONTEXT_FIELDS_V2: &[&str] = &[
12    "verifier_id",
13    "workspace_id",
14    "agent_id",
15    "session_id",
16    "invocation_id",
17    "request_hash",
18];
19
20/// Validated verifier-owned context policy. Its receipt digest is derived
21/// from the canonical policy fields, never supplied by callers; only
22/// [`V2ContextPolicy::new`] builds one.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct V2ContextPolicy {
25    profile: String,
26    require_bound: bool,
27    required_fields: Vec<String>,
28    expected_session_context: Vec<u8>,
29    digest: String,
30}
31
32/// An intermediate ordered-stage result. A caller stops on any status other
33/// than `"passed"` before constraints or status.
34#[derive(Debug, Clone, PartialEq, Eq, Default)]
35pub struct V2ContextPolicyAssessment {
36    pub assessment: String,
37    pub policy_digest: Option<String>,
38    pub status: String,
39    pub reason: String,
40    pub detail: String,
41}
42
43impl V2ContextPolicy {
44    /// Go `NewV2ContextPolicy`: validate and fingerprint a policy.
45    /// `expected_session_context` is per-invocation authenticated state and
46    /// is excluded from the policy digest (empty = none). Every failure is
47    /// `configuration_invalid` (Go returns an unclassified error).
48    pub fn new(
49        profile: &str,
50        require_bound: bool,
51        required_fields: &[String],
52        expected_session_context: &[u8],
53    ) -> V2Result<Self> {
54        let invalid = |m: String| err(V2ErrorClass::ConfigurationInvalid, m);
55        if profile.is_empty() {
56            return invalid("v2 context policy profile must be non-empty valid UTF-8".into());
57        }
58        let mut fields: Vec<String> = Vec::with_capacity(required_fields.len());
59        for (i, field) in required_fields.iter().enumerate() {
60            if field.is_empty() {
61                return invalid(format!("v2 context policy field {i} is empty or invalid UTF-8"));
62            }
63            if fields.contains(field) {
64                return invalid(format!("v2 context policy has duplicate field {field:?}"));
65            }
66            fields.push(field.clone());
67        }
68        if require_bound && (fields.is_empty() || expected_session_context.len() != 32) {
69            return invalid(
70                "bound v2 context policy requires fields and a 32-byte authenticated context".into(),
71            );
72        }
73        if !require_bound && !expected_session_context.is_empty() {
74            return invalid("unbound v2 context policy cannot carry an expected context".into());
75        }
76        if profile == VERIFY_SESSION_CONTEXT_PROFILE_V2
77            && (!require_bound
78                || fields
79                    .iter()
80                    .map(String::as_str)
81                    .ne(VERIFY_SESSION_CONTEXT_FIELDS_V2.iter().copied()))
82        {
83            return invalid(
84                "Ratify Verify session-context policy must require the canonical field set".into(),
85            );
86        }
87        let encoded = canonical(&CJ::obj(vec![
88            ("profile", CJ::s(profile)),
89            ("require_bound", CJ::Bool(require_bound)),
90            ("required_fields", CJ::strs(&fields)),
91            ("version", CJ::Int(1)),
92        ]))
93        .map_err(|e| e.classify(V2ErrorClass::ConfigurationInvalid))?;
94        Ok(V2ContextPolicy {
95            profile: profile.to_string(),
96            require_bound,
97            required_fields: fields,
98            expected_session_context: expected_session_context.to_vec(),
99            digest: format!("sha384:{}", hex::encode(sha384(&[&encoded]))),
100        })
101    }
102
103    /// The policy digest recorded in receipts.
104    pub fn digest(&self) -> &str {
105        &self.digest
106    }
107
108    /// Whether the policy requires a bound session context.
109    pub fn require_bound(&self) -> bool {
110        self.require_bound
111    }
112
113    /// The policy profile identifier.
114    pub fn profile(&self) -> &str {
115        &self.profile
116    }
117
118    /// A copy of the required field names.
119    pub fn required_fields(&self) -> Vec<String> {
120        self.required_fields.clone()
121    }
122
123    /// A copy of the per-invocation expected session context (empty = none).
124    pub fn expected_session_context(&self) -> Vec<u8> {
125        self.expected_session_context.clone()
126    }
127
128    pub(crate) fn expected_session_context_ref(&self) -> &[u8] {
129        &self.expected_session_context
130    }
131
132    /// Go `policy.valid && policy.digest != "" && validPrefixedDigestV2`.
133    /// A policy can only be built by [`V2ContextPolicy::new`], so this holds
134    /// for every value; it is kept for parity with the Go checks.
135    pub(crate) fn is_valid(&self) -> bool {
136        !self.digest.is_empty() && valid_prefixed_digest(&self.digest)
137    }
138}
139
140/// Go `EvaluateProofBundleV2ContextPolicy`: apply a validated verifier
141/// context policy after preflight and claim.
142pub fn evaluate_proof_bundle_v2_context_policy(
143    bundle: Option<&ProofBundleV2>,
144    policy: Option<&V2ContextPolicy>,
145) -> V2ContextPolicyAssessment {
146    let Some(bundle) = bundle else {
147        return context_policy_failure(
148            "unverified",
149            "authorization_unverified",
150            "action_context_unverified",
151            "proof bundle is unavailable",
152        );
153    };
154    let has_context = bundle.session_context.is_some();
155    let Some(policy) = policy else {
156        return context_policy_failure(
157            if has_context { "unverified" } else { "unbound" },
158            "authorization_unverified",
159            "action_context_unverified",
160            "no caller-authenticated context policy is configured",
161        );
162    };
163    if !policy.is_valid() {
164        return context_policy_failure(
165            if has_context { "unverified" } else { "unbound" },
166            "authorization_unverified",
167            "action_context_unverified",
168            "no valid caller-authenticated context policy is configured",
169        );
170    }
171    let digest = Some(policy.digest.clone());
172    if !policy.require_bound {
173        return V2ContextPolicyAssessment {
174            assessment: "not_required".into(),
175            policy_digest: digest,
176            status: "passed".into(),
177            ..Default::default()
178        };
179    }
180    let Some(session_context) = &bundle.session_context else {
181        return V2ContextPolicyAssessment {
182            assessment: "unverified".into(),
183            policy_digest: digest,
184            status: "authorization_unverified".into(),
185            reason: "action_context_unverified".into(),
186            detail: "required session context is absent".into(),
187        };
188    };
189    if *session_context != policy.expected_session_context {
190        return V2ContextPolicyAssessment {
191            assessment: "mismatch".into(),
192            policy_digest: digest,
193            status: "constraint_denied".into(),
194            reason: "constraint_denied".into(),
195            detail: "proof session context does not match the verifier's authenticated context"
196                .into(),
197        };
198    }
199    V2ContextPolicyAssessment {
200        assessment: "bound".into(),
201        policy_digest: digest,
202        status: "passed".into(),
203        ..Default::default()
204    }
205}
206
207fn context_policy_failure(
208    assessment: &str,
209    status: &str,
210    reason: &str,
211    detail: &str,
212) -> V2ContextPolicyAssessment {
213    V2ContextPolicyAssessment {
214        assessment: assessment.into(),
215        policy_digest: None,
216        status: status.into(),
217        reason: reason.into(),
218        detail: detail.into(),
219    }
220}
221
222/// Go `sameV2ContextPolicy`.
223pub(crate) fn same_v2_context_policy(a: Option<&V2ContextPolicy>, b: Option<&V2ContextPolicy>) -> bool {
224    match (a, b) {
225        (Some(a), Some(b)) => a.is_valid() && b.is_valid() && a == b,
226        _ => false,
227    }
228}