//! Consistent, private snapshots of the `SQLite` and filesystem storage pair. use std::path::Path; use serde::{Deserialize, Serialize}; use crate::{ blob_store::FileBlobStore, clock::now, config::Config, database::Database, error::{Error, Result}, private_fs::{self, parent_or_current}, }; const DATABASE_FILE: &str = "cpds.sqlite3"; const BLOB_DIRECTORY: &str = "blobs"; const MANIFEST_FILE: &str = "manifest.json"; #[derive(Deserialize, Serialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] struct Manifest { format_version: u8, created_at: i64, public_url: String, account_did: String, account_handle: String, repo_event_retention: usize, } /// Create a new backup directory without overwriting an existing path. /// /// `SQLite` holds an immediate transaction for the native online backup and blob /// copy, preventing repository mutations or blob lifecycle claims from crossing /// the snapshot boundary. The manifest intentionally excludes passwords and /// signing keys. /// /// # Errors /// /// Returns an error when the target is unsafe or exists, the source snapshot /// cannot be captured, or private durable files cannot be written. pub fn create( database: &Database, blobs: &FileBlobStore, config: &Config, target: &Path, ) -> Result<()> { reject_blob_descendant(&config.blob_directory, target)?; private_fs::create_directory(target)?; database .backup_with(&config.database_path, target.join(DATABASE_FILE), || { private_fs::secure_file(&target.join(DATABASE_FILE))?; blobs.copy_to(&target.join(BLOB_DIRECTORY))?; let manifest = Manifest { format_version: 1, created_at: now(), public_url: config.public_origin.to_string(), account_did: config.account.did.clone(), account_handle: config.account.handle.clone(), repo_event_retention: config.repo_event_retention, }; private_fs::write_file( &target.join(MANIFEST_FILE), &serde_json::to_vec_pretty(&manifest)?, )?; private_fs::sync_directory(target) }) .and_then(|()| private_fs::sync_directory(parent_or_current(target))) .inspect_err(|_| { let _ = std::fs::remove_dir_all(target); }) } /// Verify a colocated backup manifest when the configured database is still in /// the standard backup layout. /// /// # Errors /// /// Returns an error when the manifest is malformed, unsupported, or disagrees /// with the configured public identity, retention policy, or blob directory. pub fn verify_manifest(config: &Config) -> Result<()> { let Some(parent) = config.database_path.parent() else { return Ok(()); }; let path = parent.join(MANIFEST_FILE); if !path.try_exists()? { return Ok(()); } let manifest: Manifest = serde_json::from_slice(&std::fs::read(&path)?)?; if manifest.format_version != 1 { return Err(Error::Configuration(format!( "backup manifest format {} is not supported", manifest.format_version ))); } let expected_blobs = parent.join(BLOB_DIRECTORY); if manifest.public_url != config.public_origin.to_string() || manifest.account_did != config.account.did || manifest.account_handle != config.account.handle || manifest.repo_event_retention != config.repo_event_retention || config.blob_directory != expected_blobs { return Err(Error::Configuration( "backup manifest does not match the configured restore identity or storage".to_owned(), )); } Ok(()) } fn reject_blob_descendant(blob_root: &Path, target: &Path) -> Result<()> { let blob_root = std::fs::canonicalize(blob_root)?; let parent = parent_or_current(target); let target = std::fs::canonicalize(parent)?.join( target .file_name() .ok_or_else(|| Error::Configuration("backup target has no name".to_owned()))?, ); if target.starts_with(blob_root) { return Err(Error::Configuration( "backup target must not be inside CPDS_BLOB_DIRECTORY".to_owned(), )); } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn backup_target_cannot_descend_from_blob_storage() { let directory = tempfile::tempdir().unwrap(); let blobs = directory.path().join("blobs"); std::fs::create_dir(&blobs).unwrap(); let error = reject_blob_descendant(&blobs, &blobs.join("backup")) .unwrap_err() .to_string(); assert!(error.contains("must not be inside")); } }