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}
112pub(crate) fn 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#[derive(Serialize)]
128pub struct ClonePreview {
129    source: String,
130    destination: PathBuf,
131    effects: [&'static str; 2],
132    #[serde(skip)]
133    root: Entry,
134    #[serde(skip)]
135    config: Entry,
136    #[serde(skip)]
137    git: Entry,
138    #[serde(skip)]
139    local_source: Option<Entry>,
140}
141
142impl ClonePreview {
143    pub fn prepare(
144        host: &HostContext,
145        source: &str,
146        destination: &Path,
147        git: &Path,
148    ) -> Result<Self> {
149        let local_source = if let Some(url) = source.strip_prefix("https://") {
150            let authority = url.split('/').next().unwrap_or_default();
151            if authority.is_empty()
152                || authority.contains('@')
153                || source.contains(['?', '#', '\\'])
154                || source.bytes().any(|b| !b.is_ascii_graphic())
155            {
156                return Err(invalid(
157                    "Use an HTTPS Git URL without credentials, query or fragment",
158                ));
159            }
160            None
161        } else {
162            let path = Path::new(source);
163            observation::validate_output_path(path)
164                .map_err(|_| invalid("Use an HTTPS URL or an absolute local Git path"))?;
165            let entry = observation::inspect(path, false)?;
166            if entry.kind != Kind::Directory || destination.starts_with(path) {
167                return Err(invalid(
168                    "Choose a local Git directory and a destination outside it",
169                ));
170            }
171            Some(entry)
172        };
173        root_scope(host, destination)?;
174        if destination.to_str().is_none() {
175            return Err(invalid("Clone destination must be a UTF-8 path"));
176        }
177        let root = observation::inspect(destination, false)?;
178        let parent = observation::parent_handle(destination)?;
179        if parent.missing || root.kind != Kind::Missing {
180            return Err(invalid("Clone needs a new path with an existing parent"));
181        }
182        let stat = fs::fstat(&parent.directory)
183            .map_err(|e| io_error("inspect clone parent", destination, e))?;
184        if stat.st_uid != rustix::process::geteuid().as_raw() || stat.st_mode & 0o022 != 0 {
185            return Err(invalid(
186                "Clone parent must be owned and not group/world writable",
187            ));
188        }
189        if local::LocalConfig::load(host)?
190            .repositories
191            .values()
192            .any(|r| r.root == destination)
193        {
194            return Err(invalid("Clone destination is already registered"));
195        }
196        Git::new(git.to_owned())?;
197        let git = observation::inspect(git, false)?;
198        if git.kind != Kind::Regular || git.fingerprint.as_ref().is_none_or(|f| f.mode & 0o111 == 0)
199        {
200            return Err(invalid("Clone needs a regular Git executable"));
201        }
202        Ok(Self {
203            source: source.into(),
204            destination: destination.to_owned(),
205            root,
206            config: config_entry(host)?.0,
207            git,
208            local_source,
209            effects: [
210                "Clone Git source into the new folder",
211                "Validate dort.toml, then register and select the folder",
212            ],
213        })
214    }
215
216    pub fn destination(&self) -> &Path {
217        &self.destination
218    }
219
220    pub fn human(&self) -> String {
221        format!(
222            "Source: {:?}\nNew folder: {:?}\n\n1. {}.\n2. {}.\n\nAn invalid manifest leaves the clone unregistered. No Home files, profile choices or packages change.",
223            self.source, self.destination, self.effects[0], self.effects[1]
224        )
225    }
226
227    pub fn approve(self) -> CloneApproval {
228        CloneApproval(self)
229    }
230}
231
232pub struct CloneApproval(ClonePreview);
233
234pub enum CloneResult {
235    Registered(String),
236    InvalidManifest { repository: PathBuf, reason: String },
237}
238
239impl CloneApproval {
240    pub fn execute(self, host: &HostContext) -> Result<String> {
241        match self.execute_with_result(host)? {
242            CloneResult::Registered(id) => Ok(id),
243            CloneResult::InvalidManifest { repository, reason } => Err(Error::Invalid(format!(
244                "Clone kept at {repository:?}. Fix dort.toml, then attach this folder: {reason}"
245            ))),
246        }
247    }
248
249    pub fn execute_with_result(self, host: &HostContext) -> Result<CloneResult> {
250        let _lock = WriterLock::acquire(host)?;
251        journal::ensure_writable(host)?;
252        let p = self.0;
253        let fresh = ClonePreview::prepare(host, &p.source, &p.destination, &p.git.path)?;
254        let matches = |a: &Entry, b: &Entry| same(a, b, true) && parents_match(a, b);
255        if !matches(&p.root, &fresh.root)
256            || !matches(&p.config, &fresh.config)
257            || !matches(&p.git, &fresh.git)
258            || p.local_source
259                .as_ref()
260                .zip(fresh.local_source.as_ref())
261                .is_some_and(|(a, b)| !matches(a, b))
262        {
263            return Err(invalid("Clone inputs changed. Review again."));
264        }
265        let parent = observation::parent_handle(&p.destination)?;
266        let stage_name = format!(".dort-clone-{}", adoption::transaction_id());
267        let stage = p.destination.with_file_name(&stage_name);
268        fs::mkdirat(&parent.directory, stage_name.as_str(), Mode::RWXU)
269            .map_err(|e| io_error("create private clone folder", &stage, e))?;
270        let staged = observation::inspect(&stage, false)?;
271        let backend = Git::new(p.git.path.clone())?;
272        if let Err(error) = backend.clone_private(&stage, &p.source) {
273            let _ = fs::unlinkat(
274                &parent.directory,
275                stage_name.as_str(),
276                fs::AtFlags::REMOVEDIR,
277            );
278            return Err(Error::Invalid(format!(
279                "{error} Any partial clone is at {stage:?}."
280            )));
281        }
282        if !matches(&staged, &observation::inspect(&stage, false)?)
283            || !matches(&p.root, &observation::inspect(&p.destination, false)?)
284        {
285            return Err(Error::Invalid(format!(
286                "Clone paths changed. Review the clone at {stage:?}."
287            )));
288        }
289        fs::renameat_with(
290            &parent.directory,
291            stage_name.as_str(),
292            &parent.directory,
293            &parent.name,
294            RenameFlags::NOREPLACE,
295        )
296        .map_err(|e| io_error("publish clone without replacement", &stage, e))?;
297        parent
298            .directory
299            .sync_all()
300            .map_err(|e| io_error("sync clone parent", &p.destination, e))?;
301        let check = || -> Result<()> {
302            let (manifest, _) = observation::read_manifest(&p.destination.join("dort.toml"))?;
303            let active = manifest.active_profiles(host, &[])?;
304            manifest.validate_file_targets(host, &active, Some(&p.destination), None)?;
305            Ok(())
306        };
307        if let Err(error) = check() {
308            return Ok(CloneResult::InvalidManifest {
309                repository: p.destination,
310                reason: match error {
311                    Error::Parse(_) => "Invalid TOML. Contents withheld.".into(),
312                    other => other.to_string(),
313                },
314            });
315        }
316        if !matches(&p.config, &config_entry(host)?.0) {
317            return Err(Error::Invalid(format!(
318                "Clone kept at {:?}. Registration changed. Review attaching the clone.",
319                p.destination
320            )));
321        }
322        local::RepositoryRegistry::register(host, &_lock, &p.destination)
323            .map(CloneResult::Registered)
324    }
325}
326
327/// Destination must be absolute/physical, absent with an existing owned safe parent,
328/// or an already-valid non-bare repository. No directories, lock or state are created.
329pub fn preview(host: &HostContext, root: &Path, git: &Path) -> Result<Preview> {
330    Git::new(git.to_owned())?;
331    root_scope(host, root)?;
332    let root_entry = observation::inspect(root, false)?;
333    let parent = observation::parent_handle(root)?;
334    if parent.missing {
335        return Err(invalid("initialization requires an existing parent"));
336    }
337    let stat =
338        fs::fstat(&parent.directory).map_err(|e| io_error("inspect repository parent", root, e))?;
339    if stat.st_uid != rustix::process::geteuid().as_raw() || stat.st_mode & 0o022 != 0 {
340        return Err(invalid(
341            "repository parent must be owned and not group/world writable",
342        ));
343    }
344    if root_entry
345        .fingerprint
346        .as_ref()
347        .is_some_and(|f| f.uid != rustix::process::geteuid().as_raw() || f.mode & 0o022 != 0)
348    {
349        return Err(invalid(
350            "repository root must be owned and not group/world writable",
351        ));
352    }
353    let create = root_entry.kind == Kind::Missing;
354    if !create && root_entry.kind != Kind::Directory {
355        return Err(invalid(
356            "repository destination must be absent or a valid repository directory",
357        ));
358    }
359    let (manifest, git_marker) = if create {
360        Manifest::parse("schema = 1\n")?;
361        (None, None)
362    } else {
363        Git::new(git.to_owned())?.status(root)?;
364        let (manifest, entry) = observation::read_manifest(&root.join("dort.toml"))?;
365        manifest.validate_local_selection(host, &[], Some(root))?;
366        let marker = observation::inspect(&root.join(".git"), true)?;
367        if !matches!(marker.kind, Kind::Directory | Kind::Regular) {
368            return Err(invalid(
369                "attachment requires a regular Git marker or metadata directory",
370            ));
371        }
372        (Some(entry), Some(marker))
373    };
374    let (config, bytes) = config_entry(host)?;
375    let (id, text) = local::registration_text(host, root)?;
376    let inputs = Inputs {
377        root: root_entry,
378        manifest,
379        git_marker,
380        config,
381        state: host.state_dir.clone(),
382        config_sha256: bytes.as_deref().map(journal::digest),
383        registration_sha256: journal::digest(text.as_bytes()),
384        repository_id: id.clone(),
385    };
386    let binding = binding(&inputs)?;
387    Ok(Preview {
388        schema: 1,
389        preview_only: true,
390        create,
391        repository: root.into(),
392        repository_id: id,
393        effects: effects(create),
394        inputs,
395        binding,
396    })
397}
398
399#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
400#[serde(rename_all = "snake_case")]
401enum Step {
402    Preparing,
403    PublishIntent,
404    Published,
405    RegisterIntent,
406    Completed,
407    Abandoned,
408}
409impl Step {
410    fn phase(self) -> Phase {
411        match self {
412            Self::Preparing => Phase::Preparing,
413            Self::Completed => Phase::Completed,
414            Self::Abandoned => Phase::RolledBack,
415            _ => Phase::Running,
416        }
417    }
418    fn terminal(self) -> bool {
419        matches!(self, Self::Completed | Self::Abandoned)
420    }
421}
422#[derive(Clone, Serialize, Deserialize)]
423#[serde(deny_unknown_fields)]
424struct Prepared {
425    tree: Vec<Entry>,
426    config: Entry,
427    destination: Entry,
428}
429#[derive(Clone, Serialize, Deserialize)]
430#[serde(deny_unknown_fields)]
431pub(crate) struct Record {
432    schema: u32,
433    sequence: usize,
434    previous_sha256: Option<String>,
435    transaction_id: String,
436    inputs: Inputs,
437    step: Step,
438    prepared: Option<Prepared>,
439}
440#[derive(Serialize, Deserialize)]
441#[serde(deny_unknown_fields)]
442struct Envelope {
443    sha256: String,
444    payload: String,
445}
446struct Journal {
447    directory: PrivateDir,
448    record: Record,
449    hash: Option<String>,
450    next: usize,
451}
452impl Journal {
453    fn check_directory(&self) -> Result<()> {
454        let named = observation::inspect(&self.directory.path, false)?;
455        let retained =
456            observation::Fingerprint::from_stat(&fs::fstat(&self.directory.file).map_err(|e| {
457                io_error(
458                    "inspect retained bootstrap directory",
459                    &self.directory.path,
460                    e,
461                )
462            })?);
463        if named.kind != Kind::Directory
464            || retained.uid != rustix::process::geteuid().as_raw()
465            || retained.mode & 0o077 != 0
466            || named
467                .fingerprint
468                .as_ref()
469                .is_none_or(|f| !parent_identity(f, &retained))
470        {
471            return Err(invalid("bootstrap transaction directory substituted"));
472        }
473        if let Some(p) = &self.record.prepared
474            && !parents_match(&p.config, &observation::inspect(&p.config.path, false)?)
475        {
476            return Err(invalid("bootstrap private parent identities changed"));
477        }
478        Ok(())
479    }
480    fn save(&mut self, observer: &mut impl FnMut(&Event) -> Result<()>) -> Result<()> {
481        self.check_directory()?;
482        self.record.sequence = self.next;
483        self.record.previous_sha256 = self.hash.clone();
484        let payload = journal::encode(&self.record)?;
485        let sha256 = journal::digest(payload.as_bytes());
486        let bytes = journal::encode(&Envelope {
487            sha256: sha256.clone(),
488            payload,
489        })?;
490        if bytes.len() as u64 > journal::LIMIT {
491            return Err(invalid("bootstrap checkpoint too large"));
492        }
493        self.directory
494            .create(&format!("{:06}.json", self.next), bytes.as_bytes())?;
495        self.hash = Some(sha256);
496        self.next += 1;
497        self.notify(Boundary::Checkpoint, observer)
498    }
499    fn notify(
500        &self,
501        boundary: Boundary,
502        observer: &mut impl FnMut(&Event) -> Result<()>,
503    ) -> Result<()> {
504        observer(&Event {
505            transaction_id: self.record.transaction_id.clone(),
506            boundary,
507            sequence: self.record.sequence,
508        })
509    }
510    fn open(host: &HostContext, rid: &str, tid: &str) -> Result<Self> {
511        if !journal::valid_id(tid) {
512            return Err(invalid("invalid bootstrap transaction ID"));
513        }
514        let directory = PrivateDir::open(&journal::transactions(host, rid)?.join(tid), false)?
515            .ok_or_else(|| invalid("unknown bootstrap transaction"))?;
516        let (d, record, hash) = scan(&directory, rid, tid);
517        if d.problem.is_some() {
518            return Err(invalid(
519                "malformed bootstrap journal; manual diagnosis required",
520            ));
521        }
522        let record = record.ok_or_else(|| invalid("missing bootstrap intent"))?;
523        validate_scope(host, &record)?;
524        Ok(Self {
525            directory,
526            record,
527            hash,
528            next: d.valid_checkpoints,
529        })
530    }
531}
532fn validate_scope(host: &HostContext, r: &Record) -> Result<()> {
533    root_scope(host, &r.inputs.root.path)?;
534    if r.inputs.config.path != host.local_config_path() || r.inputs.state != host.state_dir {
535        return Err(invalid("bootstrap host scope mismatch"));
536    }
537    Ok(())
538}
539pub(crate) fn is_schema3(d: &PrivateDir) -> bool {
540    journal::read_bytes(d, "000000.json")
541        .ok()
542        .and_then(|b| serde_json::from_slice::<Envelope>(&b).ok())
543        .and_then(|e| serde_json::from_str::<serde_json::Value>(&e.payload).ok())
544        .is_some_and(|v| v.get("schema").and_then(|n| n.as_u64()) == Some(3))
545}
546pub(crate) fn scan(
547    d: &PrivateDir,
548    rid: &str,
549    tid: &str,
550) -> (Diagnosis, Option<Record>, Option<String>) {
551    let mut report = Diagnosis {
552        repository_id: rid.into(),
553        transaction_id: tid.into(),
554        phase: None,
555        journal_schema: None,
556        valid_checkpoints: 0,
557        problem: None,
558    };
559    let mut latest: Option<Record> = None;
560    let mut hash = None;
561    let result: Result<()> = (|| {
562        let names = observation::names(&d.path, 4096)?;
563        let mut cps = vec![];
564        for n in &names {
565            let n = n
566                .to_str()
567                .ok_or_else(|| invalid("invalid bootstrap artifact name"))?;
568            if n.ends_with(".json") {
569                cps.push(n);
570            } else if !matches!(n, "repository" | "config.new" | "config.backup") {
571                return Err(invalid("unknown bootstrap artifact"));
572            }
573        }
574        if cps.is_empty() {
575            return Err(invalid("missing bootstrap intent"));
576        }
577        for (i, name) in cps.into_iter().enumerate() {
578            if name != format!("{i:06}.json") {
579                return Err(invalid("bootstrap checkpoint sequence gap"));
580            }
581            let env: Envelope = serde_json::from_slice(&journal::read_bytes(d, name)?)
582                .map_err(|_| invalid("malformed bootstrap checkpoint"))?;
583            if journal::digest(env.payload.as_bytes()) != env.sha256 {
584                return Err(invalid("bootstrap checksum mismatch"));
585            }
586            let r: Record = serde_json::from_str(&env.payload)
587                .map_err(|_| invalid("unsupported bootstrap checkpoint"))?;
588            if r.schema != 3
589                || r.sequence != i
590                || r.previous_sha256 != hash
591                || r.transaction_id != tid
592                || r.inputs.repository_id != rid
593                || !journal::valid_id(rid)
594            {
595                return Err(invalid("bootstrap record binding mismatch"));
596            }
597            observation::validate_output_path(&r.inputs.root.path)?;
598            observation::validate_output_path(&r.inputs.config.path)?;
599            observation::validate_output_path(&r.inputs.state)?;
600            if !journal::valid_id(&r.inputs.registration_sha256)
601                || !matches!(r.inputs.config.kind, Kind::Missing | Kind::Regular)
602                || r.inputs.config_sha256.is_some() != (r.inputs.config.kind == Kind::Regular)
603                || r.inputs.config.sha256 != r.inputs.config_sha256
604            {
605                return Err(invalid("invalid bootstrap configuration binding"));
606            }
607            if let Some(m) = &r.inputs.manifest
608                && (m.path != r.inputs.root.path.join("dort.toml")
609                    || m.kind != Kind::Regular
610                    || m.sha256.is_none())
611            {
612                return Err(invalid("bootstrap manifest scope mismatch"));
613            }
614            if let Some(g) = &r.inputs.git_marker
615                && (g.path != r.inputs.root.path.join(".git")
616                    || !matches!(g.kind, Kind::Directory | Kind::Regular))
617            {
618                return Err(invalid("bootstrap Git marker scope mismatch"));
619            }
620            if !matches!(r.inputs.root.kind, Kind::Missing | Kind::Directory)
621                || r.inputs.manifest.is_some() != (r.inputs.root.kind == Kind::Directory)
622                || r.inputs.git_marker.is_some() != r.inputs.manifest.is_some()
623            {
624                return Err(invalid("bootstrap input scope mismatch"));
625            }
626            if let Some(p) = &r.prepared {
627                if p.destination.path != r.inputs.config.path
628                    || p.config.path != d.path.join("config.new")
629                    || p.config.sha256.as_ref() != Some(&r.inputs.registration_sha256)
630                    || p.config.kind != Kind::Regular
631                    || !same(&r.inputs.config, &p.destination, true)
632                    || p.tree.len() > 256
633                {
634                    return Err(invalid("bootstrap prepared scope mismatch"));
635                }
636                let mut paths = std::collections::BTreeSet::new();
637                for e in &p.tree {
638                    observation::validate_output_path(&e.path)?;
639                    if e.fingerprint.as_ref().is_none_or(|f| {
640                        f.uid != rustix::process::geteuid().as_raw()
641                            || f.mode & 0o7022 != 0
642                            || (e.kind == Kind::Regular && (f.links != 1 || e.sha256.is_none()))
643                    }) {
644                        return Err(invalid("unsafe bootstrap tree metadata"));
645                    }
646                    if !e.path.starts_with(d.path.join("repository"))
647                        || !matches!(e.kind, Kind::Directory | Kind::Regular)
648                        || !paths.insert(&e.path)
649                    {
650                        return Err(invalid("bootstrap tree scope mismatch"));
651                    }
652                }
653                if !p.tree.is_empty()
654                    && (!paths.contains(&d.path.join("repository"))
655                        || p.tree.iter().any(|e| {
656                            e.path != d.path.join("repository")
657                                && e.path
658                                    .parent()
659                                    .is_none_or(|parent| !paths.contains(&parent.to_owned()))
660                        }))
661                {
662                    return Err(invalid("bootstrap tree has missing directory anchors"));
663                }
664                if (r.inputs.root.kind == Kind::Missing) != !p.tree.is_empty() {
665                    return Err(invalid("bootstrap tree binding mismatch"));
666                }
667            }
668            if let Some(prev) = &latest {
669                if journal::encode(&prev.inputs)? != journal::encode(&r.inputs)?
670                    || prev.step.terminal()
671                    || (prev.step == Step::Preparing
672                        && r.step == Step::Abandoned
673                        && r.prepared.is_some())
674                    || (prev.prepared.is_some()
675                        && journal::encode(&prev.prepared)? != journal::encode(&r.prepared)?)
676                {
677                    return Err(invalid("bootstrap immutable identity changed"));
678                }
679                let valid = r.step == Step::Abandoned
680                    || matches!(
681                        (prev.step, r.step),
682                        (Step::Preparing, Step::PublishIntent)
683                            | (Step::PublishIntent, Step::Published)
684                            | (Step::Published, Step::RegisterIntent)
685                            | (Step::RegisterIntent, Step::Completed)
686                    );
687                if !valid {
688                    return Err(invalid("invalid bootstrap transition"));
689                }
690            } else if r.step != Step::Preparing || r.prepared.is_some() {
691                return Err(invalid("bootstrap must begin preparing"));
692            }
693            if !matches!(r.step, Step::Preparing | Step::Abandoned) && r.prepared.is_none() {
694                return Err(invalid("missing prepared bootstrap guards"));
695            }
696            report.phase = Some(r.step.phase());
697            report.journal_schema = Some(3);
698            report.valid_checkpoints += 1;
699            hash = Some(env.sha256);
700            latest = Some(r);
701        }
702        if let Some(r) = &latest
703            && r.prepared.is_some()
704            && let Some(expected) = &r.inputs.config_sha256
705            && journal::digest(&journal::read_bytes(d, "config.backup")?) != *expected
706        {
707            return Err(invalid("bootstrap configuration backup mismatch"));
708        }
709        Ok(())
710    })();
711    if result.is_err() {
712        report.problem =
713            Some("invalid bootstrap chain/artifacts; explicit manual diagnosis required".into());
714    }
715    (report, latest, hash)
716}
717
718/// Sync and capture a small newly initialized tree. No symlinks/special/hardlinked files.
719fn tree(root: &Path, sync: bool) -> Result<Vec<Entry>> {
720    fn walk(path: &Path, out: &mut Vec<Entry>, sync: bool) -> Result<()> {
721        if out.len() >= 256 {
722            return Err(invalid("bootstrap tree exceeds entry limit"));
723        }
724        let mut e = observation::inspect(path, true)?;
725        let fp = e
726            .fingerprint
727            .as_ref()
728            .ok_or_else(|| invalid("missing bootstrap tree entry"))?;
729        if fp.uid != rustix::process::geteuid().as_raw()
730            || fp.mode & 0o7022 != 0
731            || !matches!(e.kind, Kind::Regular | Kind::Directory)
732            || (e.kind == Kind::Regular && (fp.links != 1 || e.sha256.is_none()))
733        {
734            return Err(invalid("unsafe bootstrap tree entry"));
735        }
736        if e.kind == Kind::Directory {
737            for n in observation::names(path, 256)? {
738                walk(&path.join(n), out, sync)?;
739            }
740        }
741        if sync {
742            let h = observation::parent_handle(path)?;
743            let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC;
744            let f = File::from(
745                fs::openat(&h.directory, &h.name, flags, Mode::empty())
746                    .map_err(|e| io_error("open bootstrap tree", path, e))?,
747            );
748            f.sync_all()
749                .map_err(|e| io_error("sync bootstrap tree", path, e))?;
750            let current = observation::inspect(path, true)?;
751            if !same(&e, &current, true) {
752                return Err(invalid("bootstrap tree raced during sync"));
753            }
754            e = current;
755        }
756        out.push(e);
757        Ok(())
758    }
759    let mut entries = vec![];
760    walk(root, &mut entries, sync)?;
761    Ok(entries)
762}
763fn parents_match(before: &Entry, current: &Entry) -> bool {
764    before.parents.len() == current.parents.len()
765        && before
766            .parents
767            .iter()
768            .zip(&current.parents)
769            .all(|(a, b)| a.path == b.path && parent_identity(&a.fingerprint, &b.fingerprint))
770}
771fn tree_matches(j: &Journal, root: &Path) -> Result<()> {
772    let expected = &j
773        .record
774        .prepared
775        .as_ref()
776        .ok_or_else(|| invalid("missing bootstrap preparation"))?
777        .tree;
778    let actual = tree(root, false)?;
779    if expected.len() != actual.len() {
780        return Err(invalid("bootstrap repository has new/missing entries"));
781    }
782    for (a, b) in expected.iter().zip(&actual) {
783        let relative = a
784            .path
785            .strip_prefix(j.directory.path.join("repository"))
786            .map_err(|_| invalid("invalid bootstrap tree path"))?;
787        if b.path != root.join(relative) || !same(a, b, false) {
788            return Err(invalid("bootstrap repository edited or substituted"));
789        }
790    }
791    Ok(())
792}
793// Return true only when the exact prepared repository is already published.
794fn repository_state(j: &Journal) -> Result<bool> {
795    j.check_directory()?;
796    let i = &j.record.inputs;
797    let current = observation::inspect(&i.root.path, false)?;
798    if !parents_match(&i.root, &current) {
799        return Err(invalid("bootstrap repository parents changed"));
800    }
801    if i.root.kind == Kind::Directory {
802        if !same(&i.root, &current, false) {
803            return Err(invalid("attached repository identity changed"));
804        }
805        for e in [i.manifest.as_ref().unwrap(), i.git_marker.as_ref().unwrap()] {
806            let now = observation::inspect(&e.path, e.kind == Kind::Regular)?;
807            if !same(e, &now, true) || !parents_match(e, &now) {
808                return Err(invalid("attached repository manifest/Git marker changed"));
809            }
810        }
811        return Ok(true);
812    }
813    let stage = j.directory.path.join("repository");
814    if current.kind == Kind::Missing {
815        if j.record.prepared.is_some() {
816            tree_matches(j, &stage)?;
817        }
818        return Ok(false);
819    }
820    if j.record.prepared.is_none() || observation::inspect(&stage, false)?.kind != Kind::Missing {
821        return Err(invalid("unrecognized bootstrap publication"));
822    }
823    tree_matches(j, &i.root.path)?;
824    Ok(true)
825}
826// Exact before/after states only; recognize interrupted config exchange by identity/hash.
827fn config_state(host: &HostContext, j: &Journal) -> Result<bool> {
828    j.check_directory()?;
829    let i = &j.record.inputs;
830    let (now, bytes) = config_entry(host)?;
831    let sha = bytes.as_deref().map(journal::digest);
832    if let Some(p) = &j.record.prepared
833        && !parents_match(&p.destination, &now)
834    {
835        return Err(invalid("registration parent identity changed"));
836    }
837    if same(&i.config, &now, true) && sha == i.config_sha256 {
838        // Missing ancestors may have been created privately for registration.
839        if !i.config.parents.iter().all(|a| {
840            now.parents
841                .iter()
842                .any(|b| a.path == b.path && parent_identity(&a.fingerprint, &b.fingerprint))
843        }) {
844            return Err(invalid("bootstrap configuration parents changed"));
845        }
846        if let Some(p) = &j.record.prepared {
847            let mut stage = observation::inspect(&p.config.path, false)?;
848            stage.sha256 = Some(journal::digest(&journal::read_bytes(
849                &j.directory,
850                "config.new",
851            )?));
852            if !same(&p.config, &stage, true) {
853                return Err(invalid("prepared registration changed"));
854            }
855        }
856        return Ok(false);
857    }
858    if let Some(p) = &j.record.prepared
859        && same(&p.config, &now, false)
860        && sha.as_ref() == Some(&i.registration_sha256)
861    {
862        if i.config.kind != Kind::Missing {
863            let mut old = observation::inspect(&p.config.path, false)?;
864            old.sha256 = Some(journal::digest(&journal::read_bytes(
865                &j.directory,
866                "config.new",
867            )?));
868            if !same(&i.config, &old, false)
869                || journal::digest(&journal::read_bytes(&j.directory, "config.new")?)
870                    != i.config_sha256.clone().unwrap_or_default()
871            {
872                return Err(invalid("retained original configuration changed"));
873            }
874        } else if observation::inspect(&p.config.path, false)?.kind != Kind::Missing {
875            return Err(invalid("unexpected retained registration"));
876        }
877        return Ok(true);
878    }
879    Err(invalid("configuration changed; bootstrap recovery refused"))
880}
881fn drive(
882    host: &HostContext,
883    j: &mut Journal,
884    observer: &mut impl FnMut(&Event) -> Result<()>,
885) -> Result<()> {
886    if j.record.step == Step::PublishIntent {
887        if config_state(host, j)? {
888            return Err(invalid("registration published before durable intent"));
889        }
890        if !repository_state(j)? {
891            let h = observation::parent_handle(&j.record.inputs.root.path)?;
892            fs::renameat_with(
893                &j.directory.file,
894                "repository",
895                &h.directory,
896                &h.name,
897                RenameFlags::NOREPLACE,
898            )
899            .map_err(|e| {
900                io_error(
901                    "publish repository without replacement",
902                    &j.record.inputs.root.path,
903                    e,
904                )
905            })?;
906            h.directory
907                .sync_all()
908                .map_err(|e| io_error("sync repository parent", &j.record.inputs.root.path, e))?;
909            j.directory.sync()?;
910            j.notify(Boundary::Mutation, observer)?;
911        }
912        if !repository_state(j)? {
913            return Err(invalid("repository publication not verified"));
914        }
915        j.record.step = Step::Published;
916        j.save(observer)?;
917    }
918    if j.record.step == Step::Published {
919        if !repository_state(j)? || config_state(host, j)? {
920            return Err(invalid("unexpected published bootstrap layout"));
921        }
922        j.record.step = Step::RegisterIntent;
923        j.save(observer)?;
924    }
925    if j.record.step == Step::RegisterIntent {
926        if !repository_state(j)? {
927            return Err(invalid("published repository is no longer present"));
928        }
929        let config = PrivateDir::open(&host.config_dir, false)?
930            .ok_or_else(|| invalid("prepared configuration directory is missing"))?;
931        if !config_state(host, j)? {
932            let flags = if j.record.inputs.config.kind == Kind::Missing {
933                RenameFlags::NOREPLACE
934            } else {
935                RenameFlags::EXCHANGE
936            };
937            fs::renameat_with(
938                &j.directory.file,
939                "config.new",
940                &config.file,
941                "local.toml",
942                flags,
943            )
944            .map_err(|e| {
945                io_error(
946                    "publish repository registration",
947                    host.local_config_path(),
948                    e,
949                )
950            })?;
951            config.sync()?;
952            j.directory.sync()?;
953            j.notify(Boundary::Mutation, observer)?;
954        }
955        if !config_state(host, j)? || !repository_state(j)? {
956            return Err(invalid("bootstrap completion not verified"));
957        }
958        j.record.step = Step::Completed;
959        j.save(observer)?;
960    }
961    Ok(())
962}
963
964pub fn execute(
965    host: &HostContext,
966    lock: &WriterLock,
967    approval: Approval,
968    git: &Path,
969    mut observer: impl FnMut(&Event) -> Result<()>,
970) -> Result<String> {
971    lock.check_context(host)?;
972    journal::ensure_writable(host)?;
973    let approved = approval.0;
974    let fresh = preview(host, &approved.repository, git)?;
975    if fresh.binding != approved.binding {
976        return Err(invalid("initialization approval is stale"));
977    }
978    let tid = adoption::transaction_id();
979    let txroot = journal::transactions(host, &fresh.repository_id)?;
980    let parent = PrivateDir::open(&txroot, true)?.expect("created transaction root");
981    fs::mkdirat(
982        &parent.file,
983        tid.as_str(),
984        Mode::RUSR | Mode::WUSR | Mode::XUSR,
985    )
986    .map_err(|e| io_error("allocate bootstrap transaction", &txroot, e))?;
987    parent.sync()?;
988    let directory = PrivateDir::open(&txroot.join(&tid), false)?.expect("allocated bootstrap");
989    let mut j = Journal {
990        directory,
991        record: Record {
992            schema: 3,
993            sequence: 0,
994            previous_sha256: None,
995            transaction_id: tid.clone(),
996            inputs: fresh.inputs,
997            step: Step::Preparing,
998            prepared: None,
999        },
1000        hash: None,
1001        next: 0,
1002    };
1003    j.save(&mut observer)?;
1004    let entries = if fresh.create {
1005        fs::mkdirat(
1006            &j.directory.file,
1007            "repository",
1008            Mode::RUSR | Mode::WUSR | Mode::XUSR,
1009        )
1010        .map_err(|e| io_error("create private repository stage", &j.directory.path, e))?;
1011        j.directory.sync()?;
1012        let stage = j.directory.path.join("repository");
1013        Git::initialize_private(git.to_owned(), &stage)?;
1014        let dir = PrivateDir::open(&stage, false)?.expect("private repository");
1015        dir.create("dort.toml", b"schema = 1\n")?;
1016        Manifest::parse("schema = 1\n")?.validate_for_host(host, &[], Some(&fresh.repository))?;
1017        tree(&stage, true)?
1018    } else {
1019        vec![]
1020    };
1021    let (_, original) = config_entry(host)?;
1022    if original.as_deref().map(journal::digest) != j.record.inputs.config_sha256 {
1023        return Err(invalid("configuration changed during preparation"));
1024    }
1025    if let Some(bytes) = original {
1026        j.directory.create("config.backup", &bytes)?;
1027    }
1028    let (_, text) = local::registration_text(host, &fresh.repository)?;
1029    if journal::digest(text.as_bytes()) != j.record.inputs.registration_sha256 {
1030        return Err(invalid("registration changed during preparation"));
1031    }
1032    j.directory.create("config.new", text.as_bytes())?;
1033    let mut config = observation::inspect(&j.directory.path.join("config.new"), true)?;
1034    config.sha256 = Some(journal::digest(text.as_bytes()));
1035    PrivateDir::open(&host.config_dir, true)?.expect("created private configuration directory");
1036    let destination = config_entry(host)?.0;
1037    j.record.prepared = Some(Prepared {
1038        tree: entries,
1039        config,
1040        destination,
1041    });
1042    repository_state(&j)?;
1043    config_state(host, &j)?;
1044    // Refuse cross-device before any publication (including config on a different FS).
1045    let state_device = observation::Fingerprint::from_stat(
1046        &fs::fstat(&j.directory.file)
1047            .map_err(|e| io_error("inspect bootstrap device", &j.directory.path, e))?,
1048    )
1049    .device;
1050    for path in [&fresh.repository, &host.local_config_path()] {
1051        let entry = observation::inspect(path, false)?;
1052        if entry
1053            .parents
1054            .last()
1055            .is_none_or(|p| p.fingerprint.device != state_device)
1056        {
1057            return Err(invalid(
1058                "bootstrap requires repository/configuration/state on one filesystem",
1059            ));
1060        }
1061    }
1062    j.record.step = Step::PublishIntent;
1063    j.save(&mut observer)?;
1064    drive(host, &mut j, &mut observer)?;
1065    Ok(tid)
1066}
1067
1068#[derive(Clone, Copy, PartialEq, Eq, Serialize)]
1069#[serde(rename_all = "snake_case")]
1070pub enum RecoveryAction {
1071    Resume,
1072    Abandon,
1073}
1074#[derive(Serialize)]
1075pub struct RecoveryPreview {
1076    pub schema: u32,
1077    pub preview_only: bool,
1078    pub repository_id: String,
1079    pub transaction_id: String,
1080    pub repository: PathBuf,
1081    pub action: RecoveryAction,
1082    pub repository_published: bool,
1083    pub registration_published: bool,
1084    pub effects: Vec<&'static str>,
1085    pub journal_head_sha256: String,
1086    #[serde(skip)]
1087    binding: String,
1088}
1089pub struct RecoveryApproval(RecoveryPreview);
1090impl RecoveryApproval {
1091    pub fn from_preview(p: RecoveryPreview) -> Result<Self> {
1092        if journal::digest(journal::encode(&p)?.as_bytes()) != p.binding {
1093            return Err(invalid("bootstrap recovery preview modified"));
1094        }
1095        Ok(Self(p))
1096    }
1097}
1098pub fn recovery_preview(
1099    host: &HostContext,
1100    rid: &str,
1101    tid: &str,
1102    action: RecoveryAction,
1103) -> Result<RecoveryPreview> {
1104    let j = Journal::open(host, rid, tid)?;
1105    if j.record.step.terminal() {
1106        return Err(invalid("bootstrap is already terminal"));
1107    }
1108    if action == RecoveryAction::Resume && j.record.step == Step::Preparing {
1109        return Err(invalid(
1110            "incomplete private preparation; explicitly abandon and retry with a new transaction",
1111        ));
1112    }
1113    let repository_published = repository_state(&j)?;
1114    let registration_published = config_state(host, &j)?;
1115    if matches!(j.record.step, Step::Published | Step::RegisterIntent) && !repository_published {
1116        return Err(invalid("published repository is no longer present"));
1117    }
1118    if matches!(
1119        j.record.step,
1120        Step::Preparing | Step::PublishIntent | Step::Published
1121    ) && registration_published
1122    {
1123        return Err(invalid("registration published before durable intent"));
1124    }
1125    let effects = if action == RecoveryAction::Abandon {
1126        vec!["mark abandoned; retain repository, registration and private artifacts unchanged"]
1127    } else {
1128        vec![
1129            "publish exact prepared repository if absent",
1130            "publish exact prepared registration if absent",
1131            "mark completed",
1132        ]
1133    };
1134    let mut p = RecoveryPreview {
1135        schema: 1,
1136        preview_only: true,
1137        repository_id: rid.into(),
1138        transaction_id: tid.into(),
1139        repository: j.record.inputs.root.path.clone(),
1140        action,
1141        repository_published,
1142        registration_published,
1143        effects,
1144        journal_head_sha256: j.hash.unwrap_or_default(),
1145        binding: String::new(),
1146    };
1147    p.binding = journal::digest(journal::encode(&p)?.as_bytes());
1148    Ok(p)
1149}
1150pub fn recover(
1151    host: &HostContext,
1152    lock: &WriterLock,
1153    approval: RecoveryApproval,
1154    mut observer: impl FnMut(&Event) -> Result<()>,
1155) -> Result<()> {
1156    lock.check_context(host)?;
1157    let p = approval.0;
1158    if recovery_preview(host, &p.repository_id, &p.transaction_id, p.action)?.binding != p.binding {
1159        return Err(invalid("bootstrap recovery approval stale"));
1160    }
1161    let mut j = Journal::open(host, &p.repository_id, &p.transaction_id)?;
1162    if p.action == RecoveryAction::Abandon {
1163        j.record.step = Step::Abandoned;
1164        j.save(&mut observer)
1165    } else {
1166        drive(host, &mut j, &mut observer)
1167    }
1168}