Skip to main content

llm_provenance/
digest.rs

1//! Structured context digests and stable text/JSON encodings.
2
3use std::str::FromStr;
4
5use serde::{Deserialize, Serialize};
6
7use crate::{ContextVerification, Error, Result, SchemaId, SchemaVersion};
8
9/// Hash algorithm used for context digests.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(rename_all = "kebab-case")]
12pub enum HashAlgorithm {
13    /// SHA-256.
14    Sha256,
15}
16
17/// Canonical representation hashed to produce a context digest.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "kebab-case")]
20pub enum Canonicalization {
21    /// RFC 8785 JSON Canonicalization Scheme.
22    Rfc8785,
23}
24
25/// A self-describing digest of a versioned context.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
27pub struct ContextDigest {
28    schema: SchemaId,
29    schema_version: SchemaVersion,
30    algorithm: HashAlgorithm,
31    canonicalization: Canonicalization,
32    #[serde(with = "hex::serde")]
33    digest: [u8; 32],
34}
35
36impl ContextDigest {
37    pub(crate) fn from_parts(
38        schema: SchemaId,
39        schema_version: SchemaVersion,
40        digest: [u8; 32],
41    ) -> Self {
42        Self {
43            schema,
44            schema_version,
45            algorithm: HashAlgorithm::Sha256,
46            canonicalization: Canonicalization::Rfc8785,
47            digest,
48        }
49    }
50
51    /// Return the application schema identifier carried by the digest.
52    pub fn schema(&self) -> &SchemaId {
53        &self.schema
54    }
55
56    /// Return the application schema version carried by the digest.
57    pub fn schema_version(&self) -> SchemaVersion {
58        self.schema_version
59    }
60
61    /// Return the hash algorithm.
62    pub fn algorithm(&self) -> HashAlgorithm {
63        self.algorithm
64    }
65
66    /// Return the canonicalization scheme.
67    pub fn canonicalization(&self) -> Canonicalization {
68        self.canonicalization
69    }
70
71    /// Return the raw SHA-256 bytes.
72    pub fn as_bytes(&self) -> &[u8; 32] {
73        &self.digest
74    }
75
76    /// Return the lowercase hexadecimal digest for compatibility with stores
77    /// that already persist an opaque `context_hash` string.
78    pub fn hex(&self) -> String {
79        hex::encode(self.digest)
80    }
81
82    /// Verify that retained bytes are the exact canonical context preimage for
83    /// this digest.
84    ///
85    /// This rejects non-canonical JSON and malformed context envelopes before
86    /// comparing the resulting self-describing digest.
87    pub fn verify_canonical_bytes(&self, bytes: &[u8]) -> Result<ContextVerification> {
88        crate::context::verify_canonical_bytes(self, bytes)
89    }
90}
91
92impl std::fmt::Display for ContextDigest {
93    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        write!(
95            formatter,
96            "sha256:rfc8785:{}:{}:{}",
97            self.schema,
98            self.schema_version.get(),
99            self.hex()
100        )
101    }
102}
103
104impl FromStr for ContextDigest {
105    type Err = Error;
106
107    fn from_str(value: &str) -> Result<Self> {
108        let mut parts = value.split(':');
109        let algorithm = parts.next();
110        let canonicalization = parts.next();
111        let schema = parts.next();
112        let version = parts.next();
113        let digest = parts.next();
114        if algorithm != Some("sha256")
115            || canonicalization != Some("rfc8785")
116            || parts.next().is_some()
117        {
118            return Err(Error::InvalidDigest(value.to_owned()));
119        }
120        let schema = SchemaId::new(schema.unwrap_or_default())
121            .map_err(|_| Error::InvalidDigest(value.to_owned()))?;
122        let raw_version = version.unwrap_or_default();
123        let version = raw_version
124            .parse::<u32>()
125            .ok()
126            .filter(|parsed| parsed.to_string() == raw_version)
127            .and_then(|raw| SchemaVersion::new(raw).ok())
128            .ok_or_else(|| Error::InvalidDigest(value.to_owned()))?;
129        let raw_digest = digest.unwrap_or_default();
130        if raw_digest.len() != 64
131            || !raw_digest
132                .bytes()
133                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
134        {
135            return Err(Error::InvalidDigest(value.to_owned()));
136        }
137        let bytes = hex::decode(raw_digest).map_err(|_| Error::InvalidDigest(value.to_owned()))?;
138        let digest: [u8; 32] = bytes
139            .try_into()
140            .map_err(|_| Error::InvalidDigest(value.to_owned()))?;
141        Ok(Self::from_parts(schema, version, digest))
142    }
143}
144
145impl<'de> Deserialize<'de> for ContextDigest {
146    fn deserialize<D: serde::Deserializer<'de>>(
147        deserializer: D,
148    ) -> std::result::Result<Self, D::Error> {
149        #[derive(Deserialize)]
150        #[serde(deny_unknown_fields)]
151        struct Wire {
152            schema: SchemaId,
153            schema_version: SchemaVersion,
154            algorithm: HashAlgorithm,
155            canonicalization: Canonicalization,
156            #[serde(with = "hex::serde")]
157            digest: Vec<u8>,
158        }
159
160        let wire = Wire::deserialize(deserializer)?;
161        if wire.algorithm != HashAlgorithm::Sha256
162            || wire.canonicalization != Canonicalization::Rfc8785
163        {
164            return Err(serde::de::Error::custom("unsupported digest metadata"));
165        }
166        let digest = wire
167            .digest
168            .try_into()
169            .map_err(|_| serde::de::Error::custom("SHA-256 digest must contain 32 bytes"))?;
170        Ok(Self::from_parts(wire.schema, wire.schema_version, digest))
171    }
172}