Skip to main content

oak_core/
hash.rs

1use crate::error::{OakError, Result};
2
3/// Discriminator for the hash algorithm a `Hash` represents.
4///
5/// Inferred from the hex length so a `Hash` can flow between layers without
6/// re-serialization. Backends decide which kinds they accept.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum HashKind {
9    /// 32-byte BLAKE3 (Oak-native, 64 hex chars).
10    Blake3,
11    /// 20-byte SHA-1 (git default object id, 40 hex chars).
12    GitSha1,
13    /// 32-byte SHA-256 (git's sha256 object format, 64 hex chars).
14    /// Indistinguishable from BLAKE3 by length alone — backends disambiguate by context.
15    GitSha256,
16    /// Not a recognized canonical hash length.
17    Unknown,
18}
19
20/// A content hash. The underlying algorithm depends on the backend that produced it:
21/// SQLite/Postgres backends produce BLAKE3; the git backend produces git OIDs (SHA-1
22/// today, SHA-256 in repos using the sha256 object format).
23#[derive(Debug, Clone, PartialEq, Eq, Hash)]
24pub struct Hash(pub String);
25
26impl Hash {
27    /// Create a Hash from a hex string. Accepts 40 hex chars (git SHA-1) or 64 hex chars
28    /// (BLAKE3 or git SHA-256), lowercase only — the canonical form every
29    /// producer (BLAKE3 `to_hex`, git OIDs) emits, and the form hash preimages
30    /// embed, so an uppercase alias of a stored hash is never valid.
31    pub fn from_hex(hex: &str) -> Result<Self> {
32        let len_ok = hex.len() == 40 || hex.len() == 64;
33        let chars_ok = hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
34        if !len_ok || !chars_ok {
35            return Err(OakError::InvalidHash(hex.to_string()));
36        }
37        Ok(Hash(hex.to_string()))
38    }
39
40    /// Get the hex string representation
41    pub fn as_str(&self) -> &str {
42        &self.0
43    }
44
45    /// Get a short version of the hash (first 12 characters)
46    pub fn short(&self) -> &str {
47        let end = self
48            .0
49            .char_indices()
50            .map(|(idx, _)| idx)
51            .nth(12)
52            .unwrap_or(self.0.len());
53        &self.0[..end]
54    }
55
56    /// Best-effort algorithm identification from hex length.
57    ///
58    /// 64-char hex collides between BLAKE3 and git SHA-256; this returns `Blake3` in that case.
59    /// Callers that need to distinguish must use backend context, not this method.
60    pub fn kind(&self) -> HashKind {
61        match self.0.len() {
62            40 => HashKind::GitSha1,
63            64 => HashKind::Blake3,
64            _ => HashKind::Unknown,
65        }
66    }
67}
68
69impl std::fmt::Display for Hash {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        write!(f, "{}", self.0)
72    }
73}
74
75impl serde::Serialize for Hash {
76    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
77    where
78        S: serde::Serializer,
79    {
80        serializer.serialize_str(&self.0)
81    }
82}
83
84impl<'de> serde::Deserialize<'de> for Hash {
85    /// Deserialization is a trust boundary — wire payloads and stored JSON
86    /// land here — so it enforces the same lowercase-hex shape as
87    /// [`Hash::from_hex`]. Without it, arbitrary text (including the `\t`/`\n`
88    /// bytes the canonical tree and commit preimages use as separators) could
89    /// be injected into hash-position fields.
90    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
91    where
92        D: serde::Deserializer<'de>,
93    {
94        let s = String::deserialize(deserializer)?;
95        Hash::from_hex(&s).map_err(serde::de::Error::custom)
96    }
97}
98
99/// Hash arbitrary bytes using BLAKE3
100pub fn hash_bytes(data: &[u8]) -> Hash {
101    let hash = blake3::hash(data);
102    Hash(hash.to_hex().to_string())
103}
104
105/// Hash a string
106pub fn hash_string(s: &str) -> Hash {
107    hash_bytes(s.as_bytes())
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn test_hash_determinism() {
116        let data = b"hello world";
117        let hash1 = hash_bytes(data);
118        let hash2 = hash_bytes(data);
119        assert_eq!(hash1, hash2);
120    }
121
122    #[test]
123    fn test_hash_different_inputs() {
124        let hash1 = hash_bytes(b"hello");
125        let hash2 = hash_bytes(b"world");
126        assert_ne!(hash1, hash2);
127    }
128
129    #[test]
130    fn test_hash_length() {
131        let hash = hash_bytes(b"test");
132        assert_eq!(hash.as_str().len(), 64);
133    }
134
135    #[test]
136    fn test_hash_from_hex_blake3() {
137        let valid_hex = "a".repeat(64);
138        let h = Hash::from_hex(&valid_hex).unwrap();
139        assert_eq!(h.kind(), HashKind::Blake3);
140    }
141
142    #[test]
143    fn test_hash_from_hex_git_sha1() {
144        let valid_hex = "a".repeat(40);
145        let h = Hash::from_hex(&valid_hex).unwrap();
146        assert_eq!(h.kind(), HashKind::GitSha1);
147    }
148
149    #[test]
150    fn test_hash_from_hex_invalid_length() {
151        assert!(Hash::from_hex("abc").is_err());
152        assert!(Hash::from_hex(&"a".repeat(50)).is_err());
153    }
154
155    #[test]
156    fn test_hash_from_hex_invalid_chars() {
157        let invalid_hex = "g".repeat(64);
158        assert!(Hash::from_hex(&invalid_hex).is_err());
159    }
160
161    #[test]
162    fn test_hash_short() {
163        let hash = hash_bytes(b"test");
164        assert_eq!(hash.short().len(), 12);
165    }
166
167    #[test]
168    fn test_hash_short_handles_non_ascii_without_panicking() {
169        let hash = Hash("é".repeat(20));
170        assert_eq!(hash.short(), "éééééééééééé");
171    }
172
173    #[test]
174    fn test_hash_kind_reports_unknown_length() {
175        assert_eq!(Hash("abc".to_string()).kind(), HashKind::Unknown);
176    }
177
178    #[test]
179    fn test_hash_from_hex_rejects_uppercase() {
180        assert!(Hash::from_hex(&"A".repeat(64)).is_err());
181        assert!(Hash::from_hex(&format!("{}F", "a".repeat(63))).is_err());
182    }
183
184    #[test]
185    fn test_deserialize_valid_hex() {
186        let blake3 = format!("\"{}\"", "a".repeat(64));
187        let h: Hash = serde_json::from_str(&blake3).unwrap();
188        assert_eq!(h.kind(), HashKind::Blake3);
189
190        let sha1 = format!("\"{}\"", "0123456789abcdef0123".repeat(2));
191        let h: Hash = serde_json::from_str(&sha1).unwrap();
192        assert_eq!(h.kind(), HashKind::GitSha1);
193
194        // Round-trip: a real hash serializes and deserializes to itself.
195        let original = hash_bytes(b"round trip");
196        let json = serde_json::to_string(&original).unwrap();
197        let back: Hash = serde_json::from_str(&json).unwrap();
198        assert_eq!(original, back);
199    }
200
201    #[test]
202    fn test_deserialize_rejects_junk() {
203        let cases = [
204            "\"\"".to_string(),
205            "\"not a hash\"".to_string(),
206            format!("\"{}\"", "a".repeat(63)), // short
207            format!("\"{}\"", "a".repeat(65)), // long
208            format!("\"{}\"", "A".repeat(64)), // uppercase
209            format!("\"{}\"", "g".repeat(64)), // non-hex
210            format!("\"{}\\t{}\"", "a".repeat(31), "a".repeat(32)), // embedded tab
211            format!("\"{}\\n{}\"", "a".repeat(31), "a".repeat(32)), // embedded newline
212        ];
213        for json in cases {
214            assert!(
215                serde_json::from_str::<Hash>(&json).is_err(),
216                "should reject {json}"
217            );
218        }
219    }
220}