OXYGENHUB
# 05f1a85a2842 oxygenhub / crates / hub / src / tlog.rs
19.6 KiB · Rust · last changed The hub's transparency log (step 1 of docs/transparency.md) 18 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::repo::{PushReport, Repo};
25
use oxy_core::tlog::{self, Checkpoint, Entry, Hash, HashReader, Tile, TlogError, TILE_WIDTH};
26
use std::fs::{File, OpenOptions};
27
use std::io::Write;
28
use std::os::unix::fs::FileExt;
29
use std::path::{Path, PathBuf};
30
use std::sync::Mutex;
31
32
/// How often a new checkpoint is signed while entries arrive.
33
pub const CHECKPOINT_EVERY: std::time::Duration = std::time::Duration::from_secs(5);
34
35
struct Files {
36
    entries: File,
37
    offsets: File,
38
    hashes: File,
39
    /// Entries in the log.
40
    size: u64,
41
    /// Bytes in `entries`.
42
    entries_len: u64,
43
}
44
45
/// The stored hashes in a file, by stored index.
46
struct FileHashes<'a>(&'a File);
47
48
impl HashReader for FileHashes<'_> {
49
    fn read_hashes(&self, indexes: &[u64]) -> Result<Vec<Hash>, TlogError> {
50
        indexes
51
            .iter()
52
            .map(|&i| {
53
                let mut h = [0u8; 32];
54
                self.0.read_exact_at(&mut h, i * 32).map_err(|e| TlogError::Read(format!("stored hash {i}: {e}")))?;
55
                Ok(h)
56
            })
57
            .collect()
58
    }
