OXYGENHUB
◆ v0.6.0 oxygenhub / crates / hub / src / tlog.rs
34.3 KiB · Rust · last changed Run the hub as web and worker processes, singletons under a leader lock 16 days ago source blame history raw
1
//! The hub's transparency log (oxygenhub#238, docs/transparency.md, Oxygen
2
//! spec §14.8): one entry per signed object the hub accepts, in the order
3
//! it accepts them, kept as append-only files and served as C2SP
4
//! tlog-tiles with a signed checkpoint, so anyone can check the hub shows
5
//! everyone the same history.
6
//!
7
//! Files in `<data>/tlog/`:
8
//! - `entries`: each entry as a big-endian u16 length and its bytes;
9
//! - `offsets`: each entry's offset in `entries`, a u64 (little-endian);
10
//! - `hashes`: every hash of the tree in stored order (Oxygen spec §14.8);
11
//! - `checkpoint`: the latest signed checkpoint note (replaced, not
12
//!   appended, as it is only a signature over the others).
13
//!
14
//! Nothing is rewritten: a crash mid-append leaves at most a tail that is
15
//! cut back to the last whole entry on open, and the hashes are rebuilt
16
//! from the entries. The database's `tlog_entries` points from objects to
17
//! entry numbers.
18
19
use crate::{db, Shared};
20
use axum::extract::{Path as UrlPath, State};
21
use axum::http::{header, StatusCode};
22
use axum::response::{IntoResponse, Response};
23
use oxy_core::hash::{KeyId, ObjectRef};
24
use oxy_core::identity::Identity;
25
use oxy_core::repo::{PushReport, Repo};
26
use oxy_core::tlog::{self, Checkpoint, Entry, Hash, HashReader, Tile, TlogError, TILE_WIDTH};
27
use std::fs::{File, OpenOptions};
28
use std::io::Write;
29
use std::os::unix::fs::FileExt;
30
use std::path::{Path, PathBuf};
31
use std::sync::Mutex;
32
33
/// How often a new checkpoint is signed while entries arrive.
34
pub const CHECKPOINT_EVERY: std::time::Duration = std::time::Duration::from_secs(5);
35
36
struct Files {
37
    entries: File,
38
    offsets: File,
39
    hashes: File,
40
    /// Entries in the log.
41
    size: u64,
42
    /// Bytes in `entries`.
43
    entries_len: u64,
44
}
45
46
/// The stored hashes in a file, by stored index.
47
struct FileHashes<'a>(&'a File);
48
49
impl HashReader for FileHashes<'_> {
50
    fn read_hashes(&self, indexes: &[u64]) -> Result<Vec<Hash>, TlogError> {
51
        indexes
52
            .iter()
53
            .map(|&i| {
54
                let mut h = [0u8; 32];
55
                self.0.read_exact_at(&mut h, i * 32).map_err(|e| TlogError::Read(format!("stored hash {i}: {e}")))?;
56
                Ok(h)
57
            })
58
            .collect()
59
    }
