ratify_protocol/operation_context.rs
1//! Operation-context and session-context canonical constructions
2//! (SPEC §6.4.9).
3//!
4//! Both are raw binary, domain-separated, and length-prefixed — NOT JSON.
5//! Length prefixes exist because raw concatenation is ambiguous
6//! (`"ab" || "c"` equals `"a" || "bc"`); domain tags exist so a hash
7//! computed for one construction can never collide with the other.
8
9#[cfg(not(feature = "std"))]
10use alloc::{format, string::String, vec::Vec};
11
12use sha2::{Digest, Sha256};
13
14const OPERATION_CONTEXT_DOMAIN_TAG: &[u8] = b"ratify/operation-context/v1";
15const SESSION_CONTEXT_DOMAIN_TAG: &[u8] = b"ratify/session-context/v1";
16
17/// The inputs that identify one specific action a presentation authorizes
18/// (SPEC §6.4.9). Which fields are populated is deployment-defined —
19/// empty fields encode as zero-length and the construction stays
20/// well-defined.
21#[derive(Debug, Clone, Default)]
22pub struct OperationContext {
23 /// Scope the action requires (e.g. "files:write").
24 pub required_scope: String,
25 /// Action/operation type (e.g. "git.push", "tool.invoke").
26 pub operation: String,
27 /// Target resource identity.
28 pub resource_id: String,
29 /// Path within the resource.
30 pub requested_path: String,
31 /// Empty, or exactly 32 bytes: the SHA-256 of the canonical request
32 /// payload, where one exists.
33 pub payload_digest: Vec<u8>,
34}
35
36/// The inputs that identify the session a presentation belongs to, plus
37/// the `request_hash` binding the specific operation (SPEC §6.4.9). The
38/// Middleware Custody Profile (SPEC §15.2.1) requires all of them; other
39/// deployments populate what they have.
40#[derive(Debug, Clone, Default)]
41pub struct SessionContextInputs {
42 /// The verifier's identity (e.g. its public key ID). Including it
43 /// makes cross-verifier challenge forwarding detectable at the
44 /// cryptographic layer (SPEC §15.1).
45 pub verifier_id: String,
46 /// The deployment's workspace/tenant identifier.
47 pub workspace_id: String,
48 /// The presenting agent's identity.
49 pub agent_id: String,
50 /// The session identifier.
51 pub session_id: String,
52 /// The specific invocation within the session.
53 pub invocation_id: String,
54 /// Exactly 32 bytes — the [`operation_context_hash`] of the action
55 /// being authorized. A deployment with no operation-specific inputs
56 /// derives it from an all-empty [`OperationContext`]. Binding the
57 /// session but not the operation would let an intermediary attach a
58 /// valid proof to the wrong action inside the right session.
59 pub request_hash: Vec<u8>,
60}
61
62/// Append big-endian uint64 length || field bytes.
63fn length_prefixed(buf: &mut Vec<u8>, field: &[u8]) {
64 buf.extend_from_slice(&(field.len() as u64).to_be_bytes());
65 buf.extend_from_slice(field);
66}
67
68/// The SPEC §6.4.9 operation-context preimage: the domain tag followed
69/// by every field length-prefixed, in canonical order. Errors if
70/// `payload_digest` is neither empty nor exactly 32 bytes.
71pub fn operation_context_bytes(ctx: &OperationContext) -> Result<Vec<u8>, String> {
72 if !ctx.payload_digest.is_empty() && ctx.payload_digest.len() != 32 {
73 return Err(format!(
74 "payload digest must be empty or 32 bytes, got {}",
75 ctx.payload_digest.len()
76 ));
77 }
78 let mut buf = Vec::from(OPERATION_CONTEXT_DOMAIN_TAG);
79 length_prefixed(&mut buf, ctx.required_scope.as_bytes());
80 length_prefixed(&mut buf, ctx.operation.as_bytes());
81 length_prefixed(&mut buf, ctx.resource_id.as_bytes());
82 length_prefixed(&mut buf, ctx.requested_path.as_bytes());
83 length_prefixed(&mut buf, &ctx.payload_digest);
84 Ok(buf)
85}
86
87/// The 32-byte `request_hash`: SHA-256 over the SPEC §6.4.9
88/// operation-context bytes.
89pub fn operation_context_hash(ctx: &OperationContext) -> Result<Vec<u8>, String> {
90 Ok(Sha256::digest(operation_context_bytes(ctx)?).to_vec())
91}
92
93/// The SPEC §6.4.9 session-context preimage: the domain tag followed by
94/// every field length-prefixed, in canonical order. Errors unless
95/// `request_hash` is exactly 32 bytes — use [`operation_context_hash`]
96/// to derive it, over an all-empty [`OperationContext`] when the
97/// deployment has no operation-specific inputs.
98pub fn session_context_bytes(inputs: &SessionContextInputs) -> Result<Vec<u8>, String> {
99 if inputs.request_hash.len() != 32 {
100 return Err(format!(
101 "request hash must be exactly 32 bytes, got {}",
102 inputs.request_hash.len()
103 ));
104 }
105 let mut buf = Vec::from(SESSION_CONTEXT_DOMAIN_TAG);
106 length_prefixed(&mut buf, inputs.verifier_id.as_bytes());
107 length_prefixed(&mut buf, inputs.workspace_id.as_bytes());
108 length_prefixed(&mut buf, inputs.agent_id.as_bytes());
109 length_prefixed(&mut buf, inputs.session_id.as_bytes());
110 length_prefixed(&mut buf, inputs.invocation_id.as_bytes());
111 length_prefixed(&mut buf, &inputs.request_hash);
112 Ok(buf)
113}
114
115/// The 32-byte `session_context`: SHA-256 over the SPEC §6.4.9
116/// session-context bytes — what a session-bound deployment passes as
117/// `VerifyOptions.session_context` (and what the agent side includes in
118/// the challenge signing bytes, SPEC §6.4.2). Verification receipts and
119/// audit records bind this hash, never the preimage.
120pub fn build_session_context(inputs: &SessionContextInputs) -> Result<Vec<u8>, String> {
121 Ok(Sha256::digest(session_context_bytes(inputs)?).to_vec())
122}