~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
680 lines · 22.8 KB Raw History
//! Issuers' keys (`spec/SPACES-CREDENTIALS.md`, "Issuers' keys"): the
//! `#atproto` key a spaces token is held to. An account here's is the key
//! the server holds for it, with nothing read. Another issuer's is read from
//! its DID document and kept: used with no read for `PDS_DID_CACHE_SECS`,
//! then up to `PDS_DID_CACHE_MAX_SECS` while it is read again in the
//! background; at most one for each 1024 bytes of `PDS_CACHE_BYTES`, the one
//! used longest ago forgotten past that.
//!
//! The keys kept are a list, the one used last first, and an index of its
//! slots by DID: a key used moves to the front, and once the most are kept,
//! the slot at the back is given to the next key read. Each is held packed
//! (`Key::packed`), so that what a key costs stays within what
//! `spec/STORE.md` allows it ("Scale").
//!
//! They are written to `PDS_DATA_DIR/issuer-keys` at a shutdown and at most
//! once a minute while they change, never synced, a new file renamed over
//! the old so that no reader finds half of one; a start reads it back in the
//! background, after which they are written again. The file is `MAGIC`, then
//! each key, the one used last first: its DID's length (2 bytes,
//! big-endian), its DID, its key packed, and when its read began (8 bytes,
//! big-endian, milliseconds since the epoch); then the SHA-256 of all before.

use super::jwt::{Jwt, Key};
use crate::{Service, Shared};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufReader, Read, Seek, Write};
use std::os::unix::fs::FileExt;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

/// The file the keys are written to, in the data directory, and the one
/// written before it is renamed so.
const FILE: &str = "issuer-keys";
const TMP: &str = "issuer-keys.tmp";
/// What the file starts with.
const MAGIC: &[u8] = b"pds issuer-keys 1\n";
/// The bytes of a key packed.
const PACKED: usize = 34;
/// How often the keys are written while they change.
const EVERY: Duration = Duration::from_secs(60);
/// The keys copied out of the list at once to be written, or put into it
/// read back: the list's lock is held for no more.
const BATCH: usize = 1024;
/// One key is kept for each this many bytes of `PDS_CACHE_BYTES`.
const BYTES_EACH: u64 = 1024;
/// No slot: the end of the list.
const NIL: u32 = u32::MAX;

/// A key kept.
struct Slot {
    did: Arc<str>,
    key: [u8; PACKED],
    /// When the read that gave it began, in milliseconds since the epoch.
    at: u64,
    /// The slots used just after it and just before it: `NIL` at the ends.
    newer: u32,
    older: u32,
}

/// The keys kept, the one used last first.
struct Kept {
    index: HashMap<Arc<str>, u32>,
    slots: Vec<Slot>,
    newest: u32,
    oldest: u32,
}

impl Default for Kept {
    fn default() -> Kept {
        Kept {
            index: HashMap::new(),
            slots: Vec::new(),
            newest: NIL,
            oldest: NIL,
        }
    }
}

impl Kept {
    fn unlink(&mut self, i: u32) {
        let (newer, older) = (self.slots[i as usize].newer, self.slots[i as usize].older);
        match newer {
            NIL => self.newest = older,
            n => self.slots[n as usize].older = older,
        }
        match older {
            NIL => self.oldest = newer,
            o => self.slots[o as usize].newer = newer,
        }
    }

    fn link_newest(&mut self, i: u32) {
        let first = self.newest;
        let s = &mut self.slots[i as usize];
        (s.newer, s.older) = (NIL, first);
        match first {
            NIL => self.oldest = i,
            n => self.slots[n as usize].newer = i,
        }
        self.newest = i;
    }

    fn link_oldest(&mut self, i: u32) {
        let last = self.oldest;
        let s = &mut self.slots[i as usize];
        (s.newer, s.older) = (last, NIL);
        match last {
            NIL => self.newest = i,
            o => self.slots[o as usize].older = i,
        }
        self.oldest = i;
    }

