OXYGENHUB
◆ v0.9.0 oxygenhub / crates / hub / src / tlog.rs
40.0 KiB · Rust · last changed Create and withdraw tags on the website (closes #295, closes #301) 11 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
    /// `append.lock`: held, exclusively, around each append, so several
69
    /// processes sharing the data directory append one at a time (#274).
70
    lock: File,
71
    /// The latest signed checkpoint: its size and its note.
72
    checkpoint: Mutex<Option<(u64, String)>>,
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)>>,
77
    /// Whether this process writes the log: the web role's (#272). A
78
    /// process without it only reads, catching up with the writers.
79
    writer: bool,
80
}
81
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
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> {
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
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).
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> {
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")?);
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;
154
        let mut entries_len = 0;
155
        while size > 0 {
156
            let off = read_u64_at(&files.offsets, (size - 1) * 8)?;
157
            let mut len = [0u8; 2];
158
            if off + 2 <= entries_on_disk && files.entries.read_exact_at(&mut len, off).is_ok() {
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.
169
        let have = files.hashes.metadata()?.len() / 32;
170
        let mut whole = size;
171
        while tlog::stored_hash_count(whole) > have {
172
            whole -= 1;
173
        }
174
        if !writer {
175
            files.size = whole;
176
            files.entries_len = entries_len;
177
            return Ok(());
178
        }
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;
183
        for n in whole..size {
184
            let bytes = Self::entry_bytes(files, n)?;
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()?;
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
        }
201
    }
202
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
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
221
    /// Entry `n`'s bytes.
222
    pub fn entry(&self, n: u64) -> anyhow::Result<Vec<u8>> {
223
        let mut f = self.files.lock().unwrap();
224
        if n >= f.size {
225
            self.catch_up(&mut f);
226
        }
227
        anyhow::ensure!(n < f.size, "entry {n} is not in the log");
228
        Self::entry_bytes(&f, n)
229
    }
230
231
    /// Entries in the log.
232
    pub fn size(&self) -> u64 {
233
        let mut f = self.files.lock().unwrap();
234
        self.catch_up(&mut f);
235
        f.size
236
    }
237
238
    /// Append entries, durably; their numbers.
239
    pub fn append(&self, entries: &[Entry]) -> anyhow::Result<Vec<u64>> {
240
        if !self.writer {
241
            anyhow::bail!("this process does not write the log: it has no web role");
242
        }
243
        let mut f = self.files.lock().unwrap();
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>> {
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)?))
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(())
375
    }
376
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).
380
    pub fn checkpoint(&self) -> Option<String> {
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())
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> {
393
        if !self.writer {
394
            return Ok(false);
395
        }
396
        let size = self.size();
397
        // From the newest kept, whichever process signed it.
398
        let _ = self.checkpoint();
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 !report.results.iter().any(|r| r.ok && r.name == u.name) {
501
            continue;
502
        }
503
        // A tag's withdrawal (#301), and when the hub accepted it.
504
        if let (Some(tag), true) = (u.name.strip_prefix("tags/"), u.new_state.is_zero()) {
505
            if let Ok(Some((r, sa))) = repo.tag_withdrawal(tag) {
506
                add(&mut out, "untag", r, sig_keys(&sa.sigs));
507
                if let Ok(Some(acc)) = repo.acceptance_of(&r) {
508
                    add(&mut out, "accepted", acc.attest.hash(), sig_keys(&acc.sigs));
509
                }
510
            }
511
            continue;
512
        }
513
        if u.new_state.is_zero() {
514
            continue;
515
        }
516
        if let Some(tag) = u.name.strip_prefix("tags/") {
517
            if let Ok(Some((r, sa))) = repo.tag_attest(tag) {
518
                add(&mut out, "tag", r, sig_keys(&sa.sigs));
519
                // A short-lived key's tag, and when the hub accepted it
520
                // (oxygen#129).
521
                if let Ok(Some(acc)) = repo.acceptance_of(&r) {
522
                    add(&mut out, "accepted", acc.attest.hash(), sig_keys(&acc.sigs));
523
                }
524
            }
525
        } else if let Ok(Some((r, sa))) = repo.latest_ref_attest(&u.name) {
526
            add(&mut out, "ref", r, sig_keys(&sa.sigs));
527
            if let Ok(Some(acc)) = repo.acceptance_of(&r) {
528
                add(&mut out, "accepted", acc.attest.hash(), sig_keys(&acc.sigs));
529
            }
530
        }
531
    }
