encore-reqauth 2.0.0-beta.9

The wire protocol of Encore's service-to-service request auth
Documentation
//! Requests from the Encore platform — cron jobs, the dashboard's API calls —
//! and the `x-encore-auth` MAC it signs them with.
//!
//! A cron job's run also says why it runs ([`CRON_TRIGGER_HEADER`]) and
//! which run it is ([`CRON_EXECUTION_HEADER`]). The MAC covers neither.
//!
//! The header is `v2.` followed by the unpadded standard base64 of the signing
//! key's id (a big-endian `u32`) and
//! `HMAC-SHA256(key, "v2\0" date "\0" method "\0" service "\0" path "\0" query)`:
//! the request's `Date` header, its method, the service its `x-encore-service`
//! names (empty when absent), its path percent-decoded, as bytes, which need
//! not be UTF-8, and its query as sent, without the `?` (empty when absent). A
//! request is accepted within [`MAX_SKEW`] of its date.
//!
//! The path is signed decoded, as in v1, so a proxy re-encoding it on the way
//! does not break the MAC; `%2F` and `/` sign the same.
//!
//! The v1 MAC, over the date and path alone, is not accepted: it does not
//! cover the service a request names, so a captured request could be sent to
//! another one. Neither covers the body.

use std::borrow::Cow;
use std::fmt::Display;
use std::time::{Duration, SystemTime};

use base64::engine::general_purpose::STANDARD_NO_PAD;
use base64::Engine as _;
use hmac::Mac as _;
use percent_encoding::percent_decode_str;

use crate::svcauth::EncoreAuthKey;

/// The header a platform request's MAC is in.
pub const AUTH_HEADER: &str = "x-encore-auth";

/// The caller a platform request is made as, in `x-encore-meta-caller`, once
/// verified.
pub const CALLER: &str = "encore:platform";

/// How far a request's date may be from the verifier's clock.
pub const MAX_SKEW: Duration = Duration::from_secs(2 * 60);

/// The header the platform says why it runs a cron job in: `scheduled`, or
/// `manual`.
pub const CRON_TRIGGER_HEADER: &str = "x-encore-cron-trigger";

/// The header the platform names a cron job's run in: the same id each time
/// it sends that run, so the job's endpoint can use it as an idempotency key.
pub const CRON_EXECUTION_HEADER: &str = "x-encore-cron-execution";

/// Whether `name`, lowercase, is one of the headers the platform describes a
/// cron job's run with. Only the platform may send them: a gateway removes
/// them from every request it has not verified as the platform's.
pub fn is_cron_header(name: &str) -> bool {
    name.starts_with("x-encore-cron-")
}

const VERSION: &str = "v2";

type HmacSha256 = hmac::Hmac<sha2::Sha256>;

/// What a platform request's MAC covers.
#[derive(Debug, Clone, Copy)]
pub struct Signed<'a> {
    /// Its `Date` header.
    pub date: &'a str,
    pub method: &'a str,
    /// The service its `x-encore-service` names.
    pub service: Option<&'a str>,
    /// Its path, as sent: percent-encoded.
    pub path: &'a str,
    /// Its query, as sent, without the `?`.
    pub query: Option<&'a str>,
}

impl Signed<'_> {
    fn mac(&self, key: &[u8]) -> HmacSha256 {
        // The decoded bytes, whether or not they are UTF-8, as the platform
        // signs them: two paths that differ only in bytes that are not UTF-8
        // sign differently.
        let path: Cow<'_, [u8]> = percent_decode_str(self.path).into();
        let mut mac = HmacSha256::new_from_slice(key).expect("HMAC takes keys of any length");
        mac.update(VERSION.as_bytes());
        for part in [
            self.date.as_bytes(),
            self.method.as_bytes(),
            self.service.unwrap_or_default().as_bytes(),
            &path,
            self.query.unwrap_or_default().as_bytes(),
        ] {
            mac.update(b"\0");
            mac.update(part);
        }
        mac
    }
}

/// The `x-encore-auth` value for `req`, signed with the key `key_id`.
pub fn sign(key_id: u32, key: &[u8], req: &Signed<'_>) -> String {
    let mac = req.mac(key).finalize().into_bytes();
    let mut raw = Vec::with_capacity(4 + mac.len());
    raw.extend_from_slice(&key_id.to_be_bytes());
    raw.extend_from_slice(&mac);
    format!("{VERSION}.{}", STANDARD_NO_PAD.encode(raw))
}

