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