~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
281 lines · 9.6 KB Raw History
//! STAR archives (`spec/spaces/star.md`), and the profile
//! `atproto-space-repo`, a space repo as one (`spec/SPACES.md`, "STAR").

use crate::Error;
use crate::commit::{self, Commit};
use crate::key::SharedSecret;
use crate::lthash::{self, LtHash};
use crate::mac::{self, Received};
use pds_repo::data::{self, V};

/// The magic bytes: `*l`, version 1, and a null byte.
pub const MAGIC: [u8; 4] = [0x2a, 0x6c, 0x01, 0x00];

/// The most a reader takes, in bytes, of the metadata, a key and a value.
#[derive(Clone, Copy, Debug)]
pub struct Limits {
    pub meta: u64,
    pub key: u64,
    pub value: u64,
}

impl Limits {
    /// STAR's own: none.
    pub const NONE: Limits = Limits {
        meta: u64::MAX,
        key: u64::MAX,
        value: u64::MAX,
    };
}

/// An archive read: its metadata, a DRISL map with a String `$type`, and
/// its pairs, in order, as slices of the bytes read.
#[derive(Clone, Debug, PartialEq)]
pub struct Archive<'a> {
    pub meta: V,
    pub pairs: Vec<(&'a [u8], &'a [u8])>,
}

/// Write an archive: `meta` must be a map with a String `$type`.
pub fn write<'a>(meta: &V, pairs: impl IntoIterator<Item = (&'a [u8], &'a [u8])>) -> Vec<u8> {
    debug_assert!(
        matches!(meta, V::Map(m) if m.iter().any(|(k, v)| k == "$type" && matches!(v, V::Str(_))))
    );
    let meta = data::encode(meta);
    let mut out = MAGIC.to_vec();
    varint(&mut out, meta.len());
    out.extend_from_slice(&meta);
    for (k, v) in pairs {
        out.push(1);
        varint(&mut out, k.len());
        out.extend_from_slice(k);
        varint(&mut out, v.len());
        out.extend_from_slice(v);
    }
    out.push(0);
    out
}

fn varint(out: &mut Vec<u8>, n: usize) {
    let mut n = n as u64;
    while n >= 0x80 {
        out.push((n as u8 & 0x7f) | 0x80);
        n >>= 7;
    }
    out.push(n as u8);
}

/// Read an archive, refusing it whole on any fault, or a length past `limits`.
pub fn read<'a>(bytes: &'a [u8], limits: &Limits) -> Result<Archive<'a>, Error> {
    let mut r = Reader(bytes);
    if r.take(4)? != MAGIC {
        return Err(Error::new("not a STAR archive: no magic bytes"));
    }
    let meta = canonical(r.field(limits.meta, "metadata")?)?;
    if !matches!(&meta, V::Map(m) if m.iter().any(|(k, v)| k == "$type" && matches!(v, V::Str(_))))
    {
        return Err(Error::new("metadata that is not a map with a String $type"));
    }
    let mut pairs = Vec::new();
    loop {
        match r.take(1)?[0] {
            0 if r.0.is_empty() => return Ok(Archive { meta, pairs }),
            0 => return Err(Error::new("bytes after the archive's end")),
            1 => pairs.push((r.field(limits.key, "key")?, r.field(limits.value, "value")?)),
            c => return Err(Error::new(format!("a control byte {c:#04x}"))),
        }
    }
}

struct Reader<'a>(&'a [u8]);

impl<'a> Reader<'a> {
    fn take(&mut self, n: u64) -> Result<&'a [u8], Error> {
        let n = usize::try_from(n)
            .ok()
            .filter(|n| *n <= self.0.len())
            .ok_or_else(|| Error::new("an archive cut short"))?;
        let (got, rest) = self.0.split_at(n);
        self.0 = rest;
        Ok(got)
    }

    /// An unsigned varint: minimally encoded, at most 9 bytes.
    fn varint(&mut self) -> Result<u64, Error> {
        let mut n = 0u64;
        for i in 0..9 {
            let b = self.take(1)?[0];
            n |= u64::from(b & 0x7f) << (7 * i);
            if b < 0x80 {
                if i > 0 && b == 0 {
                    return Err(Error::new("a varint not minimally encoded"));
                }
                return Ok(n);
            }
        }
        Err(Error::new("a varint over 9 bytes"))
    }

    /// A length-prefixed field, of at most `limit` bytes.
    fn field(&mut self, limit: u64, what: &str) -> Result<&'a [u8], Error> {
        let n = self.varint()?;
        if n > limit {
            return Err(Error::new(format!("a {what} over {limit} bytes")));
        }
        self.take(n)
    }
}

/// The DRISL value `bytes` are, if they are its canonical encoding: keys in
/// order, none repeated.
pub fn canonical(bytes: &[u8]) -> Result<V, Error> {
    fn repeats_a_key(v: &V) -> bool {
        match v {
            V::Map(m) => {
                m.windows(2).any(|w| w[0].0 == w[1].0) || m.iter().any(|(_, v)| repeats_a_key(v))
            }
            V::Arr(a) => a.iter().any(repeats_a_key),
            _ => false,
        }
    }
    let v = data::decode(bytes)
        .map_err(|why| Error::new(format!("metadata that is not DRISL: {why}")))?;
    // Encoding sorts a map's keys, so a map read back the same has them in
    // order, and any key repeated next to itself.
    if data::encode(&v) != bytes || repeats_a_key(&v) {
        return Err(Error::new("metadata that is not canonical DRISL"));
    }
    Ok(v)
}

