gunnar-core 3.0.0

gunnar's repository model, identity table, ACL and path sandbox. gunnar-ssh, gunnar-grpc and gunnar-cli all sit on it.
Documentation
//! Outbound webhook delivery signatures (the event stream, the outbound leg).
//!
//! A webhook is a subscriber to the event bus that POSTs each event to a
//! configured URL. This module is the part that makes gunnar's webhook worth
//! more than a plain POST: **every delivery is signed**, so the receiver can
//! prove the body came from this gunnar and was not forged or replayed by
//! anything that merely knows the URL.
//!
//! # Why `sshsig`, and why its own namespace
//!
//! The signature is an `sshsig` — the same `SSHSIG` format `ssh-keygen -Y sign`
//! produces and `ssh-keygen -Y verify` checks — exactly as the build record
//! ([`crate::provenance`]), the forge event ([`crate::forge`]) and the signed
//! tree head ([`crate::transparency`]) are. gunnar signs everything this way,
//! and a webhook is not a place to invent a second scheme (one implementation).
//!
//! The receiver verifies with the server's **published public key** and no
//! shared secret: a leaked delivery URL is not a leaked signing key, and a
//! receiver behind a CDN or a queue can still tell a real delivery from a
//! replayed or forged one. That is the property an HMAC shared secret — the
//! GitHub model — cannot give, because with HMAC the verifier holds the same
//! secret the signer does and anything that can verify can also forge.
//!
//! The namespace is [`WEBHOOK_NAMESPACE`], distinct from `git`,
//! `gunnar-provenance`, `gunnar-grpc` and `gunnar-transparency`. `sshsig` binds
//! the namespace into what is signed, so a webhook delivery signature can never
//! be lifted and presented as a commit signature, a build attestation or a
//! control-plane credential, and none of those can be presented as a webhook
//! delivery. A signature is scoped to the one job it was made for.
//!
//! # What is signed
//!
//! The **exact bytes of the request body** — the JSON the receiver reads off
//! the socket, byte for byte. Not a re-serialisation the receiver has to
//! reproduce (JSON has no canonical form, so signing the meaning rather than
//! the bytes would make the signature depend on the receiver's serialiser), and
//! not a digest the receiver has to trust the sender computed. The verifier
//! hashes the body it actually received and checks the signature over that, so
//! a single flipped byte anywhere in transit fails the check.

use base64ct::Encoding as _;

/// The `sshsig` namespace an outbound webhook delivery is signed under.
///
/// Distinct from every other namespace in this repository so a signature made
/// for one job never verifies for another. See the module header.
pub const WEBHOOK_NAMESPACE: &str = "gunnar-webhook";

/// The HTTP header carrying the base64 of the `sshsig` PEM.
///
/// The PEM is `-----BEGIN SSH SIGNATURE-----…` and is multi-line, which an HTTP
/// header value cannot be, so it travels base64-encoded and is decoded back to
/// the PEM `ssh-keygen -Y verify` wants.
pub const SIGNATURE_HEADER: &str = "x-gunnar-signature";
/// The header naming the `sshsig` namespace, so a receiver can build the
/// `ssh-keygen -Y verify -n <namespace>` invocation without hard-coding it.
pub const NAMESPACE_HEADER: &str = "x-gunnar-signature-namespace";
/// The header carrying `SHA256:…`, the fingerprint of the key that signed —
/// which of the server's published keys to verify against.
pub const KEY_FINGERPRINT_HEADER: &str = "x-gunnar-key-fingerprint";
/// The header naming the event kind, e.g. `ref.updated`. Lets a receiver route
/// or drop before parsing the body.
pub const EVENT_HEADER: &str = "x-gunnar-event";
/// The header carrying a per-delivery id (`<epoch>:<seq>`), so a receiver can
/// deduplicate a redelivered event.
pub const DELIVERY_HEADER: &str = "x-gunnar-delivery";
/// The GitHub-compatible HMAC header, set only when an endpoint configures a
/// shared secret. `sha256=<hex>` over the body. The `sshsig` above is the
/// default and the one that does not require the receiver to hold a secret;
/// this exists so a receiver written for GitHub's webhooks can be pointed at
/// gunnar unchanged.
pub const HMAC_HEADER: &str = "x-hub-signature-256";

/// A signed delivery: the fingerprint of the signing key and the `sshsig`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedDelivery {
    /// `SHA256:…` of the key that signed. Goes in [`KEY_FINGERPRINT_HEADER`].
    pub key_fingerprint: String,
    /// The `sshsig`, PEM-armoured.
    pub signature_pem: String,
}