60
}
61
62
/// The log on disk.
63
pub struct Log {
64
    dir: PathBuf,
65
    /// The log's name in its checkpoints: the hub's host and `/log`.
66
    pub origin: String,
67
    files: Mutex<Files>,
68
    /// The latest signed checkpoint: its size and its note.
69
    checkpoint: Mutex<Option<(u64, String)>>,
70
    /// Witnesses this log asks to cosign its checkpoints.
71
    witnesses: std::sync::RwLock<Vec<Peer>>,
72
    /// Logs this hub witnesses: their origins and keys.
73
    witness_for: std::sync::RwLock<Vec<(String, Identity)>>,
74
    /// Whether this process writes the log: the web role's (#272). A
75
    /// process without it only reads what the log held when it opened.
76
    writer: bool,
77
}
78
79
/// A witness of this hub's log.
80
#[derive(Clone, Debug)]
81
pub struct Peer {
82
    pub name: String,
83
    /// Its add-checkpoint address.
84
    pub url: String,
85
    pub identity: Identity,
86
}
87
88
fn read_u64_at(f: &File, at: u64) -> std::io::Result<u64> {
89
    let mut b = [0u8; 8];
90
    f.read_exact_at(&mut b, at)?;
91
    Ok(u64::from_le_bytes(b))
92
}
93
94
/// The origin of a hub's log: its host (and port) and `/log`.
95
pub fn origin_of(base_url: &str) -> String {
96
    let host = base_url.split_once("://").map(|(_, h)| h).unwrap_or(base_url);
97
    format!("{}/log", host.trim_end_matches('/'))
98
}
99
100
impl Log {
101
    /// Open (or start) the log in `dir`, recovering from an interrupted
102
    /// append.
103
    pub fn open(dir: &Path, origin: &str) -> anyhow::Result<Log> {
104
        Self::open_as(dir, origin, true)
105
    }
106
107
    /// Open the log to read only, as a process without the web role does
108
    /// (#272): it neither appends nor signs, and leaves the files as they
109
    /// are, so it never cuts short an append the writer is making. Until
110
    /// the log has a cluster-wide writer (#274), one process per data
111
    /// directory has the web role.
112
    pub fn open_reader(dir: &Path, origin: &str) -> anyhow::Result<Log> {
113
        Self::open_as(dir, origin, false)
114
    }
115
116
    fn open_as(dir: &Path, origin: &str, writer: bool) -> anyhow::Result<Log> {
117
        std::fs::create_dir_all(dir)?;
118
        let open = |name: &str| OpenOptions::new().read(true).append(true).create(true).open(dir.join(name));
119
        let (entries, offsets, hashes) = (open("entries")?, open("offsets")?, open("hashes")?);
120
        let entries_on_disk = entries.metadata()?.len();
121
        // The whole entries: those whose offset was written and whose
122
        // bytes all were.
123
        let mut size = offsets.metadata()?.len() / 8;
124
        let mut entries_len = 0;
125
        while size > 0 {
126
            let off = read_u64_at(&offsets, (size - 1) * 8)?;
127
            let mut len = [0u8; 2];
128
            if off + 2 <= entries_on_disk && entries.read_exact_at(&mut len, off).is_ok() {
129
                let end = off + 2 + u16::from_be_bytes(len) as u64;
130
                if end <= entries_on_disk {
131
                    entries_len = end;
132
                    break;
133
                }
134
            }
135
            size -= 1;
136
        }
137
        // The hashes of every leaf whose hashes were all written; the rest
138
        // are computed again from the entries.
139
        let have = hashes.metadata()?.len() / 32;
140
        let mut whole = size;
141
        while tlog::stored_hash_count(whole) > have {
142
            whole -= 1;
143
        }
144
        if !writer {
145
            // A reader takes the leaves whose hashes are all there and
146
            // changes nothing.
147
            let files = Files { entries, offsets, hashes, size: whole, entries_len };
148
            return Ok(Log {
149
                dir: dir.to_path_buf(),
150
                origin: origin.to_string(),
151
                files: Mutex::new(files),
152
                checkpoint: Mutex::new(Self::read_checkpoint(dir, whole)),
153
                witnesses: Default::default(),
154
                witness_for: Default::default(),
155
                writer,
156
            });
157
        }
158
        offsets.set_len(size * 8)?;
159
        entries.set_len(entries_len)?;
160
        hashes.set_len(tlog::stored_hash_count(whole) * 32)?;
161
        let mut files = Files { entries, offsets, hashes, size: whole, entries_len };
162
        for n in whole..size {
163
            let bytes = Self::entry_bytes(&files, n)?;
164
            let add = tlog::stored_hashes_for_leaf(n, tlog::leaf_hash(&bytes), &FileHashes(&files.hashes))?;
165
            for h in add {
166
                files.hashes.write_all(&h)?;
167
            }
168
            files.size = n + 1;
169
        }
170
        files.size = size;
171
        files.hashes.sync_data()?;
172
        Ok(Log {
173
            dir: dir.to_path_buf(),
174
            origin: origin.to_string(),
175
            files: Mutex::new(files),
176
            checkpoint: Mutex::new(Self::read_checkpoint(dir, size)),
177
            witnesses: Default::default(),
178
            witness_for: Default::default(),
179
            writer,
180
        })
181
    }
182
183
    /// The signed checkpoint kept in `dir`, if it is of at most `size` entries.
184
    fn read_checkpoint(dir: &Path, size: u64) -> Option<(u64, String)> {
185
        std::fs::read_to_string(dir.join("checkpoint")).ok().and_then(|note| {
186
            let n = tlog::Note::parse(&note).ok()?;
187
            let c = Checkpoint::parse(&n.text).ok()?;
188
            (c.size <= size).then_some((c.size, note))
189
        })
190
    }
191
192
    fn entry_bytes(f: &Files, n: u64) -> anyhow::Result<Vec<u8>> {
193
        let off = read_u64_at(&f.offsets, n * 8)?;
194
        let mut len = [0u8; 2];
195
        f.entries.read_exact_at(&mut len, off)?;
196
        let mut b = vec![0u8; u16::from_be_bytes(len) as usize];
197
        f.entries.read_exact_at(&mut b, off + 2)?;
198
        Ok(b)
199
    }
200
201
    /// Entry `n`'s bytes.
202
    pub fn entry(&self, n: u64) -> anyhow::Result<Vec<u8>> {
203
        let f = self.files.lock().unwrap();
204
        anyhow::ensure!(n < f.size, "entry {n} is not in the log");
205
        Self::entry_bytes(&f, n)
206
    }
207
208
    /// Entries in the log.
209
    pub fn size(&self) -> u64 {
210
        self.files.lock().unwrap().size
211
    }
212
213
    /// Append entries, durably; their numbers.
214
    pub fn append(&self, entries: &[Entry]) -> anyhow::Result<Vec<u64>> {
215
        if !self.writer {
216
            anyhow::bail!("this process does not write the log: it has no web role");
217
        }
218
        let mut f = self.files.lock().unwrap();
219
        let mut out = Vec::with_capacity(entries.len());
220
        for e in entries {
221
            let bytes = e.encode();
222
            let n = f.size;
223
            let add = tlog::stored_hashes_for_leaf(n, tlog::leaf_hash(&bytes), &FileHashes(&f.hashes))?;
224
            let off = f.entries_len;
225
            let mut rec = (bytes.len() as u16).to_be_bytes().to_vec();
226
            rec.extend_from_slice(&bytes);
227
            f.entries.write_all(&rec)?;
228
            f.entries_len += rec.len() as u64;
229
            f.offsets.write_all(&off.to_le_bytes())?;
230
            let mut hs = Vec::with_capacity(add.len() * 32);
231
            for h in add {
232
                hs.extend_from_slice(&h);
233
            }
234
            f.hashes.write_all(&hs)?;
235
            f.size = n + 1;
236
            out.push(n);
237
        }
238
        f.entries.sync_data()?;
239
        f.offsets.sync_data()?;
240
        f.hashes.sync_data()?;
241
        Ok(out)
242
    }
243
244
    /// The root of the first `n` entries.
245
    pub fn tree_hash(&self, n: u64) -> anyhow::Result<Hash> {
246
        let f = self.files.lock().unwrap();
247
        Ok(tlog::tree_hash(n, &FileHashes(&f.hashes))?)
248
    }
249
250
    /// Entry `n`'s inclusion proof in the tree of `t` entries.
251
    pub fn prove_inclusion(&self, t: u64, n: u64) -> anyhow::Result<Vec<Hash>> {
252
        let f = self.files.lock().unwrap();
253
        Ok(tlog::prove_inclusion(t, n, &FileHashes(&f.hashes))?)
254
    }
255
256
    /// The consistency proof from `n` entries to `t`.
257
    pub fn prove_consistency(&self, t: u64, n: u64) -> anyhow::Result<Vec<Hash>> {
258
        let f = self.files.lock().unwrap();
259
        Ok(tlog::prove_consistency(t, n, &FileHashes(&f.hashes))?)
260
    }
261
262
    /// A tile's hashes, when the log holds all of them.
263
    pub fn tile(&self, t: &Tile) -> anyhow::Result<Option<Vec<u8>>> {
264
        let f = self.files.lock().unwrap();
265
        let at_level = f.size >> (tlog::TILE_HEIGHT * t.level);
266
        if at_level < (t.n << tlog::TILE_HEIGHT) + t.width as u64 {
267
            return Ok(None);
268
        }
269
        Ok(Some(t.read_data(&FileHashes(&f.hashes))?))
270
    }
271
272
    /// The entry bundle beside level-0 tile `t`, when the log holds it.
273
    pub fn bundle(&self, t: &Tile) -> anyhow::Result<Option<Vec<u8>>> {
274
        let f = self.files.lock().unwrap();
275
        let first = t.n << tlog::TILE_HEIGHT;
276
        if f.size < first + t.width as u64 {
277
            return Ok(None);
278
        }
279
        let entries: Vec<Vec<u8>> = (first..first + t.width as u64).map(|n| Self::entry_bytes(&f, n)).collect::<anyhow::Result<_>>()?;
280
        Ok(Some(tlog::encode_bundle(&entries)?))
281
    }
282
283
    /// Take `[tlog]` from the configuration: witnesses and witnessed logs.
284
    pub fn configure(&self, c: &crate::config::Tlog) -> anyhow::Result<()> {
285
        let key = |b64: &str, what: &str| -> anyhow::Result<Identity> {
286
            let bytes = oxy_core::dsse::base64_decode(b64.trim()).ok_or_else(|| anyhow::anyhow!("[tlog] {what}: the key is not base64"))?;
287
            Identity::decode(&bytes).map_err(|e| anyhow::anyhow!("[tlog] {what}: {e}"))
288
        };
289
        let mut ws = Vec::new();
290
        for w in &c.witnesses {
291
            ws.push(Peer { name: w.name.clone(), url: w.url.clone(), identity: key(&w.key, &w.name)? });
292
        }
293
        let mut wf = Vec::new();
294
        for l in &c.witness_for {
295
            wf.push((l.origin.clone(), key(&l.key, &l.origin)?));
296
        }
297
        self.set_witnesses(ws);
298
        for (o, k) in wf {
299
            self.add_witness_for(&o, k);
300
        }
301
        Ok(())
302
    }
303
304
    pub fn set_witnesses(&self, peers: Vec<Peer>) {
305
        *self.witnesses.write().unwrap() = peers;
306
    }
307
308
    pub fn witnesses(&self) -> Vec<Peer> {
309
        self.witnesses.read().unwrap().clone()
310
    }
311
312
    /// Witness the log named `origin`, signed with `key`.
313
    pub fn add_witness_for(&self, origin: &str, key: Identity) {
314
        let mut w = self.witness_for.write().unwrap();
315
        w.retain(|(o, _)| o != origin);
316
        w.push((origin.to_string(), key));
317
    }
318
319
    fn witnessed_key(&self, origin: &str) -> Option<Identity> {
320
        self.witness_for.read().unwrap().iter().find(|(o, _)| o == origin).map(|(_, k)| k.clone())
321
    }
322
323
    /// This hub's name as a witness: its log's host.
324
    pub fn witness_name(&self) -> &str {
325
        self.origin.trim_end_matches("/log")
326
    }
327
328
    /// Replace the latest checkpoint's note with `note` (the same
329
    /// checkpoint, with cosignatures added), unless a newer one was signed.
330
    fn set_note(&self, size: u64, note: String) -> anyhow::Result<()> {
331
        let mut cur = self.checkpoint.lock().unwrap();
332
        if cur.as_ref().map(|(s, _)| *s) != Some(size) {
333
            return Ok(());
334
        }
335
        let tmp = self.dir.join("checkpoint.new");
336
        std::fs::write(&tmp, &note)?;
337
        File::open(&tmp)?.sync_all()?;
338
        std::fs::rename(&tmp, self.dir.join("checkpoint"))?;
339
        *cur = Some((size, note));
340
        Ok(())
341
    }
342
343
    /// The latest signed checkpoint note.
344
    pub fn checkpoint(&self) -> Option<String> {
345
        self.checkpoint.lock().unwrap().as_ref().map(|(_, n)| n.clone())
346
    }
347
348
    /// Sign a checkpoint of the log as it is, unless the last one already
349
    /// covers it. True when a new one was signed.
350
    pub fn refresh_checkpoint(&self, identity: &oxy_core::identity::Identity, sk: &oxy_core::identity::SecretKey) -> anyhow::Result<bool> {
351
        if !self.writer {
352
            return Ok(false);
353
        }
354
        let size = self.size();
355
        if self.checkpoint.lock().unwrap().as_ref().is_some_and(|(s, _)| *s >= size) {
356
            return Ok(false);
357
        }
358
        let c = Checkpoint { origin: self.origin.clone(), size, root: self.tree_hash(size)?, extensions: vec![] };
359
        let note = c.sign(identity, sk)?.encode();
360
        let tmp = self.dir.join("checkpoint.new");
361
        std::fs::write(&tmp, &note)?;
362
        File::open(&tmp)?.sync_all()?;
363
        std::fs::rename(&tmp, self.dir.join("checkpoint"))?;
364
        *self.checkpoint.lock().unwrap() = Some((size, note));
365
        Ok(true)
366
    }
367
}
368
369
/// An object to log.
370
#[derive(Clone, Debug)]
371
pub struct Pending {
372
    pub kind: &'static str,
373
    /// The repository's id (zero for none) and its row on this hub.
374
    pub repo: [u8; 16],
375
    pub repo_row: Option<i64>,
376
    pub object: ObjectRef,
377
    pub signers: Vec<KeyId>,
378
}
379
380
/// Log what is not logged yet. A failure is reported, never fatal: the
381
/// object stays accepted (enforcing logging before acceptance comes with
382
/// inclusion proofs in push responses).
383
pub async fn log(app: &Shared, items: Vec<Pending>) -> Vec<u64> {
384
    let mut fresh = Vec::new();
385
    for p in items {
386
        let object = p.object.to_hex();
387
        match db::tlog::entry_of(&app.db, &object, p.kind).await {
388
            Ok(Some(_)) => continue,
389
            Ok(None) => {}
390
            Err(e) => {
391
                eprintln!("tlog: looking up {} {}: {e}", p.kind, &object[..12]);
392
                continue;
393
            }
394
        }
395
        if !fresh.iter().any(|q: &Pending| q.kind == p.kind && q.object == p.object) {
396
            fresh.push(p);
397
        }
398
    }
399
    if fresh.is_empty() {
400
        return vec![];
401
    }
402
    let now = db::now_ms();
403
    let entries: Vec<Entry> = fresh
404
        .iter()
405
        .map(|p| Entry { kind: p.kind.to_string(), repo: p.repo, object: p.object, signers: p.signers.clone(), received: now as u64 })
406
        .collect();
407
    let tl = app.tlog.clone();
408
    let numbers = match tokio::task::spawn_blocking(move || tl.append(&entries)).await {
409
        Ok(Ok(n)) => n,
410
        Ok(Err(e)) => {
411
            eprintln!("tlog: appending {} entries: {e}", fresh.len());
412
            return vec![];
413
        }
414
        Err(e) => {
415
            eprintln!("tlog: appending: {e}");
416
            return vec![];
417
        }
418
    };
419
    for (p, n) in fresh.iter().zip(&numbers) {
420
        if let Err(e) = db::tlog::record(&app.db, *n as i64, &p.object.to_hex(), p.kind, p.repo_row, now).await {
421
            eprintln!("tlog: indexing entry {n}: {e}");
422
        }
423
    }
424
    numbers
425
}
426
427
fn sig_keys(sigs: &[oxy_core::identity::Signature]) -> Vec<KeyId> {
428
    let mut keys: Vec<KeyId> = sigs.iter().map(|s| s.key).collect();
429
    keys.sort();
430
    keys.dedup();
431
    keys
432
}
433
434
/// The certificates of short-lived keys among `signers`, to log beside
435
/// what they signed.
436
fn certificates(repo: &Repo, rid: [u8; 16], row: Option<i64>, signers: &[KeyId], out: &mut Vec<Pending>) {
437
    for k in signers {
438
        if let Ok(Some(c)) = repo.store().certificate_of(k) {
439
            let issuer = repo.store().get_certificate(&c).map(|sc| vec![sc.cert.issuer]).unwrap_or_default();
440
            out.push(Pending { kind: "certificate", repo: rid, repo_row: row, object: c, signers: issuer });
441
        }
442
    }
443
}
444
445
/// What a push brought that the log keeps: the attestations of the
446
/// references it moved (and the hub's acceptance of them), tags, seals,
447
/// the repository's policy, and the certificates of short-lived signers.
448
pub fn push_entries(repo: &Repo, row: Option<i64>, report: &PushReport) -> Vec<Pending> {
449
    let Ok(rid) = repo.id() else { return vec![] };
450
    let mut out = Vec::new();
451
    let add = |out: &mut Vec<Pending>, kind: &'static str, object: ObjectRef, signers: Vec<KeyId>| {
452
        certificates(repo, rid, row, &signers, out);
453
        out.push(Pending { kind, repo: rid, repo_row: row, object, signers });
454
    };