    fn used(&mut self, i: u32) {
        if self.newest != i {
            self.unlink(i);
            self.link_newest(i);
        }
    }

    /// `did`'s key and when its read began, if that was less than `max` ms
    /// before `now`: used now.
    fn get(&mut self, did: &str, now: u64, max: u64) -> Option<([u8; PACKED], u64)> {
        let i = *self.index.get(did)?;
        let s = &self.slots[i as usize];
        if now.saturating_sub(s.at) >= max {
            return None;
        }
        let got = (s.key, s.at);
        self.used(i);
        Some(got)
    }

    /// Keep `did`'s key, read at `at`, as used now: once `most` are kept,
    /// in the place of the one used longest ago.
    fn put(&mut self, did: &str, key: [u8; PACKED], at: u64, most: usize) {
        if let Some(&i) = self.index.get(did) {
            let s = &mut self.slots[i as usize];
            (s.key, s.at) = (key, at);
            self.used(i);
            return;
        }
        if self.slots.len() < most {
            let i = self.push(did, key, at, most);
            self.link_newest(i);
            return;
        }
        let i = self.oldest;
        if i == NIL {
            return;
        }
        self.unlink(i);
        let did: Arc<str> = did.into();
        let s = &mut self.slots[i as usize];
        let forgotten = std::mem::replace(&mut s.did, did.clone());
        (s.key, s.at) = (key, at);
        self.index.remove(&forgotten);
        self.index.insert(did, i);
        self.link_newest(i);
    }

    /// Keep `did`'s key, read at `at`, as used before every key kept: unless
    /// one of it is kept already, or `most` are.
    fn put_oldest(&mut self, did: &str, key: [u8; PACKED], at: u64, most: usize) {
        if self.slots.len() >= most || self.index.contains_key(did) {
            return;
        }
        let i = self.push(did, key, at, most);
        self.link_oldest(i);
    }

    /// A new slot, in no place in the list yet.
    fn push(&mut self, did: &str, key: [u8; PACKED], at: u64, most: usize) -> u32 {
        let n = self.slots.len();
        if n == self.slots.capacity() {
            // An eighth more at a time, not twice as many: what each key
            // kept costs stays near what its slot holds.
            self.slots.reserve_exact((n / 8).max(64).min(most - n));
        }
        let did: Arc<str> = did.into();
        self.index.insert(did.clone(), n as u32);
        self.slots.push(Slot {
            did,
            key,
            at,
            newer: NIL,
            older: NIL,
        });
        n as u32
    }

    /// The slots, the one used last first.
    fn order(&self) -> Vec<u32> {
        let mut order = Vec::with_capacity(self.slots.len());
        let mut i = self.newest;
        while i != NIL {
            order.push(i);
            i = self.slots[i as usize].older;
        }
        order
    }
}

/// What the configuration says of the keys kept: how long, in ms, one is
/// used with no read, and at all; and how many are kept.
struct Terms {
    fresh: u64,
    max: u64,
    most: usize,
}

fn terms(s: &Service) -> Terms {
    let c = &s.config;
    Terms {
        fresh: c.did_cache.saturating_mul(1000),
        max: c.did_cache_max.max(c.did_cache).saturating_mul(1000),
        most: if c.did_cache == 0 {
            0
        } else {
            (c.cache_bytes / BYTES_EACH).min(u64::from(NIL - 1)) as usize
        },
    }
}

/// Issuers' keys, as their documents last gave them; each issuer's turn to
/// read its document; and what the file has of them.
#[derive(Default)]
pub(crate) struct Keys {
    kept: Mutex<Kept>,
    /// The turns of the issuers some call reads, or waits to read.
    turns: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
    /// Whether a key was kept since the keys were last written.
    changed: AtomicBool,
    /// Whether what the last run wrote has been read back: until then the
    /// keys are not written, which would leave out what it had.
    read_back: AtomicBool,
    /// Held by a write of the file: one at a time.
    writing: Mutex<()>,
}

