1use 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#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct ObjectInfo {
13 pub id: String,
15 pub bytes: u64,
17 pub modified: Option<SystemTime>,
20}
21
22pub trait SnapshotObjects: Send + Sync + std::fmt::Debug {
39 fn location(&self) -> Option<&Path>;
42
43 fn contains(&self, id: &str) -> Result<bool>;
49
50 fn put(&self, id: &str, bytes: &[u8]) -> Result<u64>;
57
58 fn get(&self, id: &str) -> Result<Vec<u8>>;
65
66 fn list(&self) -> Result<Vec<ObjectInfo>>;
72
73 fn remove(&self, id: &str) -> Result<()>;
79}
80
81pub fn object_id(bytes: &[u8]) -> String {
92 crate::fsutil::hex_digest(bytes)
93}
94
95pub 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#[derive(Debug, Default)]
149pub struct InMemorySnapshotObjects {
150 objects: Mutex<HashMap<String, Vec<u8>>>,
151}
152
153impl InMemorySnapshotObjects {
154 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#[derive(Debug, Clone)]
229pub struct FileSnapshotObjects {
230 dir: PathBuf,
231 #[cfg(feature = "encrypted")]
232 envelope: Option<crate::encrypted::StoreEnvelope>,
233}
234
235impl FileSnapshotObjects {
236 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 pub fn for_workspace(snapshots_dir: &Path, root: &Path) -> Self {
248 Self::new(snapshots_dir.join(root_digest(root)))
249 }
250
251 #[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 #[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#[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 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}