// ---- The atproto-space-repo profile ------------------------------------

/// The profile's `$type`.
pub const REPO_TYPE: &str = "atproto-space-repo";

/// The profile's limits.
pub const REPO_LIMITS: Limits = Limits {
    meta: 65536,
    key: 4096,
    value: 1048576,
};

/// A space repo: its commit, and its records, each its path
/// `{collection}/{rkey}` and its DRISL bytes, in ascending order of path.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SpaceRepo {
    pub commit: Commit,
    pub records: Vec<(String, Vec<u8>)>,
}

/// The archive of a commit and its records: the commit with its `$type` as
/// the metadata, and each record a pair, in ascending order of path.
pub fn write_repo(commit: &Commit, records: &[(String, Vec<u8>)]) -> Vec<u8> {
    let mut sorted: Vec<&(String, Vec<u8>)> = records.iter().collect();
    sorted.sort_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes()));
    debug_assert!(
        sorted.windows(2).all(|w| w[0].0 != w[1].0),
        "a record path twice"
    );
    write_sorted_repo(
        commit,
        sorted
            .into_iter()
            .map(|(k, v)| (k.as_bytes(), v.as_slice())),
    )
}

/// The archive of a commit and its records, given already in strictly
/// ascending order of path, each its path's bytes and its DRISL bytes.
pub fn write_sorted_repo<'a>(
    commit: &Commit,
    records: impl IntoIterator<Item = (&'a [u8], &'a [u8])>,
) -> Vec<u8> {
    let V::Map(mut meta) = commit.to_value() else {
        unreachable!("a commit is a map")
    };
    meta.push(("$type".into(), V::Str(REPO_TYPE.into())));
    write(&V::Map(meta), records)
}

/// Read the archive of `repo`'s repo in `space`, asked for with
/// `key_share` (a `did:key`), whose secret is `secret`, and answered with
/// the headers `mac`: as `read_any_repo`, and refused for another space or
/// repo, a commit MAC that does not check against the headers, or an
/// `Atproto-Space-Commit` naming another commit than the metadata.
pub fn read_repo(
    bytes: &[u8],
    space: &str,
    repo: &str,
    key_share: &str,
    secret: &SharedSecret,
    mac: &Received,
) -> Result<SpaceRepo, Error> {
    let r = read_any_repo(bytes)?;
    if r.commit.space != space || r.commit.repo != repo {
        return Err(Error::new("the archive of another repo"));
    }
    mac::check_commit(mac, key_share, secret, &r.commit)?;
    Ok(r)
}

/// Read the archive of a space repo, of any space and repo, with no MAC, as
/// `importRepo` takes one. Refused whole on a fault of STAR's or a limit
/// passed; metadata not canonical DRISL, not `atproto-space-repo` version 1,
/// or with a commit field missing or of another type; a key that is no
/// record path, or not after the key before it; or `data` other than the
/// LtHash digest of the records. The records' values are not read.
pub fn read_any_repo(bytes: &[u8]) -> Result<SpaceRepo, Error> {
    let archive = read(bytes, &REPO_LIMITS)?;
    let V::Map(meta) = &archive.meta else {
        unreachable!("read answers a map")
    };
    let field = |k: &str| meta.iter().find(|(f, _)| f == k).map(|(_, v)| v);
    let text = |k: &str| match field(k) {
        Some(V::Str(s)) => Ok(s.clone()),
        _ => Err(Error::new(format!("a commit with no String {k}"))),
    };
    if text("$type")? != REPO_TYPE {
        return Err(Error::new("an archive that is not atproto-space-repo"));
    }
    if field("ver") != Some(&V::Int(commit::VERSION)) {
        return Err(Error::new("a commit of another version"));
    }
    let data = match field("data") {
        Some(V::Bytes(b)) => <[u8; 32]>::try_from(b.as_slice())
            .map_err(|_| Error::new("a commit whose data is not 32 bytes"))?,
        _ => return Err(Error::new("a commit with no bytes data")),
    };
    let commit = Commit {
        repo: text("repo")?,
        space: text("space")?,
        rev: text("rev")?,
        data,
    };
    let mut hash = LtHash::new();
    let mut records: Vec<(String, Vec<u8>)> = Vec::with_capacity(archive.pairs.len());
    for (k, v) in archive.pairs {
        let path = std::str::from_utf8(k)
            .ok()
            .filter(|p| is_record_path(p))
            .ok_or_else(|| Error::new("a key that is no record path"))?;
        if records.last().is_some_and(|(prev, _)| prev.as_bytes() >= k) {
            return Err(Error::new("a key not after the key before it"));
        }
        hash.add(&lthash::element(
            path,
            &data::cid_string(&data::cid_of(0x71, v)),
        ));
        records.push((path.to_string(), v.to_vec()));
    }
    if hash.digest() != commit.data {
        return Err(Error::new("data that is not the digest of the records"));
    }
    Ok(SpaceRepo { commit, records })
}

/// Whether `path` is `{collection}/{rkey}`: an NSID, `/`, a record key.
pub fn is_record_path(path: &str) -> bool {
    path.split_once('/')
        .is_some_and(|(c, r)| data::valid_nsid(c) && data::valid_rkey(r))
}