/// Verifies that `header`, a request's `x-encore-auth`, signs `req` with one
/// of `keys`, at most [`MAX_SKEW`] from `now`.
pub fn verify(
    keys: &[EncoreAuthKey],
    header: &str,
    req: &Signed<'_>,
    now: SystemTime,
) -> Result<(), VerifyError> {
    let encoded = header
        .strip_prefix(VERSION)
        .and_then(|rest| rest.strip_prefix('.'))
        .ok_or(VerifyError::NotV2)?;
    let raw = STANDARD_NO_PAD
        .decode(encoded)
        .map_err(|_| VerifyError::Malformed)?;
    let (key_id, received) = raw.split_first_chunk::<4>().ok_or(VerifyError::Malformed)?;
    let key_id = u32::from_be_bytes(*key_id);

    let date = httpdate::parse_http_date(req.date).map_err(|_| VerifyError::InvalidDate)?;
    let skew = now.duration_since(date).unwrap_or_else(|e| e.duration());
    if skew > MAX_SKEW {
        return Err(VerifyError::DateSkew);
    }

    let key = keys
        .iter()
        .find(|k| k.key_id == key_id)
        .ok_or(VerifyError::UnknownKey(key_id))?;
    let data = key.data.resolve().map_err(VerifyError::ResolveKeyData)?;
    req.mac(data)
        .verify_slice(received)
        .map_err(|_| VerifyError::SignatureMismatch)
}

#[derive(Debug)]
pub enum VerifyError {
    /// The header is not a v2 MAC.
    NotV2,
    Malformed,
    InvalidDate,
    DateSkew,
    UnknownKey(u32),
    ResolveKeyData(Box<dyn std::error::Error + Send + Sync>),
    SignatureMismatch,
}

impl Display for VerifyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use VerifyError::*;
        match self {
            NotV2 => write!(f, "not a v2 platform signature"),
            Malformed => write!(f, "malformed platform signature"),
            InvalidDate => write!(f, "missing or invalid date header"),
            DateSkew => write!(f, "date skew"),
            UnknownKey(id) => write!(f, "unknown platform key {id}"),
            ResolveKeyData(e) => write!(f, "unable to resolve platform key data: {e}"),
            SignatureMismatch => write!(f, "signature mismatch"),
        }
    }
}

