encore-reqauth 2.0.0-beta.9

The wire protocol of Encore's service-to-service request auth
Documentation
//! Request Context on the wire (parser ADR 0014): the typed fields an app
//! declares, which travel with a request to every call made for it.
//!
//! A field is one header, `x-encore-meta-ctx-<name>`, holding its JSON value
//! base64url-encoded without padding: a value may be non-ASCII, and a header
//! value read as anything but visible ASCII is read differently by every
//! HTTP library. On a Pub/Sub message, the attribute `encore-ctx-<name>`
//! holds the same encoding.
//!
//! Fields are call metadata like the caller and the user: every entry point
//! strips them from what it is sent, and a call's signature covers them
//! ([`crate::svcauth`]). Their sizes are checked where a field is set, by the
//! SDKs, against [`MAX_FIELD_SIZE`] and [`MAX_FIELDS_SIZE`], so a value too
//! big fails the code that made it rather than a later hop's header limits.

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;

/// The header name prefix of a Request Context field: the field's name
/// follows it.
pub const HEADER_PREFIX: &str = "x-encore-meta-ctx-";

/// The Pub/Sub attribute name prefix of a Request Context field on a message
/// published with it set: the field's name follows it.
pub const ATTRIBUTE_PREFIX: &str = "encore-ctx-";

/// The most bytes one field's encoded value may have: 4 KiB, well within
/// nginx's 8 KiB for a header line.
pub const MAX_FIELD_SIZE: usize = 4096;

/// The most bytes all of a request's fields' encoded values may have
/// together: 8 KiB, half of the 16 KiB Node's HTTP server takes of a
/// request's headers in all by default, leaving the rest to the request.
pub const MAX_FIELDS_SIZE: usize = 8192;

/// The most characters a field's name has, as for every resource name the
/// parser validates.
const MAX_NAME_LEN: usize = 63;

/// `json`, a field's JSON value, as its header and attribute hold it.
pub fn encode(json: &[u8]) -> String {
    URL_SAFE_NO_PAD.encode(json)
}

/// The JSON value `encoded` holds, as [`encode`] wrote it.
pub fn decode(encoded: &str) -> Result<Vec<u8>, DecodeError> {
    URL_SAFE_NO_PAD
        .decode(encoded.trim())
        .map_err(|e| DecodeError(e.to_string()))
}

/// A field value that is not base64url without padding.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecodeError(String);

impl std::fmt::Display for DecodeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "invalid request context field value: {}", self.0)
    }
}

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

/// Whether `name` is a valid field name: kebab-case as the parser has it for
/// every resource, 1 to 63 lowercase letters, digits and hyphens, starting
/// with a letter and ending with a letter or digit.
pub fn valid_name(name: &str) -> bool {
    let bytes = name.as_bytes();
    let (Some(first), Some(last)) = (bytes.first(), bytes.last()) else {
        return false;
    };
    bytes.len() <= MAX_NAME_LEN
        && first.is_ascii_lowercase()
        && (last.is_ascii_lowercase() || last.is_ascii_digit())
        && bytes
            .iter()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
}

/// The header carrying the field `name`.
pub fn header_name(name: &str) -> String {
    format!("{HEADER_PREFIX}{name}")
}

/// The field a header carries, when `header` (lowercase, as HTTP libraries
/// hold names) is a Request Context header.
pub fn field_of(header: &str) -> Option<&str> {
    header.strip_prefix(HEADER_PREFIX)
}

/// Whether `header` (lowercase) is a Request Context header.
pub fn is_field_header(header: &str) -> bool {
    header.starts_with(HEADER_PREFIX)
}

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

    #[test]
    fn a_value_round_trips_without_padding_in_url_safe_characters() {
        let json = "{\"name\":\"Åsa\",\"tags\":[\"a?b\"]}".as_bytes();
        let encoded = encode(json);
        assert!(!encoded.contains('='), "{encoded}");
        assert!(
            encoded
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'),
            "{encoded}"
        );
        assert_eq!(decode(&encoded).unwrap(), json);
        assert!(decode("not base64!").is_err());
    }

    #[test]
    fn names_are_kebab_case() {
        for name in ["user", "tenant-id", "plan2", "a", "feature-flags-v2"] {
            assert!(valid_name(name), "{name}");
        }
        let long = "a".repeat(64);
        for name in [
            "",
            "User",
            "tenant_id",
            "2fa",
            "-user",
            "user-",
            "user.id",
            "üser",
            long.as_str(),
        ] {
            assert!(!valid_name(name), "{name}");
        }
    }

    /// The propagation check tells Request Context by these prefixes, in a
    /// crate the SDK core can depend on.
    #[test]
    fn the_propagation_check_has_the_same_prefixes() {
        use encore_telemetry::propagation;
        assert_eq!(propagation::CONTEXT_HEADER_PREFIX, HEADER_PREFIX);
        assert_eq!(propagation::CONTEXT_ATTRIBUTE_PREFIX, ATTRIBUTE_PREFIX);
    }

    #[test]
    fn a_field_has_a_header_of_its_own() {
        assert_eq!(header_name("user"), "x-encore-meta-ctx-user");
        assert_eq!(field_of("x-encore-meta-ctx-user"), Some("user"));
        assert_eq!(field_of("x-encore-meta-caller"), None);
        assert!(is_field_header("x-encore-meta-ctx-tenant"));
        assert!(!is_field_header("x-encore-meta-authdata"));
    }
}