impl SignedDelivery {
    /// The base64 of the PEM, for [`SIGNATURE_HEADER`].
    pub fn signature_header(&self) -> String {
        base64ct::Base64::encode_string(self.signature_pem.as_bytes())
    }
}

/// Sign a delivery body under [`WEBHOOK_NAMESPACE`].
///
/// `body` is the exact request body bytes. See the module header for why it is
/// the bytes and not a re-rendering of their meaning.
pub fn sign_delivery(
    key: &ssh_key::PrivateKey,
    body: &[u8],
) -> Result<SignedDelivery, ssh_key::Error> {
    let signature = key.sign(WEBHOOK_NAMESPACE, ssh_key::HashAlg::Sha512, body)?;
    Ok(SignedDelivery {
        key_fingerprint: key
            .public_key()
            .fingerprint(ssh_key::HashAlg::Sha256)
            .to_string(),
        signature_pem: signature.to_pem(ssh_key::LineEnding::LF)?,
    })
}

/// What went wrong verifying a delivery. The variants a receiver distinguishes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeliveryProblem {
    /// The signature header was not the base64 of a well-formed `sshsig`.
    Malformed(String),
    /// The delivery names a key that is not the one offered to check it.
    WrongKey {
        /// The fingerprint the delivery claims.
        signed_by: String,
        /// The fingerprint of the key given to check it.
        offered: String,
    },
    /// The signature was made under a different namespace — refused before the
    /// verify, so a signature for another job is never reported as verifying.
    WrongNamespace(String),
    /// Well formed, right key, right namespace, and it does not check out —
    /// the body was altered, or it was signed by a different key.
    NotVerified,
}

impl std::fmt::Display for DeliveryProblem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DeliveryProblem::Malformed(why) => {
                write!(
                    f,
                    "the delivery signature is not a well-formed sshsig: {why}"
                )
            }
            DeliveryProblem::WrongKey { signed_by, offered } => write!(
                f,
                "the delivery says it was signed by {signed_by} and was checked against {offered}"
            ),
            DeliveryProblem::WrongNamespace(ns) => write!(
                f,
                "the delivery signature's namespace is {ns:?}, not {WEBHOOK_NAMESPACE:?}"
            ),
            DeliveryProblem::NotVerified => {
                write!(f, "the delivery signature does not verify against the body")
            }
        }
    }
}

/// Verify a signed delivery against a public key.
///
/// `signature_header` is the value of [`SIGNATURE_HEADER`] as received (the
/// base64 of the PEM); `claimed_fingerprint` is [`KEY_FINGERPRINT_HEADER`];
/// `body` is the exact bytes the receiver read. Mirrors
/// [`crate::provenance::verify_build`]: fingerprint before signature, namespace
/// before verify, so a signature by another key or for another purpose is never
/// reported as this one verifying.
///
/// This is the Rust twin of the `ssh-keygen -Y verify` a shell receiver runs;
/// the format is standard `SSHSIG`, so the two agree. The step-by-step guide
/// gives the `ssh-keygen` recipe.
pub fn verify_delivery(
    key: &ssh_key::PublicKey,
    body: &[u8],
    signature_header: &str,
    claimed_fingerprint: &str,
) -> Result<(), DeliveryProblem> {
    let offered = key.fingerprint(ssh_key::HashAlg::Sha256).to_string();
    if offered != claimed_fingerprint {
        return Err(DeliveryProblem::WrongKey {
            signed_by: claimed_fingerprint.to_owned(),
            offered,
        });
    }
    let pem = base64ct::Base64::decode_vec(signature_header.trim())
        .map_err(|err| DeliveryProblem::Malformed(format!("header is not base64: {err}")))?;
    let signature = ssh_key::SshSig::from_pem(&pem)
        .map_err(|err| DeliveryProblem::Malformed(err.to_string()))?;
    if signature.namespace() != WEBHOOK_NAMESPACE {
        return Err(DeliveryProblem::WrongNamespace(
            signature.namespace().to_owned(),
        ));
    }
    key.verify(WEBHOOK_NAMESPACE, body, &signature)
        .map_err(|_| DeliveryProblem::NotVerified)
}

/// The GitHub-compatible `X-Hub-Signature-256` value for `body` under `secret`:
/// `sha256=<hex>` of `HMAC-SHA256(secret, body)`.
///
/// Optional and off by default. It is here for a receiver already written for
/// GitHub; the `sshsig` above is the one gunnar leads with, because it does not
/// make the verifier hold a secret it could also forge with.
pub fn hmac_sha256_header(secret: &[u8], body: &[u8]) -> String {
    format!(
        "sha256={}",
        crate::transparency::hex(&hmac_sha256(secret, body))
    )
}