impl std::error::Error for VerifyError {}

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

    const DATE: &str = "Thu, 15 Oct 2026 12:00:00 GMT";

    fn now() -> SystemTime {
        httpdate::parse_http_date(DATE).unwrap()
    }

    fn keys() -> Vec<EncoreAuthKey> {
        vec![
            EncoreAuthKey {
                key_id: 1,
                data: Box::new(b"old".to_vec()),
            },
            EncoreAuthKey {
                key_id: 2,
                data: Box::new(b"new".to_vec()),
            },
        ]
    }

    fn cron() -> Signed<'static> {
        Signed {
            date: DATE,
            method: "POST",
            service: Some("email"),
            path: "/internal/welcome%20email",
            query: None,
        }
    }

    #[test]
    fn a_signed_request_verifies_with_its_key() {
        let header = sign(2, b"new", &cron());
        assert!(header.starts_with("v2."), "{header}");
        verify(&keys(), &header, &cron(), now()).unwrap();
        let older = sign(1, b"old", &cron());
        verify(&keys(), &older, &cron(), now()).unwrap();
    }

    #[test]
    fn the_signature_covers_method_service_path_and_query() {
        let header = sign(2, b"new", &cron());
        let changed = [
            Signed {
                method: "GET",
                ..cron()
            },
            Signed {
                service: Some("billing"),
                ..cron()
            },
            Signed {
                service: None,
                ..cron()
            },
            Signed {
                path: "/internal/other",
                ..cron()
            },
            Signed {
                query: Some("all=true"),
                ..cron()
            },
            Signed {
                date: "Thu, 15 Oct 2026 12:00:01 GMT",
                ..cron()
            },
        ];
        for req in changed {
            let err = verify(&keys(), &header, &req, now()).unwrap_err();
            assert!(
                matches!(err, VerifyError::SignatureMismatch),
                "{req:?}: {err}"
            );
        }
    }

    #[test]
    fn the_path_is_compared_decoded() {
        let header = sign(2, b"new", &cron());
        let decoded = Signed {
            path: "/internal/welcome email",
            ..cron()
        };
        verify(&keys(), &header, &decoded, now()).unwrap();
    }

    #[test]
    fn the_path_is_signed_as_its_decoded_bytes() {
        // As the platform signs it: the bytes `%FF` decodes to, which are not
        // UTF-8, as they are.
        let req = Signed {
            path: "/a%FF",
            ..cron()
        };
        let header = sign(2, b"new", &req);
        let mut want = HmacSha256::new_from_slice(b"new").unwrap();
        want.update(b"v2\0Thu, 15 Oct 2026 12:00:00 GMT\0POST\0email\0/a\xff\0");
        let raw = STANDARD_NO_PAD
            .decode(header.strip_prefix("v2.").unwrap())
            .unwrap();
        assert_eq!(raw[4..], want.finalize().into_bytes()[..]);

        // So a path differing only there does not verify with it.
        let other = Signed {
            path: "/a%FE",
            ..cron()
        };
        let err = verify(&keys(), &header, &other, now()).unwrap_err();
        assert!(matches!(err, VerifyError::SignatureMismatch), "{err}");
    }

    #[test]
    fn a_query_cannot_be_moved_into_the_path() {
        // The decoded path is the one field that can hold the separator.
        let header = sign(
            2,
            b"new",
            &Signed {
                path: "/b",
                query: Some("c"),
                ..cron()
            },
        );
        let moved = Signed {
            path: "/b%00c",
            query: None,
            ..cron()
        };
        let err = verify(&keys(), &header, &moved, now()).unwrap_err();
        assert!(matches!(err, VerifyError::SignatureMismatch), "{err}");
    }

    #[test]
    fn a_v1_signature_is_refused() {
        // The v1 form: the bare base64 of the key id and a MAC over the date
        // and path.
        let mut mac = HmacSha256::new_from_slice(b"new").unwrap();
        mac.update(DATE.as_bytes());
        mac.update(b"\0");
        mac.update(b"/internal/welcome email");
        let mut raw = 2u32.to_be_bytes().to_vec();
        raw.extend_from_slice(&mac.finalize().into_bytes());
        let v1 = STANDARD_NO_PAD.encode(raw);
        let err = verify(&keys(), &v1, &cron(), now()).unwrap_err();
        assert!(matches!(err, VerifyError::NotV2), "{err}");
    }

    #[test]
    fn a_request_outside_the_skew_is_refused() {
        let header = sign(2, b"new", &cron());
        for offset in [MAX_SKEW, Duration::from_secs(1)] {
            verify(&keys(), &header, &cron(), now() + offset).unwrap();
            verify(&keys(), &header, &cron(), now() - offset).unwrap();
        }
        let late = now() + MAX_SKEW + Duration::from_secs(1);
        let err = verify(&keys(), &header, &cron(), late).unwrap_err();
        assert!(matches!(err, VerifyError::DateSkew), "{err}");
        let early = now() - MAX_SKEW - Duration::from_secs(1);
        let err = verify(&keys(), &header, &cron(), early).unwrap_err();
        assert!(matches!(err, VerifyError::DateSkew), "{err}");
    }

    #[test]
    fn unknown_keys_and_garbage_are_refused() {
        let header = sign(7, b"new", &cron());
        let err = verify(&keys(), &header, &cron(), now()).unwrap_err();
        assert!(matches!(err, VerifyError::UnknownKey(7)), "{err}");

        let forged = sign(2, b"guess", &cron());
        let err = verify(&keys(), &forged, &cron(), now()).unwrap_err();
        assert!(matches!(err, VerifyError::SignatureMismatch), "{err}");

        for garbage in ["v2.", "v2.!!", "v2.AAA", "v3.AAAAAAAA", ""] {
            assert!(
                verify(&keys(), garbage, &cron(), now()).is_err(),
                "{garbage:?}"
            );
        }

        let no_date = Signed {
            date: "yesterday",
            ..cron()
        };
        let err = verify(&keys(), &header, &no_date, now()).unwrap_err();
        assert!(matches!(err, VerifyError::InvalidDate), "{err}");
    }
}