Skip to main content

encore_reqauth/
reqctx.rs

1//! Request Context on the wire (parser ADR 0014): the typed fields an app
2//! declares, which travel with a request to every call made for it.
3//!
4//! A field is one header, `x-encore-meta-ctx-<name>`, holding its JSON value
5//! base64url-encoded without padding: a value may be non-ASCII, and a header
6//! value read as anything but visible ASCII is read differently by every
7//! HTTP library. On a Pub/Sub message, the attribute `encore-ctx-<name>`
8//! holds the same encoding.
9//!
10//! Fields are call metadata like the caller and the user: every entry point
11//! strips them from what it is sent, and a call's signature covers them
12//! ([`crate::svcauth`]). Their sizes are checked where a field is set, by the
13//! SDKs, against [`MAX_FIELD_SIZE`] and [`MAX_FIELDS_SIZE`], so a value too
14//! big fails the code that made it rather than a later hop's header limits.
15
16use base64::engine::general_purpose::URL_SAFE_NO_PAD;
17use base64::Engine as _;
18
19/// The header name prefix of a Request Context field: the field's name
20/// follows it.
21pub const HEADER_PREFIX: &str = "x-encore-meta-ctx-";
22
23/// The Pub/Sub attribute name prefix of a Request Context field on a message
24/// published with it set: the field's name follows it.
25pub const ATTRIBUTE_PREFIX: &str = "encore-ctx-";
26
27/// The most bytes one field's encoded value may have: 4 KiB, well within
28/// nginx's 8 KiB for a header line.
29pub const MAX_FIELD_SIZE: usize = 4096;
30
31/// The most bytes all of a request's fields' encoded values may have
32/// together: 8 KiB, half of the 16 KiB Node's HTTP server takes of a
33/// request's headers in all by default, leaving the rest to the request.
34pub const MAX_FIELDS_SIZE: usize = 8192;
35
36/// The most characters a field's name has, as for every resource name the
37/// parser validates.
38const MAX_NAME_LEN: usize = 63;
39
40/// `json`, a field's JSON value, as its header and attribute hold it.
41pub fn encode(json: &[u8]) -> String {
42    URL_SAFE_NO_PAD.encode(json)
43}
44
45/// The JSON value `encoded` holds, as [`encode`] wrote it.
46pub fn decode(encoded: &str) -> Result<Vec<u8>, DecodeError> {
47    URL_SAFE_NO_PAD
48        .decode(encoded.trim())
49        .map_err(|e| DecodeError(e.to_string()))
50}
51
52/// A field value that is not base64url without padding.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct DecodeError(String);
55
56impl std::fmt::Display for DecodeError {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        write!(f, "invalid request context field value: {}", self.0)
59    }
60}
61
62impl std::error::Error for DecodeError {}
63
64/// Whether `name` is a valid field name: kebab-case as the parser has it for
65/// every resource, 1 to 63 lowercase letters, digits and hyphens, starting
66/// with a letter and ending with a letter or digit.
67pub fn valid_name(name: &str) -> bool {
68    let bytes = name.as_bytes();
69    let (Some(first), Some(last)) = (bytes.first(), bytes.last()) else {
70        return false;
71    };
72    bytes.len() <= MAX_NAME_LEN
73        && first.is_ascii_lowercase()
74        && (last.is_ascii_lowercase() || last.is_ascii_digit())
75        && bytes
76            .iter()
77            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
78}
79
80/// The header carrying the field `name`.
81pub fn header_name(name: &str) -> String {
82    format!("{HEADER_PREFIX}{name}")
83}
84
85/// The field a header carries, when `header` (lowercase, as HTTP libraries
86/// hold names) is a Request Context header.
87pub fn field_of(header: &str) -> Option<&str> {
88    header.strip_prefix(HEADER_PREFIX)
89}
90
91/// Whether `header` (lowercase) is a Request Context header.
92pub fn is_field_header(header: &str) -> bool {
93    header.starts_with(HEADER_PREFIX)
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn a_value_round_trips_without_padding_in_url_safe_characters() {
102        let json = "{\"name\":\"Åsa\",\"tags\":[\"a?b\"]}".as_bytes();
103        let encoded = encode(json);
104        assert!(!encoded.contains('='), "{encoded}");
105        assert!(
106            encoded
107                .bytes()
108                .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'),
109            "{encoded}"
110        );
111        assert_eq!(decode(&encoded).unwrap(), json);
112        assert!(decode("not base64!").is_err());
113    }
114
115    #[test]
116    fn names_are_kebab_case() {
117        for name in ["user", "tenant-id", "plan2", "a", "feature-flags-v2"] {
118            assert!(valid_name(name), "{name}");
119        }
120        let long = "a".repeat(64);
121        for name in [
122            "",
123            "User",
124            "tenant_id",
125            "2fa",
126            "-user",
127            "user-",
128            "user.id",
129            "üser",
130            long.as_str(),
131        ] {
132            assert!(!valid_name(name), "{name}");
133        }
134    }
135
136    /// The propagation check tells Request Context by these prefixes, in a
137    /// crate the SDK core can depend on.
138    #[test]
139    fn the_propagation_check_has_the_same_prefixes() {
140        use encore_telemetry::propagation;
141        assert_eq!(propagation::CONTEXT_HEADER_PREFIX, HEADER_PREFIX);
142        assert_eq!(propagation::CONTEXT_ATTRIBUTE_PREFIX, ATTRIBUTE_PREFIX);
143    }
144
145    #[test]
146    fn a_field_has_a_header_of_its_own() {
147        assert_eq!(header_name("user"), "x-encore-meta-ctx-user");
148        assert_eq!(field_of("x-encore-meta-ctx-user"), Some("user"));
149        assert_eq!(field_of("x-encore-meta-caller"), None);
150        assert!(is_field_header("x-encore-meta-ctx-tenant"));
151        assert!(!is_field_header("x-encore-meta-authdata"));
152    }
153}