/// An issuer's turn to read its document: held, no other read of it goes on.
struct Turn<'a> {
    keys: &'a Keys,
    iss: String,
    held: Option<tokio::sync::OwnedMutexGuard<()>>,
}

impl Drop for Turn<'_> {
    fn drop(&mut self) {
        drop(self.held.take());
        let mut turns = lock(&self.keys.turns);
        if turns
            .get(&self.iss)
            .is_some_and(|m| Arc::strong_count(m) == 1)
        {
            turns.remove(&self.iss);
        }
    }
}

impl Keys {
    /// The key kept of `iss` and when its read began, if that was less than
    /// `max` ms before `now`: used now.
    fn kept(&self, iss: &str, now: u64, max: u64) -> Option<(Key, u64)> {
        let (packed, at) = lock(&self.kept).get(iss, now, max)?;
        Some((Key::unpacked(&packed)?, at))
    }

    /// Keep `iss`'s key, read at `at`, unless none are kept (`most` 0).
    fn keep(&self, iss: &str, key: &Key, at: u64, most: usize) {
        if most == 0 {
            return;
        }
        let packed = key.packed();
        lock(&self.kept).put(iss, packed, at, most);
        self.changed.store(true, Ordering::SeqCst);
    }

    fn mutex(&self, iss: &str) -> Arc<tokio::sync::Mutex<()>> {
        lock(&self.turns)
            .entry(iss.to_string())
            .or_default()
            .clone()
    }