59
}
60
61
/// The log on disk.
62
pub struct Log {
63
    dir: PathBuf,
64
    /// The log's name in its checkpoints: the hub's host and `/log`.
65
    pub origin: String,
66
    files: Mutex<Files>,
67
    /// The latest signed checkpoint: its size and its note.
68
    checkpoint: Mutex<Option<(u64, String)>>,
69
}
70
71
fn read_u64_at(f: &File, at: u64) -> std::io::Result<u64> {
72
    let mut b = [0u8; 8];
73
    f.read_exact_at(&mut b, at)?;
74
    Ok(u64::from_le_bytes(b))
75
}
76
77
/// The origin of a hub's log: its host (and port) and `/log`.
78
pub fn origin_of(base_url: &str) -> String {
79
    let host = base_url.split_once("://").map(|(_, h)| h).unwrap_or(base_url);
80
    format!("{}/log", host.trim_end_matches('/'))
81
}
82
83
impl Log {
84
    /// Open (or start) the log in `dir`, recovering from an interrupted
85
    /// append.
86
    pub fn open(dir: &Path, origin: &str) -> anyhow::Result<Log> {
87
        std::fs::create_dir_all(dir)?;
88
        let open = |name: &str| OpenOptions::new().read(true).append(true).create(true).open(dir.join(name));
89
        let (entries, offsets, hashes) = (open("entries")?, open("offsets")?, open("hashes")?);
90
        let entries_on_disk = entries.metadata()?.len();
91
        // The whole entries: those whose offset was written and whose
92
        // bytes all were.
93
        let mut size = offsets.metadata()?.len() / 8;
94
        let mut entries_len = 0;
95
        while size > 0 {
96
            let off = read_u64_at(&offsets, (size - 1) * 8)?;
97
            let mut len = [0u8; 2];
98
            if off + 2 <= entries_on_disk && entries.read_exact_at(&mut len, off).is_ok() {
99
                let end = off + 2 + u16::from_be_bytes(len) as u64;
100
                if end <= entries_on_disk {
101
                    entries_len = end;
102
                    break;
103
                }
104
            }
105
            size -= 1;
106
        }
107
        offsets.set_len(size * 8)?;
108
        entries.set_len(entries_len)?;
109
        // The hashes of every leaf whose hashes were all written; the rest
110
        // are computed again from the entries.
111
        let have = hashes.metadata()?.len() / 32;
112
        let mut whole = size;
113
        while tlog::stored_hash_count(whole) > have {
114
            whole -= 1;
115
        }
116
        hashes.set_len(tlog::stored_hash_count(whole) * 32)?;
117
        let mut files = Files { entries, offsets, hashes, size: whole, entries_len };
118
        for n in whole..size {
119
            let bytes = Self::entry_bytes(&files, n)?;
120
            let add = tlog::stored_hashes_for_leaf(n, tlog::leaf_hash(&bytes), &FileHashes(&files.hashes))?;
121
            for h in add {
122
                files.hashes.write_all(&h)?;
123
            }
124
            files.size = n + 1;
125
        }
126
        files.size = size;
127
        files.hashes.sync_data()?;
128
        let checkpoint = std::fs::read_to_string(dir.join("checkpoint")).ok().and_then(|note| {
129
            let n = tlog::Note::parse(&note).ok()?;
130
            let c = Checkpoint::parse(&n.text).ok()?;
131
            (c.size <= size).then_some((c.size, note))
132
        });
133
        Ok(Log { dir: dir.to_path_buf(), origin: origin.to_string(), files: Mutex::new(files), checkpoint: Mutex::new(checkpoint) })
134
    }
135
136
    fn entry_bytes(f: &Files, n: u64) -> anyhow::Result<Vec<u8>> {
137
        let off = read_u64_at(&f.offsets, n * 8)?;
138
        let mut len = [0u8; 2];
139
        f.entries.read_exact_at(&mut len, off)?;
140
        let mut b = vec![0u8; u16::from_be_bytes(len) as usize];
141
        f.entries.read_exact_at(&mut b, off + 2)?;
142
        Ok(b)
143
    }
144
145
    /// Entries in the log.
146
    pub fn size(&self) -> u64 {
147
        self.files.lock().unwrap().size
148
    }
149
150
    /// Append entries, durably; their numbers.
151
    pub fn append(&self, entries: &[Entry]) -> anyhow::Result<Vec<u64>> {
152
        let mut f = self.files.lock().unwrap();
153
        let mut out = Vec::with_capacity(entries.len());
154
        for e in entries {
155
            let bytes = e.encode();
156
            let n = f.size;
157
            let add = tlog::stored_hashes_for_leaf(n, tlog::leaf_hash(&bytes), &FileHashes(&f.hashes))?;
158
            let off = f.entries_len;
159
            let mut rec = (bytes.len() as u16).to_be_bytes().to_vec();
160
            rec.extend_from_slice(&bytes);
161
            f.entries.write_all(&rec)?;
162
            f.entries_len += rec.len() as u64;
163
            f.offsets.write_all(&off.to_le_bytes())?;
164
            let mut hs = Vec::with_capacity(add.len() * 32);
165
            for h in add {
166
                hs.extend_from_slice(&h);
167
            }
168
            f.hashes.write_all(&hs)?;
169
            f.size = n + 1;
170
            out.push(n);
171
        }
172
        f.entries.sync_data()?;
173
        f.offsets.sync_data()?;
174
        f.hashes.sync_data()?;
175
        Ok(out)
176
    }
177
178
    /// The root of the first `n` entries.
179
    pub fn tree_hash(&self, n: u64) -> anyhow::Result<Hash> {
180
        let f = self.files.lock().unwrap();
181
        Ok(tlog::tree_hash(n, &FileHashes(&f.hashes))?)
182
    }
183
184
    /// Entry `n`'s inclusion proof in the tree of `t` entries.
185
    pub fn prove_inclusion(&self, t: u64, n: u64) -> anyhow::Result<Vec<Hash>> {
186
        let f = self.files.lock().unwrap();
187
        Ok(tlog::prove_inclusion(t, n, &FileHashes(&f.hashes))?)
188
    }
189
190
    /// The consistency proof from `n` entries to `t`.
191
    pub fn prove_consistency(&self, t: u64, n: u64) -> anyhow::Result<Vec<Hash>> {
192
        let f = self.files.lock().unwrap();
193
        Ok(tlog::prove_consistency(t, n, &FileHashes(&f.hashes))?)
194
    }
195
196
    /// A tile's hashes, when the log holds all of them.
197
    pub fn tile(&self, t: &Tile) -> anyhow::Result<Option<Vec<u8>>> {
198
        let f = self.files.lock().unwrap();
199
        let at_level = f.size >> (tlog::TILE_HEIGHT * t.level);
200
        if at_level < (t.n << tlog::TILE_HEIGHT) + t.width as u64 {
201
            return Ok(None);
202
        }
203
        Ok(Some(t.read_data(&FileHashes(&f.hashes))?))
204
    }
205
206
    /// The entry bundle beside level-0 tile `t`, when the log holds it.
207
    pub fn bundle(&self, t: &Tile) -> anyhow::Result<Option<Vec<u8>>> {
208
        let f = self.files.lock().unwrap();
209
        let first = t.n << tlog::TILE_HEIGHT;
210
        if f.size < first + t.width as u64 {
211
            return Ok(None);
212
        }
213
        let entries: Vec<Vec<u8>> = (first..first + t.width as u64).map(|n| Self::entry_bytes(&f, n)).collect::<anyhow::Result<_>>()?;
214
        Ok(Some(tlog::encode_bundle(&entries)?))
215
    }
216
217
    /// The latest signed checkpoint note.
218
    pub fn checkpoint(&self) -> Option<String> {
219
        self.checkpoint.lock().unwrap().as_ref().map(|(_, n)| n.clone())
220
    }
221
222
    /// Sign a checkpoint of the log as it is, unless the last one already
223
    /// covers it. True when a new one was signed.
224
    pub fn refresh_checkpoint(&self, identity: &oxy_core::identity::Identity, sk: &oxy_core::identity::SecretKey) -> anyhow::Result<bool> {
225
        let size = self.size();
226
        if self.checkpoint.lock().unwrap().as_ref().is_some_and(|(s, _)| *s >= size) {
227
            return Ok(false);
228
        }
229
        let c = Checkpoint { origin: self.origin.clone(), size, root: self.tree_hash(size)?, extensions: vec![] };
230
        let note = c.sign(identity, sk)?.encode();
231
        let tmp = self.dir.join("checkpoint.new");
232
        std::fs::write(&tmp, &note)?;
233
        File::open(&tmp)?.sync_all()?;
234
        std::fs::rename(&tmp, self.dir.join("checkpoint"))?;
235
        *self.checkpoint.lock().unwrap() = Some((size, note));
236
        Ok(true)
237
    }
238
}
239
240
/// An object to log.
241
#[derive(Clone, Debug)]
242
pub struct Pending {
243
    pub kind: &'static str,
244
    /// The repository's id (zero for none) and its row on this hub.
245
    pub repo: [u8; 16],
246
    pub repo_row: Option<i64>,
247
    pub object: ObjectRef,
248
    pub signers: Vec<KeyId>,
249
}
250
251
/// Log what is not logged yet. A failure is reported, never fatal: the
252
/// object stays accepted (enforcing logging before acceptance comes with
253
/// inclusion proofs in push responses).
254
pub async fn log(app: &Shared, items: Vec<Pending>) -> Vec<u64> {
255
    let mut fresh = Vec::new();
256
    for p in items {
257
        let object = p.object.to_hex();
258
        match db::tlog::entry_of(&app.db, &object, p.kind).await {
259
            Ok(Some(_)) => continue,
260
            Ok(None) => {}
261
            Err(e) => {
262
                eprintln!("tlog: looking up {} {}: {e}", p.kind, &object[..12]);
263
                continue;
264
            }
265
        }
266
        if !fresh.iter().any(|q: &Pending| q.kind == p.kind && q.object == p.object) {
267
            fresh.push(p);
268
        }
269
    }
270
    if fresh.is_empty() {
271
        return vec![];
272
    }
273
    let now = db::now_ms();
274
    let entries: Vec<Entry> = fresh
275
        .iter()
276
        .map(|p| Entry { kind: p.kind.to_string(), repo: p.repo, object: p.object, signers: p.signers.clone(), received: now as u64 })
277
        .collect();
278
    let tl = app.tlog.clone();
279
    let numbers = match tokio::task::spawn_blocking(move || tl.append(&entries)).await {
280
        Ok(Ok(n)) => n,
281
        Ok(Err(e)) => {
282
            eprintln!("tlog: appending {} entries: {e}", fresh.len());
283
            return vec![];
284
        }
285
        Err(e) => {
286
            eprintln!("tlog: appending: {e}");
287
            return vec![];
288
        }
289
    };
290
    for (p, n) in fresh.iter().zip(&numbers) {
291
        if let Err(e) = db::tlog::record(&app.db, *n as i64, &p.object.to_hex(), p.kind, p.repo_row, now).await {
292
            eprintln!("tlog: indexing entry {n}: {e}");
293
        }
294
    }
295
    numbers
296
}
297
298
fn sig_keys(sigs: &[oxy_core::identity::Signature]) -> Vec<KeyId> {
299
    let mut keys: Vec<KeyId> = sigs.iter().map(|s| s.key).collect();
300
    keys.sort();
301
    keys.dedup();
302
    keys
303
}
304
305
/// The certificates of short-lived keys among `signers`, to log beside
306
/// what they signed.
307
fn certificates(repo: &Repo, rid: [u8; 16], row: Option<i64>, signers: &[KeyId], out: &mut Vec<Pending>) {
308
    for k in signers {
309
        if let Ok(Some(c)) = repo.store().certificate_of(k) {
310
            let issuer = repo.store().get_certificate(&c).map(|sc| vec![sc.cert.issuer]).unwrap_or_default();
311
            out.push(Pending { kind: "certificate", repo: rid, repo_row: row, object: c, signers: issuer });
312
        }
313
    }
314
}
315
316
/// What a push brought that the log keeps: the attestations of the
317
/// references it moved (and the hub's acceptance of them), tags, seals,
318
/// the repository's policy, and the certificates of short-lived signers.
319
pub fn push_entries(repo: &Repo, row: Option<i64>, report: &PushReport) -> Vec<Pending> {
320
    let Ok(rid) = repo.id() else { return vec![] };
321
    let mut out = Vec::new();
322
    let add = |out: &mut Vec<Pending>, kind: &'static str, object: ObjectRef, signers: Vec<KeyId>| {
323
        certificates(repo, rid, row, &signers, out);
324
        out.push(Pending { kind, repo: rid, repo_row: row, object, signers });
325
    };
