OXYGENHUB
# 9df6217f5f47 oxygen / crates / oxy-core / src / repo / fsck.rs
17.4 KiB · Rust · last changed Execution receipts: the receipt object and attestation 1 month 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
        ObjectType::Change => Change::decode(body).map(|_| ()),
92
        ObjectType::Checkpoint => crate::objects::Checkpoint::decode(body).map(|_| ()),
93
        ObjectType::Op => match Op::decode(body) {
94
            Ok(_) => Ok(()),
95
            Err(e) => Op::decode_format1(body).map(|_| ()).map_err(|_| e),
96
        },
97
        ObjectType::Attest => Attest::decode(body).map(|_| ()),
98
        ObjectType::Identity => Identity::decode(body).map(|_| ()),
99
        ObjectType::Policy => crate::policy::Policy::decode(body).map(|_| ()),
100
        ObjectType::Receipt => crate::receipt::Receipt::decode(body).map(|_| ()),
101
        ObjectType::State => crate::objects::StateObject::decode(body).map(|_| ()),
102
    };
103
    r.map_err(|e| e.to_string())
104
}
105
106
impl Repo {
107
    /// Check the whole repository; see the module documentation.
108
    pub fn fsck(&self) -> Result<FsckReport> {
109
        let mut rep = FsckReport::default();
110
        let bad = self.fsck_objects(&mut rep)?;
111
        self.fsck_ops(&mut rep, &bad);
112
        self.fsck_references(&mut rep, &bad)?;
113
        self.fsck_derived(&mut rep)?;
114
        rep.problems.sort_by_key(|p| std::cmp::Reverse(p.severity));
115
        Ok(rep)
116
    }
117
118
    /// Pass 1. Returns the objects that failed, so later passes report
119
    /// them once rather than at every reference.
120
    fn fsck_objects(&self, rep: &mut FsckReport) -> Result<HashSet<ObjectRef>> {
121
        let mut bad = HashSet::new();
122
        for r in self.store.list()? {
123
            rep.objects += 1;
124
            match self.store.get(&r) {
125
                Ok((ty, body)) => {
126
                    if let Err(e) = decodes(ty, &body) {
127
                        rep.error(
128
                            Some(r),
129
                            format!("{} object does not decode: {e}", ty.name()),
130
                        );
131
                        bad.insert(r);
132
                    }
133
                }
134
                Err(e) => {
135
                    rep.error(Some(r), format!("unreadable object: {e}"));
136
                    bad.insert(r);
137
                }
138
            }
139
        }
140
        Ok(bad)
141
    }
142
143
    /// Pass 2.
144
    fn fsck_ops(&self, rep: &mut FsckReport, bad: &HashSet<ObjectRef>) {
145
        let head = match fs::read_to_string(self.oxy.join("ops").join("head")) {
146
            Ok(h) => h,
147
            Err(e) => {
148
                rep.error(None, format!("cannot read .oxy/ops/head: {e}"));
149
                return;
150
            }
151
        };
152
        let Some(head) = ObjectRef::from_hex(head.trim()) else {
153
            rep.error(None, ".oxy/ops/head does not hold an object reference");
154
            return;
155
        };
156
        let mut seen = HashSet::new();
157
        let mut queue: VecDeque<(ObjectRef, Option<(ObjectRef, u64)>)> =
158
            VecDeque::from([(head, None)]);
159
        while let Some((r, child)) = queue.pop_front() {
160
            if !seen.insert(r) {
161
                continue;
162
            }
163
            if bad.contains(&r) {
164
                continue;
165
            }
166
            let body = match self.store.get_typed(&r, ObjectType::Op) {
167
                Ok(b) => b,
168
                Err(StoreError::NotFound(_)) => {
169
                    let by = child
170
                        .map(|(c, _)| format!(", the parent of operation {}", c.short(12)))
171
                        .unwrap_or_default();
172
                    rep.error(
173
                        Some(r),
174
                        format!("operation missing{by}; the log is cut here"),
175
                    );
176
                    continue;
177
                }
178
                Err(e) => {
179
                    rep.error(Some(r), format!("operation unreadable: {e}"));
180
                    continue;
181
                }
182
            };
183
            rep.ops += 1;
184
            let (parents, wall_ms) = match Op::decode(&body) {
185
                Ok(op) => (op.parents, op.hlc.wall_ms),
186
                Err(_) => match Op::decode_format1(&body) {
187
                    Ok(op) => (op.parents, op.hlc.wall_ms),
188
                    Err(e) => {
189
                        rep.error(Some(r), format!("operation does not decode: {e}"));
190
                        continue;
191
                    }
192
                },
193
            };
194
            if let Some((c, child_ms)) = child {
195
                if wall_ms > child_ms {
196
                    rep.warn(
197
                        Some(c),
198
                        format!(
199
                            "operation is timed before its parent {} (a clock was wrong)",
200
                            r.short(12)
201
                        ),
202
                    );
203
                }
204
            }
205
            queue.extend(parents.into_iter().map(|p| (p, Some((r, wall_ms)))));
206
        }
207
    }
208
209
    /// Pass 3.
210
    fn fsck_references(&self, rep: &mut FsckReport, bad: &HashSet<ObjectRef>) -> Result<()> {
211
        let view = match self.view() {
212
            Ok(v) => v,
213
            Err(e) => {
214
                rep.error(None, format!("cannot read the current view: {e}"));
215
                return Ok(());
216
            }
217
        };
218
        let boundary = self.boundary();
219
        let partial = self.config.max_blob.is_some() || !self.config.sparse_paths.is_empty();
220
221
        let mut roots: Vec<(ChangeHash, String)> = Vec::new();
222
        let mut states: Vec<(ObjectRef, String)> = Vec::new();
223
        states.extend(
224
            view.bookmarks
225
                .iter()
226
                .map(|(n, s)| (*s, format!("bookmark {n}"))),
227
        );
228
        states.extend(view.tags.iter().map(|(n, s)| (*s, format!("tag {n}"))));
229
        for (remote, bms) in &view.remotes {
230
            states.extend(bms.iter().map(|(n, s)| (*s, format!("{remote}/{n}"))));
231
        }
232
        for (st, what) in states {
233
            match self.store.get_state(&st) {
234
                Ok(s) => roots.extend(s.heads.into_iter().map(|h| (h, what.clone()))),
235
                Err(e) if !bad.contains(&st) => {
236
                    rep.error(Some(st), format!("state of {what} unusable: {e}"))
237
                }
238
                Err(_) => {}
239
            }
240
        }
241
        for (ws, h) in &view.workspaces {
242
            roots.push((*h, format!("workspace {}", ws.to_hex())));
243
        }
244
        if let Some(p) = view.policy {
245
            match self.store.get_typed(&p, ObjectType::Policy) {
246
                Ok(bytes) => {
247
                    if let Ok(policy) = crate::policy::Policy::decode(&bytes) {
248
                        for id in &policy.identities {
249
                            if !self.store.has(&id.hash()) {
250
                                rep.warn(
251
                                    Some(id.hash()),
252
                                    "an identity the policy names is not stored",
253
                                );
254
                            }
255
                        }
256
                    }
257
                }
258
                Err(e) if !bad.contains(&p) => {
259
                    rep.error(Some(p), format!("the policy is unusable: {e}"))
260
                }
261
                Err(_) => {}
262
            }
263
        }
264
265
        // Working-copy changes are never signed; they are checked but not tallied.
266
        let working: HashSet<ChangeHash> = view.workspaces.values().copied().collect();
267
        let mut seen: HashSet<ChangeHash> = HashSet::new();
268
        let mut blobs_seen: HashSet<ObjectRef> = HashSet::new();
269
        let mut stack = roots;
270
        while let Some((h, needed_by)) = stack.pop() {
271
            if !seen.insert(h) {
272
                continue;
273
            }
274
            let c = match self.store.get_change(&h) {
275
                Ok(c) => c,
276
                Err(StoreError::NotFound(_)) if boundary.contains(&h) => continue,
277
                Err(StoreError::NotFound(_)) => {
278
                    rep.error(Some(h), format!("change missing, needed by {needed_by}"));
279
                    continue;
280
                }
281
                Err(e) => {
282
                    if !bad.contains(&h) {
283
                        rep.error(Some(h), format!("change unusable: {e}"));
284
                    }
285
                    continue;
286
                }
287
            };
288
            rep.changes += 1;
289
            let label = format!("change {}", h.short(12));
290
            stack.extend(c.deps.iter().map(|d| (*d, label.clone())));
291
            if !c.author.is_zero() && !self.store.has(&c.author) {
292
                rep.warn(
293
                    Some(h),
294
                    format!("author identity {} is not stored", c.author.short(12)),
295
                );
296
            }
297
            for e in &c.edits {
298
                let Edit::Replace { old, new, .. } = e else {
299
                    continue;
300
                };
301
                for b in [old, new].into_iter().flatten() {
302
                    if !blobs_seen.insert(*b) {
303
                        continue;
304
                    }
305
                    self.fsck_blob(rep, *b, &label, partial, bad);
306
                }
307
            }
308
            if working.contains(&h) {
309
                continue;
310
            }
311
            match self.authenticate_change(&h) {
312
                Ok(SignatureStatus::Valid { .. }) => rep.signed += 1,
313
                Ok(SignatureStatus::Unsigned) => rep.unsigned += 1,
314
                Ok(SignatureStatus::Invalid(why)) => {
315
                    rep.error(Some(h), format!("bad signature: {why}"))
316
                }
317
                Err(e) => rep.error(Some(h), format!("cannot check signatures: {e}")),
318
            }
319
        }
320
        Ok(())
321
    }
322
323
    fn fsck_blob(
324
        &self,
325
        rep: &mut FsckReport,
326
        b: ObjectRef,
327
        used_by: &str,
328
        partial: bool,
329
        bad: &HashSet<ObjectRef>,
330
    ) {
331
        match self.store.get_typed(&b, ObjectType::Blob) {
332
            Ok(bytes) => {
333
                let Ok(blob) = Blob::decode(&bytes) else {
334
                    return;
335
                };
336
                for ch in blob.chunks {
337
                    if !self.store.has(&ch) {
338
                        rep.error(
339
                            Some(ch),
340
                            format!("chunk missing from blob {} ({used_by})", b.short(12)),
341
                        );
342
                    }
343
                }
344
            }
345
            Err(StoreError::NotFound(_)) if partial => rep.warn(
346
                Some(b),
347
                format!("blob not fetched ({used_by}); expected in a partial clone"),
348
            ),
349
            Err(StoreError::NotFound(_)) => rep.error(Some(b), format!("blob missing ({used_by})")),
350
            Err(e) if !bad.contains(&b) => {
351
                rep.error(Some(b), format!("blob unusable ({used_by}): {e}"))
352
            }
353
            Err(_) => {}
354
        }
355
    }
356
357
    /// Pass 4.
358
    fn fsck_derived(&self, rep: &mut FsckReport) -> Result<()> {
359
        let Ok(view) = self.view() else { return Ok(()) };
360
        let shallow = self.is_shallow();
361
        if !shallow {
362
            for (name, st) in &view.bookmarks {
363
                let Ok(s) = self.store.get_state(st) else {
364
                    continue;
365
                };
366
                if let Err(e) = self.load_state_full(&s.heads) {
367
                    rep.error(
368
                        Some(*st),
369
                        format!("bookmark {name} does not form a valid state: {e}"),
370
                    );
371
                }
372
            }
373
        }
374
        for r in self.checkpoint_refs()? {
375
            rep.checkpoints += 1;
376
            let cp = match self.store.get_typed(&r, ObjectType::Checkpoint) {
377
                Ok(b) => match crate::objects::Checkpoint::decode(&b) {
378
                    Ok(cp) => cp,
379
                    Err(_) => continue,
380
                },
381
                Err(StoreError::NotFound(_)) => {
382
                    rep.warn(
383
                        Some(r),
384
                        "checkpoint pointer names a missing checkpoint; it will be rewritten",
385
                    );
386
                    continue;
387
                }
388
                Err(_) => continue,
389
            };
390
            let payload = match self.read_blob(&cp.payload) {
391
                Ok(p) => p,
392
                Err(e) => {
393
                    rep.error(Some(r), format!("checkpoint payload unreadable: {e}"));
394
                    continue;
395
                }
396
            };
397
            if let Err(e) = self.state_from_checkpoint(&payload) {
398
                rep.error(Some(r), format!("checkpoint payload does not decode: {e}"));
399
                continue;
400
            }
401
            // The payload must be what the named changes produce, in its own version.
402
            let version = crate::cbor::decode(&payload).ok().and_then(|v| {
403
                crate::objects::map(&v, "payload").ok().and_then(|m| {
404
                    m.get(&0)
405
                        .and_then(|x| crate::objects::uint(x, "version").ok())
406
                })
407
            });
408
            let expected = |full: &State| {
409
                if version == Some(crate::state::CHECKPOINT_INDEX_VERSION) {
410
                    full.checkpoint_index(&full.checkpoint_file_graphs(), Repo::blob_ref)
411
                } else {
412
                    full.checkpoint_payload()
413
                }
414
            };
415
            if !shallow {
416
                match self.load_state_full(&cp.heads) {
417
                    Ok(full) if expected(&full) != payload => {
418
                        rep.error(Some(r), "checkpoint disagrees with the changes it names")
419
                    }
420
                    Ok(_) => {}
421
                    Err(e) => rep.error(
422
                        Some(r),
423
                        format!("checkpoint names changes that do not form a state: {e}"),
424
                    ),
425
                }
426
            }
427
        }
428
        let mut attests = Vec::new();
429
        for name in view.bookmarks.keys() {
430
            if let Ok(Some((r, _))) = self.latest_ref_attest(name) {
431
                attests.push((r, format!("bookmark {name}")));
432
            }
433
        }
434
        for name in view.tags.keys() {
435
            if let Ok(Some((r, _))) = self.tag_attest(name) {
436
                attests.push((r, format!("tag {name}")));
437
            }
438
        }
439
        for (r, what) in attests {
440
            rep.attestations += 1;
441
            let sigs = self.store.signatures(&r)?;
442
            if sigs.is_empty() {
443
                rep.warn(Some(r), format!("attestation for {what} is unsigned"));
444
            }
445
            for sig in sigs {
446
                match self.store.get_identity(&sig.key) {
447
                    Ok(id) => {
448
                        if let Err(e) = verify_signature(&id, &sig, Domain::Attest, &r) {
449
                            rep.error(
450
                                Some(r),
451
                                format!("attestation for {what} has a bad signature: {e}"),
452
                            );
453
                        }
454
                    }
455
                    Err(_) => rep.warn(
456
                        Some(r),
457
                        format!(
458
                            "attestation for {what} is signed by {}, whose identity is not stored",
459
                            sig.key.short(12)
460
                        ),
461
                    ),
462
                }
463
            }
464
        }
465
        Ok(())
466
    }
467
}