OXYGENHUB
# 858eca0d03c4 oxygenhub / crates / hub / src / tlog.rs
35.7 KiB · Rust · last changed Keyless agents' release tags: log and serve a tag's acceptance and log place 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
                // A short-lived key's tag, and when the hub accepted it
463
                // (oxygen#129).
464
                if let Ok(Some(acc)) = repo.acceptance_of(&r) {
465
                    add(&mut out, "accepted", acc.attest.hash(), sig_keys(&acc.sigs));
466
                }
467
            }
468
        } else if let Ok(Some((r, sa))) = repo.latest_ref_attest(&u.name) {
469
            add(&mut out, "ref", r, sig_keys(&sa.sigs));
470
            if let Ok(Some(acc)) = repo.acceptance_of(&r) {
471
                add(&mut out, "accepted", acc.attest.hash(), sig_keys(&acc.sigs));
472
            }
473
        }
474
    }
475
    let mut seals = std::collections::BTreeSet::new();
476
    for h in &report.imported {
477
        for s in repo.store().seals_for(h).unwrap_or_default() {
478
            seals.insert(s);
479
        }
480
    }
481
    for s in seals {
482
        let signers = sig_keys(&repo.store().signatures(&s).unwrap_or_default());
483
        add(&mut out, "seal", s, signers);
484
    }
485
    if let Ok(Some((r, sp))) = repo.current_policy() {
486
        add(&mut out, "policy", r, sig_keys(&sp.sigs));
487
    }
488
    out