455
    for u in &report.updated {
456
        if u.new_state.is_zero() || !report.results.iter().any(|r| r.ok && r.name == u.name) {
457
            continue;
458
        }
459
        if let Some(tag) = u.name.strip_prefix("tags/") {
460
            if let Ok(Some((r, sa))) = repo.tag_attest(tag) {
461
                add(&mut out, "tag", r, sig_keys(&sa.sigs));
462
            }
463
        } else if let Ok(Some((r, sa))) = repo.latest_ref_attest(&u.name) {
464
            add(&mut out, "ref", r, sig_keys(&sa.sigs));
465
            if let Ok(Some(acc)) = repo.acceptance_of(&r) {
466
                add(&mut out, "accepted", acc.attest.hash(), sig_keys(&acc.sigs));
467
            }
468
        }
469
    }
470
    let mut seals = std::collections::BTreeSet::new();
471
    for h in &report.imported {
472
        for s in repo.store().seals_for(h).unwrap_or_default() {
473
            seals.insert(s);
474
        }
475
    }
476
    for s in seals {
477
        let signers = sig_keys(&repo.store().signatures(&s).unwrap_or_default());
478
        add(&mut out, "seal", s, signers);
479
    }
480
    if let Ok(Some((r, sp))) = repo.current_policy() {
481
        add(&mut out, "policy", r, sig_keys(&sp.sigs));
482
    }
