Skip to main content

ratify_protocol/v2/
operation_context.rs

1//! Operation, session, and challenge-claim constructions (SPEC-v2 §2.4, §4;
2//! Go `operation_context_v2.go` and `challenge_claim_v2.go`).
3
4use sha2::{Digest, Sha256, Sha384};
5
6use super::crypto::lower_hex;
7use super::errors::{err, V2ErrorClass, V2Result};
8use super::limits::V2_MAX_SAFE_INTEGER;
9use super::wire::validate_required_scope_v2;
10
11const OPERATION_CONTEXT_V2_TAG: &[u8] = b"ratify/operation-context/v2";
12const SESSION_CONTEXT_V2_TAG: &[u8] = b"ratify/session-context/v2";
13const CLAIM_DIGEST_TAG: &[u8] = b"ratify-protocol-challenge-claim-v2\0";
14const CLAIM_ID_TAG: &[u8] = b"ratify-protocol-claim-id-v2\0";
15
16/// Action inputs bound to a Protocol v2 presentation.
17#[derive(Debug, Clone, Default, PartialEq, Eq)]
18pub struct OperationContextV2 {
19    pub required_scope: String,
20    pub operation: String,
21    pub resource_id: String,
22    pub requested_path: String,
23    /// Empty or exactly 32 raw SHA-256 bytes.
24    pub payload_digest: Vec<u8>,
25}
26
27/// Verifier session and invocation inputs bound to a Protocol v2 presentation.
28#[derive(Debug, Clone, Default, PartialEq, Eq)]
29pub struct SessionContextV2Inputs {
30    pub verifier_id: String,
31    pub workspace_id: String,
32    pub agent_id: String,
33    pub session_id: String,
34    pub invocation_id: String,
35    /// Exactly 32 raw SHA-256 bytes from [`operation_context_v2_hash`].
36    pub request_hash: Vec<u8>,
37}
38
39fn append_field(preimage: &mut Vec<u8>, field: &[u8]) {
40    preimage.extend_from_slice(&(field.len() as u64).to_be_bytes());
41    preimage.extend_from_slice(field);
42}
43
44/// Decode the Verify API `sha256:<64 lowercase hex>` form. `None` means no
45/// payload digest was supplied.
46pub fn decode_payload_digest_v2(encoded: Option<&str>) -> V2Result<Option<Vec<u8>>> {
47    let Some(encoded) = encoded else {
48        return Ok(None);
49    };
50    match encoded.strip_prefix("sha256:") {
51        Some(h) if h.len() == 64 && lower_hex(h) => match hex::decode(h) {
52            Ok(digest) => Ok(Some(digest)),
53            Err(_) => err(V2ErrorClass::Malformed, "payload digest is not hexadecimal"),
54        },
55        _ => err(
56            V2ErrorClass::Malformed,
57            "payload digest must be sha256: followed by 64 lowercase hexadecimal characters",
58        ),
59    }
60}
61
62/// The operation-context v2 preimage in canonical field order. The required
63/// scope must be one requestable scope (`invalid_required_scope`).
64pub fn operation_context_v2_bytes(ctx: &OperationContextV2) -> V2Result<Vec<u8>> {
65    validate_required_scope_v2(&ctx.required_scope)?;
66    if !ctx.payload_digest.is_empty() && ctx.payload_digest.len() != 32 {
67        return err(
68            V2ErrorClass::ConfigurationInvalid,
69            format!("payload digest must be empty or 32 bytes, got {}", ctx.payload_digest.len()),
70        );
71    }
72    let mut preimage = Vec::from(OPERATION_CONTEXT_V2_TAG);
73    for field in [
74        ctx.required_scope.as_bytes(),
75        ctx.operation.as_bytes(),
76        ctx.resource_id.as_bytes(),
77        ctx.requested_path.as_bytes(),
78        ctx.payload_digest.as_slice(),
79    ] {
80        append_field(&mut preimage, field);
81    }
82    Ok(preimage)
83}
84
85/// `request_hash = SHA-256(operation_context_bytes)`.
86pub fn operation_context_v2_hash(ctx: &OperationContextV2) -> V2Result<Vec<u8>> {
87    Ok(Sha256::digest(operation_context_v2_bytes(ctx)?).to_vec())
88}
89
90/// The session-context v2 preimage in canonical field order.
91pub fn session_context_v2_bytes(inputs: &SessionContextV2Inputs) -> V2Result<Vec<u8>> {
92    let invalid = |m: &str| err(V2ErrorClass::ConfigurationInvalid, m.to_string());
93    if !is_key_id(&inputs.verifier_id) {
94        return invalid("verifier ID must be 64 lowercase hexadecimal characters");
95    }
96    if !is_canonical_workspace_id(&inputs.workspace_id) {
97        return invalid("workspace ID must be a canonical lowercase UUID");
98    }
99    if !is_key_id(&inputs.agent_id) {
100        return invalid("agent ID must be 64 lowercase hexadecimal characters");
101    }
102    if inputs.request_hash.len() != 32 {
103        return invalid("request hash must be 32 bytes");
104    }
105    let mut preimage = Vec::from(SESSION_CONTEXT_V2_TAG);
106    for field in [
107        inputs.verifier_id.as_bytes(),
108        inputs.workspace_id.as_bytes(),
109        inputs.agent_id.as_bytes(),
110        inputs.session_id.as_bytes(),
111        inputs.invocation_id.as_bytes(),
112        inputs.request_hash.as_slice(),
113    ] {
114        append_field(&mut preimage, field);
115    }
116    Ok(preimage)
117}
118
119/// `session_context = SHA-256(session_context_bytes)`.
120pub fn build_session_context_v2(inputs: &SessionContextV2Inputs) -> V2Result<Vec<u8>> {
121    Ok(Sha256::digest(session_context_v2_bytes(inputs)?).to_vec())
122}
123
124fn is_key_id(value: &str) -> bool {
125    value.len() == 64 && lower_hex(value)
126}
127
128fn is_canonical_workspace_id(value: &str) -> bool {
129    value.len() == 36
130        && value.bytes().enumerate().all(|(index, b)| {
131            if [8, 13, 18, 23].contains(&index) {
132                b == b'-'
133            } else {
134                b.is_ascii_digit() || (b'a'..=b'f').contains(&b)
135            }
136        })
137}
138
139/// `ChallengeClaimDigest(c) = SHA-384("ratify-protocol-challenge-claim-v2"
140/// || 0x00 || c)` for exactly 32 decoded challenge bytes.
141pub fn challenge_claim_digest_v2(challenge: &[u8]) -> V2Result<Vec<u8>> {
142    if challenge.len() != 32 {
143        return err(
144            V2ErrorClass::Malformed,
145            "v2 challenge claim requires exactly 32 challenge bytes",
146        );
147    }
148    let mut hash = Sha384::new();
149    hash.update(CLAIM_DIGEST_TAG);
150    hash.update(challenge);
151    Ok(hash.finalize().to_vec())
152}
153
154/// The stable claim ID bound to the namespace and rollback-protected epoch.
155pub fn protocol_claim_id_v2(namespace: &str, replay_epoch: i64, challenge: &[u8]) -> V2Result<String> {
156    validate_namespace_epoch(namespace, replay_epoch)?;
157    protocol_claim_id_from_digest_v2(namespace, replay_epoch, &challenge_claim_digest_v2(challenge)?)
158}
159
160/// The same claim ID from a precomputed 48-byte challenge claim digest.
161pub fn protocol_claim_id_from_digest_v2(
162    namespace: &str,
163    replay_epoch: i64,
164    claim_digest: &[u8],
165) -> V2Result<String> {
166    validate_namespace_epoch(namespace, replay_epoch)?;
167    if claim_digest.len() != 48 {
168        return err(
169            V2ErrorClass::Malformed,
170            "v2 challenge claim digest must be exactly 48 bytes",
171        );
172    }
173    let mut hash = Sha256::new();
174    hash.update(CLAIM_ID_TAG);
175    hash.update((namespace.len() as u64).to_be_bytes());
176    hash.update(namespace.as_bytes());
177    hash.update((replay_epoch as u64).to_be_bytes());
178    hash.update(claim_digest);
179    Ok(hex::encode(hash.finalize()))
180}
181
182fn validate_namespace_epoch(namespace: &str, replay_epoch: i64) -> V2Result<()> {
183    if namespace.is_empty() {
184        return err(
185            V2ErrorClass::ConfigurationInvalid,
186            "v2 verifier namespace must be non-empty valid UTF-8",
187        );
188    }
189    if !(0..=V2_MAX_SAFE_INTEGER).contains(&replay_epoch) {
190        return err(
191            V2ErrorClass::ConfigurationInvalid,
192            "v2 replay epoch is outside 0..2^53-1",
193        );
194    }
195    Ok(())
196}