use std::collections::BTreeMap;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::capsule::{CapsuleId, CapsuleResolution};
use crate::error::RustyError;
use crate::journal::JournalSnapshot;
use crate::record::{
canonicalize_value, sha256_hex, EffectReceipt, JournalRef, PayloadRef, PolicyVersion,
RunEventKind, RunManifest,
};
pub const RECEIPT_FORMAT_VERSION: u32 = 1;
pub struct SigningKey(ed25519_dalek::SigningKey);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PublicKey(ed25519_dalek::VerifyingKey);
impl SigningKey {
pub fn generate() -> Self {
let mut bytes = [0u8; 32];
bytes[..16].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
bytes[16..].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
Self::from_bytes(&bytes)
}
pub fn from_bytes(bytes: &[u8; 32]) -> Self {
Self(ed25519_dalek::SigningKey::from_bytes(bytes))
}
pub fn to_bytes(&self) -> [u8; 32] {
self.0.to_bytes()
}
pub fn from_hex(hex: &str) -> Option<Self> {
let bytes = hex_decode(hex)?;
let bytes: [u8; 32] = bytes.try_into().ok()?;
Some(Self::from_bytes(&bytes))
}
pub fn to_hex(&self) -> String {
hex_encode(&self.0.to_bytes())
}
pub fn public_key(&self) -> PublicKey {
PublicKey(self.0.verifying_key())
}
pub fn key_id(&self) -> String {
derive_key_id(&self.public_key())
}
pub fn sign_hex(&self, message: &[u8]) -> String {
use ed25519_dalek::Signer as _;
hex_encode(&self.0.sign(message).to_bytes())
}
}
impl std::fmt::Debug for SigningKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "SigningKey(key_id: {})", self.key_id())
}
}
impl Clone for SigningKey {
fn clone(&self) -> Self {
Self::from_bytes(&self.0.to_bytes())
}
}
impl PublicKey {
pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self, RustyError> {
ed25519_dalek::VerifyingKey::from_bytes(bytes)
.map(Self)
.map_err(|e| invalid_key(format!("invalid Ed25519 public key: {e}")))
}
pub fn to_bytes(&self) -> [u8; 32] {
self.0.to_bytes()
}
pub fn from_hex(hex: &str) -> Result<Self, RustyError> {
let bytes = hex_decode(hex)
.ok_or_else(|| invalid_key(format!("public key is not valid hex: `{hex}`")))?;
let bytes: [u8; 32] = bytes.try_into().map_err(|_| {
invalid_key(format!(
"public key must be 32 bytes, got {}",
hex.len() / 2
))
})?;
Self::from_bytes(&bytes)
}
pub fn to_hex(&self) -> String {
hex_encode(&self.0.to_bytes())
}
pub fn key_id(&self) -> String {
derive_key_id(self)
}
}
pub fn derive_key_id(public_key: &PublicKey) -> String {
sha256_hex(&public_key.0.to_bytes())
}
fn invalid_key(detail: String) -> RustyError {
RustyError::Serialization(serde_json::Error::io(std::io::Error::new(
std::io::ErrorKind::InvalidData,
detail,
)))
}
fn hex_encode(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
use std::fmt::Write as _;
let _ = write!(out, "{byte:02x}");
}
out
}
fn hex_decode(hex: &str) -> Option<Vec<u8>> {
if hex.len() % 2 != 0 {
return None;
}
(0..hex.len())
.step_by(2)
.map(|i| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok())
.collect()
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RunReceipt {
pub format_version: u32,
pub run_id: String,
pub journal_head: JournalRef,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub manifest_digest: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub manifest: Option<RunManifest>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub capsules: BTreeMap<String, CapsuleId>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub effects: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub executor_policy: Option<PolicyVersion>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub capsule_policies: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub denials: Vec<String>,
pub signer: String,
pub signature: String,
}
#[derive(Serialize)]
struct ReceiptStatement<'a> {
format_version: u32,
run_id: &'a str,
journal_head: &'a JournalRef,
#[serde(skip_serializing_if = "Option::is_none")]
manifest_digest: &'a Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
manifest: &'a Option<RunManifest>,
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
capsules: &'a BTreeMap<String, CapsuleId>,
#[serde(skip_serializing_if = "<[_]>::is_empty")]
effects: &'a [String],
#[serde(skip_serializing_if = "Option::is_none")]
executor_policy: &'a Option<PolicyVersion>,
#[serde(skip_serializing_if = "<[_]>::is_empty")]
capsule_policies: &'a [String],
#[serde(skip_serializing_if = "<[_]>::is_empty")]
denials: &'a [String],
signer: &'a str,
}
impl RunReceipt {
fn statement(&self) -> ReceiptStatement<'_> {
ReceiptStatement {
format_version: self.format_version,
run_id: &self.run_id,
journal_head: &self.journal_head,
manifest_digest: &self.manifest_digest,
manifest: &self.manifest,
capsules: &self.capsules,
effects: &self.effects,
executor_policy: &self.executor_policy,
capsule_policies: &self.capsule_policies,
denials: &self.denials,
signer: &self.signer,
}
}
pub fn canonical_bytes(&self) -> crate::error::Result<Vec<u8>> {
let value = serde_json::to_value(self.statement())?;
Ok(serde_json::to_vec(&canonicalize_value(&value))?)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SigningKeyRotation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub previous_key_id: Option<String>,
pub new_key_id: String,
pub public_key: String,
pub rotated_at: DateTime<Utc>,
}
pub fn mint_receipt(
snapshot: &JournalSnapshot,
manifest: Option<RunManifest>,
executor_policy: Option<PolicyVersion>,
signing_key: &SigningKey,
) -> crate::error::Result<RunReceipt> {
let journal_head = verified_head(snapshot)?;
let components = derive_components(snapshot)?;
let manifest_digest = manifest_digest(manifest.as_ref())?;
let mut receipt = RunReceipt {
format_version: RECEIPT_FORMAT_VERSION,
run_id: snapshot.run_id.clone(),
journal_head,
manifest_digest,
manifest,
capsules: components.capsules,
effects: components.effects,
executor_policy,
capsule_policies: components.capsule_policies,
denials: components.denials,
signer: signing_key.key_id(),
signature: String::new(),
};
let canonical = receipt.canonical_bytes()?;
receipt.signature = signing_key.sign_hex(&canonical);
Ok(receipt)
}
pub fn manifest_digest(manifest: Option<&RunManifest>) -> crate::error::Result<Option<String>> {
let Some(manifest) = manifest else {
return Ok(None);
};
let value = serde_json::to_value(manifest)?;
Ok(Some(sha256_hex(&serde_json::to_vec(&canonicalize_value(
&value,
))?)))
}
fn verified_head(snapshot: &JournalSnapshot) -> crate::error::Result<JournalRef> {
if !snapshot.artifact_refs.is_empty() {
return Err(RustyError::Serialization(serde_json::Error::io(
std::io::Error::new(
std::io::ErrorKind::InvalidData,
"journal snapshot references an external artifact store; \
receipts v1 mint and verify over embedded snapshots",
),
)));
}
let recomputed = crate::journal::recompute_head_hash(&snapshot.events)?;
if recomputed != snapshot.head_hash {
return Err(RustyError::Serialization(serde_json::Error::io(
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"journal snapshot head hash mismatch: events recompute to \
{recomputed}, snapshot claims {}",
snapshot.head_hash
),
),
)));
}
Ok(JournalRef {
events: snapshot.events.len() as u64,
sha256: recomputed,
})
}
struct ReceiptComponents {
capsules: BTreeMap<String, CapsuleId>,
effects: Vec<String>,
capsule_policies: Vec<String>,
denials: Vec<String>,
}
fn derive_components(snapshot: &JournalSnapshot) -> crate::error::Result<ReceiptComponents> {
let mut capsules = BTreeMap::new();
let mut effects = Vec::new();
let mut capsule_policies = Vec::new();
let mut denials = Vec::new();
for event in &snapshot.events {
match event.kind {
RunEventKind::EffectReceipt => {
let Some(value) = resolve_output(snapshot, event) else {
continue;
};
if let Ok(receipt) = serde_json::from_value::<EffectReceipt>(value) {
effects.push(effect_ledger_digest(&receipt)?);
}
}
RunEventKind::CapsuleResolved => {
let Some(value) = resolve_output(snapshot, event) else {
continue;
};
if let Ok(resolution) = serde_json::from_value::<CapsuleResolution>(value) {
capsules.insert(resolution.name, resolution.capsule_id);
if let Some(version) = resolution.policy_version {
if !capsule_policies.contains(&version) {
capsule_policies.push(version);
}
}
}
}
RunEventKind::CapsuleDenied => denials.push(event.id.clone()),
_ => {}
}
}
Ok(ReceiptComponents {
capsules,
effects,
capsule_policies,
denials,
})
}
fn resolve_output(
snapshot: &JournalSnapshot,
event: &crate::record::RunEvent,
) -> Option<serde_json::Value> {
match event.output.as_ref()? {
PayloadRef::Inline(value) => Some(value.clone()),
PayloadRef::Artifact(reference) => snapshot.artifacts.get(&reference.sha256).cloned(),
}
}
#[derive(Serialize)]
struct EffectLedgerEntry<'a> {
provider: &'a str,
provider_id: &'a str,
idempotency_key: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
effect_id: Option<&'a str>,
}
fn effect_ledger_digest(receipt: &EffectReceipt) -> crate::error::Result<String> {
let entry = EffectLedgerEntry {
provider: &receipt.provider,
provider_id: &receipt.provider_id,
idempotency_key: &receipt.idempotency_key,
effect_id: receipt.effect_id.as_deref(),
};
Ok(sha256_hex(&serde_json::to_vec(&entry)?))
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ReceiptRejection {
#[error("unsupported receipt format version {claimed} (this build verifies {supported})")]
FormatVersion {
claimed: u32,
supported: u32,
},
#[error(
"the snapshot references an external artifact store; receipts v1 \
verifies embedded snapshots only"
)]
ExternalArtifacts,
#[error(
"journal head mismatch: the snapshot's events recompute to {recomputed}, \
the snapshot claims {claimed}"
)]
SnapshotHead {
claimed: String,
recomputed: String,
},
#[error("run id mismatch: the receipt attests `{claimed}`, the snapshot records `{snapshot}`")]
RunId {
claimed: String,
snapshot: String,
},
#[error(
"journal head mismatch: the receipt signs {claimed}, the snapshot's events \
recompute to {recomputed}"
)]
JournalHead {
claimed: String,
recomputed: String,
},
#[error(
"journal length mismatch: the receipt signs {claimed} events, the snapshot holds {actual}"
)]
JournalLength {
claimed: u64,
actual: u64,
},
#[error(
"manifest digest mismatch: the receipt commits {claimed:?}, the carried manifest \
re-hashes to {recomputed:?}"
)]
ManifestDigest {
claimed: Option<String>,
recomputed: Option<String>,
},
#[error("capsule resolution mismatch: {0}")]
CapsuleResolutions(String),
#[error("effect ledger mismatch: {0}")]
EffectLedger(String),
#[error("capsule policy mismatch: {0}")]
CapsulePolicies(String),
#[error("denials ledger mismatch: {0}")]
DenialsLedger(String),
#[error(
"signer mismatch: the receipt names signer {claimed}, the offered key derives {derived}"
)]
SignerKeyId {
claimed: String,
derived: String,
},
#[error("signature invalid: {0}")]
Signature(String),
}
impl ReceiptRejection {
pub fn component(&self) -> &'static str {
match self {
ReceiptRejection::FormatVersion { .. } => "format_version",
ReceiptRejection::ExternalArtifacts => "external_artifacts",
ReceiptRejection::SnapshotHead { .. } => "journal_head",
ReceiptRejection::RunId { .. } => "run_id",
ReceiptRejection::JournalHead { .. } => "journal_head",
ReceiptRejection::JournalLength { .. } => "journal_head",
ReceiptRejection::ManifestDigest { .. } => "manifest_digest",
ReceiptRejection::CapsuleResolutions(_) => "capsule_resolutions",
ReceiptRejection::EffectLedger(_) => "effect_ledger",
ReceiptRejection::CapsulePolicies(_) => "capsule_policies",
ReceiptRejection::DenialsLedger(_) => "denials_ledger",
ReceiptRejection::SignerKeyId { .. } => "signer_key_id",
ReceiptRejection::Signature(_) => "signature",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VerifiedRun {
pub run_id: String,
pub journal_head: JournalRef,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub manifest_digest: Option<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub capsules: BTreeMap<String, CapsuleId>,
pub effect_receipts: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub executor_policy: Option<PolicyVersion>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub capsule_policies: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub denials: Vec<String>,
pub signer: String,
}
pub fn verify_receipt(
snapshot: &JournalSnapshot,
receipt: &RunReceipt,
public_key: &PublicKey,
) -> Result<VerifiedRun, ReceiptRejection> {
if receipt.format_version != RECEIPT_FORMAT_VERSION {
return Err(ReceiptRejection::FormatVersion {
claimed: receipt.format_version,
supported: RECEIPT_FORMAT_VERSION,
});
}
if !snapshot.artifact_refs.is_empty() {
return Err(ReceiptRejection::ExternalArtifacts);
}
let recomputed_head = crate::journal::recompute_head_hash(&snapshot.events).map_err(|e| {
ReceiptRejection::Signature(format!("the snapshot's events cannot be hashed: {e}"))
})?;
if recomputed_head != snapshot.head_hash {
return Err(ReceiptRejection::SnapshotHead {
claimed: snapshot.head_hash.clone(),
recomputed: recomputed_head,
});
}
if receipt.run_id != snapshot.run_id {
return Err(ReceiptRejection::RunId {
claimed: receipt.run_id.clone(),
snapshot: snapshot.run_id.clone(),
});
}
if receipt.journal_head.sha256 != recomputed_head {
return Err(ReceiptRejection::JournalHead {
claimed: receipt.journal_head.sha256.clone(),
recomputed: recomputed_head,
});
}
if receipt.journal_head.events != snapshot.events.len() as u64 {
return Err(ReceiptRejection::JournalLength {
claimed: receipt.journal_head.events,
actual: snapshot.events.len() as u64,
});
}
let recomputed_manifest = manifest_digest(receipt.manifest.as_ref())
.map_err(|e| ReceiptRejection::Signature(format!("the manifest cannot be hashed: {e}")))?;
if recomputed_manifest != receipt.manifest_digest {
return Err(ReceiptRejection::ManifestDigest {
claimed: receipt.manifest_digest.clone(),
recomputed: recomputed_manifest,
});
}
let components = derive_components(snapshot)
.map_err(|e| ReceiptRejection::Signature(format!("the ledger cannot be digested: {e}")))?;
if components.capsules != receipt.capsules {
return Err(ReceiptRejection::CapsuleResolutions(ledger_diff(
"capsules",
&receipt.capsules,
&components.capsules,
)));
}
if components.effects != receipt.effects {
return Err(ReceiptRejection::EffectLedger(sequence_diff(
"effects",
&receipt.effects,
&components.effects,
)));
}
if components.capsule_policies != receipt.capsule_policies {
return Err(ReceiptRejection::CapsulePolicies(sequence_diff(
"capsule policies",
&receipt.capsule_policies,
&components.capsule_policies,
)));
}
if components.denials != receipt.denials {
return Err(ReceiptRejection::DenialsLedger(sequence_diff(
"denials",
&receipt.denials,
&components.denials,
)));
}
let derived_key_id = public_key.key_id();
if derived_key_id != receipt.signer {
return Err(ReceiptRejection::SignerKeyId {
claimed: receipt.signer.clone(),
derived: derived_key_id,
});
}
let canonical = receipt
.canonical_bytes()
.map_err(|e| ReceiptRejection::Signature(format!("the statement cannot be hashed: {e}")))?;
let signature_bytes = hex_decode(&receipt.signature)
.and_then(|bytes| <[u8; 64]>::try_from(bytes.as_slice()).ok())
.ok_or_else(|| {
ReceiptRejection::Signature("the signature is not 64 bytes of hex".to_string())
})?;
let signature = ed25519_dalek::Signature::from_bytes(&signature_bytes);
public_key
.0
.verify_strict(&canonical, &signature)
.map_err(|_| {
ReceiptRejection::Signature(
"the signature does not verify over the canonical statement".to_string(),
)
})?;
Ok(VerifiedRun {
run_id: receipt.run_id.clone(),
journal_head: receipt.journal_head.clone(),
manifest_digest: receipt.manifest_digest.clone(),
capsules: components.capsules,
effect_receipts: components.effects.len(),
executor_policy: receipt.executor_policy.clone(),
capsule_policies: components.capsule_policies,
denials: components.denials,
signer: receipt.signer.clone(),
})
}
fn sequence_diff(what: &str, claimed: &[String], recomputed: &[String]) -> String {
if claimed.len() != recomputed.len() {
return format!(
"the receipt's {what} ledger holds {} entries, the journal recomputes {}",
claimed.len(),
recomputed.len()
);
}
for (index, (claimed, recomputed)) in claimed.iter().zip(recomputed).enumerate() {
if claimed != recomputed {
return format!(
"the receipt's {what} entry {index} is `{claimed}`, the journal recomputes `{recomputed}`"
);
}
}
format!("the receipt's {what} ledger disagrees with the journal")
}
fn ledger_diff(
what: &str,
claimed: &BTreeMap<String, CapsuleId>,
recomputed: &BTreeMap<String, CapsuleId>,
) -> String {
for (name, id) in claimed {
match recomputed.get(name) {
None => {
return format!(
"the receipt resolves pin `{name}` to `{id}`, the journal holds no resolution"
)
}
Some(recomputed) if recomputed != id => {
return format!(
"the receipt resolves pin `{name}` to `{id}`, the journal recomputes `{recomputed}`"
)
}
_ => {}
}
}
for name in recomputed.keys() {
if !claimed.contains_key(name) {
return format!(
"the journal resolves pin `{name}`, the receipt's {what} ledger omits it"
);
}
}
format!("the receipt's {what} ledger disagrees with the journal")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hex_roundtrip_and_rejects_malformed() {
assert_eq!(hex_encode(&[0x00, 0xff, 0x10]), "00ff10");
assert_eq!(hex_decode("00ff10"), Some(vec![0x00, 0xff, 0x10]));
assert_eq!(hex_decode("00FF10"), Some(vec![0x00, 0xff, 0x10]));
assert_eq!(hex_decode("0ff"), None);
assert_eq!(hex_decode("zz"), None);
}
#[test]
fn key_id_is_a_content_address() {
let key = SigningKey::from_bytes(&[7u8; 32]);
let public = key.public_key();
assert_eq!(key.key_id(), derive_key_id(&public));
assert_eq!(key.key_id().len(), 64);
let other = SigningKey::from_bytes(&[8u8; 32]);
assert_ne!(key.key_id(), other.key_id());
let rehydrated = PublicKey::from_hex(&public.to_hex()).unwrap();
assert_eq!(rehydrated, public);
let secret = SigningKey::from_hex(&key.to_hex()).unwrap();
assert_eq!(secret.key_id(), key.key_id());
}
#[test]
fn generated_keys_sign_and_verify() {
let key = SigningKey::generate();
let signature = key.sign_hex(b"canonical bytes");
let bytes = hex_decode(&signature).unwrap();
let signature =
ed25519_dalek::Signature::from_bytes(&<[u8; 64]>::try_from(bytes.as_slice()).unwrap());
key.public_key()
.0
.verify_strict(b"canonical bytes", &signature)
.unwrap();
}
}