483
    out
484
}
485
486
/// Add the log to a refs answer (Oxygen spec §14.8): the latest
487
/// checkpoint, and for each bookmark's attestation its entry and inclusion
488
/// proof against it. An attestation the hub serves but never logged (one
489
/// pushed before the log began) is logged now, and proved on a later fetch.
490
pub fn add_log(app: &Shared, row: Option<i64>, refs: &mut oxy_core::protocol::RefsResponse) -> Vec<Pending> {
491
    let mut backfill = Vec::new();
492
    let Some(note) = app.tlog.checkpoint() else { return backfill };
493
    let Some(size) = tlog::Note::parse(&note).ok().and_then(|n| Checkpoint::parse(&n.text).ok()).map(|c| c.size) else {
494
        return backfill;
495
    };
496
    refs.log = Some(note);
497
    // The witnesses a client may pin, for integrated times (#240).
498
    refs.witnesses = app.tlog.witnesses().iter().map(|p| (p.name.clone(), p.identity.encode())).collect();
499
    for r in refs.refs.iter_mut() {
500
        let Some(a) = &r.attestation else { continue };
501
        let object = a.attest.hash();
502
        let idx = tokio::task::block_in_place(|| {
503
            tokio::runtime::Handle::current().block_on(db::tlog::entry_of(&app.db, &object.to_hex(), "ref"))
504
        });
505
        match idx {
506
            Ok(Some(i)) if (i as u64) < size => {
507
                let (Ok(entry), Ok(proof)) = (app.tlog.entry(i as u64), app.tlog.prove_inclusion(size, i as u64)) else { continue };
508
                r.logged = Some(oxy_core::protocol::Logged { index: i as u64, entry, proof });
509
                // When witnesses first saw it (#240): the first cosigned
510
                // checkpoints that hold it, each with the entry's proof.
511
                let notes = tokio::task::block_in_place(|| {
512
                    tokio::runtime::Handle::current().block_on(db::tlog::cosigned_notes_after(&app.db, i, 2))
513
                })
514
                .unwrap_or_default();
515
                for (at, text) in notes {
516
                    if let Ok(proof) = app.tlog.prove_inclusion(at as u64, i as u64) {
517
                        r.integration.push(oxy_core::protocol::Integration { note: text, proof });
518
                    }
519
                }
520
            }
521
            Ok(Some(_)) => {}
522
            Ok(None) => backfill.push(Pending { kind: "ref", repo: a.attest.repo, repo_row: row, object, signers: sig_keys(&a.sigs) }),
523
            Err(e) => eprintln!("tlog: looking up {}: {e}", &object.to_hex()[..12]),
524
        }
525
    }
526
    backfill
527
}
528
529
/// Ask each witness to cosign the latest checkpoint, and serve their
530
/// cosignatures with it. A witness that answers 409 is told again from the
531
/// size it says it has; one that refuses is logged.
532
pub async fn collect(app: &Shared) {
533
    let peers = app.tlog.witnesses();
534
    let Some(text) = app.tlog.checkpoint() else { return };
535
    if peers.is_empty() {
536
        return;
537
    }
538
    let Ok(mut note) = tlog::Note::parse(&text) else { return };
539
    let Ok(cp) = Checkpoint::parse(&note.text) else { return };
540
    // What a witness checks: the note as the log signed it.
541
    let own = tlog::Note { text: note.text.clone(), sigs: note.sigs.iter().filter(|s| s.name == cp.origin).cloned().collect() };
542
    let mut changed = false;
543
    for p in peers {
544
        if note.cosigned_by(&p.name, &p.identity).is_ok() {
545
            continue;
546
        }
547
        let mut old = db::tlog::cosigned_size(&app.db, &p.name).await.unwrap_or(0) as u64;
548
        for _ in 0..2 {
549
            let proof = if old == 0 || old >= cp.size { Vec::new() } else { app.tlog.prove_consistency(cp.size, old).unwrap_or_default() };
550
            let body = tlog::AddCheckpoint { old_size: old, proof, note: own.encode() }.encode();
551
            let client = match crate::net::client(&p.url, std::slice::from_ref(&p.url), std::time::Duration::from_secs(20)).await {
552
                Ok(c) => c,
553
                Err(e) => {
554
                    eprintln!("tlog: witness {}: {e}", p.name);
555
                    break;
556
                }
557
            };
558
            let res = match client.post(&p.url).header(header::CONTENT_TYPE, "text/plain").body(body).send().await {
559
                Ok(r) => r,
560
                Err(e) => {
561
                    eprintln!("tlog: witness {}: {e}", p.name);
562
                    break;
563
                }
564
            };
565
            let status = res.status();
566
            let answer = res.text().await.unwrap_or_default();
567
            if status == StatusCode::CONFLICT {
568
                match answer.trim().parse() {
569
                    Ok(n) if n != old => {
570
                        old = n;
571
                        continue;
572
                    }
573
                    _ => {
574
                        eprintln!("tlog: witness {}: a conflict without a size: {answer}", p.name);
575
                        break;
576
                    }
577
                }
578
            }
579
            if !status.is_success() {
580
                eprintln!("tlog: witness {} refused the checkpoint of {} entries ({status}): {}", p.name, cp.size, answer.trim());
581
                break;
582
            }
583
            let lines = tlog::Note::parse(&format!("{}\n{answer}", note.text)).map(|n| n.sigs).unwrap_or_default();
584
            let theirs: Vec<_> = lines.into_iter().filter(|s| s.name == p.name).collect();
585
            let check = tlog::Note { text: note.text.clone(), sigs: theirs.clone() };
586
            match check.cosigned_by(&p.name, &p.identity) {
587
                Ok(_) => {
588
                    note.sigs.extend(theirs);
589
                    db::tlog::set_cosigned(&app.db, &p.name, cp.size as i64).await.ok();
590
                    changed = true;
591
                }
592
                Err(e) => eprintln!("tlog: witness {} answered a cosignature that does not verify: {e}", p.name),
593
            }
594
            break;
595
        }
596
    }
597
    if changed {
598
        // Kept by size too, for integrated times (#240).
599
        db::tlog::keep_cosigned_note(&app.db, cp.size as i64, &note.encode()).await.ok();
600
        if let Err(e) = app.tlog.set_note(cp.size, note.encode()) {
601
            eprintln!("tlog: keeping the cosigned checkpoint: {e}");
602
        }
603
    }
604
}
605
606
/// `POST /log/witness/add-checkpoint` (C2SP tlog-witness): cosign a
607
/// checkpoint of a log this hub witnesses, if it extends the last one
608
/// cosigned.
609
pub async fn add_checkpoint(State(app): State<Shared>, body: String) -> Response {
610
    let Ok(req) = tlog::AddCheckpoint::parse(&body) else {
611
        return plain(StatusCode::BAD_REQUEST, "not an add-checkpoint request");
612
    };
613
    let Some(origin) = tlog::Note::parse(&req.note).ok().and_then(|n| Checkpoint::parse(&n.text).ok()).map(|c| c.origin) else {
614
        return plain(StatusCode::BAD_REQUEST, "the checkpoint does not parse");
615
    };
616
    let Some(key) = app.tlog.witnessed_key(&origin) else {
617
        return plain(StatusCode::NOT_FOUND, &format!("this hub does not witness {origin}"));
618
    };
619
    let latest = match db::tlog::witnessed(&app.db, &origin).await {
620
        Ok(l) => l.and_then(|(size, root)| Some((size as u64, ObjectRef::from_hex(&root)?.0))),
621
        Err(e) => return plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
622
    };
623
    let sk = match crate::keys::load_secret(&app.config.keys_dir()) {
624
        Ok((_, sk)) => sk,
625
        Err(e) => return plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
626
    };
627
    let me = tlog::WitnessKey { name: app.tlog.witness_name(), identity: &app.hub_key.identity, sk: &sk };
628
    let now = (db::now_ms() / 1000) as u64;
629
    let conflict = |n: u64| ([(header::CONTENT_TYPE, "text/x.tlog.size")], format!("{n}\n"));
630
    match tlog::witness(&req, &origin, &key, latest, &me, now) {
631
        Ok(tlog::Witnessed::Cosigned { checkpoint, lines }) => {
632
            let root = ObjectRef(checkpoint.root).to_hex();
633
            match db::tlog::witness_advance(&app.db, &origin, req.old_size as i64, checkpoint.size as i64, &root).await {
634
                Ok(true) => {
635
                    let body: String = tlog::Note { text: String::new(), sigs: lines }.encode().trim_start_matches('\n').to_string();
636
                    ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], body).into_response()
637
                }
638
                Ok(false) => {
639
                    let now = db::tlog::witnessed(&app.db, &origin).await.ok().flatten().map(|(s, _)| s as u64).unwrap_or(0);
640
                    (StatusCode::CONFLICT, conflict(now)).into_response()
641
                }
642
                Err(e) => plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
643
            }
644
        }
