OXYGENHUB

Coverage / crates/oxy-core/src/repo/transparency.rs 5.3%

9 of 169 lines run, 2 of 26 functions · run #321 on main · run missed

1
//! Checking a host's transparency log on fetch (spec §14.8, oxygenhub#238).
2
//!
3
//! A host that keeps a log sends its latest checkpoint with the refs, and
4
//! for each bookmark's attestation its entry and an inclusion proof. This
5
//! user remembers, per hub, the log's key and the last checkpoint seen
6
//! (`<oxy home>/tlog/<hub>`): the key on first sight, then never another.
7
//! Each new checkpoint must extend the last one, which oxy proves from the
8
//! hub's public tiles (C2SP tlog-tiles); one that does not means the hub
9
//! showed two histories, and the fetch fails. An attestation that is not
10
//! in the log yet, or whose proof does not verify, is only reported while
11
//! the log is new (oxygenhub docs/transparency.md, decision 3).
12
13
use super::*;
14
use crate::credentials::hub_of;
15
use crate::protocol::http_get;
16
use crate::tlog::{self, Checkpoint, Entry, Hash, HashReader, Note, Tile, TlogError};
17
use std::cell::RefCell;
18
19
/// Tiles fetched, by level and number, with the width fetched.
20
type TileCache = RefCell<HashMap<(u32, u64), (Tile, Vec<u8>)>>;
21
22
/// A hub's log as its tiles serve it, for a tree of `size` entries.
23
struct Tiles<'a> {
24
    hub: &'a str,
25
    size: u64,
26
    options: &'a RemoteOptions,
27
    cache: TileCache,
28
}
29
30
impl HashReader for Tiles<'_> {
310×
    fn read_hashes(&self, indexes: &[u64]) -> std::result::Result<Vec<Hash>, TlogError> {
320×
        let mut out = Vec::with_capacity(indexes.len());
330×
        for &i in indexes {
340×
            let (t, ..) = Tile::for_index(i);
350×
            let key = (t.level, t.n);
360×
            if !self.cache.borrow().contains_key(&key) {
370×
                let held =
380×
                    (self.size >> (tlog::TILE_HEIGHT * t.level)) - (t.n << tlog::TILE_HEIGHT);
390×
                let tile = Tile {
400×
                    width: held.min(tlog::TILE_WIDTH) as u32,
410×
                    ..t
420×
                };
430×
                let data = http_get(&format!("{}/log/{}", self.hub, tile.path()), self.options)
440×
                    .map_err(|e| TlogError::Read(e.to_string()))?;
450×
                self.cache.borrow_mut().insert(key, (tile, data));
460×
            }
470×
            let cache = self.cache.borrow();
480×
            let (tile, data) = &cache[&key];
490×
            out.push(tile.hash_at(data, i)?);
50
        }
510×
        Ok(out)
520×
    }
