~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
328 lines · 11.9 KB Raw History
//! The MACs a repo host authenticates a commit or a record with
//! (`spec/SPACES.md`, "MACs"): HTTP Message Signatures of RFC 9421 with the
//! algorithm `hmac-sha256`, keyed with the shared secret of a syncer's key
//! share and the author's KEM key, over a response header describing what
//! the answer holds. A syncer asks for one with `Accept-Signature`; the
//! answer has the covered header, `Signature-Input` and `Signature`.

use crate::Error;
use crate::commit::{Commit, VERSION};
use crate::key::{PublicKey, SharedSecret, hmac, verify_hmac};
use crate::sf::{self, Bare, Dictionary, Member};

/// The request header a syncer asks for a MAC with.
pub const ACCEPT_SIGNATURE: &str = "accept-signature";

/// The one `alg` a MAC may name.
pub const ALG: &str = "hmac-sha256";

/// What a MAC is of: each a tag, and the header it covers, of the same
/// name.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Profile {
    /// A commit, covering `Atproto-Space-Commit`.
    Commit,
    /// A record, covering `Atproto-Space-Record`.
    Record,
}

impl Profile {
    /// The profile's tag, which is also the name of the header it covers,
    /// in lower case.
    pub fn as_str(self) -> &'static str {
        match self {
            Profile::Commit => "atproto-space-commit",
            Profile::Record => "atproto-space-record",
        }
    }
}

/// A MAC asked for: the request's label, its key share, and its Inner List
/// with its parameters, serialized, as the answer's `Signature-Input` and
/// the signature base repeat it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Request {
    pub label: String,
    pub key_share: PublicKey,
    pub signature_params: String,
}

/// Read a request's `Accept-Signature` for the one profile the method
/// answers (several field lines joined by `, `, as RFC 9651 joins them):
/// `Ok(None)` where it asks for no MAC, no header or no member tagged with
/// the profile; an error where it is refused: not a Dictionary, more than
/// one member tagged with the profile, that member covering other than
/// exactly the profile's header with `sf`, its parameters other than a
/// String `keyid`, the `tag` and an `alg` of `hmac-sha256`, or a key share
/// that is no P-256 key.
pub fn read_accept_signature(
    header: Option<&str>,
    profile: Profile,
) -> Result<Option<Request>, Error> {
    let Some(header) = header else {
        return Ok(None);
    };
    let d = sf::parse_dictionary(header)
        .ok_or_else(|| Error::new("an Accept-Signature that is not a Dictionary"))?;
    let (label, items, params) = match sf::tagged(&d, profile.as_str())[..] {
        [] => return Ok(None),
        [one] => one,
        _ => {
            return Err(Error::new(
                "more than one MAC asked for in Accept-Signature",
            ));
        }
    };
    if !covers(items, profile) {
        return Err(Error::new(format!(
            "a MAC asked for over other than exactly (\"{}\";sf)",
            profile.as_str()
        )));
    }
    if let Some((k, _)) = params
        .iter()
        .find(|(k, _)| !matches!(k.as_str(), "keyid" | "tag" | "alg"))
    {
        return Err(Error::new(format!(
            "a MAC asked for with the parameter {k}"
        )));
    }
    if !alg_is_hmac(params) {
        return Err(Error::new(
            "a MAC asked for with an alg other than hmac-sha256",
        ));
    }
    let Some(Bare::String(keyid)) = sf::param(params, "keyid") else {
        return Err(Error::new("a MAC asked for with no String keyid"));
    };
    Ok(Some(Request {
        label: label.to_string(),
        key_share: PublicKey::from_did_key(keyid)?,
        signature_params: sf::serialize_inner_list(items, params),
    }))
}

/// Whether an Inner List's items are exactly the profile's header, a
/// String, with exactly the parameter `sf`, true.
fn covers(items: &[sf::Item], profile: Profile) -> bool {
    matches!(items, [(Bare::String(c), p)]
        if c == profile.as_str() && p[..] == [("sf".to_string(), Bare::Boolean(true))])
}

/// Whether `alg`, if given, is the String `hmac-sha256`.
fn alg_is_hmac(params: &sf::Params) -> bool {
    sf::param(params, "alg").is_none_or(|a| *a == Bare::String(ALG.into()))
}