326
    for u in &report.updated {
327
        if u.new_state.is_zero() || !report.results.iter().any(|r| r.ok && r.name == u.name) {
328
            continue;
329
        }
330
        if let Some(tag) = u.name.strip_prefix("tags/") {
331
            if let Ok(Some((r, sa))) = repo.tag_attest(tag) {
332
                add(&mut out, "tag", r, sig_keys(&sa.sigs));
333
            }
334
        } else if let Ok(Some((r, sa))) = repo.latest_ref_attest(&u.name) {
335
            add(&mut out, "ref", r, sig_keys(&sa.sigs));
336
            if let Ok(Some(acc)) = repo.acceptance_of(&r) {
337
                add(&mut out, "accepted", acc.attest.hash(), sig_keys(&acc.sigs));
338
            }
339
        }
340
    }
341
    let mut seals = std::collections::BTreeSet::new();
342
    for h in &report.imported {
343
        for s in repo.store().seals_for(h).unwrap_or_default() {
344
            seals.insert(s);
345
        }
346
    }
347
    for s in seals {
348
        let signers = sig_keys(&repo.store().signatures(&s).unwrap_or_default());
349
        add(&mut out, "seal", s, signers);
350
    }
351
    if let Ok(Some((r, sp))) = repo.current_policy() {
352
        add(&mut out, "policy", r, sig_keys(&sp.sigs));
353
    }