    /// `iss`'s turn, once any read of it under way has ended.
    async fn turn(&self, iss: &str) -> Turn<'_> {
        let held = self.mutex(iss).lock_owned().await;
        Turn {
            keys: self,
            iss: iss.to_string(),
            held: Some(held),
        }
    }

    /// `iss`'s turn, if no read of it is under way.
    fn try_turn(&self, iss: &str) -> Option<Turn<'_>> {
        let held = self.mutex(iss).try_lock_owned().ok();
        // Made either way, so that dropping it forgets a turn no one holds.
        let turn = Turn {
            keys: self,
            iss: iss.to_string(),
            held,
        };
        turn.held.is_some().then_some(turn)
    }

    /// Write the keys kept to `dir`'s file, if one was kept since they were
    /// last written and the last run's have been read back.
    fn write(&self, dir: &Path) -> io::Result<()> {
        if !self.read_back.load(Ordering::SeqCst) {
            return Ok(());
        }
        let _one = lock(&self.writing);
        if !self.changed.swap(false, Ordering::SeqCst) {
            return Ok(());
        }
        let written = self.write_file(dir);
        if written.is_err() {
            self.changed.store(true, Ordering::SeqCst);
        }
        written
    }

    /// A new file, `0600` as every file in the data directory is, renamed
    /// over the old; neither synced. A slot given to another key between
    /// two batches may name a DID twice: the first, used later, is read
    /// back.
    fn write_file(&self, dir: &Path) -> io::Result<()> {
        let order = lock(&self.kept).order();
        let tmp = dir.join(TMP);
        let mut f = pds_store::open_private(
            &tmp,
            std::fs::OpenOptions::new()
                .create(true)
                .write(true)
                .truncate(true),
        )?;
        let mut hash = Sha256::new();
        let mut buf = Vec::with_capacity(BATCH * 128);
        buf.extend_from_slice(MAGIC);
        for batch in order.chunks(BATCH) {
            {
                let kept = lock(&self.kept);
                for &i in batch {
                    let s = &kept.slots[i as usize];
                    let Ok(len) = u16::try_from(s.did.len()) else {
                        continue;
                    };
                    buf.extend_from_slice(&len.to_be_bytes());
                    buf.extend_from_slice(s.did.as_bytes());
                    buf.extend_from_slice(&s.key);
                    buf.extend_from_slice(&s.at.to_be_bytes());
                }
            }
            hash.update(&buf);
            f.write_all(&buf)?;
            buf.clear();
        }
        hash.update(&buf);
        buf.extend_from_slice(&hash.finalize());
        f.write_all(&buf)?;
        drop(f);
        std::fs::rename(&tmp, dir.join(FILE))
    }

    /// Read back the keys `dir`'s file holds, as used before any kept now,
    /// and at most `most` in all: but those read `max` ms before `now` or
    /// longer. A file missing, unreadable, or not as `write_file` makes it
    /// gives none.
    fn read_back(&self, dir: &Path, now: u64, max: u64, most: usize) {
        // What a write cut short left.
        let _ = std::fs::remove_file(dir.join(TMP));
        if most > 0 {
            let _ = self.read_file(&dir.join(FILE), now, max, most);
        }
        self.read_back.store(true, Ordering::SeqCst);
    }

    /// The file checked whole first, and only then its keys taken.
    fn read_file(&self, path: &Path, now: u64, max: u64, most: usize) -> io::Result<()> {
        let bad = || io::Error::new(io::ErrorKind::InvalidData, "not as the server writes it");
        let mut f = File::open(path)?;
        let body = f
            .metadata()?
            .len()
            .checked_sub(32)
            .filter(|b| *b >= MAGIC.len() as u64)
            .ok_or_else(bad)?;
        let mut hash = Sha256::new();
        let mut chunk = vec![0u8; 1 << 16];
        let mut whole = (&f).take(body);
        loop {
            match whole.read(&mut chunk)? {
                0 => break,
                n => hash.update(&chunk[..n]),
            }
        }
        let mut sum = [0u8; 32];
        f.read_exact_at(&mut sum, body)?;
        if hash.finalize()[..] != sum {
            return Err(bad());
        }
        f.rewind()?;
        let mut r = BufReader::new((&f).take(body));
        let mut magic = [0u8; MAGIC.len()];
        r.read_exact(&mut magic)?;
        if magic != MAGIC {
            return Err(bad());
        }
        let mut batch = Vec::with_capacity(BATCH);
        let take = |batch: &mut Vec<(String, [u8; PACKED], u64)>| {
            let mut kept = lock(&self.kept);
            for (did, key, at) in batch.drain(..) {
                kept.put_oldest(&did, key, at, most);
            }
        };
        loop {
            let mut len = [0u8; 2];
            match r.read_exact(&mut len) {
                Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => break,
                read => read?,
            }
            let mut did = vec![0u8; usize::from(u16::from_be_bytes(len))];
            let (mut key, mut at) = ([0u8; PACKED], [0u8; 8]);
            r.read_exact(&mut did)?;
            r.read_exact(&mut key)?;
            r.read_exact(&mut at)?;
            let did = String::from_utf8(did).map_err(|_| bad())?;
            let at = u64::from_be_bytes(at);
            if now.saturating_sub(at) < max {
                batch.push((did, key, at));
            }
            if batch.len() == BATCH {
                take(&mut batch);
            }
        }
        take(&mut batch);
        Ok(())
    }
}

fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}

/// Once the server serves: read back the keys the last run wrote, in the
/// background, a token verified meanwhile as if none were kept; and from
/// then on write them each minute they change.
pub(crate) fn start(svc: &Shared) {
    let s = svc.clone();
    tokio::task::spawn_blocking(move || {
        let t = terms(&s);
        let now = s.limits.clock.now_ms();
        s.space_credentials
            .keys
            .read_back(&s.dir, now, t.max, t.most);
    });
    let weak = Arc::downgrade(svc);
    tokio::spawn(async move {
        loop {
            tokio::time::sleep(EVERY).await;
            let Some(s) = weak.upgrade() else { return };
            let _ = tokio::task::spawn_blocking(move || write(&s)).await;
        }
    });
}