/// `Atproto-Space-Commit`'s value: the commit's `ver`, `repo`, `space`,
/// `rev` and `data` as a Dictionary, serialized.
pub fn commit_header(commit: &Commit) -> String {
    let item = |b| Member::Item((b, vec![]));
    sf::serialize_dictionary(&vec![
        ("ver".into(), item(Bare::Integer(VERSION))),
        ("repo".into(), item(Bare::String(commit.repo.clone()))),
        ("space".into(), item(Bare::String(commit.space.clone()))),
        ("rev".into(), item(Bare::String(commit.rev.clone()))),
        ("data".into(), item(Bare::Bytes(commit.data.to_vec()))),
    ])
}

/// `Atproto-Space-Record`'s value: the record's full space URI and its CID
/// as a string, as a Dictionary, serialized.
pub fn record_header(uri: &str, cid: &str) -> String {
    let item = |s: &str| Member::Item((Bare::String(s.into()), vec![]));
    sf::serialize_dictionary(&vec![("uri".into(), item(uri)), ("cid".into(), item(cid))])
}

/// The signature base: the profile's component line, the covered header's
/// value as serialized, and `@signature-params`.
pub fn signature_base(profile: Profile, covered: &str, signature_params: &str) -> String {
    format!(
        "\"{}\";sf: {covered}\n\"@signature-params\": {signature_params}",
        profile.as_str()
    )
}

/// HMAC-SHA256 of the signature base, keyed with the shared secret.
pub fn mac(secret: &SharedSecret, base: &str) -> [u8; 32] {
    hmac(&secret.0, &[base.as_bytes()])
}

/// The three headers an answer with a MAC has besides the others (and
/// `Vary` naming `Accept-Signature`): the covered header, `Signature-Input`
/// and `Signature`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MacHeaders {
    pub profile: Profile,
    /// The covered header's value.
    pub covered: String,
    pub signature_input: String,
    pub signature: String,
}

impl MacHeaders {
    /// The answer to `request` of a method answering `commit`, under
    /// `secret`, the shared secret of the request's key share.
    pub fn commit(request: &Request, secret: &SharedSecret, commit: &Commit) -> MacHeaders {
        MacHeaders::new(Profile::Commit, commit_header(commit), request, secret)
    }

    /// The answer to `request` of a method answering the record of `uri`
    /// (its full space URI) and `cid` (its CID as a string).
    pub fn record(request: &Request, secret: &SharedSecret, uri: &str, cid: &str) -> MacHeaders {
        MacHeaders::new(Profile::Record, record_header(uri, cid), request, secret)
    }

    fn new(
        profile: Profile,
        covered: String,
        request: &Request,
        secret: &SharedSecret,
    ) -> MacHeaders {
        let mac = mac(
            secret,
            &signature_base(profile, &covered, &request.signature_params),
        );
        let signature = sf::serialize_dictionary(&vec![(
            request.label.clone(),
            Member::Item((Bare::Bytes(mac.to_vec()), vec![])),
        )]);
        MacHeaders {
            profile,
            covered,
            signature_input: format!("{}={}", request.label, request.signature_params),
            signature,
        }
    }

    /// The headers by name, in lower case.
    pub fn headers(&self) -> [(&'static str, &str); 3] {
        [
            (self.profile.as_str(), &self.covered),
            ("signature-input", &self.signature_input),
            ("signature", &self.signature),
        ]
    }
}

/// The headers of an answer a MAC is checked in, each as received, or None
/// where the answer has none.
#[derive(Clone, Copy, Debug, Default)]
pub struct Received<'a> {
    /// The profile's covered header.
    pub covered: Option<&'a str>,
    pub signature_input: Option<&'a str>,
    pub signature: Option<&'a str>,
}