489
}
490
491
/// Add the log to a refs answer (Oxygen spec §14.8): the latest
492
/// checkpoint, and for each bookmark's and tag's attestation its entry and
493
/// inclusion proof against it. An attestation the hub serves but never
494
/// logged (one pushed before the log began) is logged now, and proved on a
495
/// later fetch.
496
pub fn add_log(app: &Shared, row: Option<i64>, refs: &mut oxy_core::protocol::RefsResponse) -> Vec<Pending> {
497
    let mut backfill = Vec::new();
498
    let Some(note) = app.tlog.checkpoint() else { return backfill };
499
    let Some(size) = tlog::Note::parse(&note).ok().and_then(|n| Checkpoint::parse(&n.text).ok()).map(|c| c.size) else {
500
        return backfill;
501
    };
502
    refs.log = Some(note);
503
    // The witnesses a client may pin, for integrated times (#240).
504
    refs.witnesses = app.tlog.witnesses().iter().map(|p| (p.name.clone(), p.identity.encode())).collect();
505
    for r in refs.refs.iter_mut() {
506
        let Some(a) = &r.attestation else { continue };
507
        if let Some((logged, integration)) = place(app, size, row, "ref", a, &mut backfill) {
508
            r.logged = Some(logged);
509
            r.integration = integration;
510
        }
511
    }
512
    // Tags too (oxygen#129): a short-lived key's tag is checked at its
513
    // integrated time on every later fetch.
514
    for t in refs.tags.iter_mut() {
515
        let Some(a) = &t.attestation else { continue };
516
        if let Some((logged, integration)) = place(app, size, row, "tag", a, &mut backfill) {
517
            t.logged = Some(logged);
518
            t.integration = integration;
519
        }
520
    }
521
    backfill
522
}
523
524
/// Attestation `a`'s entry (of `kind`) in a log of `size` entries, its
525
/// inclusion proof, and the first cosigned checkpoints that hold it; none
526
/// when it is not in that checkpoint yet, and queued in `backfill` when it
527
/// was never logged.
528
fn place(
529
    app: &Shared,
530
    size: u64,
531
    row: Option<i64>,
532
    kind: &'static str,
533
    a: &oxy_core::protocol::SignedAttest,
534
    backfill: &mut Vec<Pending>,
535
) -> Option<(oxy_core::protocol::Logged, Vec<oxy_core::protocol::Integration>)> {
536
    let object = a.attest.hash();
537
    let idx =
538
        tokio::task::block_in_place(|| tokio::runtime::Handle::current().block_on(db::tlog::entry_of(&app.db, &object.to_hex(), kind)));
539
    match idx {
540
        Ok(Some(i)) if (i as u64) < size => {
541
            let (Ok(entry), Ok(proof)) = (app.tlog.entry(i as u64), app.tlog.prove_inclusion(size, i as u64)) else { return None };
542
            // When witnesses first saw it (#240): the first cosigned
543
            // checkpoints that hold it, each with the entry's proof.
544
            let notes =
545
                tokio::task::block_in_place(|| tokio::runtime::Handle::current().block_on(db::tlog::cosigned_notes_after(&app.db, i, 2)))
546
                    .unwrap_or_default();
547
            let mut integration = Vec::new();
548
            for (at, text) in notes {
549
                if let Ok(proof) = app.tlog.prove_inclusion(at as u64, i as u64) {
550
                    integration.push(oxy_core::protocol::Integration { note: text, proof });
551
                }
552
            }
553
            Some((oxy_core::protocol::Logged { index: i as u64, entry, proof }, integration))
554
        }
555
        Ok(Some(_)) => None,
556
        Ok(None) => {
557
            backfill.push(Pending { kind, repo: a.attest.repo, repo_row: row, object, signers: sig_keys(&a.sigs) });
558
            None
559
        }
560
        Err(e) => {
561
            eprintln!("tlog: looking up {}: {e}", &object.to_hex()[..12]);
562
            None
563
        }
564
    }
565
}
566
567
/// Ask each witness to cosign the latest checkpoint, and serve their
568
/// cosignatures with it. A witness that answers 409 is told again from the
569
/// size it says it has; one that refuses is logged.
570
pub async fn collect(app: &Shared) {
571
    let peers = app.tlog.witnesses();
572
    let Some(text) = app.tlog.checkpoint() else { return };
573
    if peers.is_empty() {
574
        return;
575
    }
576
    let Ok(mut note) = tlog::Note::parse(&text) else { return };
577
    let Ok(cp) = Checkpoint::parse(&note.text) else { return };
578
    // What a witness checks: the note as the log signed it.
579
    let own = tlog::Note { text: note.text.clone(), sigs: note.sigs.iter().filter(|s| s.name == cp.origin).cloned().collect() };
580
    let mut changed = false;
581
    for p in peers {
582
        if note.cosigned_by(&p.name, &p.identity).is_ok() {
583
            continue;
584
        }
585
        let mut old = db::tlog::cosigned_size(&app.db, &p.name).await.unwrap_or(0) as u64;
586
        for _ in 0..2 {
587
            let proof = if old == 0 || old >= cp.size { Vec::new() } else { app.tlog.prove_consistency(cp.size, old).unwrap_or_default() };
588
            let body = tlog::AddCheckpoint { old_size: old, proof, note: own.encode() }.encode();
589
            let client = match crate::net::client(&p.url, std::slice::from_ref(&p.url), std::time::Duration::from_secs(20)).await {
590
                Ok(c) => c,
591
                Err(e) => {
592
                    eprintln!("tlog: witness {}: {e}", p.name);
593
                    break;
594
                }
595
            };
596
            let res = match client.post(&p.url).header(header::CONTENT_TYPE, "text/plain").body(body).send().await {
597
                Ok(r) => r,
598
                Err(e) => {
599
                    eprintln!("tlog: witness {}: {e}", p.name);
600
                    break;
601
                }
602
            };
603
            let status = res.status();
604
            let answer = res.text().await.unwrap_or_default();
605
            if status == StatusCode::CONFLICT {
606
                match answer.trim().parse() {
607
                    Ok(n) if n != old => {
608
                        old = n;
609
                        continue;
610
                    }
611
                    _ => {
612
                        eprintln!("tlog: witness {}: a conflict without a size: {answer}", p.name);
613
                        break;
614
                    }
615
                }
616
            }
617
            if !status.is_success() {
618
                eprintln!("tlog: witness {} refused the checkpoint of {} entries ({status}): {}", p.name, cp.size, answer.trim());
619
                break;
620
            }
621
            let lines = tlog::Note::parse(&format!("{}\n{answer}", note.text)).map(|n| n.sigs).unwrap_or_default();
622
            let theirs: Vec<_> = lines.into_iter().filter(|s| s.name == p.name).collect();
623
            let check = tlog::Note { text: note.text.clone(), sigs: theirs.clone() };
624
            match check.cosigned_by(&p.name, &p.identity) {
625
                Ok(_) => {
626
                    note.sigs.extend(theirs);
627
                    db::tlog::set_cosigned(&app.db, &p.name, cp.size as i64).await.ok();
628
                    changed = true;
629
                }
630
                Err(e) => eprintln!("tlog: witness {} answered a cosignature that does not verify: {e}", p.name),
631
            }
632
            break;
633
        }
634
    }
635
    if changed {
636
        // Kept by size too, for integrated times (#240).
637
        db::tlog::keep_cosigned_note(&app.db, cp.size as i64, &note.encode()).await.ok();
638
        if let Err(e) = app.tlog.set_note(cp.size, note.encode()) {
639
            eprintln!("tlog: keeping the cosigned checkpoint: {e}");
640
        }
641
    }
642
}
643
644
/// `POST /log/witness/add-checkpoint` (C2SP tlog-witness): cosign a
645
/// checkpoint of a log this hub witnesses, if it extends the last one
646
/// cosigned.
647
pub async fn add_checkpoint(State(app): State<Shared>, body: String) -> Response {
648
    let Ok(req) = tlog::AddCheckpoint::parse(&body) else {
649
        return plain(StatusCode::BAD_REQUEST, "not an add-checkpoint request");
650
    };
651
    let Some(origin) = tlog::Note::parse(&req.note).ok().and_then(|n| Checkpoint::parse(&n.text).ok()).map(|c| c.origin) else {
652
        return plain(StatusCode::BAD_REQUEST, "the checkpoint does not parse");
653
    };
654
    let Some(key) = app.tlog.witnessed_key(&origin) else {
655
        return plain(StatusCode::NOT_FOUND, &format!("this hub does not witness {origin}"));
656
    };
657
    let latest = match db::tlog::witnessed(&app.db, &origin).await {
658
        Ok(l) => l.and_then(|(size, root)| Some((size as u64, ObjectRef::from_hex(&root)?.0))),
659
        Err(e) => return plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
660
    };
661
    let sk = match crate::keys::load_secret(&app.config.keys_dir()) {
662
        Ok((_, sk)) => sk,
663
        Err(e) => return plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
664
    };
665
    let me = tlog::WitnessKey { name: app.tlog.witness_name(), identity: &app.hub_key.identity, sk: &sk };
666
    let now = (db::now_ms() / 1000) as u64;
667
    let conflict = |n: u64| ([(header::CONTENT_TYPE, "text/x.tlog.size")], format!("{n}\n"));
668
    match tlog::witness(&req, &origin, &key, latest, &me, now) {
669
        Ok(tlog::Witnessed::Cosigned { checkpoint, lines }) => {
670
            let root = ObjectRef(checkpoint.root).to_hex();
671
            match db::tlog::witness_advance(&app.db, &origin, req.old_size as i64, checkpoint.size as i64, &root).await {
672
                Ok(true) => {
673
                    let body: String = tlog::Note { text: String::new(), sigs: lines }.encode().trim_start_matches('\n').to_string();
674
                    ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], body).into_response()
675
                }
676
                Ok(false) => {
677
                    let now = db::tlog::witnessed(&app.db, &origin).await.ok().flatten().map(|(s, _)| s as u64).unwrap_or(0);
678
                    (StatusCode::CONFLICT, conflict(now)).into_response()
679
                }
680
                Err(e) => plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
681
            }
682
        }