532
    let mut seals = std::collections::BTreeSet::new();
533
    for h in &report.imported {
534
        for s in repo.store().seals_for(h).unwrap_or_default() {
535
            seals.insert(s);
536
        }
537
    }
538
    for s in seals {
539
        let signers = sig_keys(&repo.store().signatures(&s).unwrap_or_default());
540
        add(&mut out, "seal", s, signers);
541
    }
542
    if let Ok(Some((r, sp))) = repo.current_policy() {
543
        add(&mut out, "policy", r, sig_keys(&sp.sigs));
544
    }
545
    out
546
}
547
548
/// Add the log to a refs answer (Oxygen spec §14.8): the latest
549
/// checkpoint, and for each bookmark's and tag's attestation its entry and
550
/// inclusion proof against it. An attestation the hub serves but never
551
/// logged (one pushed before the log began) is logged now, and proved on a
552
/// later fetch.
553
pub fn add_log(app: &Shared, row: Option<i64>, refs: &mut oxy_core::protocol::RefsResponse) -> Vec<Pending> {
554
    let mut backfill = Vec::new();
555
    let Some(note) = app.tlog.checkpoint() else { return backfill };
556
    let Some(size) = tlog::Note::parse(&note).ok().and_then(|n| Checkpoint::parse(&n.text).ok()).map(|c| c.size) else {
557
        return backfill;
558
    };
559
    refs.log = Some(note);
560
    // The witnesses a client may pin, for integrated times (#240).
561
    refs.witnesses = app.tlog.witnesses().iter().map(|p| (p.name.clone(), p.identity.encode())).collect();
562
    for r in refs.refs.iter_mut() {
563
        let Some(a) = &r.attestation else { continue };
564
        if let Some((logged, integration)) = place(app, size, row, "ref", a, &mut backfill) {
565
            r.logged = Some(logged);
566
            r.integration = integration;
567
        }
568
    }
569
    // Tags too (oxygen#129): a short-lived key's tag is checked at its
570
    // integrated time on every later fetch.
571
    for t in refs.tags.iter_mut() {
572
        let Some(a) = &t.attestation else { continue };
573
        if let Some((logged, integration)) = place(app, size, row, "tag", a, &mut backfill) {
574
            t.logged = Some(logged);
575
            t.integration = integration;
576
        }
577
    }
578
    backfill
579
}
580
581
/// Attestation `a`'s entry (of `kind`) in a log of `size` entries, its
582
/// inclusion proof, and the first cosigned checkpoints that hold it; none
583
/// when it is not in that checkpoint yet, and queued in `backfill` when it
584
/// was never logged.
585
fn place(
586
    app: &Shared,
587
    size: u64,
588
    row: Option<i64>,
589
    kind: &'static str,
590
    a: &oxy_core::protocol::SignedAttest,
591
    backfill: &mut Vec<Pending>,
592
) -> Option<(oxy_core::protocol::Logged, Vec<oxy_core::protocol::Integration>)> {
593
    let object = a.attest.hash();
594
    let idx =
595
        tokio::task::block_in_place(|| tokio::runtime::Handle::current().block_on(db::tlog::entry_of(&app.db, &object.to_hex(), kind)));
596
    match idx {
597
        Ok(Some(i)) if (i as u64) < size => {
598
            let (Ok(entry), Ok(proof)) = (app.tlog.entry(i as u64), app.tlog.prove_inclusion(size, i as u64)) else { return None };
599
            // When witnesses first saw it (#240): the first cosigned
600
            // checkpoints that hold it, each with the entry's proof.
601
            let notes =
602
                tokio::task::block_in_place(|| tokio::runtime::Handle::current().block_on(db::tlog::cosigned_notes_after(&app.db, i, 2)))
603
                    .unwrap_or_default();
604
            let mut integration = Vec::new();
605
            for (at, text) in notes {
606
                if let Ok(proof) = app.tlog.prove_inclusion(at as u64, i as u64) {
607
                    integration.push(oxy_core::protocol::Integration { note: text, proof });
608
                }
609
            }
610
            Some((oxy_core::protocol::Logged { index: i as u64, entry, proof }, integration))
611
        }
612
        Ok(Some(_)) => None,
613
        Ok(None) => {
614
            backfill.push(Pending { kind, repo: a.attest.repo, repo_row: row, object, signers: sig_keys(&a.sigs) });
615
            None
616
        }
617
        Err(e) => {
618
            eprintln!("tlog: looking up {}: {e}", &object.to_hex()[..12]);
619
            None
620
        }
621
    }
622
}
623
624
/// Ask each witness to cosign the latest checkpoint, and serve their
625
/// cosignatures with it. A witness that answers 409 is told again from the
626
/// size it says it has; one that refuses is logged.
627
pub async fn collect(app: &Shared) {
628
    let peers = app.tlog.witnesses();
629
    let Some(text) = app.tlog.checkpoint() else { return };
630
    if peers.is_empty() {
631
        return;
632
    }
633
    let Ok(mut note) = tlog::Note::parse(&text) else { return };
634
    let Ok(cp) = Checkpoint::parse(&note.text) else { return };
635
    // What a witness checks: the note as the log signed it.
636
    let own = tlog::Note { text: note.text.clone(), sigs: note.sigs.iter().filter(|s| s.name == cp.origin).cloned().collect() };
637
    let mut changed = false;
638
    for p in peers {
639
        if note.cosigned_by(&p.name, &p.identity).is_ok() {
640
            continue;
641
        }
642
        let mut old = db::tlog::cosigned_size(&app.db, &p.name).await.unwrap_or(0) as u64;
643
        for _ in 0..2 {
644
            let proof = if old == 0 || old >= cp.size { Vec::new() } else { app.tlog.prove_consistency(cp.size, old).unwrap_or_default() };
645
            let body = tlog::AddCheckpoint { old_size: old, proof, note: own.encode() }.encode();
646
            let client = match crate::net::client(&p.url, std::slice::from_ref(&p.url), std::time::Duration::from_secs(20)).await {
647
                Ok(c) => c,
648
                Err(e) => {
649
                    eprintln!("tlog: witness {}: {e}", p.name);
650
                    break;
651
                }
652
            };
653
            let res = match client.post(&p.url).header(header::CONTENT_TYPE, "text/plain").body(body).send().await {
654
                Ok(r) => r,
655
                Err(e) => {
656
                    eprintln!("tlog: witness {}: {e}", p.name);
657
                    break;
658
                }
659
            };
660
            let status = res.status();
661
            let answer = res.text().await.unwrap_or_default();
662
            if status == StatusCode::CONFLICT {
663
                match answer.trim().parse() {
664
                    Ok(n) if n != old => {
665
                        old = n;
666
                        continue;
667
                    }
668
                    _ => {
669
                        eprintln!("tlog: witness {}: a conflict without a size: {answer}", p.name);
670
                        break;
671
                    }
672
                }
673
            }
674
            if !status.is_success() {
675
                eprintln!("tlog: witness {} refused the checkpoint of {} entries ({status}): {}", p.name, cp.size, answer.trim());
676
                break;
677
            }
678
            let lines = tlog::Note::parse(&format!("{}\n{answer}", note.text)).map(|n| n.sigs).unwrap_or_default();
679
            let theirs: Vec<_> = lines.into_iter().filter(|s| s.name == p.name).collect();
680
            let check = tlog::Note { text: note.text.clone(), sigs: theirs.clone() };
681
            match check.cosigned_by(&p.name, &p.identity) {
682
                Ok(_) => {
683
                    note.sigs.extend(theirs);
684
                    db::tlog::set_cosigned(&app.db, &p.name, cp.size as i64).await.ok();
685
                    changed = true;
686
                }
687
                Err(e) => eprintln!("tlog: witness {} answered a cosignature that does not verify: {e}", p.name),
688
            }
689
            break;
690
        }
691
    }
692
    if changed {
693
        // Kept by size too, for integrated times (#240).
694
        db::tlog::keep_cosigned_note(&app.db, cp.size as i64, &note.encode()).await.ok();
695
        if let Err(e) = app.tlog.set_note(cp.size, note.encode()) {
696
            eprintln!("tlog: keeping the cosigned checkpoint: {e}");
697
        }
698
    }
699
}
700
701
/// `POST /log/witness/add-checkpoint` (C2SP tlog-witness): cosign a
702
/// checkpoint of a log this hub witnesses, if it extends the last one
703
/// cosigned.
704
pub async fn add_checkpoint(State(app): State<Shared>, body: String) -> Response {
705
    let Ok(req) = tlog::AddCheckpoint::parse(&body) else {
706
        return plain(StatusCode::BAD_REQUEST, "not an add-checkpoint request");
707
    };
708
    let Some(origin) = tlog::Note::parse(&req.note).ok().and_then(|n| Checkpoint::parse(&n.text).ok()).map(|c| c.origin) else {
709
        return plain(StatusCode::BAD_REQUEST, "the checkpoint does not parse");
710
    };
711
    let Some(key) = app.tlog.witnessed_key(&origin) else {
712
        return plain(StatusCode::NOT_FOUND, &format!("this hub does not witness {origin}"));
713
    };
714
    let latest = match db::tlog::witnessed(&app.db, &origin).await {
715
        Ok(l) => l.and_then(|(size, root)| Some((size as u64, ObjectRef::from_hex(&root)?.0))),
716
        Err(e) => return plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
717
    };
718
    let sk = match crate::keys::load_secret(&app.config.keys_dir()) {
719
        Ok((_, sk)) => sk,
720
        Err(e) => return plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
721
    };
722
    let me = tlog::WitnessKey { name: app.tlog.witness_name(), identity: &app.hub_key.identity, sk: &sk };
723
    let now = (db::now_ms() / 1000) as u64;
724
    let conflict = |n: u64| ([(header::CONTENT_TYPE, "text/x.tlog.size")], format!("{n}\n"));
725
    match tlog::witness(&req, &origin, &key, latest, &me, now) {
726
        Ok(tlog::Witnessed::Cosigned { checkpoint, lines }) => {
727
            let root = ObjectRef(checkpoint.root).to_hex();
728
            match db::tlog::witness_advance(&app.db, &origin, req.old_size as i64, checkpoint.size as i64, &root).await {
729
                Ok(true) => {
730
                    let body: String = tlog::Note { text: String::new(), sigs: lines }.encode().trim_start_matches('\n').to_string();
731
                    ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], body).into_response()
732
                }
733
                Ok(false) => {
734
                    let now = db::tlog::witnessed(&app.db, &origin).await.ok().flatten().map(|(s, _)| s as u64).unwrap_or(0);
735
                    (StatusCode::CONFLICT, conflict(now)).into_response()
736
                }
737
                Err(e) => plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
738
            }
739
        }
