#[cfg(not(feature = "std"))]
use alloc::{format, string::String, vec::Vec};
use sha2::{Digest, Sha256};
const OPERATION_CONTEXT_DOMAIN_TAG: &[u8] = b"ratify/operation-context/v1";
const SESSION_CONTEXT_DOMAIN_TAG: &[u8] = b"ratify/session-context/v1";
#[derive(Debug, Clone, Default)]
pub struct OperationContext {
pub required_scope: String,
pub operation: String,
pub resource_id: String,
pub requested_path: String,
pub payload_digest: Vec<u8>,
}
#[derive(Debug, Clone, Default)]
pub struct SessionContextInputs {
pub verifier_id: String,
pub workspace_id: String,
pub agent_id: String,
pub session_id: String,
pub invocation_id: String,
pub request_hash: Vec<u8>,
}
fn length_prefixed(buf: &mut Vec<u8>, field: &[u8]) {
buf.extend_from_slice(&(field.len() as u64).to_be_bytes());
buf.extend_from_slice(field);
}
pub fn operation_context_bytes(ctx: &OperationContext) -> Result<Vec<u8>, String> {
if !ctx.payload_digest.is_empty() && ctx.payload_digest.len() != 32 {
return Err(format!(
"payload digest must be empty or 32 bytes, got {}",
ctx.payload_digest.len()
));
}
let mut buf = Vec::from(OPERATION_CONTEXT_DOMAIN_TAG);
length_prefixed(&mut buf, ctx.required_scope.as_bytes());
length_prefixed(&mut buf, ctx.operation.as_bytes());
length_prefixed(&mut buf, ctx.resource_id.as_bytes());
length_prefixed(&mut buf, ctx.requested_path.as_bytes());
length_prefixed(&mut buf, &ctx.payload_digest);
Ok(buf)
}
pub fn operation_context_hash(ctx: &OperationContext) -> Result<Vec<u8>, String> {
Ok(Sha256::digest(operation_context_bytes(ctx)?).to_vec())
}
pub fn session_context_bytes(inputs: &SessionContextInputs) -> Result<Vec<u8>, String> {
if inputs.request_hash.len() != 32 {
return Err(format!(
"request hash must be exactly 32 bytes, got {}",
inputs.request_hash.len()
));
}
let mut buf = Vec::from(SESSION_CONTEXT_DOMAIN_TAG);
length_prefixed(&mut buf, inputs.verifier_id.as_bytes());
length_prefixed(&mut buf, inputs.workspace_id.as_bytes());
length_prefixed(&mut buf, inputs.agent_id.as_bytes());
length_prefixed(&mut buf, inputs.session_id.as_bytes());
length_prefixed(&mut buf, inputs.invocation_id.as_bytes());
length_prefixed(&mut buf, &inputs.request_hash);
Ok(buf)
}
pub fn build_session_context(inputs: &SessionContextInputs) -> Result<Vec<u8>, String> {
Ok(Sha256::digest(session_context_bytes(inputs)?).to_vec())
}