/// Check, as a syncer does, an answer's MAC of a commit, asked for with
/// `key_share` (a `did:key`), whose secret is `secret`: that it checks, and
/// that its `Atproto-Space-Commit` names `commit`, every field equal and of
/// its type.
pub fn check_commit(
    h: &Received,
    key_share: &str,
    secret: &SharedSecret,
    commit: &Commit,
) -> Result<(), Error> {
    let d = check(Profile::Commit, h, key_share, secret)?;
    let names = d.len() == 5
        && field(&d, "ver") == Some(&Bare::Integer(VERSION))
        && field(&d, "repo") == Some(&Bare::String(commit.repo.clone()))
        && field(&d, "space") == Some(&Bare::String(commit.space.clone()))
        && field(&d, "rev") == Some(&Bare::String(commit.rev.clone()))
        && field(&d, "data") == Some(&Bare::Bytes(commit.data.to_vec()));
    if !names {
        return Err(Error::new(
            "an Atproto-Space-Commit that names another commit",
        ));
    }
    Ok(())
}

/// Check, as a syncer does, an answer's MAC of a record: as `check_commit`,
/// its `Atproto-Space-Record` naming `uri` and `cid` (a string).
pub fn check_record(
    h: &Received,
    key_share: &str,
    secret: &SharedSecret,
    uri: &str,
    cid: &str,
) -> Result<(), Error> {
    let d = check(Profile::Record, h, key_share, secret)?;
    let names = d.len() == 2
        && field(&d, "uri") == Some(&Bare::String(uri.into()))
        && field(&d, "cid") == Some(&Bare::String(cid.into()));
    if !names {
        return Err(Error::new(
            "an Atproto-Space-Record that names another record",
        ));
    }
    Ok(())
}

/// The bare item of a member of `d` that is an Item with no parameters.
fn field<'a>(d: &'a Dictionary, key: &str) -> Option<&'a Bare> {
    match sf::member(d, key)? {
        Member::Item((bare, p)) if p.is_empty() => Some(bare),
        _ => None,
    }
}

/// Check a MAC: `Signature-Input` has exactly one member tagged with the
/// profile, covering exactly its header with `sf`, its `keyid`, if given,
/// the key share, its `alg`, if given, `hmac-sha256`; `Signature` has a
/// Byte Sequence of 32 bytes with no parameters under its label; and that
/// is the MAC of the base the covered header, read and serialized again,
/// gives. Answers the covered header as read.
fn check(
    profile: Profile,
    h: &Received,
    key_share: &str,
    secret: &SharedSecret,
) -> Result<Dictionary, Error> {
    let refuse = |why: &str| Error::new(why);
    let input = sf::parse_dictionary(
        h.signature_input
            .ok_or_else(|| refuse("no Signature-Input"))?,
    )
    .ok_or_else(|| refuse("a Signature-Input that is not a Dictionary"))?;
    let [(label, items, params)] = sf::tagged(&input, profile.as_str())[..] else {
        return Err(refuse(
            "not exactly one signature tagged with the profile in Signature-Input",
        ));
    };
    if !covers(items, profile) {
        return Err(refuse(
            "a MAC that does not cover exactly the profile's header, with sf",
        ));
    }
    if sf::param(params, "keyid").is_some_and(|k| *k != Bare::String(key_share.into())) {
        return Err(refuse("a MAC whose keyid is not the key share asked with"));
    }
    if !alg_is_hmac(params) {
        return Err(refuse("a MAC of another alg"));
    }
    let signature = sf::parse_dictionary(h.signature.ok_or_else(|| refuse("no Signature"))?)
        .ok_or_else(|| refuse("a Signature that is not a Dictionary"))?;
    let Some(Member::Item((Bare::Bytes(got), p))) = sf::member(&signature, label) else {
        return Err(refuse("no Byte Sequence of the MAC's label in Signature"));
    };
    if !p.is_empty() || got.len() != 32 {
        return Err(refuse("a MAC that is not 32 bytes with no parameters"));
    }
    let covered = sf::parse_dictionary(
        h.covered
            .ok_or_else(|| refuse("no header the MAC covers"))?,
    )
    .ok_or_else(|| refuse("a covered header that is not a Dictionary"))?;
    let base = signature_base(
        profile,
        &sf::serialize_dictionary(&covered),
        &sf::serialize_inner_list(items, params),
    );
    if !verify_hmac(&secret.0, base.as_bytes(), got) {
        return Err(refuse("a MAC that does not check"));
    }
    Ok(covered)
}