53
}
54
55
/// What this user last saw of a hub's log.
56
struct Seen {
57
    identity: Identity,
58
    checkpoint: Checkpoint,
59
}
60
610×
fn file_name(hub: &str) -> String {
620×
    hub.chars()
630×
        .map(|c| {
640×
            if c.is_ascii_alphanumeric() || c == '.' || c == '-' {
650×
                c
66
            } else {
670×
                '_'
68
            }
690×
        })
700×
        .collect()
710×
}
72
73
impl Repo {
740×
    fn tlog_file(&self, hub: &str) -> PathBuf {
750×
        self.user_config
760×
            .parent()
770×
            .map(Path::to_path_buf)
780×
            .unwrap_or_else(default_home)
790×
            .join("tlog")
800×
            .join(file_name(hub))
810×
    }
82
830×
    fn seen_log(&self, hub: &str) -> Option<Seen> {
840×
        let text = fs::read_to_string(self.tlog_file(hub)).ok()?;
850×
        let (key, note) = text.split_once('\n')?;
860×
        let identity = Identity::decode(&crate::dsse::base64_decode(key)?).ok()?;
870×
        let note = Note::parse(note).ok()?;
88
        Some(Seen {
890×
            checkpoint: Checkpoint::parse(&note.text).ok()?,
900×
            identity,
91
        })
920×
    }
93
940×
    fn remember_log(&self, hub: &str, identity: &Identity, note: &Note) -> Result<()> {
950×
        let path = self.tlog_file(hub);
960×
        if let Some(dir) = path.parent() {
970×
            fs::create_dir_all(dir)?;
980×
        }
990×
        let text = format!(
100
            "{}\n{}",
1010×
            crate::dsse::base64(&identity.encode()),
1020×
            note.encode()
103
        );
1040×
        crate::durable::write_atomic(&path, text.as_bytes())?;
1050×
        Ok(())
1060×
    }
107
108
    /// Check what a refs answer from `url` says about its host's log.
109
    /// Fails only when the host showed two histories (or a log key other
110
    /// than the one it showed before); everything else is a note.
111359×
    pub(crate) fn check_log(
112359×
        &self,
113359×
        url: &str,
114359×
        ca: Option<&Path>,
115359×
        resp: &RefsResponse,
116359×
    ) -> Result<Vec<String>> {
117359×
        let (Some(text), Some(hub)) = (&resp.log, hub_of(url)) else {
118359×
            return Ok(vec![]);
119
        };
1200×
        let mut notes = Vec::new();
1210×
        let unchecked = |why: String| {
1220×
            Ok(vec![format!(
1230×
                "{hub}'s transparency log was not checked: {why}"
1240×
            )])
1250×
        };
1260×
        let note = match Note::parse(text) {
1270×
            Ok(n) => n,
1280×
            Err(e) => return unchecked(e.to_string()),
129
        };
1300×
        let cp = match Checkpoint::parse(&note.text) {
1310×
            Ok(c) => c,
1320×
            Err(e) => return unchecked(e.to_string()),
133
        };
1340×
        let options = RemoteOptions {
1350×
            ca: ca.map(Path::to_path_buf),
1360×
            ..RemoteOptions::default()
1370×
        };
1380×
        let seen = self.seen_log(&hub);
1390×
        let identity = match &seen {
1400×
            Some(s) => s.identity.clone(),
1410×
            None => match http_get(&format!("{hub}/.well-known/oxyhub-key"), &options)
1420×
                .and_then(|b| Ok(Identity::decode(&b)?))
143
            {
1440×
                Ok(i) => i,
1450×
                Err(e) => return unchecked(format!("its key could not be fetched ({e})")),
146
            },
147
        };
1480×
        let two = |why: String| {
1490×
            fail(format!(
150
                "{hub} showed two histories: {why}. Do not trust what it serves; tell its operator. \
151
                 (What this user saw of its log is in {}.)",
1520×
                self.tlog_file(&hub).display()
153
            ))
1540×
        };
1550×
        if let Err(e) = note.verify(&cp.origin, &identity) {
1560×
            return match &seen {
1570×
                Some(_) => two(format!(
1580×
                    "its checkpoint is not signed by the log key it showed before ({e})"
1590×
                )),
1600×
                None => unchecked(e.to_string()),
161
            };
1620×
        }
1630×
        if let Some(s) = &seen {
1640×
            let old = &s.checkpoint;
1650×
            if old.origin != cp.origin {
1660×
                return two(format!("its log is now {}, not {}", cp.origin, old.origin));
1670×
            }
1680×
            if cp.size < old.size {
1690×
                return two(format!(
1700×
                    "its log has {} entries, fewer than the {} it showed before",
1710×
                    cp.size, old.size
1720×
                ));
1730×
            }
1740×
            if cp.size == old.size && cp.root != old.root {
1750×
                return two(format!("two different logs of {} entries", cp.size));
1760×
            }
1770×
            if cp.size > old.size && old.size > 0 {
1780×
                let tiles = Tiles {
1790×
                    hub: &hub,
1800×
                    size: cp.size,
1810×
                    options: &options,
1820×
                    cache: RefCell::new(HashMap::new()),
1830×
                };
1840×
                match tlog::prove_consistency(cp.size, old.size, &tiles).and_then(|p| {
1850×
                    tlog::check_consistency(&p, cp.size, &cp.root, old.size, &old.root)
1860×
                }) {
1870×
                    Ok(()) => {}
188
                    Err(TlogError::ProofFailed) | Err(TlogError::BadIndex(_)) => {
1890×
                        return two(format!(
1900×
                            "its log of {} entries does not extend the one of {} it showed before",
1910×
                            cp.size, old.size
1920×
                        ))
193
                    }
194
                    // Keep the older checkpoint: the next fetch tries again.
1950×
                    Err(e) => return unchecked(format!("its tiles could not be read ({e})")),
196
                }
1970×
            }
1980×
        }
1990×
        self.remember_log(&hub, &identity, &note)?;
2000×
        let mut missing = 0;
2010×
        for r in &resp.refs {
2020×
            let Some(a) = &r.attestation else { continue };
2030×
            let Some(l) = &r.logged else {
2040×
                missing += 1;
2050×
                continue;
206
            };
2070×
            let fits = Entry::decode(&l.entry).is_ok_and(|e| {
2080×
                e.kind == "ref" && e.object == a.attest.hash() && e.repo == a.attest.repo
2090×
            });
2100×
            let included = fits
2110×
                && tlog::check_inclusion(
2120×
                    &l.proof,
2130×
                    cp.size,
2140×
                    &cp.root,
2150×
                    l.index,
2160×
                    &tlog::leaf_hash(&l.entry),
2170×
                )
2180×
                .is_ok();
2190×
            if !included {
2200×
                notes.push(format!(
2210×
                    "{hub}'s log entry {} for {} does not prove its attestation is in the log",
2220×
                    l.index, r.name
2230×
                ));
2240×
            }
225
        }
2260×
        if missing > 0 {
2270×
            notes.push(format!(
228
                "{} of {hub}'s attestations {} not in its transparency log yet (logged within seconds of a push; checked on a later fetch)",
229
                missing,
2300×
                if missing == 1 { "is" } else { "are" }
231
            ));
2320×
        }
2330×
        Ok(notes)
234359×
    }
235
}