Skip to main content

surjection_core/apply/
backup.rs

1//! Pre-write copies of client files (SPEC 8.4 step 2, 9.5):
2//! `backups/files/<ts>-<apply-id>/<encoded-path>`, readable by the current
3//! user only, because client files may hold secrets. Machine-local; never
4//! pushed.
5//!
6//! An import that moves literal secrets to references leaves the old values
7//! in the backups its apply made (M35): [`mark_old_values`] records which
8//! ones in the run's result, and [`purge_old_values`] removes exactly those.
9
10use std::collections::BTreeSet;
11use std::path::{Path, PathBuf};
12use std::time::{Duration, SystemTime, UNIX_EPOCH};
13
14use crate::apply::{ApplyEnv, journal};
15use crate::error::{CoreError, ErrorCode};
16use crate::fs::Fs;
17use crate::paths::SurjectionHome;
18use crate::secrets::SecretValue;
19use crate::secrets::scanner::MIN_TRACKED_LEN;
20use crate::store::{LOCK_TIMEOUT, StoreLock, utc_datetime};
21
22/// Directory under `backups/` holding one directory per apply run.
23pub const FILES_DIR: &str = "files";
24/// Runs always kept.
25const KEEP_RUNS: usize = 50;
26/// Older runs beyond [`KEEP_RUNS`] are kept until they are this old.
27const KEEP_FOR: Duration = Duration::from_secs(30 * 86_400);
28
29/// `20260101T000000Z`: sorts by time, safe in a file name on every OS.
30pub fn timestamp(time: SystemTime) -> String {
31    let datetime = utc_datetime(time);
32    let (date, clock) = (datetime.date.expect("set"), datetime.time.expect("set"));
33    format!(
34        "{:04}{:02}{:02}T{:02}{:02}{:02}Z",
35        date.year,
36        date.month,
37        date.day,
38        clock.hour,
39        clock.minute,
40        clock.second.unwrap_or(0)
41    )
42}
43
44/// The directory of one apply run's backups.
45pub fn run_dir(home: &SurjectionHome, time: SystemTime, apply_id: &str) -> PathBuf {
46    home.backups_dir()
47        .join(FILES_DIR)
48        .join(format!("{}-{apply_id}", timestamp(time)))
49}
50
51/// An absolute path as one file name: `%`, the drive colon, both
52/// separators and every other character a file name cannot hold on some
53/// OS are percent-encoded, so the original path is unambiguous on every OS
54/// (`C%3A%5CUsers%5Cme%5C.claude.json`).
55pub fn encode_path(path: &Path) -> String {
56    let text = path.to_string_lossy();
57    let mut out = String::with_capacity(text.len());
58    for c in text.chars() {
59        let reserved = matches!(
60            c,
61            '%' | ':' | '/' | '\\' | '<' | '>' | '"' | '|' | '?' | '*'
62        ) || c.is_control();
63        if reserved {
64            let mut buf = [0u8; 4];
65            for byte in c.encode_utf8(&mut buf).bytes() {
66                out.push_str(&format!("%{byte:02X}"));
67            }
68        } else {
69            out.push(c);
70        }
71    }
72    out
73}
74
75/// The path an [`encode_path`] name stands for.
76pub fn decode_path(name: &str) -> Option<String> {
77    let bytes = name.as_bytes();
78    let mut out = Vec::with_capacity(bytes.len());
79    let mut index = 0;
80    while index < bytes.len() {
81        if bytes[index] == b'%' {
82            let hex = name.get(index + 1..index + 3)?;
83            out.push(u8::from_str_radix(hex, 16).ok()?);
84            index += 3;
85        } else {
86            out.push(bytes[index]);
87            index += 1;
88        }
89    }
90    String::from_utf8(out).ok()
91}
92
93/// Copies `bytes`, the current content of `file`, into the run directory
94/// `dir`. The `backups/`, `backups/files/` and run directories and the copy
95/// are restricted to the current user.
96pub fn save(
97    fs: &dyn Fs,
98    home: &SurjectionHome,
99    dir: &Path,
100    file: &Path,
101    bytes: &[u8],
102) -> Result<PathBuf, CoreError> {
103    for level in [
104        home.backups_dir(),
105        home.backups_dir().join(FILES_DIR),
106        dir.to_path_buf(),
107    ] {
108        fs.create_private_dir_all(&level).map_err(|err| {
109            CoreError::new(
110                ErrorCode::IoError,
111                format!("cannot create backup directory: {err}"),
112            )
113            .with_path(&level)
114        })?;
115    }
116    let path = dir.join(encode_path(file));
117    fs.write_private(&path, bytes).map_err(|err| {
118        CoreError::new(ErrorCode::IoError, format!("cannot write backup: {err}")).with_path(&path)
119    })?;
120    Ok(path)
121}
122
123/// Retention (SPEC 9.5): the last 50 runs, or 30 days, whichever keeps
124/// more. Directories that do not look like runs are left alone.
125pub fn prune(fs: &dyn Fs, home: &SurjectionHome, now: SystemTime) -> Result<(), CoreError> {
126    let root = home.backups_dir().join(FILES_DIR);
127    if !fs.is_dir(&root) {
128        return Ok(());
129    }
130    let mut runs: Vec<(PathBuf, SystemTime)> = fs
131        .read_dir(&root)
132        .map_err(|err| {
133            CoreError::new(ErrorCode::IoError, format!("cannot list backups: {err}"))
134                .with_path(&root)
135        })?
136        .into_iter()
137        .filter_map(|path| {
138            let name = path.file_name()?.to_str()?;
139            let time = parse_timestamp(name.get(..16)?)?;
140            Some((path, time))
141        })
142        .collect();
143    runs.sort_by_key(|(_, time)| *time);
144    let old = runs.len().saturating_sub(KEEP_RUNS);
145    for (path, time) in runs.into_iter().take(old) {
146        let age = now.duration_since(time).unwrap_or_default();
147        if age > KEEP_FOR {
148            fs.remove_dir_all(&path).map_err(|err| {
149                CoreError::new(ErrorCode::IoError, format!("cannot prune backups: {err}"))
150                    .with_path(&path)
151            })?;
152        }
153    }
154    Ok(())
155}
156
157/// One apply run's client file backups.
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct BackupRun {
160    /// The run's directory name (`<ts>-<apply-id>`), unique per run.
161    pub dir: String,
162    /// The apply id, or `restore-<run id>-<ulid>` for the bytes a client
163    /// file restore replaced.
164    pub apply_id: String,
165    pub time: SystemTime,
166    /// The original paths of the files backed up, sorted.
167    pub files: Vec<PathBuf>,
168}
169
170/// Every apply run with file backups on this machine, newest first.
171/// Directories that do not look like runs are skipped.
172pub fn list_runs(fs: &dyn Fs, home: &SurjectionHome) -> Result<Vec<BackupRun>, CoreError> {
173    let root = home.backups_dir().join(FILES_DIR);
174    if !fs.is_dir(&root) {
175        return Ok(Vec::new());
176    }
177    let list = |dir: &Path| {
178        fs.read_dir(dir).map_err(|err| {
179            CoreError::new(ErrorCode::IoError, format!("cannot list backups: {err}")).with_path(dir)
180        })
181    };
182    let mut runs = Vec::new();
183    for dir in list(&root)? {
184        let Some(name) = dir.file_name().and_then(|name| name.to_str()) else {
185            continue;
186        };
187        let (Some(time), Some(apply_id)) = (
188            name.get(..16).and_then(parse_timestamp),
189            name.get(17..)
190                .filter(|_| name.as_bytes().get(16) == Some(&b'-')),
191        ) else {
192            continue;
193        };
194        if !fs.is_dir(&dir) {
195            continue;
196        }
197        let mut files: Vec<PathBuf> = list(&dir)?
198            .iter()
199            .filter_map(|file| decode_path(file.file_name()?.to_str()?))
200            .map(PathBuf::from)
201            .collect();
202        files.sort();
203        runs.push(BackupRun {
204            dir: name.to_owned(),
205            apply_id: apply_id.to_owned(),
206            time,
207            files,
208        });
209    }
210    runs.sort_by(|a, b| {
211        b.time
212            .cmp(&a.time)
213            .then_with(|| b.apply_id.cmp(&a.apply_id))
214    });
215    Ok(runs)
216}
217
218/// Reads a [`timestamp`].
219pub fn parse_timestamp(text: &str) -> Option<SystemTime> {
220    let bytes = text.as_bytes();
221    if bytes.len() != 16 || bytes[8] != b'T' || bytes[15] != b'Z' {
222        return None;
223    }
224    let number = |range: std::ops::Range<usize>| text.get(range)?.parse::<i64>().ok();
225    let (year, month, day) = (number(0..4)?, number(4..6)?, number(6..8)?);
226    let (hour, minute, second) = (number(9..11)?, number(11..13)?, number(13..15)?);
227    let days = days_from_civil(year, month, day);
228    let seconds = days * 86_400 + hour * 3600 + minute * 60 + second;
229    Some(UNIX_EPOCH + Duration::from_secs(u64::try_from(seconds).ok()?))
230}
231
232/// Days since 1970-01-01 of a proleptic Gregorian date (Howard Hinnant's
233/// `days_from_civil`).
234fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
235    let year = if month <= 2 { year - 1 } else { year };
236    let era = year.div_euclid(400);
237    let yoe = year - era * 400;
238    let mp = (month + 9) % 12;
239    let doy = (153 * mp + 2) / 5 + day - 1;
240    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
241    era * 146_097 + doe - 719_468
242}
243
244/// The client files whose backup of the finished run `apply_id` holds one
245/// of `values` (an import's extracted secrets, which the run replaced with
246/// references), each marked `old_values` in the run's result (M35). Values
247/// are compared in memory and never kept; values shorter than the leak
248/// scanner's minimum are not looked for, and a backup that cannot be read
249/// is left unmarked.
250pub fn mark_old_values(
251    fs: &dyn Fs,
252    state_dir: &Path,
253    apply_id: &str,
254    values: &[SecretValue],
255) -> Result<Vec<PathBuf>, CoreError> {
256    let needles = value_forms(values);
257    if needles.is_empty() {
258        return Ok(Vec::new());
259    }
260    let Some(mut run) = journal::result(fs, state_dir, apply_id)? else {
261        return Ok(Vec::new());
262    };
263    let mut found = Vec::new();
264    for record in run.files.iter_mut().filter(|record| !record.backup_removed) {
265        let Some(backup) = record.backup.as_deref() else {
266            continue;
267        };
268        let Ok(bytes) = fs.read(Path::new(backup)) else {
269            continue;
270        };
271        if needles.iter().any(|needle| contains(&bytes, needle)) {
272            record.old_values = true;
273            found.push(PathBuf::from(&record.file));
274        }
275    }
276    if !found.is_empty() {
277        run.save_result(fs, state_dir)?;
278    }
279    Ok(found)
280}
281
282/// Each value as a client file may hold it: as is, trimmed, and escaped in
283/// a JSON or TOML string.
284fn value_forms(values: &[SecretValue]) -> Vec<Vec<u8>> {
285    let mut forms: BTreeSet<Vec<u8>> = BTreeSet::new();
286    for value in values {
287        let value = value.expose();
288        let escaped = serde_json::to_string(value).unwrap_or_default();
289        let escaped = escaped
290            .strip_prefix('"')
291            .and_then(|rest| rest.strip_suffix('"'))
292            .unwrap_or_default();
293        for form in [value, value.trim(), escaped] {
294            if form.len() >= MIN_TRACKED_LEN {
295                forms.insert(form.as_bytes().to_vec());
296            }
297        }
298    }
299    forms.into_iter().collect()
300}
301
302fn contains(haystack: &[u8], needle: &[u8]) -> bool {
303    haystack
304        .windows(needle.len())
305        .any(|window| window == needle)
306}
307
308/// The files of `files` that hold one of `values` (compared as in
309/// [`mark_old_values`]); a file that cannot be read is left out.
310pub(crate) fn files_holding(
311    fs: &dyn Fs,
312    files: &[PathBuf],
313    values: &[SecretValue],
314) -> Vec<PathBuf> {
315    let needles = value_forms(values);
316    if needles.is_empty() {
317        return Vec::new();
318    }
319    files
320        .iter()
321        .filter(|file| {
322            fs.read(file)
323                .is_ok_and(|bytes| needles.iter().any(|needle| contains(&bytes, needle)))
324        })
325        .cloned()
326        .collect()
327}
328
329/// What [`purge_old_values`] did.
330#[derive(Debug, Default)]
331pub struct Purge {
332    /// The client files whose backup was overwritten with zeros (and, but
333    /// for those in `not_deleted`, deleted): the old values are gone.
334    pub removed: Vec<PathBuf>,
335    /// Of `removed`, the client files whose zeroed backup could not be
336    /// deleted, with why. It holds no old value any more and is never
337    /// restored.
338    pub not_deleted: Vec<(PathBuf, CoreError)>,
339    /// The client files whose backup was left as it was, with why.
340    pub failed: Vec<(PathBuf, CoreError)>,
341}
342
343/// Removes the backups of apply run `apply_id` that hold old secret values
344/// (those [`mark_old_values`] marked; M35). A recorded backup is touched
345/// only when it is this run's backup of its file
346/// (`backups/files/<ts>-<apply-id>/<encoded file>`) and a regular file,
347/// not a link. It is overwritten with zeros in place, recorded as removed
348/// right then (so `restore --files` never writes the zeros back), and
349/// deleted. A failure is reported for its file and the others still go. A
350/// rollback or `restore --files` of that run then reports the file's
351/// original as no longer kept. A run left without backups is removed.
352/// Nothing marked is a no-op. Holds the store lock.
353pub fn purge_old_values(ax: &ApplyEnv<'_>, apply_id: &str) -> Result<Purge, CoreError> {
354    let fs = ax.fs;
355    let state_dir = ax.home.state_dir();
356    let _lock = StoreLock::acquire(fs, &state_dir, LOCK_TIMEOUT)?;
357    let Some(mut run) = journal::result(fs, &state_dir, apply_id)? else {
358        return Err(CoreError::new(
359            ErrorCode::NotFound,
360            format!("no apply run {apply_id:?} is recorded on this machine"),
361        ));
362    };
363    let mut purge = Purge::default();
364    let mut dirs: BTreeSet<PathBuf> = BTreeSet::new();
365    for record in run
366        .files
367        .iter_mut()
368        .filter(|record| record.old_values && !record.backup_removed)
369    {
370        let Some(backup) = record
371            .backup
372            .as_deref()
373            .map(|recorded| rebased(ax.home, Path::new(recorded)))
374        else {
375            continue;
376        };
377        let file = PathBuf::from(&record.file);
378        if let Err(err) = check_backup_path(ax.home, apply_id, &backup, &file) {
379            purge.failed.push((file, err));
380            continue;
381        }
382        let fail = |what: &str, err: std::io::Error| {
383            CoreError::new(ErrorCode::IoError, format!("{what}: {err}")).with_path(&backup)
384        };
385        if fs.is_regular_file(&backup) {
386            if let Err(err) = fs.overwrite_with_zeros(&backup) {
387                purge
388                    .failed
389                    .push((file, fail("cannot overwrite backup", err)));
390                continue;
391            }
392            // The old values are gone: from here on the backup is removed,
393            // whether or not the zeroed file can be deleted.
394            record.backup_removed = true;
395            if let Err(err) = fs.remove_file(&backup) {
396                purge
397                    .not_deleted
398                    .push((file.clone(), fail("cannot delete the zeroed backup", err)));
399            }
400        } else if fs.exists(&backup) || fs.is_dir(&backup) {
401            purge.failed.push((
402                file,
403                CoreError::new(
404                    ErrorCode::InvalidValue,
405                    "the recorded backup is not a regular file (a link or a folder); left alone",
406                )
407                .with_path(&backup),
408            ));
409            continue;
410        } else {
411            // Gone already (pruned, deleted by hand), or a dangling link,
412            // which holds no value either.
413            record.backup_removed = true;
414        }
415        purge.removed.push(file);
416        if let Some(dir) = backup.parent() {
417            dirs.insert(dir.to_path_buf());
418        }
419    }
420    if !purge.removed.is_empty() {
421        run.save_result(fs, &state_dir)?;
422    }
423    for dir in dirs {
424        if fs.read_dir(&dir).is_ok_and(|entries| entries.is_empty()) {
425            // Best effort: an empty run directory lists as a run without files.
426            let _ = fs.remove_dir_all(&dir);
427        }
428    }
429    Ok(purge)
430}
431
432/// The recorded backup path rebuilt under this data folder's backups:
433/// `backups/files/<run folder>/<file name>` from its last two components,
434/// so a run recorded before the data folder moved (`surject migrate
435/// loadout`) still finds its backups. The recorded prefix is never
436/// trusted; [`check_backup_path`] checks the rest.
437fn rebased(home: &SurjectionHome, recorded: &Path) -> PathBuf {
438    let name = recorded.file_name();
439    let run = recorded.parent().and_then(Path::file_name);
440    match (run, name) {
441        (Some(run), Some(name)) => home.backups_dir().join(FILES_DIR).join(run).join(name),
442        _ => recorded.to_path_buf(),
443    }
444}
445
446/// Whether the recorded `backup` is run `apply_id`'s backup of `file`:
447/// `backups/files/<ts>-<apply-id>/<encode_path(file)>`, no `..`. The run
448/// result is a file on disk, so it is never trusted to name what to
449/// overwrite.
450fn check_backup_path(
451    home: &SurjectionHome,
452    apply_id: &str,
453    backup: &Path,
454    file: &Path,
455) -> Result<(), CoreError> {
456    let root = home.backups_dir().join(FILES_DIR);
457    let suffix = format!("-{apply_id}");
458    let in_run = backup.parent().is_some_and(|dir| {
459        dir.parent() == Some(root.as_path())
460            && dir
461                .file_name()
462                .and_then(|name| name.to_str())
463                .is_some_and(|name| {
464                    name.get(..16).and_then(parse_timestamp).is_some()
465                        && name.get(16..) == Some(suffix.as_str())
466                })
467    });
468    let plain = backup
469        .components()
470        .all(|part| !matches!(part, std::path::Component::ParentDir));
471    let named =
472        backup.file_name().and_then(|name| name.to_str()) == Some(encode_path(file).as_str());
473    if in_run && plain && named {
474        Ok(())
475    } else {
476        Err(CoreError::new(
477            ErrorCode::InvalidValue,
478            format!(
479                "the recorded backup is not apply {apply_id}'s backup of this file; left alone"
480            ),
481        )
482        .with_path(backup))
483    }
484}
485
486/// The client files whose backup of apply run `apply_id` was removed
487/// because it held old secret values ([`purge_old_values`]): their content
488/// from before that run is no longer kept.
489pub fn removed_backups(
490    fs: &dyn Fs,
491    state_dir: &Path,
492    apply_id: &str,
493) -> Result<Vec<PathBuf>, CoreError> {
494    Ok(journal::result(fs, state_dir, apply_id)?
495        .map(|run| {
496            run.files
497                .into_iter()
498                .filter(|record| record.backup_removed)
499                .map(|record| PathBuf::from(record.file))
500                .collect()
501        })
502        .unwrap_or_default())
503}
504
505#[cfg(test)]
506mod rebase_tests {
507    use std::path::{Path, PathBuf};
508
509    use super::{FILES_DIR, rebased};
510    use crate::paths::{HomeSource, SurjectionHome};
511
512    /// A backup recorded under Loadout's old data folder is looked for under
513    /// this one's backups, and a recorded prefix is never trusted.
514    #[test]
515    fn recorded_backups_are_rebuilt_under_this_data_folder() {
516        let root = std::env::temp_dir().join("surjection-rebase");
517        let home = SurjectionHome {
518            path: root.join("Surjection"),
519            source: HomeSource::Default,
520            sync_root: None,
521        };
522        let run = "20260101T000000Z-01M8WVNEZ659GZ5Q8B30FY2344";
523        let recorded: PathBuf = root
524            .join("Loadout")
525            .join("backups")
526            .join(FILES_DIR)
527            .join(run)
528            .join("file.json");
529        assert_eq!(
530            rebased(&home, &recorded),
531            home.backups_dir()
532                .join(FILES_DIR)
533                .join(run)
534                .join("file.json")
535        );
536        let elsewhere = Path::new("file.json");
537        assert_eq!(rebased(&home, elsewhere), elsewhere);
538    }
539}