/// HMAC-SHA256, computed here rather than with a new crate: `sha2` is already a
/// dependency (the crate budget), and HMAC over a fixed hash is the RFC 2104
/// construction and nothing more.
fn hmac_sha256(key: &[u8], message: &[u8]) -> [u8; 32] {
    use sha2::Digest as _;
    const BLOCK: usize = 64; // SHA-256's block size in bytes.
    let mut block = [0u8; BLOCK];
    if key.len() > BLOCK {
        let digest: [u8; 32] = sha2::Sha256::digest(key).into();
        block[..32].copy_from_slice(&digest);
    } else {
        block[..key.len()].copy_from_slice(key);
    }
    let mut ipad = [0x36u8; BLOCK];
    let mut opad = [0x5cu8; BLOCK];
    for i in 0..BLOCK {
        ipad[i] ^= block[i];
        opad[i] ^= block[i];
    }
    let mut inner = sha2::Sha256::new();
    inner.update(ipad);
    inner.update(message);
    let inner: [u8; 32] = inner.finalize().into();
    let mut outer = sha2::Sha256::new();
    outer.update(opad);
    outer.update(inner);
    outer.finalize().into()
}

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

    fn key() -> ssh_key::PrivateKey {
        ssh_key::PrivateKey::from_openssh(crate::mint_ed25519().expect("mint")).expect("parse")
    }

    #[test]
    fn a_signed_delivery_verifies_against_the_signing_key() {
        let key = key();
        let body = br#"{"kind":"ref.updated","seq":7}"#;
        let signed = sign_delivery(&key, body).expect("sign");
        // The applied output: the exact received bytes plus a PASSING verify.
        verify_delivery(
            key.public_key(),
            body,
            &signed.signature_header(),
            &signed.key_fingerprint,
        )
        .expect("a delivery signed by this key must verify against it");
    }

    #[test]
    fn a_delivery_signed_by_another_key_is_refused() {
        // The red first: a body signed with the WRONG key must FAIL. Without
        // the namespace-and-fingerprint discipline this is exactly the check
        // that silently passes.
        let signer = key();
        let attacker = key();
        let body = br#"{"kind":"ref.updated","seq":7}"#;
        let signed = sign_delivery(&attacker, body).expect("sign");
        // Presented as if it came from the server's key.
        let err = verify_delivery(
            signer.public_key(),
            body,
            &signed.signature_header(),
            &signer
                .public_key()
                .fingerprint(ssh_key::HashAlg::Sha256)
                .to_string(),
        )
        .expect_err("a body signed by another key must not verify");
        assert_eq!(err, DeliveryProblem::NotVerified);
    }

    #[test]
    fn a_tampered_body_is_refused() {
        let key = key();
        let body = br#"{"kind":"ref.updated","seq":7}"#;
        let signed = sign_delivery(&key, body).expect("sign");
        let tampered = br#"{"kind":"ref.updated","seq":8}"#;
        let err = verify_delivery(
            key.public_key(),
            tampered,
            &signed.signature_header(),
            &signed.key_fingerprint,
        )
        .expect_err("a single flipped byte in the body must fail the verify");
        assert_eq!(err, DeliveryProblem::NotVerified);
    }

    #[test]
    fn a_signature_from_another_namespace_is_refused() {
        // A provenance signature (a different namespace) must never pass as a
        // webhook delivery. Sign the same bytes under the provenance namespace
        // and present it as a delivery.
        let key = key();
        let body = br#"{"kind":"ref.updated","seq":7}"#;
        let other = key
            .sign(
                crate::provenance::PROVENANCE_NAMESPACE,
                ssh_key::HashAlg::Sha512,
                body,
            )
            .expect("sign under provenance");
        let header = base64ct::Base64::encode_string(
            other
                .to_pem(ssh_key::LineEnding::LF)
                .expect("pem")
                .as_bytes(),
        );
        let fp = key
            .public_key()
            .fingerprint(ssh_key::HashAlg::Sha256)
            .to_string();
        let err = verify_delivery(key.public_key(), body, &header, &fp)
            .expect_err("a signature under another namespace must be refused");
        assert_eq!(
            err,
            DeliveryProblem::WrongNamespace(crate::provenance::PROVENANCE_NAMESPACE.to_owned())
        );
    }

    #[test]
    fn hmac_matches_the_rfc_construction() {
        // A known GitHub-doc vector shape: HMAC-SHA256 is deterministic, so a
        // stable secret/body gives a stable digest. This guards the hand-rolled
        // HMAC against a block-padding bug.
        let mac = hmac_sha256_header(b"It's a Secret to Everybody", b"Hello, World!");
        assert_eq!(
            mac,
            "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17"
        );
    }
}