Skip to main content

dort_core/
bootstrap.rs

1//! Staged local repository setup. No network or automatic replay.
2use crate::{
3    Error, Manifest, Result,
4    adoption::{self, Boundary, Event, parent_identity, same},
5    context::HostContext,
6    error::io_error,
7    git::Git,
8    journal::{self, Diagnosis, Phase},
9    local,
10    observation::{self, Entry, Kind},
11    state::{PrivateDir, WriterLock},
12};
13use rustix::fs::{self, Mode, OFlags, RenameFlags};
14use serde::{Deserialize, Serialize};
15use std::{
16    fs::File,
17    path::{Path, PathBuf},
18};
19
20fn invalid(message: &str) -> Error {
21    Error::Invalid(message.into())
22}
23
24#[derive(Clone, Serialize, Deserialize)]
25#[serde(deny_unknown_fields)]
26struct Inputs {
27    root: Entry,
28    manifest: Option<Entry>,
29    git_marker: Option<Entry>,
30    config: Entry,
31    state: PathBuf,
32    config_sha256: Option<String>,
33    registration_sha256: String,
34    repository_id: String,
35}
36#[derive(Serialize)]
37pub struct Preview {
38    pub schema: u32,
39    pub preview_only: bool,
40    pub create: bool,
41    pub repository: PathBuf,
42    pub repository_id: String,
43    pub effects: Vec<&'static str>,
44    #[serde(skip)]
45    inputs: Inputs,
46    #[serde(skip)]
47    binding: String,
48}
49pub struct Approval(Preview);
50impl Approval {
51    pub fn from_preview(preview: Preview) -> Result<Self> {
52        if binding(&preview.inputs)? != preview.binding
53            || preview.repository != preview.inputs.root.path
54            || preview.create != (preview.inputs.root.kind == Kind::Missing)
55            || preview.repository_id != preview.inputs.repository_id
56            || preview.effects != effects(preview.create)
57            || preview.schema != 1
58            || !preview.preview_only
59        {
60            return Err(invalid("initialization preview was modified"));
61        }
62        Ok(Self(preview))
63    }
64}
65fn effects(create: bool) -> Vec<&'static str> {
66    if create {
67        vec![
68            "create private staged Git repository and minimal manifest",
69            "publish repository without replacement",
70            "register and select repository",
71        ]
72    } else {
73        vec!["register and select existing repository"]
74    }
75}
76fn binding(inputs: &Inputs) -> Result<String> {
77    let mut i = inputs.clone();
78    for e in [&mut i.root, &mut i.config]
79        .into_iter()
80        .chain(i.manifest.iter_mut())
81        .chain(i.git_marker.iter_mut())
82    {
83        for p in &mut e.parents {
84            p.fingerprint.size = 0;
85            p.fingerprint.links = 0;
86            p.fingerprint.modified = (0, 0);
87            p.fingerprint.changed = (0, 0);
88        }
89        if e.kind == Kind::Directory
90            && let Some(f) = &mut e.fingerprint
91        {
92            f.size = 0;
93            f.links = 0;
94            f.modified = (0, 0);
95            f.changed = (0, 0);
96        }
97    }
98    Ok(journal::digest(journal::encode(&i)?.as_bytes()))
99}
100fn config_entry(host: &HostContext) -> Result<(Entry, Option<Vec<u8>>)> {
101    let mut entry = observation::inspect(&host.local_config_path(), false)?;
102    let bytes = if entry.kind == Kind::Missing {
103        None
104    } else {
105        let dir = PrivateDir::open(&host.config_dir, false)?
106            .ok_or_else(|| invalid("missing configuration directory"))?;
107        Some(journal::read_bytes(&dir, "local.toml")?)
108    };
109    entry.sha256 = bytes.as_deref().map(journal::digest);
110    Ok((entry, bytes))
111}
112fn root_scope(host: &HostContext, root: &Path) -> Result<()> {
113    observation::validate_output_path(root)?;
114    if root == host.home
115        || root.parent().is_none()
116        || root.starts_with(&host.config_dir)
117        || host.config_dir.starts_with(root)
118        || root.starts_with(&host.state_dir)
119        || host.state_dir.starts_with(root)
120    {
121        return Err(invalid(
122            "repository cannot be HOME/root or overlap Dort metadata",
123        ));
124    }
125    Ok(())
126}
127/// Destination must be absolute/physical, absent with an existing owned safe parent,
128/// or an already-valid non-bare repository. No directories, lock or state are created.
129pub fn preview(host: &HostContext, root: &Path, git: &Path) -> Result<Preview> {
130    Git::new(git.to_owned())?;
131    root_scope(host, root)?;
132    let root_entry = observation::inspect(root, false)?;
133    let parent = observation::parent_handle(root)?;
134    if parent.missing {
135        return Err(invalid("initialization requires an existing parent"));
136    }
137    let stat =
138        fs::fstat(&parent.directory).map_err(|e| io_error("inspect repository parent", root, e))?;
139    if stat.st_uid != rustix::process::geteuid().as_raw() || stat.st_mode & 0o022 != 0 {
140        return Err(invalid(
141            "repository parent must be owned and not group/world writable",
142        ));
143    }
144    if root_entry
145        .fingerprint
146        .as_ref()
147        .is_some_and(|f| f.uid != rustix::process::geteuid().as_raw() || f.mode & 0o022 != 0)
148    {
149        return Err(invalid(
150            "repository root must be owned and not group/world writable",
151        ));
152    }
153    let create = root_entry.kind == Kind::Missing;
154    if !create && root_entry.kind != Kind::Directory {
155        return Err(invalid(
156            "repository destination must be absent or a valid repository directory",
157        ));
158    }
159    let (manifest, git_marker) = if create {
160        Manifest::parse("schema = 1\n")?.validate_for_host(
161            host,
162            &local::LocalConfig::load(host)?.active_profiles,
163            Some(root),
164        )?;
165        (None, None)
166    } else {
167        Git::new(git.to_owned())?.status(root)?;
168        let (manifest, entry) = observation::read_manifest(&root.join("dort.toml"))?;
169        manifest.validate_for_host(
170            host,
171            &local::LocalConfig::load(host)?.active_profiles,
172            Some(root),
173        )?;
174        let marker = observation::inspect(&root.join(".git"), true)?;
175        if !matches!(marker.kind, Kind::Directory | Kind::Regular) {
176            return Err(invalid(
177                "attachment requires a regular Git marker or metadata directory",
178            ));
179        }
180        (Some(entry), Some(marker))
181    };
182    let (config, bytes) = config_entry(host)?;
183    let (id, text) = local::registration_text(host, root)?;
184    let inputs = Inputs {
185        root: root_entry,
186        manifest,
187        git_marker,
188        config,
189        state: host.state_dir.clone(),
190        config_sha256: bytes.as_deref().map(journal::digest),
191        registration_sha256: journal::digest(text.as_bytes()),
192        repository_id: id.clone(),
193    };
194    let binding = binding(&inputs)?;
195    Ok(Preview {
196        schema: 1,
197        preview_only: true,
198        create,
199        repository: root.into(),
200        repository_id: id,
201        effects: effects(create),
202        inputs,
203        binding,
204    })
205}
206
207#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
208#[serde(rename_all = "snake_case")]
209enum Step {
210    Preparing,
211    PublishIntent,
212    Published,
213    RegisterIntent,
214    Completed,
215    Abandoned,
216}
217impl Step {
218    fn phase(self) -> Phase {
219        match self {
220            Self::Preparing => Phase::Preparing,
221            Self::Completed => Phase::Completed,
222            Self::Abandoned => Phase::RolledBack,
223            _ => Phase::Running,
224        }
225    }
226    fn terminal(self) -> bool {
227        matches!(self, Self::Completed | Self::Abandoned)
228    }
229}
230#[derive(Clone, Serialize, Deserialize)]
231#[serde(deny_unknown_fields)]
232struct Prepared {
233    tree: Vec<Entry>,
234    config: Entry,
235    destination: Entry,
236}
237#[derive(Clone, Serialize, Deserialize)]
238#[serde(deny_unknown_fields)]
239pub(crate) struct Record {
240    schema: u32,
241    sequence: usize,
242    previous_sha256: Option<String>,
243    transaction_id: String,
244    inputs: Inputs,
245    step: Step,
246    prepared: Option<Prepared>,
247}
248#[derive(Serialize, Deserialize)]
249#[serde(deny_unknown_fields)]
250struct Envelope {
251    sha256: String,
252    payload: String,
253}
254struct Journal {
255    directory: PrivateDir,
256    record: Record,
257    hash: Option<String>,
258    next: usize,
259}
260impl Journal {
261    fn check_directory(&self) -> Result<()> {
262        let named = observation::inspect(&self.directory.path, false)?;
263        let retained =
264            observation::Fingerprint::from_stat(&fs::fstat(&self.directory.file).map_err(|e| {
265                io_error(
266                    "inspect retained bootstrap directory",
267                    &self.directory.path,
268                    e,
269                )
270            })?);
271        if named.kind != Kind::Directory
272            || retained.uid != rustix::process::geteuid().as_raw()
273            || retained.mode & 0o077 != 0
274            || named
275                .fingerprint
276                .as_ref()
277                .is_none_or(|f| !parent_identity(f, &retained))
278        {
279            return Err(invalid("bootstrap transaction directory substituted"));
280        }
281        if let Some(p) = &self.record.prepared
282            && !parents_match(&p.config, &observation::inspect(&p.config.path, false)?)
283        {
284            return Err(invalid("bootstrap private parent identities changed"));
285        }
286        Ok(())
287    }
288    fn save(&mut self, observer: &mut impl FnMut(&Event) -> Result<()>) -> Result<()> {
289        self.check_directory()?;
290        self.record.sequence = self.next;
291        self.record.previous_sha256 = self.hash.clone();
292        let payload = journal::encode(&self.record)?;
293        let sha256 = journal::digest(payload.as_bytes());
294        let bytes = journal::encode(&Envelope {
295            sha256: sha256.clone(),
296            payload,
297        })?;
298        if bytes.len() as u64 > journal::LIMIT {
299            return Err(invalid("bootstrap checkpoint too large"));
300        }
301        self.directory
302            .create(&format!("{:06}.json", self.next), bytes.as_bytes())?;
303        self.hash = Some(sha256);
304        self.next += 1;
305        self.notify(Boundary::Checkpoint, observer)
306    }
307    fn notify(
308        &self,
309        boundary: Boundary,
310        observer: &mut impl FnMut(&Event) -> Result<()>,
311    ) -> Result<()> {
312        observer(&Event {
313            transaction_id: self.record.transaction_id.clone(),
314            boundary,
315            sequence: self.record.sequence,
316        })
317    }
318    fn open(host: &HostContext, rid: &str, tid: &str) -> Result<Self> {
319        if !journal::valid_id(tid) {
320            return Err(invalid("invalid bootstrap transaction ID"));
321        }
322        let directory = PrivateDir::open(&journal::transactions(host, rid)?.join(tid), false)?
323            .ok_or_else(|| invalid("unknown bootstrap transaction"))?;
324        let (d, record, hash) = scan(&directory, rid, tid);
325        if d.problem.is_some() {
326            return Err(invalid(
327                "malformed bootstrap journal; manual diagnosis required",
328            ));
329        }
330        let record = record.ok_or_else(|| invalid("missing bootstrap intent"))?;
331        validate_scope(host, &record)?;
332        Ok(Self {
333            directory,
334            record,
335            hash,
336            next: d.valid_checkpoints,
337        })
338    }
339}
340fn validate_scope(host: &HostContext, r: &Record) -> Result<()> {
341    root_scope(host, &r.inputs.root.path)?;
342    if r.inputs.config.path != host.local_config_path() || r.inputs.state != host.state_dir {
343        return Err(invalid("bootstrap host scope mismatch"));
344    }
345    Ok(())
346}
347pub(crate) fn is_schema3(d: &PrivateDir) -> bool {
348    journal::read_bytes(d, "000000.json")
349        .ok()
350        .and_then(|b| serde_json::from_slice::<Envelope>(&b).ok())
351        .and_then(|e| serde_json::from_str::<serde_json::Value>(&e.payload).ok())
352        .is_some_and(|v| v.get("schema").and_then(|n| n.as_u64()) == Some(3))
353}
354pub(crate) fn scan(
355    d: &PrivateDir,
356    rid: &str,
357    tid: &str,
358) -> (Diagnosis, Option<Record>, Option<String>) {
359    let mut report = Diagnosis {
360        repository_id: rid.into(),
361        transaction_id: tid.into(),
362        phase: None,
363        journal_schema: None,
364        valid_checkpoints: 0,
365        problem: None,
366    };
367    let mut latest: Option<Record> = None;
368    let mut hash = None;
369    let result: Result<()> = (|| {
370        let names = observation::names(&d.path, 4096)?;
371        let mut cps = vec![];
372        for n in &names {
373            let n = n
374                .to_str()
375                .ok_or_else(|| invalid("invalid bootstrap artifact name"))?;
376            if n.ends_with(".json") {
377                cps.push(n);
378            } else if !matches!(n, "repository" | "config.new" | "config.backup") {
379                return Err(invalid("unknown bootstrap artifact"));
380            }
381        }
382        if cps.is_empty() {
383            return Err(invalid("missing bootstrap intent"));
384        }
385        for (i, name) in cps.into_iter().enumerate() {
386            if name != format!("{i:06}.json") {
387                return Err(invalid("bootstrap checkpoint sequence gap"));
388            }
389            let env: Envelope = serde_json::from_slice(&journal::read_bytes(d, name)?)
390                .map_err(|_| invalid("malformed bootstrap checkpoint"))?;
391            if journal::digest(env.payload.as_bytes()) != env.sha256 {
392                return Err(invalid("bootstrap checksum mismatch"));
393            }
394            let r: Record = serde_json::from_str(&env.payload)
395                .map_err(|_| invalid("unsupported bootstrap checkpoint"))?;
396            if r.schema != 3
397                || r.sequence != i
398                || r.previous_sha256 != hash
399                || r.transaction_id != tid
400                || r.inputs.repository_id != rid
401                || !journal::valid_id(rid)
402            {
403                return Err(invalid("bootstrap record binding mismatch"));
404            }
405            observation::validate_output_path(&r.inputs.root.path)?;
406            observation::validate_output_path(&r.inputs.config.path)?;
407            observation::validate_output_path(&r.inputs.state)?;
408            if !journal::valid_id(&r.inputs.registration_sha256)
409                || !matches!(r.inputs.config.kind, Kind::Missing | Kind::Regular)
410                || r.inputs.config_sha256.is_some() != (r.inputs.config.kind == Kind::Regular)
411                || r.inputs.config.sha256 != r.inputs.config_sha256
412            {
413                return Err(invalid("invalid bootstrap configuration binding"));
414            }
415            if let Some(m) = &r.inputs.manifest
416                && (m.path != r.inputs.root.path.join("dort.toml")
417                    || m.kind != Kind::Regular
418                    || m.sha256.is_none())
419            {
420                return Err(invalid("bootstrap manifest scope mismatch"));
421            }
422            if let Some(g) = &r.inputs.git_marker
423                && (g.path != r.inputs.root.path.join(".git")
424                    || !matches!(g.kind, Kind::Directory | Kind::Regular))
425            {
426                return Err(invalid("bootstrap Git marker scope mismatch"));
427            }
428            if !matches!(r.inputs.root.kind, Kind::Missing | Kind::Directory)
429                || r.inputs.manifest.is_some() != (r.inputs.root.kind == Kind::Directory)
430                || r.inputs.git_marker.is_some() != r.inputs.manifest.is_some()
431            {
432                return Err(invalid("bootstrap input scope mismatch"));
433            }
434            if let Some(p) = &r.prepared {
435                if p.destination.path != r.inputs.config.path
436                    || p.config.path != d.path.join("config.new")
437                    || p.config.sha256.as_ref() != Some(&r.inputs.registration_sha256)
438                    || p.config.kind != Kind::Regular
439                    || !same(&r.inputs.config, &p.destination, true)
440                    || p.tree.len() > 256
441                {
442                    return Err(invalid("bootstrap prepared scope mismatch"));
443                }
444                let mut paths = std::collections::BTreeSet::new();
445                for e in &p.tree {
446                    observation::validate_output_path(&e.path)?;
447                    if e.fingerprint.as_ref().is_none_or(|f| {
448                        f.uid != rustix::process::geteuid().as_raw()
449                            || f.mode & 0o7022 != 0
450                            || (e.kind == Kind::Regular && (f.links != 1 || e.sha256.is_none()))
451                    }) {
452                        return Err(invalid("unsafe bootstrap tree metadata"));
453                    }
454                    if !e.path.starts_with(d.path.join("repository"))
455                        || !matches!(e.kind, Kind::Directory | Kind::Regular)
456                        || !paths.insert(&e.path)
457                    {
458                        return Err(invalid("bootstrap tree scope mismatch"));
459                    }
460                }
461                if !p.tree.is_empty()
462                    && (!paths.contains(&d.path.join("repository"))
463                        || p.tree.iter().any(|e| {
464                            e.path != d.path.join("repository")
465                                && e.path
466                                    .parent()
467                                    .is_none_or(|parent| !paths.contains(&parent.to_owned()))
468                        }))
469                {
470                    return Err(invalid("bootstrap tree has missing directory anchors"));
471                }
472                if (r.inputs.root.kind == Kind::Missing) != !p.tree.is_empty() {
473                    return Err(invalid("bootstrap tree binding mismatch"));
474                }
475            }
476            if let Some(prev) = &latest {
477                if journal::encode(&prev.inputs)? != journal::encode(&r.inputs)?
478                    || prev.step.terminal()
479                    || (prev.step == Step::Preparing
480                        && r.step == Step::Abandoned
481                        && r.prepared.is_some())
482                    || (prev.prepared.is_some()
483                        && journal::encode(&prev.prepared)? != journal::encode(&r.prepared)?)
484                {
485                    return Err(invalid("bootstrap immutable identity changed"));
486                }
487                let valid = r.step == Step::Abandoned
488                    || matches!(
489                        (prev.step, r.step),
490                        (Step::Preparing, Step::PublishIntent)
491                            | (Step::PublishIntent, Step::Published)
492                            | (Step::Published, Step::RegisterIntent)
493                            | (Step::RegisterIntent, Step::Completed)
494                    );
495                if !valid {
496                    return Err(invalid("invalid bootstrap transition"));
497                }
498            } else if r.step != Step::Preparing || r.prepared.is_some() {
499                return Err(invalid("bootstrap must begin preparing"));
500            }
501            if !matches!(r.step, Step::Preparing | Step::Abandoned) && r.prepared.is_none() {
502                return Err(invalid("missing prepared bootstrap guards"));
503            }
504            report.phase = Some(r.step.phase());
505            report.journal_schema = Some(3);
506            report.valid_checkpoints += 1;
507            hash = Some(env.sha256);
508            latest = Some(r);
509        }
510        if let Some(r) = &latest
511            && r.prepared.is_some()
512            && let Some(expected) = &r.inputs.config_sha256
513            && journal::digest(&journal::read_bytes(d, "config.backup")?) != *expected
514        {
515            return Err(invalid("bootstrap configuration backup mismatch"));
516        }
517        Ok(())
518    })();
519    if result.is_err() {
520        report.problem =
521            Some("invalid bootstrap chain/artifacts; explicit manual diagnosis required".into());
522    }
523    (report, latest, hash)
524}
525
526/// Sync and capture a small newly initialized tree. No symlinks/special/hardlinked files.
527fn tree(root: &Path, sync: bool) -> Result<Vec<Entry>> {
528    fn walk(path: &Path, out: &mut Vec<Entry>, sync: bool) -> Result<()> {
529        if out.len() >= 256 {
530            return Err(invalid("bootstrap tree exceeds entry limit"));
531        }
532        let mut e = observation::inspect(path, true)?;
533        let fp = e
534            .fingerprint
535            .as_ref()
536            .ok_or_else(|| invalid("missing bootstrap tree entry"))?;
537        if fp.uid != rustix::process::geteuid().as_raw()
538            || fp.mode & 0o7022 != 0
539            || !matches!(e.kind, Kind::Regular | Kind::Directory)
540            || (e.kind == Kind::Regular && (fp.links != 1 || e.sha256.is_none()))
541        {
542            return Err(invalid("unsafe bootstrap tree entry"));
543        }
544        if e.kind == Kind::Directory {
545            for n in observation::names(path, 256)? {
546                walk(&path.join(n), out, sync)?;
547            }
548        }
549        if sync {
550            let h = observation::parent_handle(path)?;
551            let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC;
552            let f = File::from(
553                fs::openat(&h.directory, &h.name, flags, Mode::empty())
554                    .map_err(|e| io_error("open bootstrap tree", path, e))?,
555            );
556            f.sync_all()
557                .map_err(|e| io_error("sync bootstrap tree", path, e))?;
558            let current = observation::inspect(path, true)?;
559            if !same(&e, &current, true) {
560                return Err(invalid("bootstrap tree raced during sync"));
561            }
562            e = current;
563        }
564        out.push(e);
565        Ok(())
566    }
567    let mut entries = vec![];
568    walk(root, &mut entries, sync)?;
569    Ok(entries)
570}
571fn parents_match(before: &Entry, current: &Entry) -> bool {
572    before.parents.len() == current.parents.len()
573        && before
574            .parents
575            .iter()
576            .zip(&current.parents)
577            .all(|(a, b)| a.path == b.path && parent_identity(&a.fingerprint, &b.fingerprint))
578}
579fn tree_matches(j: &Journal, root: &Path) -> Result<()> {
580    let expected = &j
581        .record
582        .prepared
583        .as_ref()
584        .ok_or_else(|| invalid("missing bootstrap preparation"))?
585        .tree;
586    let actual = tree(root, false)?;
587    if expected.len() != actual.len() {
588        return Err(invalid("bootstrap repository has new/missing entries"));
589    }
590    for (a, b) in expected.iter().zip(&actual) {
591        let relative = a
592            .path
593            .strip_prefix(j.directory.path.join("repository"))
594            .map_err(|_| invalid("invalid bootstrap tree path"))?;
595        if b.path != root.join(relative) || !same(a, b, false) {
596            return Err(invalid("bootstrap repository edited or substituted"));
597        }
598    }
599    Ok(())
600}
601// Return true only when the exact prepared repository is already published.
602fn repository_state(j: &Journal) -> Result<bool> {
603    j.check_directory()?;
604    let i = &j.record.inputs;
605    let current = observation::inspect(&i.root.path, false)?;
606    if !parents_match(&i.root, &current) {
607        return Err(invalid("bootstrap repository parents changed"));
608    }
609    if i.root.kind == Kind::Directory {
610        if !same(&i.root, &current, false) {
611            return Err(invalid("attached repository identity changed"));
612        }
613        for e in [i.manifest.as_ref().unwrap(), i.git_marker.as_ref().unwrap()] {
614            let now = observation::inspect(&e.path, e.kind == Kind::Regular)?;
615            if !same(e, &now, true) || !parents_match(e, &now) {
616                return Err(invalid("attached repository manifest/Git marker changed"));
617            }
618        }
619        return Ok(true);
620    }
621    let stage = j.directory.path.join("repository");
622    if current.kind == Kind::Missing {
623        if j.record.prepared.is_some() {
624            tree_matches(j, &stage)?;
625        }
626        return Ok(false);
627    }
628    if j.record.prepared.is_none() || observation::inspect(&stage, false)?.kind != Kind::Missing {
629        return Err(invalid("unrecognized bootstrap publication"));
630    }
631    tree_matches(j, &i.root.path)?;
632    Ok(true)
633}
634// Exact before/after states only; recognize interrupted config exchange by identity/hash.
635fn config_state(host: &HostContext, j: &Journal) -> Result<bool> {
636    j.check_directory()?;
637    let i = &j.record.inputs;
638    let (now, bytes) = config_entry(host)?;
639    let sha = bytes.as_deref().map(journal::digest);
640    if let Some(p) = &j.record.prepared
641        && !parents_match(&p.destination, &now)
642    {
643        return Err(invalid("registration parent identity changed"));
644    }
645    if same(&i.config, &now, true) && sha == i.config_sha256 {
646        // Missing ancestors may have been created privately for registration.
647        if !i.config.parents.iter().all(|a| {
648            now.parents
649                .iter()
650                .any(|b| a.path == b.path && parent_identity(&a.fingerprint, &b.fingerprint))
651        }) {
652            return Err(invalid("bootstrap configuration parents changed"));
653        }
654        if let Some(p) = &j.record.prepared {
655            let mut stage = observation::inspect(&p.config.path, false)?;
656            stage.sha256 = Some(journal::digest(&journal::read_bytes(
657                &j.directory,
658                "config.new",
659            )?));
660            if !same(&p.config, &stage, true) {
661                return Err(invalid("prepared registration changed"));
662            }
663        }
664        return Ok(false);
665    }
666    if let Some(p) = &j.record.prepared
667        && same(&p.config, &now, false)
668        && sha.as_ref() == Some(&i.registration_sha256)
669    {
670        if i.config.kind != Kind::Missing {
671            let mut old = observation::inspect(&p.config.path, false)?;
672            old.sha256 = Some(journal::digest(&journal::read_bytes(
673                &j.directory,
674                "config.new",
675            )?));
676            if !same(&i.config, &old, false)
677                || journal::digest(&journal::read_bytes(&j.directory, "config.new")?)
678                    != i.config_sha256.clone().unwrap_or_default()
679            {
680                return Err(invalid("retained original configuration changed"));
681            }
682        } else if observation::inspect(&p.config.path, false)?.kind != Kind::Missing {
683            return Err(invalid("unexpected retained registration"));
684        }
685        return Ok(true);
686    }
687    Err(invalid("configuration changed; bootstrap recovery refused"))
688}
689fn drive(
690    host: &HostContext,
691    j: &mut Journal,
692    observer: &mut impl FnMut(&Event) -> Result<()>,
693) -> Result<()> {
694    if j.record.step == Step::PublishIntent {
695        if config_state(host, j)? {
696            return Err(invalid("registration published before durable intent"));
697        }
698        if !repository_state(j)? {
699            let h = observation::parent_handle(&j.record.inputs.root.path)?;
700            fs::renameat_with(
701                &j.directory.file,
702                "repository",
703                &h.directory,
704                &h.name,
705                RenameFlags::NOREPLACE,
706            )
707            .map_err(|e| {
708                io_error(
709                    "publish repository without replacement",
710                    &j.record.inputs.root.path,
711                    e,
712                )
713            })?;
714            h.directory
715                .sync_all()
716                .map_err(|e| io_error("sync repository parent", &j.record.inputs.root.path, e))?;
717            j.directory.sync()?;
718            j.notify(Boundary::Mutation, observer)?;
719        }
720        if !repository_state(j)? {
721            return Err(invalid("repository publication not verified"));
722        }
723        j.record.step = Step::Published;
724        j.save(observer)?;
725    }
726    if j.record.step == Step::Published {
727        if !repository_state(j)? || config_state(host, j)? {
728            return Err(invalid("unexpected published bootstrap layout"));
729        }
730        j.record.step = Step::RegisterIntent;
731        j.save(observer)?;
732    }
733    if j.record.step == Step::RegisterIntent {
734        if !repository_state(j)? {
735            return Err(invalid("published repository is no longer present"));
736        }
737        let config = PrivateDir::open(&host.config_dir, false)?
738            .ok_or_else(|| invalid("prepared configuration directory is missing"))?;
739        if !config_state(host, j)? {
740            let flags = if j.record.inputs.config.kind == Kind::Missing {
741                RenameFlags::NOREPLACE
742            } else {
743                RenameFlags::EXCHANGE
744            };
745            fs::renameat_with(
746                &j.directory.file,
747                "config.new",
748                &config.file,
749                "local.toml",
750                flags,
751            )
752            .map_err(|e| {
753                io_error(
754                    "publish repository registration",
755                    host.local_config_path(),
756                    e,
757                )
758            })?;
759            config.sync()?;
760            j.directory.sync()?;
761            j.notify(Boundary::Mutation, observer)?;
762        }
763        if !config_state(host, j)? || !repository_state(j)? {
764            return Err(invalid("bootstrap completion not verified"));
765        }
766        j.record.step = Step::Completed;
767        j.save(observer)?;
768    }
769    Ok(())
770}
771
772pub fn execute(
773    host: &HostContext,
774    lock: &WriterLock,
775    approval: Approval,
776    git: &Path,
777    mut observer: impl FnMut(&Event) -> Result<()>,
778) -> Result<String> {
779    lock.check_context(host)?;
780    journal::ensure_writable(host)?;
781    let approved = approval.0;
782    let fresh = preview(host, &approved.repository, git)?;
783    if fresh.binding != approved.binding {
784        return Err(invalid("initialization approval is stale"));
785    }
786    let tid = adoption::transaction_id();
787    let txroot = journal::transactions(host, &fresh.repository_id)?;
788    let parent = PrivateDir::open(&txroot, true)?.expect("created transaction root");
789    fs::mkdirat(
790        &parent.file,
791        tid.as_str(),
792        Mode::RUSR | Mode::WUSR | Mode::XUSR,
793    )
794    .map_err(|e| io_error("allocate bootstrap transaction", &txroot, e))?;
795    parent.sync()?;
796    let directory = PrivateDir::open(&txroot.join(&tid), false)?.expect("allocated bootstrap");
797    let mut j = Journal {
798        directory,
799        record: Record {
800            schema: 3,
801            sequence: 0,
802            previous_sha256: None,
803            transaction_id: tid.clone(),
804            inputs: fresh.inputs,
805            step: Step::Preparing,
806            prepared: None,
807        },
808        hash: None,
809        next: 0,
810    };
811    j.save(&mut observer)?;
812    let entries = if fresh.create {
813        fs::mkdirat(
814            &j.directory.file,
815            "repository",
816            Mode::RUSR | Mode::WUSR | Mode::XUSR,
817        )
818        .map_err(|e| io_error("create private repository stage", &j.directory.path, e))?;
819        j.directory.sync()?;
820        let stage = j.directory.path.join("repository");
821        Git::initialize_private(git.to_owned(), &stage)?;
822        let dir = PrivateDir::open(&stage, false)?.expect("private repository");
823        dir.create("dort.toml", b"schema = 1\n")?;
824        Manifest::parse("schema = 1\n")?.validate_for_host(host, &[], Some(&fresh.repository))?;
825        tree(&stage, true)?
826    } else {
827        vec![]
828    };
829    let (_, original) = config_entry(host)?;
830    if original.as_deref().map(journal::digest) != j.record.inputs.config_sha256 {
831        return Err(invalid("configuration changed during preparation"));
832    }
833    if let Some(bytes) = original {
834        j.directory.create("config.backup", &bytes)?;
835    }
836    let (_, text) = local::registration_text(host, &fresh.repository)?;
837    if journal::digest(text.as_bytes()) != j.record.inputs.registration_sha256 {
838        return Err(invalid("registration changed during preparation"));
839    }
840    j.directory.create("config.new", text.as_bytes())?;
841    let mut config = observation::inspect(&j.directory.path.join("config.new"), true)?;
842    config.sha256 = Some(journal::digest(text.as_bytes()));
843    PrivateDir::open(&host.config_dir, true)?.expect("created private configuration directory");
844    let destination = config_entry(host)?.0;
845    j.record.prepared = Some(Prepared {
846        tree: entries,
847        config,
848        destination,
849    });
850    repository_state(&j)?;
851    config_state(host, &j)?;
852    // Refuse cross-device before any publication (including config on a different FS).
853    let state_device = observation::Fingerprint::from_stat(
854        &fs::fstat(&j.directory.file)
855            .map_err(|e| io_error("inspect bootstrap device", &j.directory.path, e))?,
856    )
857    .device;
858    for path in [&fresh.repository, &host.local_config_path()] {
859        let entry = observation::inspect(path, false)?;
860        if entry
861            .parents
862            .last()
863            .is_none_or(|p| p.fingerprint.device != state_device)
864        {
865            return Err(invalid(
866                "bootstrap requires repository/configuration/state on one filesystem",
867            ));
868        }
869    }
870    j.record.step = Step::PublishIntent;
871    j.save(&mut observer)?;
872    drive(host, &mut j, &mut observer)?;
873    Ok(tid)
874}
875
876#[derive(Clone, Copy, PartialEq, Eq, Serialize)]
877#[serde(rename_all = "snake_case")]
878pub enum RecoveryAction {
879    Resume,
880    Abandon,
881}
882#[derive(Serialize)]
883pub struct RecoveryPreview {
884    pub schema: u32,
885    pub preview_only: bool,
886    pub repository_id: String,
887    pub transaction_id: String,
888    pub repository: PathBuf,
889    pub action: RecoveryAction,
890    pub repository_published: bool,
891    pub registration_published: bool,
892    pub effects: Vec<&'static str>,
893    pub journal_head_sha256: String,
894    #[serde(skip)]
895    binding: String,
896}
897pub struct RecoveryApproval(RecoveryPreview);
898impl RecoveryApproval {
899    pub fn from_preview(p: RecoveryPreview) -> Result<Self> {
900        if journal::digest(journal::encode(&p)?.as_bytes()) != p.binding {
901            return Err(invalid("bootstrap recovery preview modified"));
902        }
903        Ok(Self(p))
904    }
905}
906pub fn recovery_preview(
907    host: &HostContext,
908    rid: &str,
909    tid: &str,
910    action: RecoveryAction,
911) -> Result<RecoveryPreview> {
912    let j = Journal::open(host, rid, tid)?;
913    if j.record.step.terminal() {
914        return Err(invalid("bootstrap is already terminal"));
915    }
916    if action == RecoveryAction::Resume && j.record.step == Step::Preparing {
917        return Err(invalid(
918            "incomplete private preparation; explicitly abandon and retry with a new transaction",
919        ));
920    }
921    let repository_published = repository_state(&j)?;
922    let registration_published = config_state(host, &j)?;
923    if matches!(j.record.step, Step::Published | Step::RegisterIntent) && !repository_published {
924        return Err(invalid("published repository is no longer present"));
925    }
926    if matches!(
927        j.record.step,
928        Step::Preparing | Step::PublishIntent | Step::Published
929    ) && registration_published
930    {
931        return Err(invalid("registration published before durable intent"));
932    }
933    let effects = if action == RecoveryAction::Abandon {
934        vec!["mark abandoned; retain repository, registration and private artifacts unchanged"]
935    } else {
936        vec![
937            "publish exact prepared repository if absent",
938            "publish exact prepared registration if absent",
939            "mark completed",
940        ]
941    };
942    let mut p = RecoveryPreview {
943        schema: 1,
944        preview_only: true,
945        repository_id: rid.into(),
946        transaction_id: tid.into(),
947        repository: j.record.inputs.root.path.clone(),
948        action,
949        repository_published,
950        registration_published,
951        effects,
952        journal_head_sha256: j.hash.unwrap_or_default(),
953        binding: String::new(),
954    };
955    p.binding = journal::digest(journal::encode(&p)?.as_bytes());
956    Ok(p)
957}
958pub fn recover(
959    host: &HostContext,
960    lock: &WriterLock,
961    approval: RecoveryApproval,
962    mut observer: impl FnMut(&Event) -> Result<()>,
963) -> Result<()> {
964    lock.check_context(host)?;
965    let p = approval.0;
966    if recovery_preview(host, &p.repository_id, &p.transaction_id, p.action)?.binding != p.binding {
967        return Err(invalid("bootstrap recovery approval stale"));
968    }
969    let mut j = Journal::open(host, &p.repository_id, &p.transaction_id)?;
970    if p.action == RecoveryAction::Abandon {
971        j.record.step = Step::Abandoned;
972        j.save(&mut observer)
973    } else {
974        drive(host, &mut j, &mut observer)
975    }
976}