Skip to main content

dort_core/
journal.rs

1//! Immutable schema-1 checkpoint chains. Checksums detect corruption, not a malicious owner.
2use crate::{
3    Error, Result,
4    context::HostContext,
5    error::io_error,
6    local::{LocalConfig, repository_state_path},
7    model::ManagedFile,
8    observation::{self, Entry, Parent},
9    state::PrivateDir,
10};
11use rustix::fs::{self, Mode};
12use serde::{Deserialize, Serialize};
13use sha2::{Digest, Sha256};
14use std::{fs::File, io::Read, path::Path};
15
16pub(crate) const LIMIT: u64 = 16 * 1024 * 1024;
17
18pub(crate) fn digest(bytes: &[u8]) -> String {
19    format!("{:x}", Sha256::digest(bytes))
20}
21
22pub(crate) fn encode<T: Serialize>(value: &T) -> Result<String> {
23    serde_json::to_string(value)
24        .map_err(|_| Error::Invalid("cannot encode transaction metadata".into()))
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "snake_case")]
29pub enum Phase {
30    Preparing,
31    Running,
32    Verifying,
33    Completed,
34    RollingBack,
35    RolledBack,
36}
37
38impl Phase {
39    pub fn terminal(self) -> bool {
40        matches!(self, Self::Completed | Self::RolledBack)
41    }
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(rename_all = "snake_case")]
46pub(crate) enum Role {
47    Directory,
48    Source,
49    Manifest,
50    Destination,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(rename_all = "snake_case")]
55pub(crate) enum Progress {
56    Pending,
57    Intent,
58    Done,
59    UndoIntent,
60    Undone,
61}
62
63#[derive(Clone, Serialize, Deserialize)]
64#[serde(deny_unknown_fields)]
65pub(crate) struct Operation {
66    pub id: usize,
67    pub role: Role,
68    pub before: Entry,
69    pub staged: Entry,
70    pub after: Option<Entry>,
71    pub progress: Progress,
72}
73
74#[derive(Clone, Serialize, Deserialize)]
75#[serde(deny_unknown_fields)]
76pub(crate) struct Header {
77    pub repository_id: String,
78    pub repository: std::path::PathBuf,
79    pub transaction_id: String,
80    pub approved_plan_sha256: String,
81    pub mapping: ManagedFile,
82    pub profiles: Vec<String>,
83    pub manifest: Entry,
84    pub destination: Entry,
85    pub source: Entry,
86    pub local_config: Entry,
87    pub anchors: Vec<Parent>,
88    pub manifest_backup_sha256: String,
89    pub destination_backup_sha256: String,
90}
91
92#[derive(Clone, Serialize, Deserialize)]
93#[serde(deny_unknown_fields)]
94pub(crate) struct Record {
95    pub schema: u32,
96    pub sequence: usize,
97    pub previous_sha256: Option<String>,
98    pub header: Header,
99    pub phase: Phase,
100    pub operations: Vec<Operation>,
101}
102
103#[derive(Serialize, Deserialize)]
104#[serde(deny_unknown_fields)]
105struct Envelope {
106    sha256: String,
107    payload: String,
108}
109
110/// Content-free diagnostics; malformed records never appear verbatim in errors/reports.
111#[derive(Debug, Serialize)]
112pub struct Diagnosis {
113    pub repository_id: String,
114    pub transaction_id: String,
115    pub phase: Option<Phase>,
116    /// Last fully validated checkpoint schema, not an untrusted dispatch hint.
117    pub journal_schema: Option<u32>,
118    pub valid_checkpoints: usize,
119    pub problem: Option<String>,
120}
121
122impl Diagnosis {
123    pub fn blocks_writes(&self) -> bool {
124        self.problem.is_some() || self.phase.is_none_or(|p| !p.terminal())
125    }
126}
127
128pub(crate) struct Journal {
129    pub directory: PrivateDir,
130    pub record: Record,
131    last_sha256: Option<String>,
132    next: usize,
133}
134
135pub(crate) fn valid_id(id: &str) -> bool {
136    id.len() == 64
137        && id
138            .bytes()
139            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
140}
141
142pub(crate) fn transactions(host: &HostContext, repository_id: &str) -> Result<std::path::PathBuf> {
143    Ok(repository_state_path(host, repository_id)?.join("transactions"))
144}
145
146pub(crate) fn read_bytes(directory: &PrivateDir, name: &str) -> Result<Vec<u8>> {
147    let mut file = File::from(
148        fs::openat(
149            &directory.file,
150            name,
151            fs::OFlags::RDONLY | fs::OFlags::NOFOLLOW | fs::OFlags::NONBLOCK | fs::OFlags::CLOEXEC,
152            Mode::empty(),
153        )
154        .map_err(|e| io_error("open transaction artifact", directory.path.join(name), e))?,
155    );
156    directory.check_file(&file, name)?;
157    let before = observation::Fingerprint::from_stat(
158        &fs::fstat(&file)
159            .map_err(|e| io_error("inspect transaction artifact", &directory.path, e))?,
160    );
161    if before.size < 0 || before.size as u64 > LIMIT {
162        return Err(Error::Invalid(
163            "transaction artifact exceeds size limit".into(),
164        ));
165    }
166    let mut bytes = vec![];
167    (&mut file)
168        .take(LIMIT + 1)
169        .read_to_end(&mut bytes)
170        .map_err(|e| io_error("read transaction artifact", &directory.path, e))?;
171    let after = observation::Fingerprint::from_stat(
172        &fs::fstat(&file)
173            .map_err(|e| io_error("recheck transaction artifact", &directory.path, e))?,
174    );
175    let named = observation::Fingerprint::from_stat(
176        &fs::statat(&directory.file, name, fs::AtFlags::SYMLINK_NOFOLLOW)
177            .map_err(|e| io_error("recheck named transaction artifact", &directory.path, e))?,
178    );
179    if before != after || after != named || bytes.len() as u64 > LIMIT {
180        return Err(Error::Invalid(
181            "transaction artifact changed during read".into(),
182        ));
183    }
184    Ok(bytes)
185}
186
187impl Journal {
188    pub(crate) fn begin(host: &HostContext, header: Header) -> Result<Self> {
189        let root = transactions(host, &header.repository_id)?;
190        let parent = PrivateDir::open(&root, true)?.expect("created transactions directory");
191        fs::mkdirat(
192            &parent.file,
193            header.transaction_id.as_str(),
194            Mode::RUSR | Mode::WUSR | Mode::XUSR,
195        )
196        .map_err(|e| io_error("allocate unique transaction", &root, e))?;
197        parent.sync()?;
198        let directory =
199            PrivateDir::open(&root.join(&header.transaction_id), false)?.expect("new transaction");
200        let record = Record {
201            schema: 1,
202            sequence: 0,
203            previous_sha256: None,
204            header,
205            phase: Phase::Preparing,
206            operations: vec![],
207        };
208        let mut journal = Self {
209            directory,
210            record,
211            last_sha256: None,
212            next: 0,
213        };
214        journal.save()?;
215        Ok(journal)
216    }
217
218    /// A torn final file is deliberately retained. Earlier durable intent is never replaced.
219    pub(crate) fn save(&mut self) -> Result<()> {
220        self.record.sequence = self.next;
221        self.record.previous_sha256 = self.last_sha256.clone();
222        let payload = encode(&self.record)?;
223        let checksum = digest(payload.as_bytes());
224        let envelope = encode(&Envelope {
225            sha256: checksum.clone(),
226            payload,
227        })?;
228        if envelope.len() as u64 > LIMIT {
229            return Err(Error::Invalid("checkpoint exceeds size limit".into()));
230        }
231        self.directory
232            .create(&format!("{:06}.json", self.next), envelope.as_bytes())?;
233        self.last_sha256 = Some(checksum);
234        self.next += 1;
235        Ok(())
236    }
237
238    pub(crate) fn open(
239        host: &HostContext,
240        repository_id: &str,
241        transaction_id: &str,
242    ) -> Result<Self> {
243        if !valid_id(transaction_id) {
244            return Err(Error::Invalid("invalid transaction ID".into()));
245        }
246        let path = transactions(host, repository_id)?.join(transaction_id);
247        let directory = PrivateDir::open(&path, false)?
248            .ok_or_else(|| Error::Invalid("unknown transaction".into()))?;
249        let (diagnosis, latest, hash) = scan(&directory, repository_id, transaction_id);
250        if diagnosis.problem.is_some() || latest.is_none() {
251            return Err(Error::Invalid(
252                "malformed transaction; read-only diagnosis/manual repair required".into(),
253            ));
254        }
255        Ok(Self {
256            directory,
257            record: latest.unwrap(),
258            last_sha256: hash,
259            next: diagnosis.valid_checkpoints,
260        })
261    }
262
263    pub(crate) fn verify_backups(&self) -> Result<()> {
264        for (name, expected) in [
265            (
266                "manifest.backup",
267                &self.record.header.manifest_backup_sha256,
268            ),
269            (
270                "destination.backup",
271                &self.record.header.destination_backup_sha256,
272            ),
273        ] {
274            if digest(&read_bytes(&self.directory, name)?) != *expected {
275                return Err(Error::Invalid(
276                    "backup integrity mismatch; recovery refused".into(),
277                ));
278            }
279        }
280        Ok(())
281    }
282}
283
284fn transition(previous: &Record, next: &Record) -> Result<()> {
285    if encode(&previous.header)? != encode(&next.header)? || previous.phase.terminal() {
286        // Completed transactions may be explicitly rolled back, but never resumed forward.
287        if !(previous.phase == Phase::Completed
288            && next.phase == Phase::RollingBack
289            && encode(&previous.header)? == encode(&next.header)?)
290        {
291            return Err(Error::Invalid(
292                "invalid journal header/terminal transition".into(),
293            ));
294        }
295    }
296    let allowed = match previous.phase {
297        Phase::Preparing => matches!(next.phase, Phase::Running | Phase::RolledBack),
298        Phase::Running => matches!(
299            next.phase,
300            Phase::Running | Phase::Verifying | Phase::RollingBack
301        ),
302        Phase::Verifying => matches!(next.phase, Phase::Completed | Phase::RollingBack),
303        Phase::Completed => next.phase == Phase::RollingBack,
304        Phase::RollingBack => matches!(next.phase, Phase::RollingBack | Phase::RolledBack),
305        Phase::RolledBack => false,
306    };
307    if !allowed {
308        return Err(Error::Invalid("invalid journal phase transition".into()));
309    }
310    if previous.phase != Phase::Preparing {
311        if previous.operations.len() != next.operations.len() {
312            return Err(Error::Invalid("journal operation set changed".into()));
313        }
314        for (a, b) in previous.operations.iter().zip(&next.operations) {
315            if a.id != b.id
316                || a.role != b.role
317                || a.before != b.before
318                || a.staged != b.staged
319                || (a.after.is_some() && a.after != b.after)
320            {
321                return Err(Error::Invalid("journal operation identity changed".into()));
322            }
323            let ok = a.progress == b.progress
324                || matches!(
325                    (a.progress, b.progress),
326                    (Progress::Pending, Progress::Intent)
327                        | (Progress::Intent, Progress::Done)
328                        | (
329                            Progress::Pending | Progress::Intent | Progress::Done,
330                            Progress::UndoIntent
331                        )
332                        | (Progress::UndoIntent, Progress::Undone)
333                );
334            if !ok {
335                return Err(Error::Invalid("invalid operation transition".into()));
336            }
337        }
338    }
339    Ok(())
340}
341
342fn validate_structure(record: &Record, directory: &Path) -> Result<()> {
343    let h = &record.header;
344    if !valid_id(&h.approved_plan_sha256)
345        || !valid_id(&h.manifest_backup_sha256)
346        || !valid_id(&h.destination_backup_sha256)
347    {
348        return Err(Error::Invalid("invalid transaction digest binding".into()));
349    }
350    if record.phase == Phase::Preparing && !record.operations.is_empty() {
351        return Err(Error::Invalid(
352            "preparing checkpoint cannot contain live operations".into(),
353        ));
354    }
355    if record.operations.is_empty() {
356        if !matches!(record.phase, Phase::Preparing | Phase::RolledBack) {
357            return Err(Error::Invalid("missing adoption operation set".into()));
358        }
359        return Ok(());
360    }
361    let n = record.operations.len();
362    if n < 3 {
363        return Err(Error::Invalid("incomplete adoption operation set".into()));
364    }
365    if h.source.kind != observation::Kind::Missing
366        || h.manifest.kind != observation::Kind::Regular
367        || h.destination.kind != observation::Kind::Regular
368        || h.manifest.sha256.as_ref() != Some(&h.manifest_backup_sha256)
369        || h.destination.sha256.as_ref() != Some(&h.destination_backup_sha256)
370    {
371        return Err(Error::Invalid(
372            "invalid adoption input/backup binding".into(),
373        ));
374    }
375    let mut forward_boundary = false;
376    let mut undone_suffix = false;
377    let mut inverse_intents = 0;
378    for (id, op) in record.operations.iter().enumerate() {
379        let expected = if id == n - 3 {
380            (Role::Source, &h.source)
381        } else if id == n - 2 {
382            (Role::Manifest, &h.manifest)
383        } else if id == n - 1 {
384            (Role::Destination, &h.destination)
385        } else {
386            (Role::Directory, &op.before)
387        };
388        if op.id != id
389            || op.role != expected.0
390            || &op.before != expected.1
391            || op.staged.path != directory.join(format!("op-{id:04}"))
392            || op
393                .after
394                .as_ref()
395                .is_some_and(|after| after.path != op.before.path)
396            || (op.progress == Progress::Done && op.after.is_none())
397            || (matches!(op.progress, Progress::Pending | Progress::Intent) && op.after.is_some())
398        {
399            return Err(Error::Invalid(
400                "invalid operation ID, binding or postcondition".into(),
401            ));
402        }
403        let staged_kind = match op.role {
404            Role::Directory => observation::Kind::Directory,
405            Role::Source | Role::Manifest => observation::Kind::Regular,
406            Role::Destination => observation::Kind::Symlink,
407        };
408        if op.staged.kind != staged_kind
409            || (op.role == Role::Directory && op.before.kind != observation::Kind::Missing)
410            || (op.role == Role::Source && op.staged.sha256 != h.destination.sha256)
411            || (op.role == Role::Destination
412                && op.staged.link_target.as_ref() != Some(&h.source.path))
413        {
414            return Err(Error::Invalid(
415                "invalid prepared operation postcondition".into(),
416            ));
417        }
418        match record.phase {
419            Phase::Running => match op.progress {
420                Progress::Done if !forward_boundary => {}
421                Progress::Intent if !forward_boundary => forward_boundary = true,
422                Progress::Pending => forward_boundary = true,
423                _ => return Err(Error::Invalid("invalid forward operation ordering".into())),
424            },
425            Phase::Verifying | Phase::Completed if op.progress != Progress::Done => {
426                return Err(Error::Invalid(
427                    "completion without verified operations".into(),
428                ));
429            }
430            Phase::RollingBack => {
431                if op.progress == Progress::UndoIntent {
432                    inverse_intents += 1;
433                }
434                if inverse_intents > 1 {
435                    return Err(Error::Invalid("multiple inverse intents".into()));
436                }
437                if matches!(op.progress, Progress::UndoIntent | Progress::Undone) {
438                    undone_suffix = true;
439                } else if undone_suffix {
440                    return Err(Error::Invalid("invalid inverse operation ordering".into()));
441                }
442            }
443            Phase::RolledBack if op.progress != Progress::Undone => {
444                return Err(Error::Invalid(
445                    "rollback completion without inverse operations".into(),
446                ));
447            }
448            _ => {}
449        }
450    }
451    Ok(())
452}
453
454fn scan(
455    directory: &PrivateDir,
456    repository_id: &str,
457    transaction_id: &str,
458) -> (Diagnosis, Option<Record>, Option<String>) {
459    let mut diagnosis = Diagnosis {
460        repository_id: repository_id.into(),
461        transaction_id: transaction_id.into(),
462        journal_schema: None,
463        phase: None,
464        valid_checkpoints: 0,
465        problem: None,
466    };
467    let mut latest: Option<Record> = None;
468    let mut hash = None;
469    let result: Result<()> = (|| {
470        let names = observation::names(&directory.path, 4096)?;
471        for name in &names {
472            let name = name
473                .to_str()
474                .ok_or_else(|| Error::Invalid("unrepresentable transaction artifact".into()))?;
475            let stage = name
476                .strip_prefix("op-")
477                .is_some_and(|id| id.len() == 4 && id.bytes().all(|b| b.is_ascii_digit()));
478            if !name.ends_with(".json")
479                && !stage
480                && !matches!(name, "manifest.backup" | "destination.backup")
481            {
482                return Err(Error::Invalid("unknown transaction artifact".into()));
483            }
484        }
485        let checkpoints: Vec<_> = names
486            .iter()
487            .filter_map(|n| n.to_str())
488            .filter(|n| n.ends_with(".json"))
489            .collect();
490        if checkpoints.is_empty() {
491            return Err(Error::Invalid("transaction has no durable intent".into()));
492        }
493        for (i, name) in checkpoints.into_iter().enumerate() {
494            if name != format!("{i:06}.json") {
495                return Err(Error::Invalid(
496                    "checkpoint sequence gap or unknown record".into(),
497                ));
498            }
499            let bytes = read_bytes(directory, name)?;
500            let envelope: Envelope = serde_json::from_slice(&bytes)
501                .map_err(|_| Error::Invalid("truncated or malformed checkpoint".into()))?;
502            if digest(envelope.payload.as_bytes()) != envelope.sha256 {
503                return Err(Error::Invalid("checkpoint checksum mismatch".into()));
504            }
505            let record: Record = serde_json::from_str(&envelope.payload)
506                .map_err(|_| Error::Invalid("unsupported or malformed checkpoint".into()))?;
507            if record.schema != 1
508                || record.sequence != i
509                || record.previous_sha256 != hash
510                || record.header.repository_id != repository_id
511                || record.header.transaction_id != transaction_id
512            {
513                return Err(Error::Invalid(
514                    "unsupported schema or invalid checkpoint binding".into(),
515                ));
516            }
517            validate_structure(&record, &directory.path)?;
518            if let Some(previous) = &latest {
519                transition(previous, &record)?;
520            } else if record.phase != Phase::Preparing || !record.operations.is_empty() {
521                return Err(Error::Invalid("first checkpoint must be preparing".into()));
522            }
523            diagnosis.valid_checkpoints += 1;
524            diagnosis.phase = Some(record.phase);
525            diagnosis.journal_schema = Some(record.schema);
526            hash = Some(envelope.sha256);
527            latest = Some(record);
528        }
529        if let Some(record) = &latest
530            && !record.operations.is_empty()
531        {
532            for (name, expected) in [
533                ("manifest.backup", &record.header.manifest_backup_sha256),
534                (
535                    "destination.backup",
536                    &record.header.destination_backup_sha256,
537                ),
538            ] {
539                if digest(&read_bytes(directory, name)?) != *expected {
540                    return Err(Error::Invalid("backup integrity mismatch".into()));
541                }
542            }
543        }
544        Ok(())
545    })();
546    if let Err(error) = result {
547        diagnosis.problem = Some(error.to_string());
548    }
549    (diagnosis, latest, hash)
550}
551
552/// Does not create state, lock, repair, read live file contents or replay anything.
553pub fn diagnose(host: &HostContext) -> Result<Vec<Diagnosis>> {
554    let root = host.state_dir.join("repositories");
555    if PrivateDir::open(&host.state_dir, false)?.is_none() {
556        return Ok(vec![]);
557    }
558    if observation::inspect(&root, false)?.kind == observation::Kind::Missing {
559        return Ok(vec![]);
560    }
561    let mut reports = vec![];
562    for repository in observation::names(&root, 4096)? {
563        let id = repository
564            .to_str()
565            .filter(|id| valid_id(id))
566            .ok_or_else(|| Error::Invalid("invalid repository state directory".into()))?;
567        let path = transactions(host, id)?;
568        if observation::inspect(&path, false)?.kind == observation::Kind::Missing {
569            continue;
570        }
571        PrivateDir::open(&path, false)?
572            .ok_or_else(|| Error::Invalid("missing transactions directory".into()))?;
573        for name in observation::names(&path, 4096)? {
574            let Some(txid) = name.to_str().filter(|id| valid_id(id)) else {
575                reports.push(Diagnosis {
576                    repository_id: id.into(),
577                    transaction_id: "<invalid name>".into(),
578                    journal_schema: None,
579                    phase: None,
580                    valid_checkpoints: 0,
581                    problem: Some("unknown transaction entry".into()),
582                });
583                continue;
584            };
585            match PrivateDir::open(&path.join(txid), false) {
586                Ok(Some(directory)) => reports.push(if crate::bootstrap::is_schema3(&directory) {
587                    crate::bootstrap::scan(&directory, id, txid).0
588                } else if crate::batch_journal::is_schema4(&directory) {
589                    crate::batch_journal::scan(&directory, id, txid).0
590                } else if crate::lifecycle_journal::is_schema2(&directory) {
591                    crate::lifecycle_journal::scan(&directory, id, txid).0
592                } else {
593                    scan(&directory, id, txid).0
594                }),
595                _ => reports.push(Diagnosis {
596                    repository_id: id.into(),
597                    transaction_id: txid.into(),
598                    journal_schema: None,
599                    phase: None,
600                    valid_checkpoints: 0,
601                    problem: Some("unsafe transaction directory".into()),
602                }),
603            }
604        }
605    }
606    Ok(reports)
607}
608
609/// Registry and executor writes fail closed on every incomplete/malformed transaction.
610pub(crate) fn ensure_writable(host: &HostContext) -> Result<()> {
611    if diagnose(host)?.iter().any(Diagnosis::blocks_writes) {
612        return Err(Error::Invalid(
613            "incomplete or malformed transaction blocks writes; explicit recovery required".into(),
614        ));
615    }
616    Ok(())
617}
618
619pub(crate) fn registered_root(host: &HostContext, id: &str, root: &Path) -> Result<()> {
620    let local = LocalConfig::load(host)?;
621    if local.repositories.get(id).is_none_or(|r| r.root != root) {
622        return Err(Error::Invalid(
623            "transaction repository is not registered at this root".into(),
624        ));
625    }
626    Ok(())
627}