/// Write the keys kept, if one was kept since they were last written: at a
/// shutdown, and each minute.
pub(crate) fn write(s: &Service) {
    if let Err(e) = s.space_credentials.keys.write(&s.dir) {
        crate::ops::failed("writing the issuers' keys", e);
    }
}

/// Why a JWT does not verify against its issuer's key.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Unverified {
    /// The issuer's document cannot be read, or names no `#atproto` key.
    NoKey,
    /// The signature does not verify against it.
    Signature,
}

/// Verify `jwt`'s signature against `iss`'s `#atproto` key. An account
/// here's is tried first against the key the server holds for it. Then a
/// key kept less than `PDS_DID_CACHE_MAX_SECS` is: if it verifies, one kept
/// `PDS_DID_CACHE_SECS` or more is read again after, with no call waiting.
/// With none kept, or one that does not verify, the document is read, once
/// at a time, and the token verifies if it verifies against the key read
/// then.
pub(crate) async fn verify_issuer(
    s: &Shared,
    iss: &str,
    jwt: &Jwt,
    high_s: bool,
) -> Result<(), Unverified> {
    let alg = jwt.header("alg").unwrap_or_default();
    let sig = jwt.signature.as_deref().unwrap_or_default();
    let verifies = |k: &Key| k.verifies(alg, jwt.signed.as_bytes(), sig, high_s);
    if held(s, iss).is_some_and(|k| verifies(&k)) {
        return Ok(());
    }
    let keys = &s.space_credentials.keys;
    let t = terms(s);
    let now = s.limits.clock.now_ms();
    let mut failed = None;
    if let Some((k, at)) = keys.kept(iss, now, t.max) {
        if verifies(&k) {
            if now.saturating_sub(at) >= t.fresh {
                renew(s, iss);
            }
            return Ok(());
        }
        failed = Some(k);
    }
    let _turn = keys.turn(iss).await;
    // Another call may have read it meanwhile.
    if let Some((k, _)) = keys.kept(iss, s.limits.clock.now_ms(), t.max)
        && failed.as_ref() != Some(&k)
    {
        if verifies(&k) {
            return Ok(());
        }
        failed = Some(k);
    }
    let began = s.limits.clock.now_ms();
    let Some(key) = fetch_key(s, iss).await else {
        return Err(if failed.is_some() {
            Unverified::Signature
        } else {
            Unverified::NoKey
        });
    };
    keys.keep(iss, &key, began, t.most);
    if verifies(&key) {
        Ok(())
    } else {
        Err(Unverified::Signature)
    }
}

/// The key the server holds for `did`, an account here: none for a DID
/// that is no account here, or one deleted.
fn held(s: &Service, did: &str) -> Option<Key> {
    let a = s.by_did(did)?;
    if crate::read(&a.state).deleted {
        return None;
    }
    Some(Key::K256(*a.store.signing_key().verifying_key()))
}

/// Read `iss`'s document again, the call that found its key past
/// `PDS_DID_CACHE_SECS` answered: unless another read of it is under way,
/// or one ended since.
fn renew(s: &Shared, iss: &str) {
    let (s, iss) = (s.clone(), iss.to_string());
    tokio::spawn(async move {
        let keys = &s.space_credentials.keys;
        let Some(_turn) = keys.try_turn(&iss) else {
            return;
        };
        let t = terms(&s);
        let began = s.limits.clock.now_ms();
        if keys.kept(&iss, began, t.fresh).is_some() {
            return;
        }
        if let Some(key) = fetch_key(&s, &iss).await {
            keys.keep(&iss, &key, began, t.most);
        }
    });
}