645
        Ok(tlog::Witnessed::Conflict(n)) => (StatusCode::CONFLICT, conflict(n)).into_response(),
646
        Err(tlog::WitnessError::Unsigned(e)) => plain(StatusCode::FORBIDDEN, &e),
647
        Err(tlog::WitnessError::Inconsistent(e)) => plain(StatusCode::UNPROCESSABLE_ENTITY, &e),
648
        Err(tlog::WitnessError::Bad(e)) => plain(StatusCode::BAD_REQUEST, &e),
649
    }
650
}
651
652
/// Sign a new checkpoint every few seconds while entries arrive.
653
pub async fn checkpointer(app: Shared) {
654
    let mut tick = tokio::time::interval(CHECKPOINT_EVERY);
655
    loop {
656
        tick.tick().await;
657
        let (identity, keys) = (app.hub_key.identity.clone(), app.config.keys_dir());
658
        let tl = app.tlog.clone();
659
        let done = tokio::task::spawn_blocking(move || -> anyhow::Result<bool> {
660
            let (_, sk) = crate::keys::load_secret(&keys)?;
661
            tl.refresh_checkpoint(&identity, &sk)
662
        })
663
        .await;
664
        match done {
665
            Ok(Err(e)) => eprintln!("tlog: signing a checkpoint: {e}"),
666
            // A new checkpoint, or one some witness has not cosigned yet.
667
            _ => collect(&app).await,
668
        }
669
    }
670
}
671
672
fn plain(status: StatusCode, why: &str) -> Response {
673
    (status, [(header::CONTENT_TYPE, "text/plain; charset=utf-8")], format!("{why}\n")).into_response()
674
}
675
676
/// `GET /log/checkpoint`: the latest signed checkpoint (C2SP
677
/// tlog-checkpoint, a signed note).
678
pub async fn checkpoint(State(app): State<Shared>) -> Response {
679
    match app.tlog.checkpoint() {
680
        Some(note) => ([(header::CONTENT_TYPE, "text/plain; charset=utf-8"), (header::CACHE_CONTROL, "no-cache")], note).into_response(),
681
        None => plain(StatusCode::SERVICE_UNAVAILABLE, "no checkpoint yet: the log signs one within seconds"),
682
    }
683
}
684
685
/// `GET /log/witnesses` (#240): this log's witnesses, one `NAME BASE64`
686
/// line each (the identity object), which `oxy tlog verify` pins.
687
pub async fn witnesses(State(app): State<Shared>) -> Response {
688
    let body: String =
689
        app.tlog.witnesses().iter().map(|p| format!("{} {}\n", p.name, oxy_core::dsse::base64(&p.identity.encode()))).collect();
690
    ([(header::CONTENT_TYPE, "text/plain; charset=utf-8"), (header::CACHE_CONTROL, "no-cache")], body).into_response()
691
}
692
693
/// `GET /log/tile/{L}/{N}[.p/{W}]` and `/log/tile/entries/{N}[.p/{W}]`:
694
/// a tile of hashes or an entry bundle (C2SP tlog-tiles). Full tiles never
695
/// change and are cached for good.
696
pub async fn tile(State(app): State<Shared>, UrlPath(path): UrlPath<String>) -> Response {
697
    let (entries, rest) = match path.strip_prefix("entries/") {
698
        Some(r) => (true, format!("0/{r}")),
699
        None => (false, path.clone()),
700
    };
701
    let Some(t) = Tile::parse(&rest) else {
702
        return plain(StatusCode::NOT_FOUND, "no such tile");
703
    };
704
    let tl = app.tlog.clone();
705
    let got = tokio::task::spawn_blocking(move || if entries { tl.bundle(&t) } else { tl.tile(&t) }).await;
706
    match got {
707
        Ok(Ok(Some(data))) => {
708
            let cache = if t.width as u64 == TILE_WIDTH { "public, max-age=31536000, immutable" } else { "public, max-age=5" };
709
            ([(header::CONTENT_TYPE, "application/octet-stream"), (header::CACHE_CONTROL, cache)], data).into_response()
710
        }
711
        Ok(Ok(None)) => plain(StatusCode::NOT_FOUND, "the log does not hold that tile yet"),
712
        Ok(Err(e)) => plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
713
        Err(e) => plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
714
    }
715
}
716
717
#[cfg(test)]
718
mod tests {
719
    use super::*;
720
721
    #[test]
722
    fn a_reader_leaves_the_files_alone_and_cannot_append() {
723
        let dir = tempfile::tempdir().unwrap();
724
        let log = Log::open(dir.path(), "hub.example/log").unwrap();
725
        log.append(&[entry(0), entry(1)]).unwrap();
726
        // A torn append: an offset whose entry never arrived.
727
        std::fs::OpenOptions::new().append(true).open(dir.path().join("offsets")).unwrap().write_all(&9999u64.to_le_bytes()).unwrap();
728
        let before = std::fs::metadata(dir.path().join("offsets")).unwrap().len();
729
        let reader = Log::open_reader(dir.path(), "hub.example/log").unwrap();
730
        assert_eq!(reader.size(), 2);
731
        assert_eq!(std::fs::metadata(dir.path().join("offsets")).unwrap().len(), before, "the writer's files are untouched");
732
        assert!(reader.append(&[entry(2)]).is_err());
733
        assert_eq!(reader.tree_hash(2).unwrap(), log.tree_hash(2).unwrap());
734
    }
735
736
    fn entry(i: u64) -> Entry {
737
        Entry { kind: "ref".into(), repo: [1; 16], object: ObjectRef([i as u8; 32]), signers: vec![], received: i }
738
    }
739
740
    #[test]
741
    fn the_log_survives_a_torn_append_and_keeps_its_root() {
742
        let dir = tempfile::tempdir().unwrap();
743
        let log = Log::open(dir.path(), "hub.example/log").unwrap();
744
        let first: Vec<Entry> = (0..300).map(entry).collect();
745
        assert_eq!(log.append(&first).unwrap(), (0..300).collect::<Vec<_>>());
746
        let root = log.tree_hash(300).unwrap();
747
        // Leaves alone, as RFC 6962 roots them.
748
        let mut stored: Vec<Hash> = Vec::new();
749
        for (n, e) in first.iter().enumerate() {
750
            stored.extend(tlog::stored_hashes_for_leaf(n as u64, e.leaf_hash(), &stored).unwrap());
751
        }
752
        assert_eq!(root, tlog::tree_hash(300, &stored).unwrap());
753
        drop(log);
754
        // A crash after the entry and part of the hashes were written.
755
        let torn = dir.path().join("hashes");
756
        let len = std::fs::metadata(&torn).unwrap().len();
757
        OpenOptions::new().write(true).open(&torn).unwrap().set_len(len - 40).unwrap();
758
        let mut f = OpenOptions::new().append(true).open(dir.path().join("entries")).unwrap();
759
        f.write_all(&[0, 200, 1, 2]).unwrap(); // a partial entry
760
        let log = Log::open(dir.path(), "hub.example/log").unwrap();
761
        assert_eq!(log.size(), 300);
762
        assert_eq!(log.tree_hash(300).unwrap(), root);
763
        log.append(&[entry(300)]).unwrap();
764
        assert_eq!(log.size(), 301);
765
        let p = log.prove_inclusion(301, 7).unwrap();
766
        tlog::check_inclusion(&p, 301, &log.tree_hash(301).unwrap(), 7, &first[7].leaf_hash()).unwrap();
767
        let c = log.prove_consistency(301, 300).unwrap();
768
        tlog::check_consistency(&c, 301, &log.tree_hash(301).unwrap(), 300, &root).unwrap();
769
        // Tiles and bundles: the full level-0 tile and the partial one.
770
        let full = log.tile(&Tile { level: 0, n: 0, width: 256 }).unwrap().unwrap();
771
        assert_eq!(full.len(), 256 * 32);
772
        assert!(log.tile(&Tile { level: 0, n: 1, width: 45 }).unwrap().is_some());
773
        assert!(log.tile(&Tile { level: 0, n: 1, width: 46 }).unwrap().is_none(), "not yet");
774
        let bundle = log.bundle(&Tile { level: 0, n: 1, width: 45 }).unwrap().unwrap();
775
        assert_eq!(tlog::decode_bundle(&bundle).unwrap()[0], first[256].encode());
776
    }
777
778
    #[test]
779
    fn checkpoints_are_signed_when_the_log_grows() {
780
        let dir = tempfile::tempdir().unwrap();
781
        let sk = oxy_core::identity::SecretKey::generate();
782
        let hub = sk.identity("hub", "[email protected]", 1);
783
        let log = Log::open(dir.path(), &origin_of("https://hub.example:7343/")).unwrap();
784
        assert_eq!(log.origin, "hub.example:7343/log");
785
        assert!(log.refresh_checkpoint(&hub, &sk).unwrap(), "the empty log's");
786
        assert!(!log.refresh_checkpoint(&hub, &sk).unwrap(), "nothing new");
787
        log.append(&[entry(1), entry(2)]).unwrap();
788
        assert!(log.refresh_checkpoint(&hub, &sk).unwrap());
789
        let note = tlog::Note::parse(&log.checkpoint().unwrap()).unwrap();
790
        let c = Checkpoint::verify(&note, "hub.example:7343/log", &hub).unwrap();
791
        assert_eq!((c.size, c.root), (2, log.tree_hash(2).unwrap()));
792
        // Kept across a restart.
793
        drop(log);
794
        let log = Log::open(dir.path(), "hub.example:7343/log").unwrap();
795
        assert_eq!(log.checkpoint().map(|n| n.contains("\n2\n")), Some(true));
796
    }
797
}