Skip to main content

adk_harness/snapshot/
objects.rs

1//! The content-addressed object store of snapshots (spec 3.1 §7.27, §9.2 I68).
2
3use std::collections::HashMap;
4use std::path::{Path, PathBuf};
5use std::sync::Mutex;
6use std::time::SystemTime;
7
8use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
9
10/// One stored object, as [`SnapshotObjects::list`] reports it.
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct ObjectInfo {
13    /// The object's id: the lowercase hex SHA-256 of its plaintext.
14    pub id: String,
15    /// Bytes it takes in the store (sealed, when sealed).
16    pub bytes: u64,
17    /// When it was written, where the store knows; garbage collection spares recent
18    /// objects, which another process may be about to reference.
19    pub modified: Option<SystemTime>,
20}
21
22/// Where snapshot contents live: objects addressed by the SHA-256 of their plaintext, so a
23/// file that did not change between snapshots is stored once (spec 3.1 §7.27).
24///
25/// The methods are synchronous: the snapshot walk calls them from a blocking task.
26///
27/// # Example
28///
29/// ```rust
30/// use adk_harness::snapshot::{InMemorySnapshotObjects, SnapshotObjects};
31///
32/// let objects = InMemorySnapshotObjects::new();
33/// let id = adk_harness::snapshot::object_id(b"hello");
34/// assert_eq!(objects.put(&id, b"hello").unwrap(), 5);
35/// assert_eq!(objects.put(&id, b"hello").unwrap(), 0, "stored once");
36/// assert_eq!(objects.get(&id).unwrap(), b"hello");
37/// ```
38pub trait SnapshotObjects: Send + Sync + std::fmt::Debug {
39    /// The directory the objects are kept in, when they are on disk: a snapshot store is
40    /// refused inside the workspace it snapshots (I68).
41    fn location(&self) -> Option<&Path>;
42
43    /// Whether `id` is stored.
44    ///
45    /// # Errors
46    ///
47    /// Returns `harness.snapshot.io` when the store cannot be read.
48    fn contains(&self, id: &str) -> Result<bool>;
49
50    /// Stores `bytes` under `id` unless it is stored; returns the bytes written, `0` when
51    /// it was already there.
52    ///
53    /// # Errors
54    ///
55    /// Returns `harness.snapshot.io` when the object cannot be written.
56    fn put(&self, id: &str, bytes: &[u8]) -> Result<u64>;
57
58    /// The plaintext of `id`.
59    ///
60    /// # Errors
61    ///
62    /// Returns `harness.snapshot.missing_object` when `id` is not stored, or the store's
63    /// key error when it cannot be opened.
64    fn get(&self, id: &str) -> Result<Vec<u8>>;
65
66    /// Every stored object.
67    ///
68    /// # Errors
69    ///
70    /// Returns `harness.snapshot.io` when the store cannot be read.
71    fn list(&self) -> Result<Vec<ObjectInfo>>;
72
73    /// Removes `id`; removing an object that is not stored succeeds.
74    ///
75    /// # Errors
76    ///
77    /// Returns `harness.snapshot.io` when the object cannot be removed.
78    fn remove(&self, id: &str) -> Result<()>;
79}
80
81/// The object id of `bytes`: the lowercase hex SHA-256.
82///
83/// # Example
84///
85/// ```rust
86/// assert_eq!(
87///     adk_harness::snapshot::object_id(b""),
88///     "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
89/// );
90/// ```
91pub fn object_id(bytes: &[u8]) -> String {
92    crate::fsutil::hex_digest(bytes)
93}
94
95/// The directory name of a workspace's snapshots: the SHA-256 of its canonical root.
96///
97/// # Example
98///
99/// ```rust
100/// let a = adk_harness::snapshot::root_digest(std::path::Path::new("/work/a"));
101/// assert_eq!(a.len(), 64);
102/// assert_ne!(a, adk_harness::snapshot::root_digest(std::path::Path::new("/work/b")));
103/// ```
104pub fn root_digest(root: &Path) -> String {
105    crate::fsutil::sha256_hex(&root.to_string_lossy())
106}
107
108pub(crate) fn snapshot_error(
109    code: &'static str,
110    category: ErrorCategory,
111    message: impl Into<String>,
112) -> AdkError {
113    AdkError::new(ErrorComponent::Agent, category, code, message)
114}
115
116fn io_error(path: &Path, action: &str, error: &std::io::Error) -> AdkError {
117    snapshot_error(
118        "harness.snapshot.io",
119        ErrorCategory::Unavailable,
120        format!("{action} {}: {error}", path.display()),
121    )
122}
123
124fn missing(id: &str) -> AdkError {
125    snapshot_error(
126        "harness.snapshot.missing_object",
127        ErrorCategory::NotFound,
128        format!(
129            "snapshot object {id} is not in the store: it was collected or the store was moved; \
130             this snapshot cannot be restored"
131        ),
132    )
133}
134
135fn valid_id(id: &str) -> Result<()> {
136    if id.len() == 64 && id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
137        Ok(())
138    } else {
139        Err(snapshot_error(
140            "harness.snapshot.invalid_object",
141            ErrorCategory::InvalidInput,
142            format!("'{id}' is not a snapshot object id (64 lowercase hex characters)"),
143        ))
144    }
145}
146
147/// Snapshot objects in memory, for tests and `--ephemeral` sessions.
148#[derive(Debug, Default)]
149pub struct InMemorySnapshotObjects {
150    objects: Mutex<HashMap<String, Vec<u8>>>,
151}
152
153impl InMemorySnapshotObjects {
154    /// An empty store.
155    pub fn new() -> Self {
156        Self::default()
157    }
158}
159
160impl SnapshotObjects for InMemorySnapshotObjects {
161    fn location(&self) -> Option<&Path> {
162        None
163    }
164
165    fn contains(&self, id: &str) -> Result<bool> {
166        Ok(self.objects.lock().unwrap_or_else(|e| e.into_inner()).contains_key(id))
167    }
168
169    fn put(&self, id: &str, bytes: &[u8]) -> Result<u64> {
170        valid_id(id)?;
171        let mut objects = self.objects.lock().unwrap_or_else(|e| e.into_inner());
172        if objects.contains_key(id) {
173            return Ok(0);
174        }
175        objects.insert(id.to_string(), bytes.to_vec());
176        Ok(bytes.len() as u64)
177    }
178
179    fn get(&self, id: &str) -> Result<Vec<u8>> {
180        self.objects
181            .lock()
182            .unwrap_or_else(|e| e.into_inner())
183            .get(id)
184            .cloned()
185            .ok_or_else(|| missing(id))
186    }
187
188    fn list(&self) -> Result<Vec<ObjectInfo>> {
189        Ok(self
190            .objects
191            .lock()
192            .unwrap_or_else(|e| e.into_inner())
193            .iter()
194            .map(|(id, bytes)| ObjectInfo {
195                id: id.clone(),
196                bytes: bytes.len() as u64,
197                modified: None,
198            })
199            .collect())
200    }
201
202    fn remove(&self, id: &str) -> Result<()> {
203        self.objects.lock().unwrap_or_else(|e| e.into_inner()).remove(id);
204        Ok(())
205    }
206}
207
208/// Snapshot objects on disk: `<dir>/objects/<first two hex digits>/<the rest>`, each
209/// readable by its owner only, and sealed with the §7.12 envelope when a store key is
210/// configured (spec 3.1 §7.27, I68).
211///
212/// [`for_workspace`](Self::for_workspace) puts a workspace's objects under
213/// `<snapshots dir>/<sha256 of the canonical root>/`; adk-cli's snapshots dir is
214/// `<config dir>/adk-rust/snapshots`, beside `harness.db`.
215///
216/// # Example
217///
218/// ```rust
219/// use adk_harness::snapshot::{FileSnapshotObjects, SnapshotObjects};
220///
221/// let home = tempfile::tempdir().unwrap();
222/// let objects = FileSnapshotObjects::for_workspace(home.path(), std::path::Path::new("/work/app"));
223/// let id = adk_harness::snapshot::object_id(b"fn main() {}");
224/// objects.put(&id, b"fn main() {}").unwrap();
225/// assert_eq!(objects.get(&id).unwrap(), b"fn main() {}");
226/// assert!(objects.location().unwrap().starts_with(home.path()));
227/// ```
228#[derive(Debug, Clone)]
229pub struct FileSnapshotObjects {
230    dir: PathBuf,
231    #[cfg(feature = "encrypted")]
232    envelope: Option<crate::encrypted::StoreEnvelope>,
233}
234
235impl FileSnapshotObjects {
236    /// Objects under `dir`.
237    pub fn new(dir: impl Into<PathBuf>) -> Self {
238        Self {
239            dir: dir.into(),
240            #[cfg(feature = "encrypted")]
241            envelope: None,
242        }
243    }
244
245    /// The objects of the workspace at `root` under `snapshots_dir`:
246    /// `<snapshots_dir>/<sha256 of root>/`. Pass the canonical root.
247    pub fn for_workspace(snapshots_dir: &Path, root: &Path) -> Self {
248        Self::new(snapshots_dir.join(root_digest(root)))
249    }
250
251    /// Seals every object under `keyring` (spec 3.1 §7.12): an object written in
252    /// plaintext then fails to open (I57) until `rewrap` seals it.
253    #[cfg(feature = "encrypted")]
254    #[must_use]
255    pub fn with_keyring(mut self, keyring: crate::encrypted::StoreKeyring) -> Self {
256        self.envelope = Some(crate::encrypted::StoreEnvelope::new(keyring, "snapshot-objects"));
257        self
258    }
259
260    /// Seals every object a previous key or no key sealed under the current key, and
261    /// returns how many changed. Without a keyring, nothing changes.
262    ///
263    /// # Errors
264    ///
265    /// Returns `harness.store.decrypt_failed` when an object opens under no key the
266    /// keyring holds, or `harness.snapshot.io`.
267    #[cfg(feature = "encrypted")]
268    pub fn rewrap(&self) -> Result<u64> {
269        let Some(envelope) = &self.envelope else {
270            return Ok(0);
271        };
272        let mut changed = 0;
273        for info in self.list()? {
274            let path = self.path(&info.id);
275            let bytes = std::fs::read(&path).map_err(|error| io_error(&path, "read", &error))?;
276            let address = [info.id.as_str()];
277            let text =
278                std::str::from_utf8(&bytes).ok().filter(|t| adk_session::envelope::is_envelope(t));
279            let resealed = match text {
280                Some(text) => envelope.reseal(&address, text)?,
281                None => Some(envelope.seal(&address, &bytes)?),
282            };
283            if let Some(resealed) = resealed {
284                crate::fsutil::write_atomic_private_sync(&path, resealed.as_bytes())?;
285                changed += 1;
286            }
287        }
288        Ok(changed)
289    }
290
291    fn objects_dir(&self) -> PathBuf {
292        self.dir.join("objects")
293    }
294
295    fn path(&self, id: &str) -> PathBuf {
296        let (fan, rest) = id.split_at(2.min(id.len()));
297        self.objects_dir().join(fan).join(rest)
298    }
299
300    #[cfg(feature = "encrypted")]
301    fn encode(&self, id: &str, bytes: &[u8]) -> Result<Vec<u8>> {
302        match &self.envelope {
303            Some(envelope) => Ok(envelope.seal(&[id], bytes)?.into_bytes()),
304            None => Ok(bytes.to_vec()),
305        }
306    }
307
308    #[cfg(not(feature = "encrypted"))]
309    fn encode(&self, _id: &str, bytes: &[u8]) -> Result<Vec<u8>> {
310        Ok(bytes.to_vec())
311    }
312
313    #[cfg(feature = "encrypted")]
314    fn decode(&self, id: &str, stored: Vec<u8>) -> Result<Vec<u8>> {
315        let text =
316            std::str::from_utf8(&stored).ok().filter(|t| adk_session::envelope::is_envelope(t));
317        match (&self.envelope, text) {
318            (Some(envelope), Some(text)) => Ok(envelope.open(&[id], text)?.0),
319            (Some(envelope), None) => Err(snapshot_error(
320                "harness.store.unencrypted",
321                ErrorCategory::InvalidInput,
322                format!(
323                    "snapshot object {id} is in plaintext while a store key is configured; seal \
324                     existing objects with `adk-rust store rotate-key` ({})",
325                    envelope.store()
326                ),
327            )),
328            (None, Some(_)) => Err(snapshot_error(
329                "harness.store.key_required",
330                ErrorCategory::Unauthorized,
331                "the snapshot objects were written under a store key; pass --store-key (or set \
332                 [store] key in the user config) — they never open in plaintext",
333            )),
334            (None, None) => Ok(stored),
335        }
336    }
337
338    #[cfg(not(feature = "encrypted"))]
339    fn decode(&self, _id: &str, stored: Vec<u8>) -> Result<Vec<u8>> {
340        Ok(stored)
341    }
342}
343
344impl SnapshotObjects for FileSnapshotObjects {
345    fn location(&self) -> Option<&Path> {
346        Some(&self.dir)
347    }
348
349    fn contains(&self, id: &str) -> Result<bool> {
350        valid_id(id)?;
351        let path = self.path(id);
352        match path.symlink_metadata() {
353            Ok(metadata) => Ok(metadata.is_file()),
354            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
355            Err(error) => Err(io_error(&path, "read", &error)),
356        }
357    }
358
359    fn put(&self, id: &str, bytes: &[u8]) -> Result<u64> {
360        if self.contains(id)? {
361            return Ok(0);
362        }
363        let encoded = self.encode(id, bytes)?;
364        crate::fsutil::write_atomic_private_sync(&self.path(id), &encoded)?;
365        Ok(encoded.len() as u64)
366    }
367
368    fn get(&self, id: &str) -> Result<Vec<u8>> {
369        valid_id(id)?;
370        let path = self.path(id);
371        let stored = match std::fs::read(&path) {
372            Ok(bytes) => bytes,
373            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Err(missing(id)),
374            Err(error) => return Err(io_error(&path, "read", &error)),
375        };
376        let plaintext = self.decode(id, stored)?;
377        if object_id(&plaintext) != id {
378            return Err(snapshot_error(
379                "harness.snapshot.corrupt_object",
380                ErrorCategory::Internal,
381                format!("snapshot object {id} does not hash to its id; it was changed on disk"),
382            ));
383        }
384        Ok(plaintext)
385    }
386
387    fn list(&self) -> Result<Vec<ObjectInfo>> {
388        let root = self.objects_dir();
389        let fans = match std::fs::read_dir(&root) {
390            Ok(fans) => fans,
391            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
392            Err(error) => return Err(io_error(&root, "list", &error)),
393        };
394        let mut out = Vec::new();
395        for fan in fans.flatten() {
396            let fan_name = fan.file_name().to_string_lossy().into_owned();
397            let Ok(entries) = std::fs::read_dir(fan.path()) else {
398                continue;
399            };
400            for entry in entries.flatten() {
401                let id = format!("{fan_name}{}", entry.file_name().to_string_lossy());
402                if valid_id(&id).is_err() {
403                    continue;
404                }
405                let Ok(metadata) = entry.metadata() else {
406                    continue;
407                };
408                out.push(ObjectInfo {
409                    id,
410                    bytes: metadata.len(),
411                    modified: metadata.modified().ok(),
412                });
413            }
414        }
415        Ok(out)
416    }
417
418    fn remove(&self, id: &str) -> Result<()> {
419        valid_id(id)?;
420        let path = self.path(id);
421        match std::fs::remove_file(&path) {
422            Ok(()) => Ok(()),
423            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
424            Err(error) => Err(io_error(&path, "remove", &error)),
425        }
426    }
427}
428
429/// Seals every workspace's objects under `snapshots_dir` with `keyring`'s current key
430/// (`adk-rust store rotate-key`); returns how many objects changed.
431///
432/// # Errors
433///
434/// As [`FileSnapshotObjects::rewrap`].
435#[cfg(feature = "encrypted")]
436pub fn rewrap_all(snapshots_dir: &Path, keyring: &crate::encrypted::StoreKeyring) -> Result<u64> {
437    let Ok(roots) = std::fs::read_dir(snapshots_dir) else {
438        return Ok(0);
439    };
440    let mut changed = 0;
441    for root in roots.flatten() {
442        if root.path().is_dir() {
443            changed +=
444                FileSnapshotObjects::new(root.path()).with_keyring(keyring.clone()).rewrap()?;
445        }
446    }
447    Ok(changed)
448}
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453
454    #[test]
455    fn an_object_is_stored_once_and_listed() {
456        let dir = tempfile::tempdir().unwrap();
457        let objects = FileSnapshotObjects::new(dir.path());
458        let id = object_id(b"content");
459        assert!(!objects.contains(&id).unwrap());
460        assert_eq!(objects.put(&id, b"content").unwrap(), 7);
461        assert_eq!(objects.put(&id, b"content").unwrap(), 0);
462        assert_eq!(objects.list().unwrap().len(), 1);
463        objects.remove(&id).unwrap();
464        assert!(objects.list().unwrap().is_empty());
465        assert_eq!(objects.get(&id).unwrap_err().code, "harness.snapshot.missing_object");
466        assert!(objects.put("../escape", b"x").is_err(), "an id is never a path");
467    }
468
469    #[cfg(unix)]
470    #[test]
471    fn objects_are_readable_by_their_owner_only() {
472        use std::os::unix::fs::PermissionsExt as _;
473        let dir = tempfile::tempdir().unwrap();
474        let objects = FileSnapshotObjects::new(dir.path());
475        let id = object_id(b"secret");
476        objects.put(&id, b"secret").unwrap();
477        let mode = std::fs::metadata(objects.path(&id)).unwrap().permissions().mode();
478        assert_eq!(mode & 0o777, 0o600);
479    }
480
481    #[cfg(feature = "encrypted")]
482    #[test]
483    fn sealed_objects_hold_no_plaintext_and_need_the_key() {
484        let dir = tempfile::tempdir().unwrap();
485        let keyring = crate::encrypted::StoreKeyring::generate();
486        let sealed = FileSnapshotObjects::new(dir.path()).with_keyring(keyring.clone());
487        let id = object_id(b"password = hunter2");
488        sealed.put(&id, b"password = hunter2").unwrap();
489        let on_disk = std::fs::read(sealed.path(&id)).unwrap();
490        assert!(!String::from_utf8_lossy(&on_disk).contains("hunter2"));
491        assert_eq!(sealed.get(&id).unwrap(), b"password = hunter2");
492        let plain = FileSnapshotObjects::new(dir.path());
493        assert_eq!(plain.get(&id).unwrap_err().code, "harness.store.key_required");
494        let other = FileSnapshotObjects::new(dir.path())
495            .with_keyring(crate::encrypted::StoreKeyring::generate());
496        assert!(other.get(&id).is_err(), "another key opens nothing");
497
498        // A plaintext object written before the key fails closed until it is rewrapped.
499        let plain_id = object_id(b"older");
500        plain.put(&plain_id, b"older").unwrap();
501        assert_eq!(sealed.get(&plain_id).unwrap_err().code, "harness.store.unencrypted");
502        assert_eq!(sealed.rewrap().unwrap(), 1);
503        assert_eq!(sealed.get(&plain_id).unwrap(), b"older");
504    }
505}