~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
103 lines · 4.1 KB Raw History
//! The HTTP Message Signature of a request made with a space credential
//! (`spec/SPACES.md`, "HTTP Message Signatures"): RFC 9421 with exactly the
//! choices the page makes. Only the signature: the credential, and whether
//! the audience is the one a request needs, are the caller's.

use crate::Error;
use crate::key::PublicKey;
use crate::sf::{self, Bare, Member};
use p256::ecdsa::signature::Verifier;

/// The `tag` the signature is found by in `Signature-Input`, under any
/// label.
pub const TAG: &str = "atproto-space-credential";

/// The covered components, in order.
pub const COMPONENTS: [&str; 2] = ["authorization", "atproto-space-audience"];

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

/// The headers of a request that a signature covers or is in, each as
/// received, or None where the request has none.
#[derive(Clone, Copy, Debug, Default)]
pub struct Headers<'a> {
    pub authorization: Option<&'a str>,
    pub audience: Option<&'a str>,
    pub signature_input: Option<&'a str>,
    pub signature: Option<&'a str>,
}

/// The signature base: the covered headers' values, less leading and
/// trailing whitespace, and `@signature-params`, the Inner List with its
/// parameters as serialized, three lines joined by a line feed.
pub fn signature_base(authorization: &str, audience: &str, signature_params: &str) -> String {
    let ows = [' ', '\t'];
    format!(
        "\"authorization\": {}\n\"atproto-space-audience\": {}\n\"@signature-params\": {signature_params}",
        authorization.trim_matches(ows),
        audience.trim_matches(ows)
    )
}

/// Verify a request's signature against the credential's key, a P-256
/// `did:key`: the one member of `Signature-Input` tagged
/// `atproto-space-credential`, and the member of `Signature` of the same
/// label. Answers the signature base it verified.
pub fn verify(h: &Headers, key: &str) -> Result<String, Error> {
    let refuse = |why: &str| Error::new(why);
    let public = PublicKey::from_did_key(key)?;
    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, TAG)[..] else {
        return Err(refuse(
            "not exactly one signature tagged atproto-space-credential in Signature-Input",
        ));
    };
    let covered = items.len() == COMPONENTS.len()
        && items
            .iter()
            .zip(COMPONENTS)
            .all(|((bare, p), c)| *bare == Bare::String(c.into()) && p.is_empty());
    if !covered {
        return Err(refuse(
            "a signature that does not cover exactly authorization and atproto-space-audience",
        ));
    }
    if sf::param(params, "alg").is_some_and(|a| *a != Bare::String(ALG.into())) {
        return Err(refuse("a signature of another alg"));
    }
    if sf::param(params, "keyid").is_some_and(|k| *k != Bare::String(key.into())) {
        return Err(refuse(
            "a signature whose keyid is not the credential's key",
        ));
    }
    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(sig), sig_params))) = sf::member(&signature, label) else {
        return Err(refuse(
            "no Byte Sequence in Signature of the signature's label",
        ));
    };
    if !sig_params.is_empty() || sig.len() != 64 {
        return Err(refuse(
            "a signature that is not 64 bytes with no parameters",
        ));
    }
    let base = signature_base(
        h.authorization.ok_or_else(|| refuse("no Authorization"))?,
        h.audience
            .ok_or_else(|| refuse("no Atproto-Space-Audience"))?,
        &sf::serialize_inner_list(items, params),
    );
    let sig =
        p256::ecdsa::Signature::from_slice(sig).map_err(|_| refuse("not an ECDSA signature"))?;
    public
        .verifying_key()
        .verify(base.as_bytes(), &sig)
        .map_err(|_| refuse("a signature that does not verify"))?;
    Ok(base)
}