/// `did`'s `#atproto` key, from its document as served now: a `did:plc`'s
/// from the directory, a `did:web`'s through the guard.
async fn fetch_key(s: &Service, did: &str) -> Option<Key> {
    Key::of_document(&crate::space_authz::document(s, did).await?, did)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn key(n: u8) -> [u8; PACKED] {
        Key::K256(
            *k256::ecdsa::SigningKey::from_slice(&[n; 32])
                .unwrap()
                .verifying_key(),
        )
        .packed()
    }

    fn dids(k: &Kept) -> Vec<&str> {
        k.order()
            .into_iter()
            .map(|i| &*k.slots[i as usize].did)
            .collect()
    }

    #[test]
    fn the_key_used_longest_ago_is_forgotten() {
        let mut k = Kept::default();
        for d in ["a", "b", "c"] {
            k.put(d, key(1), 10, 3);
        }
        assert_eq!(dids(&k), ["c", "b", "a"]);
        // Used, `a` is the newest; `b` goes for `d`.
        assert!(k.get("a", 10, 5).is_some());
        k.put("d", key(2), 10, 3);
        assert_eq!(dids(&k), ["d", "a", "c"]);
        assert!(k.get("b", 10, 5).is_none());
        // A key past its time is not used, and moves nowhere.
        assert!(k.get("c", 20, 5).is_none());
        k.put("e", key(3), 20, 3);
        assert_eq!(dids(&k), ["e", "d", "a"]);
        // Read again, a key kept takes its place at the front.
        k.put("a", key(4), 30, 3);
        assert_eq!(dids(&k), ["a", "e", "d"]);
        assert_eq!(k.get("a", 30, 5), Some((key(4), 30)));
        // Read back, keys go behind those kept, and only into room left.
        let mut k = Kept::default();
        k.put("x", key(1), 10, 3);
        k.put_oldest("y", key(2), 10, 3);
        k.put_oldest("x", key(3), 10, 3);
        k.put_oldest("z", key(4), 10, 3);
        k.put_oldest("w", key(5), 10, 3);
        assert_eq!(dids(&k), ["x", "y", "z"]);
        assert_eq!(k.get("x", 10, 5), Some((key(1), 10)));
        assert_eq!(k.index.len(), k.slots.len());
    }

    #[test]
    fn keys_written_are_read_back() {
        let dir = crate::testing::scratch("issuer-keys");
        std::fs::create_dir_all(&dir).unwrap();
        let k = Keys::default();
        let p = Key::P256(
            *p256::ecdsa::SigningKey::from_slice(&[7u8; 32])
                .unwrap()
                .verifying_key(),
        );
        k.keep("did:web:old.example", &p, 1_000, 8);
        k.keep("did:web:a.example", &p, 50_000, 8);
        k.keep("did:plc:b", &Key::unpacked(&key(1)).unwrap(), 60_000, 8);
        // Nothing is written until the last run's keys are read back.
        k.write(&dir).unwrap();
        assert!(!dir.join(FILE).exists());
        k.read_back(&dir, 0, 0, 8);
        k.write(&dir).unwrap();
        use std::os::unix::fs::PermissionsExt;
        let mode = std::fs::metadata(dir.join(FILE))
            .unwrap()
            .permissions()
            .mode();
        assert_eq!(mode & 0o777, 0o600);
        assert!(!dir.join(TMP).exists());
        let back = Keys::default();
        back.keep("did:plc:b", &p, 70_000, 8);
        back.read_back(&dir, 100_000, 60_000, 8);
        let k = lock(&back.kept);
        // `did:plc:b`, read since, keeps its key; the one read 99 s before is dropped.
        assert_eq!(dids(&k), ["did:plc:b", "did:web:a.example"]);
        assert_eq!(k.slots[0].key, p.packed());
        drop(k);
        // A file changed in any byte is as none.
        let mut bytes = std::fs::read(dir.join(FILE)).unwrap();
        let last = bytes.len() - 40;
        bytes[last] ^= 1;
        std::fs::write(dir.join(FILE), &bytes).unwrap();
        let none = Keys::default();
        none.read_back(&dir, 100_000, 60_000, 8);
        assert!(lock(&none.kept).slots.is_empty());
        let _ = std::fs::remove_dir_all(&dir);
    }
}