Skip to main content

dort_core/
adoption.rs

1//! Recoverable one-file adoption. Apply and unmanage live in lifecycle.
2use crate::{
3    Error, Manifest, Result,
4    context::HostContext,
5    error::io_error,
6    journal::{self, Header, Journal, Operation, Phase, Progress, Role},
7    model::ManagedFile,
8    observation::{self, Entry, Fingerprint, Kind, Parent},
9    planner::{self, Plan, Request},
10    state::WriterLock,
11};
12use rustix::fs::{self, Mode, OFlags, RenameFlags};
13use serde::Serialize;
14use std::{
15    collections::BTreeMap,
16    fs::File,
17    path::{Path, PathBuf},
18    sync::atomic::{AtomicU64, Ordering},
19    time::{SystemTime, UNIX_EPOCH},
20};
21
22/// Not deserializable. A preview JSON document can never be passed directly to execution.
23pub struct Approval {
24    plan: Plan,
25    digest: String,
26}
27
28impl Approval {
29    /// An explicit caller approval boundary, not an interactive prompt. The caller must
30    /// privately review the destination content and present the preview before calling.
31    pub fn from_plan(plan: Plan) -> Result<Self> {
32        if !matches!(plan.inputs.request, Request::Adopt { .. })
33            || plan.files.len() != 1
34            || plan.has_blockers()
35            || canonical(&plan)? != canonical(&planner::plan(plan.inputs.clone()))?
36        {
37            return Err(Error::Invalid(
38                "approval requires an unmodified, unblocked one-file adoption plan".into(),
39            ));
40        }
41        let digest = journal::digest(canonical(&plan)?.as_bytes());
42        Ok(Self { plan, digest })
43    }
44    pub fn sha256(&self) -> &str {
45        &self.digest
46    }
47}
48
49// Directory timestamps/link counts change when state or siblings are created. Bind their
50// identities, ownership and permissions, not unrelated directory churn.
51pub(crate) fn canonical(plan: &impl Serialize) -> Result<String> {
52    let mut value =
53        serde_json::to_value(plan).map_err(|_| Error::Invalid("cannot encode approval".into()))?;
54    fn normalize(value: &mut serde_json::Value) {
55        match value {
56            serde_json::Value::Object(map) => {
57                for (key, value) in map {
58                    if key == "parents" {
59                        if let Some(parents) = value.as_array_mut() {
60                            for parent in parents {
61                                if let Some(fp) = parent
62                                    .get_mut("fingerprint")
63                                    .and_then(|f| f.as_object_mut())
64                                {
65                                    for field in ["size", "modified", "changed", "links"] {
66                                        fp.remove(field);
67                                    }
68                                }
69                            }
70                        }
71                    } else {
72                        normalize(value);
73                    }
74                }
75            }
76            serde_json::Value::Array(values) => values.iter_mut().for_each(normalize),
77            _ => {}
78        }
79    }
80    normalize(&mut value);
81    journal::encode(&value)
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum Boundary {
86    Checkpoint,
87    Mutation,
88}
89
90/// Progress callbacks also support deterministic error/crash testing without environment
91/// switches in production code. Errors leave durable intent; nothing auto-rolls back.
92#[derive(Debug)]
93pub struct Event {
94    pub transaction_id: String,
95    pub boundary: Boundary,
96    pub sequence: usize,
97}
98
99fn notify(
100    journal: &Journal,
101    boundary: Boundary,
102    observer: &mut impl FnMut(&Event) -> Result<()>,
103) -> Result<()> {
104    observer(&Event {
105        transaction_id: journal.record.header.transaction_id.clone(),
106        boundary,
107        sequence: journal.record.sequence,
108    })
109}
110fn checkpoint(
111    journal: &mut Journal,
112    observer: &mut impl FnMut(&Event) -> Result<()>,
113) -> Result<()> {
114    journal.save()?;
115    notify(journal, Boundary::Checkpoint, observer)
116}
117
118pub(crate) fn transaction_id() -> String {
119    static NEXT: AtomicU64 = AtomicU64::new(0);
120    journal::digest(
121        format!(
122            "{}-{}-{}",
123            std::process::id(),
124            SystemTime::now()
125                .duration_since(UNIX_EPOCH)
126                .unwrap_or_default()
127                .as_nanos(),
128            NEXT.fetch_add(1, Ordering::Relaxed)
129        )
130        .as_bytes(),
131    )
132}
133
134pub(crate) fn parent_identity(a: &Fingerprint, b: &Fingerprint) -> bool {
135    a.device == b.device
136        && a.inode == b.inode
137        && a.mode == b.mode
138        && a.uid == b.uid
139        && a.gid == b.gid
140}
141
142pub(crate) fn same(a: &Entry, b: &Entry, strict: bool) -> bool {
143    if a.kind != b.kind || a.link_target != b.link_target || a.sha256 != b.sha256 {
144        return false;
145    }
146    match (&a.fingerprint, &b.fingerprint) {
147        (None, None) => true,
148        (Some(a), Some(b)) if a.mode & 0o170000 == 0o040000 => parent_identity(a, b),
149        (Some(a), Some(b)) => {
150            let mut a = a.clone();
151            let mut b = b.clone();
152            if !strict {
153                a.changed = (0, 0);
154                b.changed = (0, 0);
155            }
156            a == b
157        }
158        _ => false,
159    }
160}
161
162fn inspect(path: &Path, role: Role) -> Result<Entry> {
163    if role == Role::Manifest && observation::inspect(path, false)?.kind == Kind::Regular {
164        observation::read_manifest(path).map(|(_, entry)| entry)
165    } else {
166        observation::inspect(path, true)
167    }
168}
169
170pub(crate) fn checked_bytes(entry: &Entry) -> Result<Vec<u8>> {
171    let handle = observation::parent_handle(&entry.path)?;
172    let bytes = observation::read_checked(
173        &handle,
174        &entry.path,
175        entry
176            .fingerprint
177            .as_ref()
178            .ok_or_else(|| Error::Invalid("missing regular-file fingerprint".into()))?,
179    )?;
180    if entry.sha256.as_deref() != Some(&journal::digest(&bytes)) {
181        return Err(Error::Invalid("approved content changed".into()));
182    }
183    Ok(bytes)
184}
185
186fn stage_name(id: usize) -> String {
187    format!("op-{id:04}")
188}
189fn stage_path(journal: &Journal, id: usize) -> PathBuf {
190    journal.directory.path.join(stage_name(id))
191}
192
193fn stage_file(journal: &Journal, id: usize, bytes: &[u8], mode: u32, gid: u32) -> Result<()> {
194    let name = stage_name(id);
195    journal.directory.create(&name, bytes)?;
196    let file = File::from(
197        fs::openat(
198            &journal.directory.file,
199            name.as_str(),
200            OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
201            Mode::empty(),
202        )
203        .map_err(|e| io_error("open prepared file", &journal.directory.path, e))?,
204    );
205    fs::fchown(&file, None, Some(rustix::process::Gid::from_raw(gid)))
206        .map_err(|e| io_error("preserve prepared file group", &journal.directory.path, e))?;
207    fs::fchmod(&file, Mode::from_bits_truncate(mode as _))
208        .map_err(|e| io_error("set prepared file permissions", &journal.directory.path, e))?;
209    file.sync_all()
210        .map_err(|e| io_error("sync prepared file", &journal.directory.path, e))?;
211    journal.directory.sync()
212}
213
214pub(crate) fn anchors(entries: &[&Entry]) -> Vec<Parent> {
215    let mut all = BTreeMap::new();
216    for entry in entries {
217        for parent in &entry.parents {
218            all.insert(parent.path.clone(), parent.clone());
219        }
220    }
221    all.into_values().collect()
222}
223
224fn check_parents(journal: &Journal, entry: &Entry) -> Result<()> {
225    for actual in &entry.parents {
226        let expected = journal
227            .record
228            .header
229            .anchors
230            .iter()
231            .find(|p| p.path == actual.path)
232            .map(|p| &p.fingerprint)
233            .or_else(|| {
234                journal
235                    .record
236                    .operations
237                    .iter()
238                    .find(|op| op.role == Role::Directory && op.before.path == actual.path)
239                    .and_then(|op| op.staged.fingerprint.as_ref())
240            });
241        if expected.is_none_or(|expected| !parent_identity(expected, &actual.fingerprint)) {
242            return Err(Error::Invalid(
243                "parent identity/permissions changed; transaction refused".into(),
244            ));
245        }
246    }
247    Ok(())
248}
249
250fn check_configuration(host: &HostContext, journal: &Journal) -> Result<()> {
251    journal::registered_root(
252        host,
253        &journal.record.header.repository_id,
254        &journal.record.header.repository,
255    )?;
256    let current = observation::inspect(&host.local_config_path(), false)?;
257    if !same(&journal.record.header.local_config, &current, true) {
258        return Err(Error::Invalid(
259            "local configuration changed since approval".into(),
260        ));
261    }
262    check_parents(journal, &current)
263}
264
265/// Requires a registered repository and the application lock. Only a freshly revalidated,
266/// explicitly approved adoption is accepted. Returns a retained transaction ID.
267pub fn execute(
268    host: &HostContext,
269    lock: &WriterLock,
270    approval: Approval,
271    mut observer: impl FnMut(&Event) -> Result<()>,
272) -> Result<String> {
273    lock.check_context(host)?;
274    journal::ensure_writable(host)?;
275    let inputs = &approval.plan.inputs;
276    if journal::encode(host)? != journal::encode(&inputs.host)? {
277        return Err(Error::Invalid(
278            "approval belongs to another host context".into(),
279        ));
280    }
281    let profiles: Vec<_> = inputs.active_profiles.iter().cloned().collect();
282    let fresh = planner::plan(planner::observe(
283        host,
284        &inputs.repository,
285        &profiles,
286        inputs.request.clone(),
287    )?);
288    if fresh.has_blockers() || journal::digest(canonical(&fresh)?.as_bytes()) != approval.digest {
289        return Err(Error::Invalid(
290            "stale or substituted adoption plan; observe and approve again".into(),
291        ));
292    }
293    let local = crate::local::LocalConfig::load(host)?;
294    let repository_id = local
295        .repositories
296        .iter()
297        .find(|(_, record)| record.root == inputs.repository)
298        .map(|(id, _)| id.clone())
299        .ok_or_else(|| Error::Invalid("adoption requires a registered repository".into()))?;
300    let file = &fresh.inputs.files[0];
301    let source = file
302        .source
303        .as_ref()
304        .ok_or_else(|| Error::Invalid("missing adoption source".into()))?;
305    let destination = file
306        .destination
307        .as_ref()
308        .ok_or_else(|| Error::Invalid("missing adoption destination".into()))?;
309    if fresh
310        .inputs
311        .manifest
312        .fingerprint
313        .as_ref()
314        .is_none_or(|f| f.mode & 0o7000 != 0)
315    {
316        return Err(Error::Invalid(
317            "manifest must not have special permission bits".into(),
318        ));
319    }
320    let manifest_bytes = checked_bytes(&fresh.inputs.manifest)?;
321    let destination_bytes = checked_bytes(destination)?;
322    #[derive(Serialize)]
323    struct Addition<'a> {
324        files: Vec<&'a ManagedFile>,
325    }
326    let addition = toml::to_string(&Addition {
327        files: vec![&file.mapping],
328    })
329    .map_err(|_| Error::Invalid("cannot encode adoption mapping".into()))?;
330    let new_manifest = format!(
331        "{}\n{}",
332        std::str::from_utf8(&manifest_bytes)
333            .map_err(|_| Error::Invalid("manifest must be UTF-8".into()))?,
334        addition
335    );
336    Manifest::parse(&new_manifest)?.validate_for_host(host, &profiles, Some(&inputs.repository))?;
337    let header = Header {
338        repository_id,
339        repository: inputs.repository.clone(),
340        transaction_id: transaction_id(),
341        approved_plan_sha256: approval.digest,
342        mapping: file.mapping.clone(),
343        profiles,
344        manifest: fresh.inputs.manifest.clone(),
345        destination: destination.clone(),
346        source: source.clone(),
347        local_config: fresh.inputs.local_config.clone(),
348        anchors: anchors(&[
349            &fresh.inputs.manifest,
350            destination,
351            source,
352            &fresh.inputs.local_config,
353        ]),
354        manifest_backup_sha256: journal::digest(&manifest_bytes),
355        destination_backup_sha256: journal::digest(&destination_bytes),
356    };
357    let mut journal = Journal::begin(host, header)?;
358    notify(&journal, Boundary::Checkpoint, &mut observer)?;
359    journal
360        .directory
361        .create("manifest.backup", &manifest_bytes)?;
362    journal
363        .directory
364        .create("destination.backup", &destination_bytes)?;
365    journal.verify_backups()?;
366    let device = Fingerprint::from_stat(
367        &fs::fstat(&journal.directory.file)
368            .map_err(|e| io_error("inspect transaction filesystem", &journal.directory.path, e))?,
369    )
370    .device;
371    // No cross-filesystem fallback: every publication/inverse must be an atomic rename.
372    for entry in [&fresh.inputs.manifest, destination, source] {
373        if entry
374            .parents
375            .last()
376            .is_none_or(|p| p.fingerprint.device != device)
377            || entry
378                .fingerprint
379                .as_ref()
380                .is_some_and(|f| f.device != device)
381        {
382            return Err(Error::Invalid(
383                "adoption requires repository, destination and transaction state on one filesystem"
384                    .into(),
385            ));
386        }
387        if entry
388            .parents
389            .last()
390            .is_none_or(|p| p.fingerprint.uid != fresh.inputs.user_id)
391        {
392            return Err(Error::Invalid(
393                "live file parents must be owned by this user".into(),
394            ));
395        }
396    }
397    let mut directories = vec![];
398    let mut parent = file
399        .source_path
400        .parent()
401        .ok_or_else(|| Error::Invalid("missing source parent directory".into()))?;
402    while observation::inspect(parent, false)?.kind == Kind::Missing {
403        directories.push(parent.to_owned());
404        parent = parent
405            .parent()
406            .ok_or_else(|| Error::Invalid("missing repository root".into()))?;
407    }
408    directories.reverse();
409    let mut roles: Vec<_> = directories
410        .into_iter()
411        .map(|path| (Role::Directory, path))
412        .collect();
413    roles.extend([
414        (Role::Source, file.source_path.clone()),
415        (Role::Manifest, inputs.manifest.path.clone()),
416        (Role::Destination, file.target_path.clone()),
417    ]);
418    let destination_fingerprint = destination
419        .fingerprint
420        .as_ref()
421        .ok_or_else(|| Error::Invalid("missing destination fingerprint".into()))?;
422    let manifest_fingerprint = inputs
423        .manifest
424        .fingerprint
425        .as_ref()
426        .ok_or_else(|| Error::Invalid("missing manifest fingerprint".into()))?;
427    for (id, (role, path)) in roles.into_iter().enumerate() {
428        let name = stage_name(id);
429        match role {
430            Role::Directory => {
431                fs::mkdirat(
432                    &journal.directory.file,
433                    name.as_str(),
434                    Mode::RUSR | Mode::WUSR | Mode::XUSR,
435                )
436                .map_err(|e| io_error("prepare source parent", &journal.directory.path, e))?;
437                let fd = File::from(
438                    fs::openat(
439                        &journal.directory.file,
440                        name.as_str(),
441                        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
442                        Mode::empty(),
443                    )
444                    .map_err(|e| io_error("open prepared directory", &journal.directory.path, e))?,
445                );
446                fd.sync_all()
447                    .map_err(|e| io_error("sync prepared directory", &journal.directory.path, e))?;
448            }
449            Role::Source => stage_file(
450                &journal,
451                id,
452                &destination_bytes,
453                destination_fingerprint.mode & 0o777,
454                destination_fingerprint.gid,
455            )?,
456            Role::Manifest => stage_file(
457                &journal,
458                id,
459                new_manifest.as_bytes(),
460                manifest_fingerprint.mode & 0o777,
461                manifest_fingerprint.gid,
462            )?,
463            Role::Destination => {
464                fs::symlinkat(&file.source_path, &journal.directory.file, name.as_str())
465                    .map_err(|e| io_error("prepare destination link", &journal.directory.path, e))?
466            }
467        }
468        journal.directory.sync()?;
469        let before = match role {
470            Role::Source => journal.record.header.source.clone(),
471            Role::Manifest => journal.record.header.manifest.clone(),
472            Role::Destination => journal.record.header.destination.clone(),
473            Role::Directory => inspect(&path, role)?,
474        };
475        let staged = inspect(&stage_path(&journal, id), role)?;
476        journal.record.operations.push(Operation {
477            id,
478            role,
479            before,
480            staged,
481            after: None,
482            progress: Progress::Pending,
483        });
484    }
485    journal.record.phase = Phase::Running;
486    checkpoint(&mut journal, &mut observer)?;
487    validate_layout(host, &journal)?;
488    for id in 0..journal.record.operations.len() {
489        check_configuration(host, &journal)?;
490        validate_layout(host, &journal)?;
491        journal.verify_backups()?;
492        journal.record.operations[id].progress = Progress::Intent;
493        checkpoint(&mut journal, &mut observer)?;
494        validate_layout(host, &journal)?;
495        journal.verify_backups()?;
496        mutate(&journal, id, false)?;
497        notify(&journal, Boundary::Mutation, &mut observer)?;
498        let after = inspect(
499            &journal.record.operations[id].before.path,
500            journal.record.operations[id].role,
501        )?;
502        if !same(&journal.record.operations[id].staged, &after, false) {
503            return Err(Error::Invalid("adoption postcondition mismatch".into()));
504        }
505        journal.record.operations[id].after = Some(after);
506        journal.record.operations[id].progress = Progress::Done;
507        checkpoint(&mut journal, &mut observer)?;
508    }
509    journal.record.phase = Phase::Verifying;
510    checkpoint(&mut journal, &mut observer)?;
511    validate_layout(host, &journal)?;
512    journal.verify_backups()?;
513    journal.record.phase = Phase::Completed;
514    checkpoint(&mut journal, &mut observer)?;
515    Ok(journal.record.header.transaction_id)
516}
517
518// Resolve an intent interrupted immediately before/after its atomic rename. Inode,
519// content, mode and mtime must match; ctime alone changes as a consequence of rename.
520fn applied(journal: &Journal, op: &Operation) -> Result<bool> {
521    let live = inspect(&op.before.path, op.role)?;
522    check_parents(journal, &live)?;
523    let stage = inspect(&stage_path(journal, op.id), op.role)?;
524    let before = same(&op.before, &live, op.progress == Progress::Pending)
525        && same(&op.staged, &stage, op.progress == Progress::Pending);
526    let after = same(&op.staged, &live, false)
527        && if matches!(op.role, Role::Directory | Role::Source) {
528            stage.kind == Kind::Missing
529        } else {
530            same(&op.before, &stage, false)
531        };
532    match op.progress {
533        Progress::Pending if before => Ok(false),
534        Progress::Intent | Progress::UndoIntent if before => Ok(false),
535        Progress::Intent | Progress::UndoIntent if after => Ok(true),
536        Progress::Done
537            if after
538                && op
539                    .after
540                    .as_ref()
541                    .is_some_and(|expected| same(expected, &live, true)) =>
542        {
543            Ok(true)
544        }
545        Progress::Undone if before => Ok(false),
546        _ => Err(Error::Invalid(
547            "transaction guard mismatch (file, source, stage or parent edited); recovery refused"
548                .into(),
549        )),
550    }
551}
552
553fn validate_layout(host: &HostContext, journal: &Journal) -> Result<()> {
554    check_configuration(host, journal)?;
555    let states: Vec<_> = journal
556        .record
557        .operations
558        .iter()
559        .map(|op| applied(journal, op))
560        .collect::<Result<_>>()?;
561    for op in &journal.record.operations {
562        if op.role != Role::Directory {
563            continue;
564        }
565        let path = if states[op.id] {
566            op.before.path.clone()
567        } else {
568            stage_path(journal, op.id)
569        };
570        let mut expected: Vec<_> = journal
571            .record
572            .operations
573            .iter()
574            .filter(|child| {
575                states[op.id]
576                    && states[child.id]
577                    && child.before.path.parent() == Some(op.before.path.as_path())
578            })
579            .map(|child| {
580                child
581                    .before
582                    .path
583                    .file_name()
584                    .map(|name| name.to_owned())
585                    .ok_or_else(|| Error::Invalid("missing source directory entry name".into()))
586            })
587            .collect::<Result<Vec<_>>>()?;
588        expected.sort();
589        if observation::names(&path, 4096)? != expected {
590            return Err(Error::Invalid(
591                "created/prepared source directory contains unapproved entries; recovery refused"
592                    .into(),
593            ));
594        }
595    }
596    Ok(())
597}
598
599fn mutate(journal: &Journal, id: usize, undo: bool) -> Result<()> {
600    let op = &journal.record.operations[id];
601    let live = observation::parent_handle(&op.before.path)?;
602    if live.missing {
603        return Err(Error::Invalid("operation parent is missing".into()));
604    }
605    let current = inspect(&op.before.path, op.role)?;
606    check_parents(journal, &current)?;
607    // Re-opened descriptors must refer to the same parents just validated by name.
608    if live.parents.len() != current.parents.len() {
609        return Err(Error::Invalid(
610            "parent disappeared during transaction".into(),
611        ));
612    }
613    for (a, b) in live.parents.iter().zip(&current.parents) {
614        if a.path != b.path || !parent_identity(&a.fingerprint, &b.fingerprint) {
615            return Err(Error::Invalid(
616                "parent substituted during transaction".into(),
617            ));
618        }
619    }
620    let is_applied = applied(journal, op)?;
621    if is_applied != undo {
622        return Err(Error::Invalid(
623            "operation is not at the expected precondition".into(),
624        ));
625    }
626    let name = stage_name(id);
627    let created = matches!(op.role, Role::Directory | Role::Source);
628    if undo && op.role == Role::Directory && !observation::names(&op.before.path, 1)?.is_empty() {
629        return Err(Error::Invalid(
630            "created source directory is no longer empty".into(),
631        ));
632    }
633    let flags = if created {
634        RenameFlags::NOREPLACE
635    } else {
636        RenameFlags::EXCHANGE
637    };
638    let result = if undo && created {
639        fs::renameat_with(
640            &live.directory,
641            &live.name,
642            &journal.directory.file,
643            name.as_str(),
644            flags,
645        )
646    } else {
647        fs::renameat_with(
648            &journal.directory.file,
649            name.as_str(),
650            &live.directory,
651            &live.name,
652            flags,
653        )
654    };
655    result.map_err(|e| {
656        io_error(
657            "publish/invert journalled rename (no unsafe fallback)",
658            &op.before.path,
659            e,
660        )
661    })?;
662    live.directory
663        .sync_all()
664        .map_err(|e| io_error("sync live parent", &op.before.path, e))?;
665    journal.directory.sync()
666}
667
668/// Read-only preflight and conservative inverse paths for the head-bound recovery service.
669pub(crate) fn rollback_preview(
670    host: &HostContext,
671    repository_id: &str,
672    transaction_id: &str,
673) -> Result<(String, Vec<PathBuf>)> {
674    let j = Journal::open(host, repository_id, transaction_id)?;
675    validate_record(host, &j)?;
676    if !matches!(j.record.phase, Phase::Preparing | Phase::RolledBack) {
677        j.verify_backups()?;
678        validate_layout(host, &j)?;
679    }
680    let effects = if matches!(j.record.phase, Phase::Preparing | Phase::RolledBack) {
681        vec![]
682    } else {
683        j.record
684            .operations
685            .iter()
686            .rev()
687            .filter(|o| o.progress != Progress::Undone)
688            .map(|o| o.before.path.clone())
689            .collect()
690    };
691    Ok((
692        journal::digest(journal::encode(&j.record)?.as_bytes()),
693        effects,
694    ))
695}
696
697/// Explicit guarded rollback, never startup replay. Can also undo a completed adoption.
698/// Preflight ALL guards (including linked-source content) before changing anything.
699pub fn rollback(
700    host: &HostContext,
701    lock: &WriterLock,
702    repository_id: &str,
703    transaction_id: &str,
704    mut observer: impl FnMut(&Event) -> Result<()>,
705) -> Result<()> {
706    lock.check_context(host)?;
707    let mut journal = Journal::open(host, repository_id, transaction_id)?;
708    validate_record(host, &journal)?;
709    if journal.record.phase == Phase::RolledBack {
710        return Ok(());
711    }
712    if journal.record.phase == Phase::Preparing {
713        // Only private staging/backups may exist; no live effects can precede Running.
714        journal.record.phase = Phase::RolledBack;
715        return checkpoint(&mut journal, &mut observer);
716    }
717    journal.verify_backups()?;
718    validate_layout(host, &journal)?;
719    if journal.record.phase != Phase::RollingBack {
720        journal.record.phase = Phase::RollingBack;
721        checkpoint(&mut journal, &mut observer)?;
722    }
723    for id in (0..journal.record.operations.len()).rev() {
724        if journal.record.operations[id].progress == Progress::Undone {
725            continue;
726        }
727        validate_layout(host, &journal)?;
728        let was_applied = applied(&journal, &journal.record.operations[id])?;
729        journal.record.operations[id].progress = Progress::UndoIntent;
730        checkpoint(&mut journal, &mut observer)?;
731        validate_layout(host, &journal)?;
732        journal.verify_backups()?;
733        if was_applied {
734            mutate(&journal, id, true)?;
735            notify(&journal, Boundary::Mutation, &mut observer)?;
736        }
737        journal.record.operations[id].progress = Progress::Undone;
738        checkpoint(&mut journal, &mut observer)?;
739    }
740    validate_layout(host, &journal)?;
741    journal.record.phase = Phase::RolledBack;
742    checkpoint(&mut journal, &mut observer)
743}
744
745// Check scope independently of checksums. Journal strings are never arbitrary write paths.
746fn validate_record(host: &HostContext, journal: &Journal) -> Result<()> {
747    let h = &journal.record.header;
748    journal::registered_root(host, &h.repository_id, &h.repository)?;
749    observation::validate_output_path(&h.repository)?;
750    if h.source.path != h.repository.join(&h.mapping.source)
751        || h.destination.path != host.target_path(&h.mapping.target, Some(&h.repository))?
752        || h.manifest.path != h.repository.join("dort.toml")
753        || h.local_config.path != host.local_config_path()
754    {
755        return Err(Error::Invalid(
756            "journal paths do not match adoption scope".into(),
757        ));
758    }
759    let mut minimal = Manifest::parse("schema=1\n")?;
760    minimal.files.push(h.mapping.clone());
761    minimal.profiles.available = h
762        .profiles
763        .iter()
764        .chain(&h.mapping.profiles)
765        .filter(|p| p.as_str() != "base")
766        .cloned()
767        .collect::<std::collections::BTreeSet<_>>()
768        .into_iter()
769        .collect();
770    minimal.validate_for_host(host, &h.profiles, Some(&h.repository))?;
771    if h.mapping.mode != crate::model::FileMode::Link
772        || !h.mapping.requires.is_empty()
773        || !h.mapping.overrides.is_empty()
774    {
775        return Err(Error::Invalid("unsupported journal mapping".into()));
776    }
777    if journal.record.phase != Phase::Preparing
778        && !(journal.record.phase == Phase::RolledBack && journal.record.operations.is_empty())
779    {
780        let n = journal.record.operations.len();
781        if n < 3 {
782            return Err(Error::Invalid("incomplete adoption operation set".into()));
783        }
784        let mut previous_dir: Option<&Path> = None;
785        for (id, op) in journal.record.operations.iter().enumerate() {
786            let (role, path) = if id == n - 3 {
787                (Role::Source, &h.source.path)
788            } else if id == n - 2 {
789                (Role::Manifest, &h.manifest.path)
790            } else if id == n - 1 {
791                (Role::Destination, &h.destination.path)
792            } else {
793                let source_parent = h
794                    .source
795                    .path
796                    .parent()
797                    .ok_or_else(|| Error::Invalid("missing source parent directory".into()))?;
798                if !op.before.path.starts_with(&h.repository)
799                    || op.before.path == h.repository
800                    || !source_parent.starts_with(&op.before.path)
801                    || previous_dir.is_some_and(|p| op.before.path.parent() != Some(p))
802                {
803                    return Err(Error::Invalid("invalid source parent operation".into()));
804                }
805                previous_dir = Some(op.before.path.as_path());
806                (Role::Directory, &op.before.path)
807            };
808            if op.id != id
809                || op.role != role
810                || &op.before.path != path
811                || op.staged.path != stage_path(journal, id)
812            {
813                return Err(Error::Invalid(
814                    "invalid journal operation ID/path/order".into(),
815                ));
816            }
817        }
818    }
819    Ok(())
820}