740
        Ok(tlog::Witnessed::Conflict(n)) => (StatusCode::CONFLICT, conflict(n)).into_response(),
741
        Err(tlog::WitnessError::Unsigned(e)) => plain(StatusCode::FORBIDDEN, &e),
742
        Err(tlog::WitnessError::Inconsistent(e)) => plain(StatusCode::UNPROCESSABLE_ENTITY, &e),
743
        Err(tlog::WitnessError::Bad(e)) => plain(StatusCode::BAD_REQUEST, &e),
744
    }
745
}
746
747
/// Sign a new checkpoint every few seconds while entries arrive.
748
pub async fn checkpointer(app: Shared) {
749
    let mut tick = tokio::time::interval(CHECKPOINT_EVERY);
750
    loop {
751
        tick.tick().await;
752
        let (identity, keys) = (app.hub_key.identity.clone(), app.config.keys_dir());
753
        let tl = app.tlog.clone();
754
        let done = tokio::task::spawn_blocking(move || -> anyhow::Result<bool> {
755
            let (_, sk) = crate::keys::load_secret(&keys)?;
756
            tl.refresh_checkpoint(&identity, &sk)
757
        })
758
        .await;
759
        match done {
760
            Ok(Err(e)) => eprintln!("tlog: signing a checkpoint: {e}"),
761
            // A new checkpoint, or one some witness has not cosigned yet.
762
            _ => collect(&app).await,
763
        }
764
    }
765
}
766
767
fn plain(status: StatusCode, why: &str) -> Response {
768
    (status, [(header::CONTENT_TYPE, "text/plain; charset=utf-8")], format!("{why}\n")).into_response()
769
}
770
771
/// `GET /log/checkpoint`: the latest signed checkpoint (C2SP
772
/// tlog-checkpoint, a signed note).
773
pub async fn checkpoint(State(app): State<Shared>) -> Response {
774
    match app.tlog.checkpoint() {
775
        Some(note) => ([(header::CONTENT_TYPE, "text/plain; charset=utf-8"), (header::CACHE_CONTROL, "no-cache")], note).into_response(),
776
        None => plain(StatusCode::SERVICE_UNAVAILABLE, "no checkpoint yet: the log signs one within seconds"),
777
    }
778
}
779
780
/// `GET /log/witnesses` (#240): this log's witnesses, one `NAME BASE64`
781
/// line each (the identity object), which `oxy tlog verify` pins.
782
pub async fn witnesses(State(app): State<Shared>) -> Response {
783
    let body: String =
784
        app.tlog.witnesses().iter().map(|p| format!("{} {}\n", p.name, oxy_core::dsse::base64(&p.identity.encode()))).collect();
785
    ([(header::CONTENT_TYPE, "text/plain; charset=utf-8"), (header::CACHE_CONTROL, "no-cache")], body).into_response()
786
}
787
788
/// `GET /log/tile/{L}/{N}[.p/{W}]` and `/log/tile/entries/{N}[.p/{W}]`:
789
/// a tile of hashes or an entry bundle (C2SP tlog-tiles). Full tiles never
790
/// change and are cached for good.
791
pub async fn tile(State(app): State<Shared>, UrlPath(path): UrlPath<String>) -> Response {
792
    let (entries, rest) = match path.strip_prefix("entries/") {
793
        Some(r) => (true, format!("0/{r}")),
794
        None => (false, path.clone()),
795
    };
796
    let Some(t) = Tile::parse(&rest) else {
797
        return plain(StatusCode::NOT_FOUND, "no such tile");
798
    };
799
    let tl = app.tlog.clone();
800
    let got = tokio::task::spawn_blocking(move || if entries { tl.bundle(&t) } else { tl.tile(&t) }).await;
801
    match got {
802
        Ok(Ok(Some(data))) => {
803
            let cache = if t.width as u64 == TILE_WIDTH { "public, max-age=31536000, immutable" } else { "public, max-age=5" };
804
            ([(header::CONTENT_TYPE, "application/octet-stream"), (header::CACHE_CONTROL, cache)], data).into_response()
805
        }
806
        Ok(Ok(None)) => plain(StatusCode::NOT_FOUND, "the log does not hold that tile yet"),
807
        Ok(Err(e)) => plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
808
        Err(e) => plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
809
    }
810
}
811
812
#[cfg(test)]
813
mod tests {
814
    use super::*;
815
816
    #[test]
817
    fn a_reader_leaves_the_files_alone_and_cannot_append() {
818
        let dir = tempfile::tempdir().unwrap();
819
        let log = Log::open(dir.path(), "hub.example/log").unwrap();
820
        log.append(&[entry(0), entry(1)]).unwrap();
821
        // A torn append: an offset whose entry never arrived.
822
        std::fs::OpenOptions::new().append(true).open(dir.path().join("offsets")).unwrap().write_all(&9999u64.to_le_bytes()).unwrap();
823
        let before = std::fs::metadata(dir.path().join("offsets")).unwrap().len();
824
        let reader = Log::open_reader(dir.path(), "hub.example/log").unwrap();
825
        assert_eq!(reader.size(), 2);
826
        assert_eq!(std::fs::metadata(dir.path().join("offsets")).unwrap().len(), before, "the writer's files are untouched");
827
        assert!(reader.append(&[entry(2)]).is_err());
828
        assert_eq!(reader.tree_hash(2).unwrap(), log.tree_hash(2).unwrap());
829
    }
830
831
    fn entry(i: u64) -> Entry {
832
        Entry { kind: "ref".into(), repo: [1; 16], object: ObjectRef([i as u8; 32]), signers: vec![], received: i }
833
    }
834
835
    #[test]
836
    fn the_log_survives_a_torn_append_and_keeps_its_root() {
837
        let dir = tempfile::tempdir().unwrap();
838
        let log = Log::open(dir.path(), "hub.example/log").unwrap();
839
        let first: Vec<Entry> = (0..300).map(entry).collect();
840
        assert_eq!(log.append(&first).unwrap(), (0..300).collect::<Vec<_>>());
841
        let root = log.tree_hash(300).unwrap();
842
        // Leaves alone, as RFC 6962 roots them.
843
        let mut stored: Vec<Hash> = Vec::new();
844
        for (n, e) in first.iter().enumerate() {
845
            stored.extend(tlog::stored_hashes_for_leaf(n as u64, e.leaf_hash(), &stored).unwrap());
846
        }
847
        assert_eq!(root, tlog::tree_hash(300, &stored).unwrap());
848
        drop(log);
849
        // A crash after the entry and part of the hashes were written.
850
        let torn = dir.path().join("hashes");
851
        let len = std::fs::metadata(&torn).unwrap().len();
852
        OpenOptions::new().write(true).open(&torn).unwrap().set_len(len - 40).unwrap();
853
        let mut f = OpenOptions::new().append(true).open(dir.path().join("entries")).unwrap();
854
        f.write_all(&[0, 200, 1, 2]).unwrap(); // a partial entry
855
        let log = Log::open(dir.path(), "hub.example/log").unwrap();
856
        assert_eq!(log.size(), 300);
857
        assert_eq!(log.tree_hash(300).unwrap(), root);
858
        log.append(&[entry(300)]).unwrap();
859
        assert_eq!(log.size(), 301);
860
        let p = log.prove_inclusion(301, 7).unwrap();
861
        tlog::check_inclusion(&p, 301, &log.tree_hash(301).unwrap(), 7, &first[7].leaf_hash()).unwrap();
862
        let c = log.prove_consistency(301, 300).unwrap();
863
        tlog::check_consistency(&c, 301, &log.tree_hash(301).unwrap(), 300, &root).unwrap();
864
        // Tiles and bundles: the full level-0 tile and the partial one.
865
        let full = log.tile(&Tile { level: 0, n: 0, width: 256 }).unwrap().unwrap();
866
        assert_eq!(full.len(), 256 * 32);
867
        assert!(log.tile(&Tile { level: 0, n: 1, width: 45 }).unwrap().is_some());
868
        assert!(log.tile(&Tile { level: 0, n: 1, width: 46 }).unwrap().is_none(), "not yet");
869
        let bundle = log.bundle(&Tile { level: 0, n: 1, width: 45 }).unwrap().unwrap();
870
        assert_eq!(tlog::decode_bundle(&bundle).unwrap()[0], first[256].encode());
871
    }
872
873
    /// oxygenhub#274: writers sharing the directory (each its own handles,
874
    /// as separate processes have) append one at a time, each from the log
875
    /// as the others left it; readers and checkpoints follow.
876
    #[test]
877
    fn writers_sharing_the_directory_append_one_at_a_time() {
878
        let dir = tempfile::tempdir().unwrap();
879
        let a = std::sync::Arc::new(Log::open(dir.path(), "hub.example/log").unwrap());
880
        let b = std::sync::Arc::new(Log::open(dir.path(), "hub.example/log").unwrap());
881
        let reader = Log::open_reader(dir.path(), "hub.example/log").unwrap();
882
        let spawn = |log: std::sync::Arc<Log>, from: u64| {
883
            std::thread::spawn(move || {
884
                let mut got = Vec::new();
885
                for i in 0..150 {
886
                    got.extend(log.append(&[entry(from + i)]).unwrap());
887
                }
888
                got
889
            })
890
        };
891
        let (ta, tb) = (spawn(a.clone(), 0), spawn(b.clone(), 1000));
892
        let mut numbers: Vec<u64> = ta.join().unwrap().into_iter().chain(tb.join().unwrap()).collect();
893
        numbers.sort();
894
        assert_eq!(numbers, (0..300).collect::<Vec<_>>(), "every entry its own place");
895
        assert_eq!((a.size(), b.size(), reader.size()), (300, 300, 300));
896
        let root = a.tree_hash(300).unwrap();
897
        assert_eq!(b.tree_hash(300).unwrap(), root);
898
        let fresh = Log::open(dir.path(), "hub.example/log").unwrap();
899
        assert_eq!(fresh.tree_hash(300).unwrap(), root, "the files are one log");
900
        assert_eq!(b.entry(299).unwrap(), fresh.entry(299).unwrap());
901
        assert_eq!(reader.entry(299).unwrap(), fresh.entry(299).unwrap());
902
        // A checkpoint one signs, the other serves.
903
        let sk = oxy_core::identity::SecretKey::generate();
904
        let hub = sk.identity("hub", "[email protected]", 1);
905
        assert!(a.refresh_checkpoint(&hub, &sk).unwrap());
906
        assert_eq!(b.checkpoint(), a.checkpoint());
907
        assert!(!b.refresh_checkpoint(&hub, &sk).unwrap(), "already covered by the other's");
908
    }
909
910
    #[test]
911
    fn checkpoints_are_signed_when_the_log_grows() {
912
        let dir = tempfile::tempdir().unwrap();
913
        let sk = oxy_core::identity::SecretKey::generate();
914
        let hub = sk.identity("hub", "[email protected]", 1);
915
        let log = Log::open(dir.path(), &origin_of("https://hub.example:7343/")).unwrap();
916
        assert_eq!(log.origin, "hub.example:7343/log");
917
        assert!(log.refresh_checkpoint(&hub, &sk).unwrap(), "the empty log's");
918
        assert!(!log.refresh_checkpoint(&hub, &sk).unwrap(), "nothing new");
919
        log.append(&[entry(1), entry(2)]).unwrap();
920
        assert!(log.refresh_checkpoint(&hub, &sk).unwrap());
921
        let note = tlog::Note::parse(&log.checkpoint().unwrap()).unwrap();
922
        let c = Checkpoint::verify(&note, "hub.example:7343/log", &hub).unwrap();
923
        assert_eq!((c.size, c.root), (2, log.tree_hash(2).unwrap()));
924
        // Kept across a restart.
925
        drop(log);
926
        let log = Log::open(dir.path(), "hub.example:7343/log").unwrap();
927
        assert_eq!(log.checkpoint().map(|n| n.contains("\n2\n")), Some(true));
928
    }
929
}