OXYGENHUB
# f53cbe7a204e oxygen / crates / oxy-core / src / repo / fsck.rs
19.4 KiB · Rust · last changed Certificates for short-lived keys (keyless, step 1) 20 days ago source blame history raw
1
//! Repository integrity check (spec §21.1): `oxy fsck`.
2
//!
3
//! Reads everything and changes nothing. Four passes:
4
//!
5
//! 1. every stored object: header, length, hash, and that its body decodes
6
//!    as its type says;
7
//! 2. the operation log: every operation reachable from the head is
8
//!    present and decodes, and clocks never run backwards;
9
//! 3. references: the current view's bookmarks, tags, remote bookmarks,
10
//!    workspaces and policy, then the dependency closure of everything
11
//!    they name, with each change's author identity, blobs and chunks,
12
//!    and each change's signatures or seals;
13
//! 4. derived data: every bookmark's state validates, every checkpoint
14
//!    restores exactly the state it names, and reference and tag
15
//!    attestations carry good signatures.
16
//!
17
//! Missing blobs are warnings, not errors, in a partial clone
18
//! (`filter.max-blob` or a sparse filter), and changes beyond a shallow
19
//! boundary are expected to be absent.
20
21
use super::*;
22
use std::collections::{HashSet, VecDeque};
23
24
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
25
pub enum Severity {
26
    /// Worth knowing; the repository is still sound.
27
    Warning,
28
    /// Data is missing, corrupt or fails verification.
29
    Error,
30
}
31
32
#[derive(Clone, Debug, PartialEq, Eq)]
33
pub struct Problem {
34
    pub severity: Severity,
35
    /// The object the problem is about, when there is one.
36
    pub object: Option<ObjectRef>,
37
    pub what: String,
38
}
39
40
#[derive(Clone, Debug, Default, PartialEq, Eq)]
41
pub struct FsckReport {
42
    pub objects: usize,
43
    pub ops: usize,
44
    /// Changes checked, working-copy changes included.
45
    pub changes: usize,
46
    /// Committed changes authenticated by their own signature or by a seal.
47
    pub signed: usize,
48
    pub unsigned: usize,
49
    pub checkpoints: usize,
50
    pub attestations: usize,
51
    pub problems: Vec<Problem>,
52
}
53
54
impl FsckReport {
55
    pub fn errors(&self) -> usize {
56
        self.problems
57
            .iter()
58
            .filter(|p| p.severity == Severity::Error)
59
            .count()
60
    }
61
62
    pub fn warnings(&self) -> usize {
63
        self.problems
64
            .iter()
65
            .filter(|p| p.severity == Severity::Warning)
66
            .count()
67
    }
68
69
    fn error(&mut self, object: Option<ObjectRef>, what: impl Into<String>) {
70
        self.problems.push(Problem {
71
            severity: Severity::Error,
72
            object,
73
            what: what.into(),
74
        });
75
    }
76
77
    fn warn(&mut self, object: Option<ObjectRef>, what: impl Into<String>) {
78
        self.problems.push(Problem {
79
            severity: Severity::Warning,
80
            object,
81
            what: what.into(),
82
        });
83
    }
84
}
85
86
/// Whether `body` decodes as an object of type `ty`.
87
fn decodes(ty: ObjectType, body: &[u8]) -> std::result::Result<(), String> {
88
    let r = match ty {
89
        ObjectType::Chunk => Ok(()),
90
        ObjectType::Blob => Blob::decode(body).map(|_| ()),
91
        // Structure only: the text blobs are checked with the change graph.
92
        ObjectType::Change => {
93
            Change::decode_with(body, &mut |_, _, _| Ok(crate::lines::Lines::default())).map(|_| ())
94
        }
95
        ObjectType::Checkpoint => crate::objects::Checkpoint::decode(body).map(|_| ()),
96
        ObjectType::Op => match Op::decode(body) {
97
            Ok(_) => Ok(()),
98
            Err(e) => Op::decode_format1(body).map(|_| ()).map_err(|_| e),
99
        },
100
        ObjectType::Attest => Attest::decode(body).map(|_| ()),
101
        ObjectType::Identity => Identity::decode(body).map(|_| ()),
102
        ObjectType::Policy => crate::policy::Policy::decode(body).map(|_| ()),
103
        ObjectType::Receipt => crate::receipt::Receipt::decode(body).map(|_| ()),
104
        ObjectType::Certificate => crate::cert::Certificate::decode(body).map(|_| ()),
105
        ObjectType::State => crate::objects::StateObject::decode(body).map(|_| ()),
106
    };
107
    r.map_err(|e| e.to_string())
108
}
109
110
impl Repo {
111
    /// Check the whole repository; see the module documentation.
112
    pub fn fsck(&self) -> Result<FsckReport> {
113
        let mut rep = FsckReport::default();
114
        let bad = {
115
            let _t = crate::timing::phase("fsck: objects");
116
            self.fsck_objects(&mut rep)?
117
        };
118
        {
119
            let _t = crate::timing::phase("fsck: operations");
120
            self.fsck_ops(&mut rep, &bad);
121
        }
122
        {
123
            let _t = crate::timing::phase("fsck: references");
124
            self.fsck_references(&mut rep, &bad)?;
125
        }
126
        {
127
            let _t = crate::timing::phase("fsck: states and checkpoints");
128
            self.fsck_derived(&mut rep)?;
129
        }
130
        rep.problems.sort_by_key(|p| std::cmp::Reverse(p.severity));
131
        Ok(rep)
132
    }
133
134
    /// Pass 1. Returns the objects that failed, so later passes report
135
    /// them once rather than at every reference.
136
    fn fsck_objects(&self, rep: &mut FsckReport) -> Result<HashSet<ObjectRef>> {
137
        use rayon::prelude::*;
138
        let mut bad = HashSet::new();
139
        // A chunk at a time, read (and verified) and decoded on every core.
140
        for refs in self.store.list()?.chunks(8192) {
141
            let checked: Vec<std::result::Result<(), String>> = self
142
                .store
143
                .get_many(refs)
144
                .into_par_iter()
145
                .map(|got| match got {
146
                    Ok((ty, body)) => decodes(ty, &body)
147
                        .map_err(|e| format!("{} object does not decode: {e}", ty.name())),
148
                    Err(e) => Err(format!("unreadable object: {e}")),
149
                })
150
                .collect();
151
            for (r, c) in refs.iter().zip(checked) {
152
                rep.objects += 1;
153
                if let Err(e) = c {
154
                    rep.error(Some(*r), e);
155
                    bad.insert(*r);
156
                }
157
            }
158
        }
159
        Ok(bad)
160
    }
161
162
    /// Pass 2.
163
    fn fsck_ops(&self, rep: &mut FsckReport, bad: &HashSet<ObjectRef>) {
164
        let head = match fs::read_to_string(self.oxy.join("ops").join("head")) {
165
            Ok(h) => h,
166
            Err(e) => {
167
                rep.error(None, format!("cannot read .oxy/ops/head: {e}"));
168
                return;
169
            }
170
        };
171
        let Some(head) = ObjectRef::from_hex(head.trim()) else {
172
            rep.error(None, ".oxy/ops/head does not hold an object reference");
173
            return;
174
        };
175
        let mut seen = HashSet::new();
176
        let mut queue: VecDeque<(ObjectRef, Option<(ObjectRef, u64)>)> =
177
            VecDeque::from([(head, None)]);
178
        while let Some((r, child)) = queue.pop_front() {
179
            if !seen.insert(r) {
180
                continue;
181
            }
182
            if bad.contains(&r) {
183
                continue;
184
            }
185
            let body = match self.store.get_typed(&r, ObjectType::Op) {
186
                Ok(b) => b,
187
                Err(StoreError::NotFound(_)) => {
188
                    let by = child
189
                        .map(|(c, _)| format!(", the parent of operation {}", c.short(12)))
190
                        .unwrap_or_default();
191
                    rep.error(
192
                        Some(r),
193
                        format!("operation missing{by}; the log is cut here"),
194
                    );
195
                    continue;
196
                }
197
                Err(e) => {
198
                    rep.error(Some(r), format!("operation unreadable: {e}"));
199
                    continue;
200
                }
201
            };
202
            rep.ops += 1;
203
            let (parents, wall_ms) = match Op::decode(&body) {
204
                Ok(op) => (op.parents, op.hlc.wall_ms),
205
                Err(_) => match Op::decode_format1(&body) {
206
                    Ok(op) => (op.parents, op.hlc.wall_ms),
207
                    Err(e) => {
208
                        rep.error(Some(r), format!("operation does not decode: {e}"));
209
                        continue;
210
                    }
211
                },
212
            };
213
            if let Some((c, child_ms)) = child {
214
                if wall_ms > child_ms {
215
                    rep.warn(
216
                        Some(c),
217
                        format!(
218
                            "operation is timed before its parent {} (a clock was wrong)",
219
                            r.short(12)
220
                        ),
221
                    );
222
                }
223
            }
224
            queue.extend(parents.into_iter().map(|p| (p, Some((r, wall_ms)))));
225
        }
226
    }
227
228
    /// Pass 3.
229
    fn fsck_references(&self, rep: &mut FsckReport, bad: &HashSet<ObjectRef>) -> Result<()> {
230
        let view = match self.view() {
231
            Ok(v) => v,
232
            Err(e) => {
233
                rep.error(None, format!("cannot read the current view: {e}"));
234
                return Ok(());
235
            }
236
        };
237
        let boundary = self.boundary();
238
        let partial = self.config.max_blob.is_some() || !self.config.sparse_paths.is_empty();
239
240
        let mut roots: Vec<(ChangeHash, String)> = Vec::new();
241
        let mut states: Vec<(ObjectRef, String)> = Vec::new();
242
        states.extend(
243
            view.bookmarks
244
                .iter()
245
                .map(|(n, s)| (*s, format!("bookmark {n}"))),
246
        );
247
        states.extend(view.tags.iter().map(|(n, s)| (*s, format!("tag {n}"))));
248
        for (remote, bms) in &view.remotes {
249
            states.extend(bms.iter().map(|(n, s)| (*s, format!("{remote}/{n}"))));
250
        }
251
        for (st, what) in states {
252
            match self.store.get_state(&st) {
253
                Ok(s) => roots.extend(s.heads.into_iter().map(|h| (h, what.clone()))),
254
                Err(e) if !bad.contains(&st) => {
255
                    rep.error(Some(st), format!("state of {what} unusable: {e}"))
256
                }
257
                Err(_) => {}
258
            }
259
        }
260
        for (ws, h) in &view.workspaces {
261
            roots.push((*h, format!("workspace {}", ws.to_hex())));
262
        }
263
        if let Some(p) = view.policy {
264
            match self.store.get_typed(&p, ObjectType::Policy) {
265
                Ok(bytes) => {
266
                    if let Ok(policy) = crate::policy::Policy::decode(&bytes) {
267
                        for id in &policy.identities {
268
                            if !self.store.has(&id.hash()) {
269
                                rep.warn(
270
                                    Some(id.hash()),
271
                                    "an identity the policy names is not stored",
272
                                );
273
                            }
274
                        }
275
                    }
276
                }
277
                Err(e) if !bad.contains(&p) => {
278
                    rep.error(Some(p), format!("the policy is unusable: {e}"))
279
                }
280
                Err(_) => {}
281
            }
282
        }
283
284
        // Working-copy changes are never signed; they are checked but not tallied.
285
        let working: HashSet<ChangeHash> = view.workspaces.values().copied().collect();
286
        let mut seen: HashSet<ChangeHash> = HashSet::new();
287
        let mut blobs_seen: HashSet<ObjectRef> = HashSet::new();
288
        let mut stack = roots;
289
        while let Some((h, needed_by)) = stack.pop() {
290
            if !seen.insert(h) {
291
                continue;
292
            }
293
            // The skeleton: the text is checked as the blobs it is stored
294
            // in, not decoded (the objects pass checked every object).
295
            let (c, texts) = match self.store.get_change_lazy(&h) {
296
                Ok(c) => c,
297
                Err(StoreError::NotFound(_)) if boundary.contains(&h) => continue,
298
                Err(StoreError::NotFound(_)) => {
299
                    rep.error(Some(h), format!("change missing, needed by {needed_by}"));
300
                    continue;
301
                }
302
                Err(e) => {
303
                    if !bad.contains(&h) {
304
                        rep.error(Some(h), format!("change unusable: {e}"));
305
                    }
306
                    continue;
307
                }
308
            };
309
            rep.changes += 1;
310
            let label = format!("change {}", h.short(12));
311
            stack.extend(c.deps.iter().map(|d| (*d, label.clone())));
312
            if !c.author.is_zero() && !self.store.has(&c.author) {
313
                rep.warn(
314
                    Some(h),
315
                    format!("author identity {} is not stored", c.author.short(12)),
316
                );
317
            }
318
            for t in texts {
319
                if let crate::objects::TextRef::Blob(b, _, _) = t {
320
                    if blobs_seen.insert(b) {
321
                        // A change cannot be read without its text: never partial.
322
                        self.fsck_blob(rep, b, &label, false, bad);
323
                    }
324
                }
325
            }
326
            for e in &c.edits {
327
                let Edit::Replace { old, new, .. } = e else {
328
                    continue;
329
                };
330
                for b in [old, new].into_iter().flatten() {
331
                    if !blobs_seen.insert(*b) {
332
                        continue;
333
                    }
334
                    self.fsck_blob(rep, *b, &label, partial, bad);
335
                }
336
            }
337
            if working.contains(&h) {
338
                continue;
339
            }
340
            match self.authenticate_change(&h) {
341
                Ok(SignatureStatus::Valid { .. }) => rep.signed += 1,
342
                Ok(SignatureStatus::Unsigned) => rep.unsigned += 1,
343
                Ok(SignatureStatus::Invalid(why)) => {
344
                    rep.error(Some(h), format!("bad signature: {why}"))
345
                }
346
                Err(e) => rep.error(Some(h), format!("cannot check signatures: {e}")),
347
            }
348
        }
349
        Ok(())
350
    }
351
352
    fn fsck_blob(
353
        &self,
354
        rep: &mut FsckReport,
355
        b: ObjectRef,
356
        used_by: &str,
357
        partial: bool,
358
        bad: &HashSet<ObjectRef>,
359
    ) {
360
        match self.store.get_typed(&b, ObjectType::Blob) {
361
            Ok(bytes) => {
362
                let Ok(blob) = Blob::decode(&bytes) else {
363
                    return;
364
                };
365
                for ch in blob.chunks {
366
                    if !self.store.has(&ch) {
367
                        rep.error(
368
                            Some(ch),
369
                            format!("chunk missing from blob {} ({used_by})", b.short(12)),
370
                        );
371
                    }
372
                }
373
            }
374
            Err(StoreError::NotFound(_)) if partial => rep.warn(
375
                Some(b),
376
                format!("blob not fetched ({used_by}); expected in a partial clone"),
377
            ),
378
            Err(StoreError::NotFound(_)) => rep.error(Some(b), format!("blob missing ({used_by})")),
379
            Err(e) if !bad.contains(&b) => {
380
                rep.error(Some(b), format!("blob unusable ({used_by}): {e}"))
381
            }
382
            Err(_) => {}
383
        }
384
    }
385
386
    /// Whether `heads` form a valid state: its history loads and every file
387
    /// graph builds. Graphs are built a batch at a time and dropped, so the
388
    /// check needs the memory of a batch, not of the whole tree.
389
    fn check_state(&self, heads: &[ChangeHash]) -> Result<()> {
390
        let mut st = self.load_state_history(heads)?;
391
        let nodes = st.unbuilt_nodes();
392
        for batch in nodes.chunks(2048) {
393
            self.load_graphs_of(&mut st, batch)?;
394
            st.drop_graphs(batch);
395
        }
396
        Ok(())
397
    }
398
399
    /// Pass 4.
400
    fn fsck_derived(&self, rep: &mut FsckReport) -> Result<()> {
401
        let Ok(view) = self.view() else { return Ok(()) };
402
        let shallow = self.is_shallow();
403
        if !shallow {
404
            let mut checked: HashSet<ObjectRef> = HashSet::new();
405
            for (name, st) in &view.bookmarks {
406
                if !checked.insert(*st) {
407
                    continue;
408
                }
409
                let Ok(s) = self.store.get_state(st) else {
410
                    continue;
411
                };
412
                if let Err(e) = self.check_state(&s.heads) {
413
                    rep.error(
414
                        Some(*st),
415
                        format!("bookmark {name} does not form a valid state: {e}"),
416
                    );
417
                }
418
            }
419
        }
420
        for r in self.checkpoint_refs()? {
421
            rep.checkpoints += 1;
422
            let cp = match self.store.get_typed(&r, ObjectType::Checkpoint) {
423
                Ok(b) => match crate::objects::Checkpoint::decode(&b) {
424
                    Ok(cp) => cp,
425
                    Err(_) => continue,
426
                },
427
                Err(StoreError::NotFound(_)) => {
428
                    rep.warn(
429
                        Some(r),
430
                        "checkpoint pointer names a missing checkpoint; it will be rewritten",
431
                    );
432
                    continue;
433
                }
434
                Err(_) => continue,
435
            };
436
            let payload = match self.read_blob(&cp.payload) {
437
                Ok(p) => p,
438
                Err(e) => {
439
                    rep.error(Some(r), format!("checkpoint payload unreadable: {e}"));
440
                    continue;
441
                }
442
            };
443
            if let Err(e) = self.state_from_checkpoint(&payload) {
444
                rep.error(Some(r), format!("checkpoint payload does not decode: {e}"));
445
                continue;
446
            }
447
            // The payload must be what the named changes produce, in its own version.
448
            let version = crate::cbor::decode(&payload).ok().and_then(|v| {
449
                crate::objects::map(&v, "payload").ok().and_then(|m| {
450
                    m.get(&0)
451
                        .and_then(|x| crate::objects::uint(x, "version").ok())
452
                })
453
            });
454
            let expected = |full: &State| {
455
                if version == Some(crate::state::CHECKPOINT_INDEX_VERSION) {
456
                    full.checkpoint_index(&full.checkpoint_file_graphs(), Repo::blob_ref)
457
                } else {
458
                    full.checkpoint_payload()
459
                }
460
            };
461
            if !shallow {
462
                match self.load_state_full(&cp.heads) {
463
                    Ok(full) if expected(&full) != payload => {
464
                        rep.error(Some(r), "checkpoint disagrees with the changes it names")
465
                    }
466
                    Ok(_) => {}
467
                    Err(e) => rep.error(
468
                        Some(r),
469
                        format!("checkpoint names changes that do not form a state: {e}"),
470
                    ),
471
                }
472
            }
473
        }
474
        let mut attests = Vec::new();
475
        for name in view.bookmarks.keys() {
476
            if let Ok(Some((r, _))) = self.latest_ref_attest(name) {
477
                attests.push((r, format!("bookmark {name}")));
478
            }
479
        }
480
        for name in view.tags.keys() {
481
            if let Ok(Some((r, _))) = self.tag_attest(name) {
482
                attests.push((r, format!("tag {name}")));
483
            }
484
        }
485
        for (r, what) in attests {
486
            rep.attestations += 1;
487
            let sigs = self.store.signatures(&r)?;
488
            if sigs.is_empty() {
489
                rep.warn(Some(r), format!("attestation for {what} is unsigned"));
490
            }
491
            for sig in sigs {
492
                match self.store.get_identity(&sig.key) {
493
                    Ok(id) => {
494
                        if let Err(e) = verify_signature(&id, &sig, Domain::Attest, &r) {
495
                            rep.error(
496
                                Some(r),
497
                                format!("attestation for {what} has a bad signature: {e}"),
498
                            );
499
                        }
500
                    }
501
                    Err(_) => rep.warn(
502
                        Some(r),
503
                        format!(
504
                            "attestation for {what} is signed by {}, whose identity is not stored",
505
                            sig.key.short(12)
506
                        ),
507
                    ),
508
                }
509
            }
510
        }
511
        Ok(())
512
    }
513
}