use crate::ask::Entry;
use crate::canonical::{self, JcsError};
use crate::ed25519::{self, Sign1};
use crate::record::{Header, RecordError, HEADER_VERSION};
use crate::substrate::Signer;
use ciborium::Value as Cbor;
use evidence_request::time::parse_utc;
use serde_json::{json, Map, Value};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
pub const SPEC_VERSION: &str = "draft-mih-scitt-agent-action-capsule-05";
pub const FORMAT_VERSION: &str = "4";
pub const CAPSULE_ID_MEDIA_TYPE: &str = "application/agent-action-capsule-id";
const ATTESTATION: &str = "model_attestation";
pub const DEFAULT_DEVELOPER: &str = "evidencebook";
pub struct Producer<'a> {
pub operator: &'a str,
pub developer: &'a str,
pub signer: &'a dyn Signer,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SealedRecord {
pub record_id: String,
pub header: Vec<u8>,
pub capsule: Vec<u8>,
pub body: Vec<u8>,
pub envelope: Vec<u8>,
}
#[derive(Debug, thiserror::Error)]
pub enum SealRecordError {
#[error("invalid: {0}")]
Invalid(String),
#[error(transparent)]
Record(#[from] RecordError),
#[error("header: {0}")]
Canonical(#[from] JcsError),
#[error(transparent)]
Sign(#[from] crate::substrate::SignError),
#[error("not sealed: {0}")]
Mismatch(String),
}
fn invalid(why: impl Into<String>) -> SealRecordError {
SealRecordError::Invalid(why.into())
}
pub fn header(
book_id: &str,
seq: u64,
committed_at: &str,
entry: &Entry,
) -> Result<Header, SealRecordError> {
let committed_at = go_time(committed_at, 6).ok_or_else(|| {
invalid(format!(
"committed_at {committed_at:?} is not an RFC 3339 UTC time"
))
})?;
Ok(Header {
version: HEADER_VERSION,
book_id: book_id.to_string(),
seq,
record_type: entry.record_type.clone(),
epistemic_type: entry.epistemic_type,
committed_at,
event_time_claim: None,
payload_commitments: Vec::new(),
retention_state: None,
links: entry.links.clone(),
subject_ref: None,
principal_ref: None,
counterparty_ref: None,
correlation: Default::default(),
reproduction: None,
statement: (!entry.statement.is_null()).then(|| entry.statement.clone()),
})
}
pub fn rfc3339_nano(text: &str) -> Option<String> {
go_time(text, 9)
}
fn go_time(text: &str, digits: usize) -> Option<String> {
parse_utc(text)?;
let (seconds, fraction) = split_fraction(text);
let kept = &fraction[..fraction.len().min(digits)];
let kept = kept.trim_end_matches('0');
Some(if kept.is_empty() {
format!("{seconds}Z")
} else {
format!("{seconds}.{kept}Z")
})
}
fn split_fraction(text: &str) -> (&str, &str) {
let seconds = &text[..19];
let fraction = text[19..]
.strip_prefix('.')
.map_or("", |f| f.trim_end_matches('Z'));
(seconds, fraction)
}
fn capsule_timestamp(committed_at: &str) -> String {
let (seconds, fraction) = split_fraction(committed_at);
if fraction.is_empty() {
format!("{seconds}Z")
} else {
format!("{seconds}.{fraction:0<6}Z")
}
}
fn producer_protected(public_key: &[u8; 32]) -> Vec<u8> {
let mut out = vec![0xa3, 0x03, 0x78, CAPSULE_ID_MEDIA_TYPE.len() as u8];
out.extend_from_slice(CAPSULE_ID_MEDIA_TYPE.as_bytes());
out.extend_from_slice(&[0x04, 0x58, 0x20]);
out.extend_from_slice(public_key);
out.extend_from_slice(&[0x01, 0x27]);
out
}
fn public_key_of(signer: &dyn Signer) -> Result<[u8; 32], SealRecordError> {
hex::decode(signer.key_id())
.ok()
.and_then(|k| k.try_into().ok())
.ok_or_else(|| invalid("the signer's key id is not a 32-byte Ed25519 public key in hex"))
}
fn sha256_hex(bytes: &[u8]) -> String {
hex::encode(Sha256::digest(bytes))
}
fn canonical_header(header: &Header) -> Result<Vec<u8>, SealRecordError> {
header.validate()?;
if go_time(&header.committed_at, 6).as_deref() != Some(header.committed_at.as_str()) {
return Err(invalid(format!(
"committed_at {:?} is not a UTC time in microseconds, written as Go writes it",
header.committed_at
)));
}
if let Some(claim) = &header.event_time_claim {
if rfc3339_nano(claim).as_deref() != Some(claim.as_str()) {
return Err(invalid(format!(
"event_time_claim {claim:?} is not a UTC time written as Go writes it"
)));
}
}
let refs = [
("subject_ref", &header.subject_ref),
("principal_ref", &header.principal_ref),
("counterparty_ref", &header.counterparty_ref),
];
if let Some((name, _)) = refs.iter().find(|(_, r)| r.as_deref() == Some("")) {
return Err(invalid(format!("{name} is empty; leave it unset")));
}
if let Some((key, _)) = header.correlation.iter().find(|(_, v)| v.is_empty()) {
return Err(invalid(format!(
"correlation key {key:?} is empty; leave it unset"
)));
}
let value = serde_json::to_value(header).map_err(|e| invalid(e.to_string()))?;
Ok(canonical::jcs(&value)?)
}
const BASE_MEMBERS: &[&str] = &[
"spec_version",
"format_version",
"canonicalization_id",
"capsule_id",
"action_id",
"action_type",
"operator",
"developer",
"timestamp",
"epoch_id",
"domain",
"provenance",
"provenance_mode",
"disposition",
"effect",
"chain",
"assurance",
"cross_party",
ATTESTATION,
"references",
"constraints",
"compliance",
"signature",
"key_id",
];
fn fyi_capsule(
action_id: &str,
timestamp: &str,
agent_input_digest: &str,
references: Vec<Value>,
extensions: &BTreeMap<String, Value>,
operator: &str,
developer: &str,
) -> Result<(Vec<u8>, String, Vec<u8>), SealRecordError> {
if operator.trim().is_empty() || developer.trim().is_empty() {
return Err(invalid("operator and developer must not be empty"));
}
if action_id.trim().is_empty() {
return Err(invalid("action id is required"));
}
let mut capsule = Map::new();
capsule.insert("spec_version".into(), json!(SPEC_VERSION));
capsule.insert("format_version".into(), json!(FORMAT_VERSION));
capsule.insert(
"canonicalization_id".into(),
json!(canonical::CANONICALIZATION_JCS),
);
capsule.insert("action_id".into(), json!(action_id));
capsule.insert("action_type".into(), json!("fyi"));
capsule.insert("operator".into(), json!(operator));
capsule.insert("developer".into(), json!(developer));
capsule.insert("timestamp".into(), json!(timestamp));
capsule.insert(
"assurance".into(),
json!({"attestation_mode": "self_attested", "effect_mode": "not_applicable", "ledger_mode": "standalone"}),
);
let attestation = json!({"compute_attestation": {"agent_input_digest": agent_input_digest}});
capsule.insert(ATTESTATION.into(), attestation);
if !references.is_empty() {
capsule.insert("references".into(), Value::Array(references));
}
for (name, value) in extensions {
let mut chars = name.chars();
let named = chars.next().is_some_and(|c| c.is_ascii_lowercase())
&& chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
if !named {
return Err(invalid(format!(
"extension name {name:?} must be lowercase letters, digits and underscores, starting with a letter"
)));
}
if BASE_MEMBERS.contains(&name.as_str()) {
return Err(invalid(format!(
"extension {name:?} is a base-profile member"
)));
}
if value.is_null() {
return Err(invalid(format!("extension {name:?} must not be null")));
}
if let Err(e) = canonical::jcs(value) {
return Err(invalid(format!("extension {name:?}: {e}")));
}
capsule.insert(name.clone(), value.clone());
}
let body = canonical::jcs(&Value::Object(capsule.clone()))?;
let capsule_id = sha256_hex(&body);
capsule.insert("capsule_id".into(), json!(capsule_id));
let capsule = canonical::jcs(&Value::Object(capsule))?;
Ok((body, capsule_id, capsule))
}
fn record_capsule(
header: &Header,
header_bytes: &[u8],
operator: &str,
developer: &str,
) -> Result<(Vec<u8>, String, Vec<u8>), SealRecordError> {
let references: Vec<Value> = header
.links
.iter()
.map(|l| json!({"type": "agent-action-capsule", "digest_alg": "SHA-256", "digest": l.target}))
.collect();
fyi_capsule(
&format!("{}#{}", header.book_id, header.seq),
&capsule_timestamp(&header.committed_at),
&sha256_hex(header_bytes),
references,
&BTreeMap::new(),
operator,
developer,
)
}
fn producer_envelope(capsule_id: &str, signer: &dyn Signer) -> Result<Vec<u8>, SealRecordError> {
let public_key = public_key_of(signer)?;
let protected = producer_protected(&public_key);
let id = hex::decode(capsule_id).expect("a SHA-256 hex digest decodes");
let to_be_signed = ed25519::to_be_signed(&protected, &id);
let signature = signer.sign(&to_be_signed)?;
if !ed25519::verify(&public_key, &to_be_signed, &signature) {
return Err(invalid(
"the signer's signature does not verify under its key id",
));
}
Ok(ed25519::encode(&Cbor::Tag(
ed25519::COSE_SIGN1_TAG,
Box::new(Cbor::Array(vec![
Cbor::Bytes(protected),
Cbor::Map(Vec::new()),
Cbor::Bytes(id),
Cbor::Bytes(signature.to_vec()),
])),
)))
}
pub fn seal_record(
header: &Header,
producer: &Producer<'_>,
) -> Result<SealedRecord, SealRecordError> {
let header_bytes = canonical_header(header)?;
public_key_of(producer.signer)?;
let (body, record_id, capsule) =
record_capsule(header, &header_bytes, producer.operator, producer.developer)?;
let envelope = producer_envelope(&record_id, producer.signer)?;
Ok(SealedRecord {
record_id,
header: header_bytes,
capsule,
body,
envelope,
})
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SealedCapsule {
pub capsule_id: String,
pub capsule: Vec<u8>,
pub envelope: Vec<u8>,
}
pub fn seal_payload(
action_id: &str,
at: &str,
payload: &[u8],
extensions: &BTreeMap<String, Value>,
producer: &Producer<'_>,
) -> Result<SealedCapsule, SealRecordError> {
let decoded: Value = serde_json::from_slice(payload)
.map_err(|e| invalid(format!("the payload is not JSON: {e}")))?;
if canonical::jcs(&decoded)? != payload {
return Err(invalid("the payload is not its canonical JSON (JCS) bytes"));
}
let Some(timestamp) = go_time(at, 6) else {
return Err(invalid("the capsule timestamp is not an RFC 3339 UTC time"));
};
public_key_of(producer.signer)?;
let (_, capsule_id, capsule) = fyi_capsule(
action_id,
&capsule_timestamp(×tamp),
&sha256_hex(payload),
Vec::new(),
extensions,
producer.operator,
producer.developer,
)?;
let envelope = producer_envelope(&capsule_id, producer.signer)?;
Ok(SealedCapsule {
capsule_id,
capsule,
envelope,
})
}
impl SealedRecord {
pub fn verify(&self, public_key: &[u8; 32]) -> Result<(), SealRecordError> {
let mismatch =
|why: &str| SealRecordError::Mismatch(format!("record {}: {why}", self.record_id));
let header: Header = serde_json::from_slice(&self.header)
.map_err(|_| mismatch("the header is not a record header"))?;
if canonical_header(&header).ok().as_deref() != Some(self.header.as_slice()) {
return Err(mismatch("the header is not one a book seals, in JCS"));
}
let capsule: Value = serde_json::from_slice(&self.capsule)
.map_err(|_| mismatch("the capsule is not JSON"))?;
let named = |member: &str| capsule.get(member).and_then(Value::as_str).unwrap_or("");
let (body, record_id, expected) =
record_capsule(&header, &self.header, named("operator"), named("developer"))
.map_err(|e| mismatch(&format!("no record capsule of this header: {e}")))?;
if expected != self.capsule || body != self.body || record_id != self.record_id {
return Err(mismatch(
"the capsule is not the record capsule of this header",
));
}
let message = Sign1::decode(&self.envelope)
.ok_or_else(|| mismatch("the envelope is not a COSE_Sign1"))?;
if message.protected != producer_protected(public_key)
|| !message.unprotected.is_empty()
|| hex::encode(&message.payload) != self.record_id
{
return Err(mismatch(
"the envelope is not the Producer Envelope of this record and key",
));
}
if !message.verifies_under(public_key) {
return Err(mismatch("the envelope's signature does not verify"));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn times_are_written_as_go_writes_them() {
assert_eq!(
go_time("2026-10-15T00:00:01Z", 6).unwrap(),
"2026-10-15T00:00:01Z"
);
assert_eq!(
go_time("2026-10-15T00:00:01.000Z", 6).unwrap(),
"2026-10-15T00:00:01Z"
);
assert_eq!(
go_time("2026-10-15T00:00:01.1234567Z", 6).unwrap(),
"2026-10-15T00:00:01.123456Z"
);
assert_eq!(
go_time("2026-10-15T00:00:01.120Z", 6).unwrap(),
"2026-10-15T00:00:01.12Z"
);
assert_eq!(
rfc3339_nano("2026-10-15T00:00:01.123456789Z").unwrap(),
"2026-10-15T00:00:01.123456789Z"
);
assert!(go_time("2026-10-15T00:00:01+00:00", 6).is_none());
assert!(go_time("2026-13-15T00:00:01Z", 6).is_none());
assert_eq!(
capsule_timestamp("2026-10-15T00:00:01Z"),
"2026-10-15T00:00:01Z"
);
assert_eq!(
capsule_timestamp("2026-10-15T00:00:01.12Z"),
"2026-10-15T00:00:01.120000Z"
);
}
}