683
        Ok(tlog::Witnessed::Conflict(n)) => (StatusCode::CONFLICT, conflict(n)).into_response(),
684
        Err(tlog::WitnessError::Unsigned(e)) => plain(StatusCode::FORBIDDEN, &e),
685
        Err(tlog::WitnessError::Inconsistent(e)) => plain(StatusCode::UNPROCESSABLE_ENTITY, &e),
686
        Err(tlog::WitnessError::Bad(e)) => plain(StatusCode::BAD_REQUEST, &e),
687
    }
688
}
689
690
/// Sign a new checkpoint every few seconds while entries arrive.
691
pub async fn checkpointer(app: Shared) {
692
    let mut tick = tokio::time::interval(CHECKPOINT_EVERY);
693
    loop {
694
        tick.tick().await;
695
        let (identity, keys) = (app.hub_key.identity.clone(), app.config.keys_dir());
696
        let tl = app.tlog.clone();
697
        let done = tokio::task::spawn_blocking(move || -> anyhow::Result<bool> {
698
            let (_, sk) = crate::keys::load_secret(&keys)?;
699
            tl.refresh_checkpoint(&identity, &sk)
700
        })
701
        .await;
702
        match done {
703
            Ok(Err(e)) => eprintln!("tlog: signing a checkpoint: {e}"),
704
            // A new checkpoint, or one some witness has not cosigned yet.
705
            _ => collect(&app).await,
706
        }
707
    }
708
}
709
710
fn plain(status: StatusCode, why: &str) -> Response {
711
    (status, [(header::CONTENT_TYPE, "text/plain; charset=utf-8")], format!("{why}\n")).into_response()
712
}
713
714
/// `GET /log/checkpoint`: the latest signed checkpoint (C2SP
715
/// tlog-checkpoint, a signed note).
716
pub async fn checkpoint(State(app): State<Shared>) -> Response {
717
    match app.tlog.checkpoint() {
718
        Some(note) => ([(header::CONTENT_TYPE, "text/plain; charset=utf-8"), (header::CACHE_CONTROL, "no-cache")], note).into_response(),
719
        None => plain(StatusCode::SERVICE_UNAVAILABLE, "no checkpoint yet: the log signs one within seconds"),
720
    }
721
}
722
723
/// `GET /log/witnesses` (#240): this log's witnesses, one `NAME BASE64`
724
/// line each (the identity object), which `oxy tlog verify` pins.
725
pub async fn witnesses(State(app): State<Shared>) -> Response {
726
    let body: String =
727
        app.tlog.witnesses().iter().map(|p| format!("{} {}\n", p.name, oxy_core::dsse::base64(&p.identity.encode()))).collect();
728
    ([(header::CONTENT_TYPE, "text/plain; charset=utf-8"), (header::CACHE_CONTROL, "no-cache")], body).into_response()
729
}
730
731
/// `GET /log/tile/{L}/{N}[.p/{W}]` and `/log/tile/entries/{N}[.p/{W}]`:
732
/// a tile of hashes or an entry bundle (C2SP tlog-tiles). Full tiles never
733
/// change and are cached for good.
734
pub async fn tile(State(app): State<Shared>, UrlPath(path): UrlPath<String>) -> Response {
735
    let (entries, rest) = match path.strip_prefix("entries/") {
736
        Some(r) => (true, format!("0/{r}")),
737
        None => (false, path.clone()),
738
    };
739
    let Some(t) = Tile::parse(&rest) else {
740
        return plain(StatusCode::NOT_FOUND, "no such tile");
741
    };
742
    let tl = app.tlog.clone();
743
    let got = tokio::task::spawn_blocking(move || if entries { tl.bundle(&t) } else { tl.tile(&t) }).await;
744
    match got {
745
        Ok(Ok(Some(data))) => {
746
            let cache = if t.width as u64 == TILE_WIDTH { "public, max-age=31536000, immutable" } else { "public, max-age=5" };
747
            ([(header::CONTENT_TYPE, "application/octet-stream"), (header::CACHE_CONTROL, cache)], data).into_response()
748
        }
749
        Ok(Ok(None)) => plain(StatusCode::NOT_FOUND, "the log does not hold that tile yet"),
750
        Ok(Err(e)) => plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
751
        Err(e) => plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
752
    }
753
}
754
755
#[cfg(test)]
756
mod tests {
757
    use super::*;
758
759
    #[test]
760
    fn a_reader_leaves_the_files_alone_and_cannot_append() {
761
        let dir = tempfile::tempdir().unwrap();
762
        let log = Log::open(dir.path(), "hub.example/log").unwrap();
763
        log.append(&[entry(0), entry(1)]).unwrap();
764
        // A torn append: an offset whose entry never arrived.
765
        std::fs::OpenOptions::new().append(true).open(dir.path().join("offsets")).unwrap().write_all(&9999u64.to_le_bytes()).unwrap();
766
        let before = std::fs::metadata(dir.path().join("offsets")).unwrap().len();
767
        let reader = Log::open_reader(dir.path(), "hub.example/log").unwrap();
768
        assert_eq!(reader.size(), 2);
769
        assert_eq!(std::fs::metadata(dir.path().join("offsets")).unwrap().len(), before, "the writer's files are untouched");
770
        assert!(reader.append(&[entry(2)]).is_err());
771
        assert_eq!(reader.tree_hash(2).unwrap(), log.tree_hash(2).unwrap());
772
    }
773
774
    fn entry(i: u64) -> Entry {
775
        Entry { kind: "ref".into(), repo: [1; 16], object: ObjectRef([i as u8; 32]), signers: vec![], received: i }
776
    }
777
778
    #[test]
779
    fn the_log_survives_a_torn_append_and_keeps_its_root() {
780
        let dir = tempfile::tempdir().unwrap();
781
        let log = Log::open(dir.path(), "hub.example/log").unwrap();
782
        let first: Vec<Entry> = (0..300).map(entry).collect();
783
        assert_eq!(log.append(&first).unwrap(), (0..300).collect::<Vec<_>>());
784
        let root = log.tree_hash(300).unwrap();
785
        // Leaves alone, as RFC 6962 roots them.
786
        let mut stored: Vec<Hash> = Vec::new();
787
        for (n, e) in first.iter().enumerate() {
788
            stored.extend(tlog::stored_hashes_for_leaf(n as u64, e.leaf_hash(), &stored).unwrap());
789
        }
790
        assert_eq!(root, tlog::tree_hash(300, &stored).unwrap());
791
        drop(log);
792
        // A crash after the entry and part of the hashes were written.
793
        let torn = dir.path().join("hashes");
794
        let len = std::fs::metadata(&torn).unwrap().len();
795
        OpenOptions::new().write(true).open(&torn).unwrap().set_len(len - 40).unwrap();
796
        let mut f = OpenOptions::new().append(true).open(dir.path().join("entries")).unwrap();
797
        f.write_all(&[0, 200, 1, 2]).unwrap(); // a partial entry
798
        let log = Log::open(dir.path(), "hub.example/log").unwrap();
799
        assert_eq!(log.size(), 300);
800
        assert_eq!(log.tree_hash(300).unwrap(), root);
801
        log.append(&[entry(300)]).unwrap();
802
        assert_eq!(log.size(), 301);
803
        let p = log.prove_inclusion(301, 7).unwrap();
804
        tlog::check_inclusion(&p, 301, &log.tree_hash(301).unwrap(), 7, &first[7].leaf_hash()).unwrap();
805
        let c = log.prove_consistency(301, 300).unwrap();
806
        tlog::check_consistency(&c, 301, &log.tree_hash(301).unwrap(), 300, &root).unwrap();
807
        // Tiles and bundles: the full level-0 tile and the partial one.
808
        let full = log.tile(&Tile { level: 0, n: 0, width: 256 }).unwrap().unwrap();
809
        assert_eq!(full.len(), 256 * 32);
810
        assert!(log.tile(&Tile { level: 0, n: 1, width: 45 }).unwrap().is_some());
811
        assert!(log.tile(&Tile { level: 0, n: 1, width: 46 }).unwrap().is_none(), "not yet");
812
        let bundle = log.bundle(&Tile { level: 0, n: 1, width: 45 }).unwrap().unwrap();
813
        assert_eq!(tlog::decode_bundle(&bundle).unwrap()[0], first[256].encode());
814
    }
815
816
    #[test]
817
    fn checkpoints_are_signed_when_the_log_grows() {
818
        let dir = tempfile::tempdir().unwrap();
819
        let sk = oxy_core::identity::SecretKey::generate();
820
        let hub = sk.identity("hub", "[email protected]", 1);
821
        let log = Log::open(dir.path(), &origin_of("https://hub.example:7343/")).unwrap();
822
        assert_eq!(log.origin, "hub.example:7343/log");
823
        assert!(log.refresh_checkpoint(&hub, &sk).unwrap(), "the empty log's");
824
        assert!(!log.refresh_checkpoint(&hub, &sk).unwrap(), "nothing new");
825
        log.append(&[entry(1), entry(2)]).unwrap();
826
        assert!(log.refresh_checkpoint(&hub, &sk).unwrap());
827
        let note = tlog::Note::parse(&log.checkpoint().unwrap()).unwrap();
828
        let c = Checkpoint::verify(&note, "hub.example:7343/log", &hub).unwrap();
829
        assert_eq!((c.size, c.root), (2, log.tree_hash(2).unwrap()));
830
        // Kept across a restart.
831
        drop(log);
832
        let log = Log::open(dir.path(), "hub.example:7343/log").unwrap();
833
        assert_eq!(log.checkpoint().map(|n| n.contains("\n2\n")), Some(true));
834
    }
835
}