354
    out
355
}
356
357
/// Sign a new checkpoint every few seconds while entries arrive.
358
pub async fn checkpointer(app: Shared) {
359
    let mut tick = tokio::time::interval(CHECKPOINT_EVERY);
360
    loop {
361
        tick.tick().await;
362
        let (identity, keys) = (app.hub_key.identity.clone(), app.config.keys_dir());
363
        let tl = app.tlog.clone();
364
        let done = tokio::task::spawn_blocking(move || -> anyhow::Result<bool> {
365
            let (_, sk) = crate::keys::load_secret(&keys)?;
366
            tl.refresh_checkpoint(&identity, &sk)
367
        })
368
        .await;
369
        if let Ok(Err(e)) = done {
370
            eprintln!("tlog: signing a checkpoint: {e}");
371
        }
372
    }
373
}
374
375
fn plain(status: StatusCode, why: &str) -> Response {
376
    (status, [(header::CONTENT_TYPE, "text/plain; charset=utf-8")], format!("{why}\n")).into_response()
377
}
378
379
/// `GET /log/checkpoint`: the latest signed checkpoint (C2SP
380
/// tlog-checkpoint, a signed note).
381
pub async fn checkpoint(State(app): State<Shared>) -> Response {
382
    match app.tlog.checkpoint() {
383
        Some(note) => ([(header::CONTENT_TYPE, "text/plain; charset=utf-8"), (header::CACHE_CONTROL, "no-cache")], note).into_response(),
384
        None => plain(StatusCode::SERVICE_UNAVAILABLE, "no checkpoint yet: the log signs one within seconds"),
385
    }
386
}
387
388
/// `GET /log/tile/{L}/{N}[.p/{W}]` and `/log/tile/entries/{N}[.p/{W}]`:
389
/// a tile of hashes or an entry bundle (C2SP tlog-tiles). Full tiles never
390
/// change and are cached for good.
391
pub async fn tile(State(app): State<Shared>, UrlPath(path): UrlPath<String>) -> Response {
392
    let (entries, rest) = match path.strip_prefix("entries/") {
393
        Some(r) => (true, format!("0/{r}")),
394
        None => (false, path.clone()),
395
    };
396
    let Some(t) = Tile::parse(&rest) else {
397
        return plain(StatusCode::NOT_FOUND, "no such tile");
398
    };
399
    let tl = app.tlog.clone();
400
    let got = tokio::task::spawn_blocking(move || if entries { tl.bundle(&t) } else { tl.tile(&t) }).await;
401
    match got {
402
        Ok(Ok(Some(data))) => {
403
            let cache = if t.width as u64 == TILE_WIDTH { "public, max-age=31536000, immutable" } else { "public, max-age=5" };
404
            ([(header::CONTENT_TYPE, "application/octet-stream"), (header::CACHE_CONTROL, cache)], data).into_response()
405
        }
406
        Ok(Ok(None)) => plain(StatusCode::NOT_FOUND, "the log does not hold that tile yet"),
407
        Ok(Err(e)) => plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
408
        Err(e) => plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
409
    }
410
}
411
412
#[cfg(test)]
413
mod tests {
414
    use super::*;
415
416
    fn entry(i: u64) -> Entry {
417
        Entry { kind: "ref".into(), repo: [1; 16], object: ObjectRef([i as u8; 32]), signers: vec![], received: i }
418
    }
419
420
    #[test]
421
    fn the_log_survives_a_torn_append_and_keeps_its_root() {
422
        let dir = tempfile::tempdir().unwrap();
423
        let log = Log::open(dir.path(), "hub.example/log").unwrap();
424
        let first: Vec<Entry> = (0..300).map(entry).collect();
425
        assert_eq!(log.append(&first).unwrap(), (0..300).collect::<Vec<_>>());
426
        let root = log.tree_hash(300).unwrap();
427
        // Leaves alone, as RFC 6962 roots them.
428
        let mut stored: Vec<Hash> = Vec::new();
429
        for (n, e) in first.iter().enumerate() {
430
            stored.extend(tlog::stored_hashes_for_leaf(n as u64, e.leaf_hash(), &stored).unwrap());
431
        }
432
        assert_eq!(root, tlog::tree_hash(300, &stored).unwrap());
433
        drop(log);
434
        // A crash after the entry and part of the hashes were written.
435
        let torn = dir.path().join("hashes");
436
        let len = std::fs::metadata(&torn).unwrap().len();
437
        OpenOptions::new().write(true).open(&torn).unwrap().set_len(len - 40).unwrap();
438
        let mut f = OpenOptions::new().append(true).open(dir.path().join("entries")).unwrap();
439
        f.write_all(&[0, 200, 1, 2]).unwrap(); // a partial entry
440
        let log = Log::open(dir.path(), "hub.example/log").unwrap();
441
        assert_eq!(log.size(), 300);
442
        assert_eq!(log.tree_hash(300).unwrap(), root);
443
        log.append(&[entry(300)]).unwrap();
444
        assert_eq!(log.size(), 301);
445
        let p = log.prove_inclusion(301, 7).unwrap();
446
        tlog::check_inclusion(&p, 301, &log.tree_hash(301).unwrap(), 7, &first[7].leaf_hash()).unwrap();
447
        let c = log.prove_consistency(301, 300).unwrap();
448
        tlog::check_consistency(&c, 301, &log.tree_hash(301).unwrap(), 300, &root).unwrap();
449
        // Tiles and bundles: the full level-0 tile and the partial one.
450
        let full = log.tile(&Tile { level: 0, n: 0, width: 256 }).unwrap().unwrap();
451
        assert_eq!(full.len(), 256 * 32);
452
        assert!(log.tile(&Tile { level: 0, n: 1, width: 45 }).unwrap().is_some());
453
        assert!(log.tile(&Tile { level: 0, n: 1, width: 46 }).unwrap().is_none(), "not yet");
454
        let bundle = log.bundle(&Tile { level: 0, n: 1, width: 45 }).unwrap().unwrap();
455
        assert_eq!(tlog::decode_bundle(&bundle).unwrap()[0], first[256].encode());
456
    }
457
458
    #[test]
459
    fn checkpoints_are_signed_when_the_log_grows() {
460
        let dir = tempfile::tempdir().unwrap();
461
        let sk = oxy_core::identity::SecretKey::generate();
462
        let hub = sk.identity("hub", "[email protected]", 1);
463
        let log = Log::open(dir.path(), &origin_of("https://hub.example:7343/")).unwrap();
464
        assert_eq!(log.origin, "hub.example:7343/log");
465
        assert!(log.refresh_checkpoint(&hub, &sk).unwrap(), "the empty log's");
466
        assert!(!log.refresh_checkpoint(&hub, &sk).unwrap(), "nothing new");
467
        log.append(&[entry(1), entry(2)]).unwrap();
468
        assert!(log.refresh_checkpoint(&hub, &sk).unwrap());
469
        let note = tlog::Note::parse(&log.checkpoint().unwrap()).unwrap();
470
        let c = Checkpoint::verify(&note, "hub.example:7343/log", &hub).unwrap();
471
        assert_eq!((c.size, c.root), (2, log.tree_hash(2).unwrap()));
472
        // Kept across a restart.
473
        drop(log);
474
        let log = Log::open(dir.path(), "hub.example:7343/log").unwrap();
475
        assert_eq!(log.checkpoint().map(|n| n.contains("\n2\n")), Some(true));
476
    }
477
}