Skip to main content

qualia_client_core/wellfair/
blob_store.rs

1//! Content-addressed blob store for WellFair payloads (master plan ยง5).
2//!
3//! Large or structured payloads that don't belong inline on the journal โ€” credential claim
4//! sets, clinical attachment bytes, letter scans โ€” are stored here as content-addressed blobs.
5//! Their identifier is the SHA-256 (hex) of the bytes, which is exactly the `blob_hash` the
6//! record envelope already carries, so a journal row's `blob_hash` is a direct handle to its
7//! blob. Writes are idempotent (same bytes โ†’ same file) and reads verify integrity.
8
9use std::fs::{self, OpenOptions};
10use std::io::Write;
11use std::path::{Path, PathBuf};
12
13use sha2::{Digest, Sha256};
14
15pub const BLOB_DIR: &str = "wellfair/blobs";
16
17/// Content-addressed store rooted under `{storage_root}/wellfair/blobs`.
18pub struct BlobStore {
19    dir: PathBuf,
20}
21
22fn sha256_hex(bytes: &[u8]) -> String {
23    hex::encode(Sha256::digest(bytes))
24}
25
26/// A content hash is a 64-char lowercase hex string; reject anything else so a hostile or
27/// malformed handle can never escape the blob directory (path-traversal defense).
28fn is_valid_hash(hash_hex: &str) -> bool {
29    hash_hex.len() == 64 && hash_hex.bytes().all(|b| b.is_ascii_hexdigit())
30}
31
32impl BlobStore {
33    /// Opens.
34    pub fn open(storage_root: impl AsRef<Path>) -> std::io::Result<Self> {
35        let dir = storage_root.as_ref().join(BLOB_DIR);
36        fs::create_dir_all(&dir)?;
37        Ok(Self { dir })
38    }
39
40    fn path_for(&self, hash_hex: &str) -> Option<PathBuf> {
41        if is_valid_hash(hash_hex) {
42            Some(self.dir.join(hash_hex))
43        } else {
44            None
45        }
46    }
47
48    /// Store bytes, returning their content hash. Idempotent: re-storing identical bytes is a
49    /// no-op that returns the same hash. Written via a temp file + rename so a reader never sees
50    /// a partial blob.
51    pub fn put(&self, bytes: &[u8]) -> std::io::Result<String> {
52        let hash = sha256_hex(bytes);
53        let path = self.dir.join(&hash);
54        if path.exists() {
55            return Ok(hash);
56        }
57        let tmp = self.dir.join(format!("{hash}.tmp"));
58        {
59            let mut file = OpenOptions::new()
60                .create(true)
61                .write(true)
62                .truncate(true)
63                .open(&tmp)?;
64            file.write_all(bytes)?;
65            file.sync_all()?;
66        }
67        fs::rename(&tmp, &path)?;
68        Ok(hash)
69    }
70
71    /// Read a blob by content hash, verifying integrity. Returns `Ok(None)` if absent, and an
72    /// error if the stored bytes no longer hash to the requested handle (corruption/tamper).
73    pub fn get(&self, hash_hex: &str) -> std::io::Result<Option<Vec<u8>>> {
74        let Some(path) = self.path_for(hash_hex) else {
75            return Err(std::io::Error::new(
76                std::io::ErrorKind::InvalidInput,
77                "invalid blob hash",
78            ));
79        };
80        if !path.exists() {
81            return Ok(None);
82        }
83        let bytes = fs::read(&path)?;
84        if sha256_hex(&bytes) != hash_hex {
85            return Err(std::io::Error::new(
86                std::io::ErrorKind::InvalidData,
87                "blob content hash mismatch (corrupt or tampered)",
88            ));
89        }
90        Ok(Some(bytes))
91    }
92
93    /// `true` when it exists.
94    pub fn exists(&self, hash_hex: &str) -> bool {
95        self.path_for(hash_hex).map(|p| p.exists()).unwrap_or(false)
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    #[test]
104    fn put_returns_content_hash_and_round_trips() {
105        let dir = tempfile::tempdir().unwrap();
106        let store = BlobStore::open(dir.path()).unwrap();
107        let payload = b"{\"claims\":[[\"postcode\",\"3000\"]]}";
108        let hash = store.put(payload).unwrap();
109        assert_eq!(hash.len(), 64);
110        assert!(store.exists(&hash));
111        assert_eq!(store.get(&hash).unwrap().unwrap(), payload);
112    }
113
114    #[test]
115    fn put_is_idempotent() {
116        let dir = tempfile::tempdir().unwrap();
117        let store = BlobStore::open(dir.path()).unwrap();
118        let h1 = store.put(b"same bytes").unwrap();
119        let h2 = store.put(b"same bytes").unwrap();
120        assert_eq!(h1, h2);
121    }
122
123    #[test]
124    fn get_missing_is_none() {
125        let dir = tempfile::tempdir().unwrap();
126        let store = BlobStore::open(dir.path()).unwrap();
127        let absent = sha256_hex(b"never stored");
128        assert!(store.get(&absent).unwrap().is_none());
129    }
130
131    #[test]
132    fn invalid_hash_is_rejected() {
133        let dir = tempfile::tempdir().unwrap();
134        let store = BlobStore::open(dir.path()).unwrap();
135        // Path-traversal attempt and wrong-length handles must not resolve.
136        assert!(store.get("../secret").is_err());
137        assert!(store.get("deadbeef").is_err());
138        assert!(!store.exists("../secret"));
139    }
140
141    #[test]
142    fn tampered_blob_fails_integrity() {
143        let dir = tempfile::tempdir().unwrap();
144        let store = BlobStore::open(dir.path()).unwrap();
145        let hash = store.put(b"original").unwrap();
146        // Overwrite the stored file with different bytes under the same name.
147        fs::write(dir.path().join(BLOB_DIR).join(&hash), b"tampered").unwrap();
148        assert!(store.get(&hash).is_err());
149    }
150
151    #[test]
152    fn survives_reopen() {
153        let dir = tempfile::tempdir().unwrap();
154        let hash = {
155            let store = BlobStore::open(dir.path()).unwrap();
156            store.put(b"persisted payload").unwrap()
157        };
158        let reopened = BlobStore::open(dir.path()).unwrap();
159        assert_eq!(reopened.get(&hash).unwrap().unwrap(), b"persisted payload");
160    }
161}