Skip to main content

encore_reqauth/
platform.rs

1//! Requests from the Encore platform — cron jobs, the dashboard's API calls —
2//! and the `x-encore-auth` MAC it signs them with.
3//!
4//! A cron job's run also says why it runs ([`CRON_TRIGGER_HEADER`]) and
5//! which run it is ([`CRON_EXECUTION_HEADER`]). The MAC covers neither.
6//!
7//! The header is `v2.` followed by the unpadded standard base64 of the signing
8//! key's id (a big-endian `u32`) and
9//! `HMAC-SHA256(key, "v2\0" date "\0" method "\0" service "\0" path "\0" query)`:
10//! the request's `Date` header, its method, the service its `x-encore-service`
11//! names (empty when absent), its path percent-decoded, as bytes, which need
12//! not be UTF-8, and its query as sent, without the `?` (empty when absent). A
13//! request is accepted within [`MAX_SKEW`] of its date.
14//!
15//! The path is signed decoded, as in v1, so a proxy re-encoding it on the way
16//! does not break the MAC; `%2F` and `/` sign the same.
17//!
18//! The v1 MAC, over the date and path alone, is not accepted: it does not
19//! cover the service a request names, so a captured request could be sent to
20//! another one. Neither covers the body.
21
22use std::borrow::Cow;
23use std::fmt::Display;
24use std::time::{Duration, SystemTime};
25
26use base64::engine::general_purpose::STANDARD_NO_PAD;
27use base64::Engine as _;
28use hmac::Mac as _;
29use percent_encoding::percent_decode_str;
30
31use crate::svcauth::EncoreAuthKey;
32
33/// The header a platform request's MAC is in.
34pub const AUTH_HEADER: &str = "x-encore-auth";
35
36/// The caller a platform request is made as, in `x-encore-meta-caller`, once
37/// verified.
38pub const CALLER: &str = "encore:platform";
39
40/// How far a request's date may be from the verifier's clock.
41pub const MAX_SKEW: Duration = Duration::from_secs(2 * 60);
42
43/// The header the platform says why it runs a cron job in: `scheduled`, or
44/// `manual`.
45pub const CRON_TRIGGER_HEADER: &str = "x-encore-cron-trigger";
46
47/// The header the platform names a cron job's run in: the same id each time
48/// it sends that run, so the job's endpoint can use it as an idempotency key.
49pub const CRON_EXECUTION_HEADER: &str = "x-encore-cron-execution";
50
51/// Whether `name`, lowercase, is one of the headers the platform describes a
52/// cron job's run with. Only the platform may send them: a gateway removes
53/// them from every request it has not verified as the platform's.
54pub fn is_cron_header(name: &str) -> bool {
55    name.starts_with("x-encore-cron-")
56}
57
58const VERSION: &str = "v2";
59
60type HmacSha256 = hmac::Hmac<sha2::Sha256>;
61
62/// What a platform request's MAC covers.
63#[derive(Debug, Clone, Copy)]
64pub struct Signed<'a> {
65    /// Its `Date` header.
66    pub date: &'a str,
67    pub method: &'a str,
68    /// The service its `x-encore-service` names.
69    pub service: Option<&'a str>,
70    /// Its path, as sent: percent-encoded.
71    pub path: &'a str,
72    /// Its query, as sent, without the `?`.
73    pub query: Option<&'a str>,
74}
75
76impl Signed<'_> {
77    fn mac(&self, key: &[u8]) -> HmacSha256 {
78        // The decoded bytes, whether or not they are UTF-8, as the platform
79        // signs them: two paths that differ only in bytes that are not UTF-8
80        // sign differently.
81        let path: Cow<'_, [u8]> = percent_decode_str(self.path).into();
82        let mut mac = HmacSha256::new_from_slice(key).expect("HMAC takes keys of any length");
83        mac.update(VERSION.as_bytes());
84        for part in [
85            self.date.as_bytes(),
86            self.method.as_bytes(),
87            self.service.unwrap_or_default().as_bytes(),
88            &path,
89            self.query.unwrap_or_default().as_bytes(),
90        ] {
91            mac.update(b"\0");
92            mac.update(part);
93        }
94        mac
95    }
96}
97
98/// The `x-encore-auth` value for `req`, signed with the key `key_id`.
99pub fn sign(key_id: u32, key: &[u8], req: &Signed<'_>) -> String {
100    let mac = req.mac(key).finalize().into_bytes();
101    let mut raw = Vec::with_capacity(4 + mac.len());
102    raw.extend_from_slice(&key_id.to_be_bytes());
103    raw.extend_from_slice(&mac);
104    format!("{VERSION}.{}", STANDARD_NO_PAD.encode(raw))
105}
106
107/// Verifies that `header`, a request's `x-encore-auth`, signs `req` with one
108/// of `keys`, at most [`MAX_SKEW`] from `now`.
109pub fn verify(
110    keys: &[EncoreAuthKey],
111    header: &str,
112    req: &Signed<'_>,
113    now: SystemTime,
114) -> Result<(), VerifyError> {
115    let encoded = header
116        .strip_prefix(VERSION)
117        .and_then(|rest| rest.strip_prefix('.'))
118        .ok_or(VerifyError::NotV2)?;
119    let raw = STANDARD_NO_PAD
120        .decode(encoded)
121        .map_err(|_| VerifyError::Malformed)?;
122    let (key_id, received) = raw.split_first_chunk::<4>().ok_or(VerifyError::Malformed)?;
123    let key_id = u32::from_be_bytes(*key_id);
124
125    let date = httpdate::parse_http_date(req.date).map_err(|_| VerifyError::InvalidDate)?;
126    let skew = now.duration_since(date).unwrap_or_else(|e| e.duration());
127    if skew > MAX_SKEW {
128        return Err(VerifyError::DateSkew);
129    }
130
131    let key = keys
132        .iter()
133        .find(|k| k.key_id == key_id)
134        .ok_or(VerifyError::UnknownKey(key_id))?;
135    let data = key.data.resolve().map_err(VerifyError::ResolveKeyData)?;
136    req.mac(data)
137        .verify_slice(received)
138        .map_err(|_| VerifyError::SignatureMismatch)
139}
140
141#[derive(Debug)]
142pub enum VerifyError {
143    /// The header is not a v2 MAC.
144    NotV2,
145    Malformed,
146    InvalidDate,
147    DateSkew,
148    UnknownKey(u32),
149    ResolveKeyData(Box<dyn std::error::Error + Send + Sync>),
150    SignatureMismatch,
151}
152
153impl Display for VerifyError {
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        use VerifyError::*;
156        match self {
157            NotV2 => write!(f, "not a v2 platform signature"),
158            Malformed => write!(f, "malformed platform signature"),
159            InvalidDate => write!(f, "missing or invalid date header"),
160            DateSkew => write!(f, "date skew"),
161            UnknownKey(id) => write!(f, "unknown platform key {id}"),
162            ResolveKeyData(e) => write!(f, "unable to resolve platform key data: {e}"),
163            SignatureMismatch => write!(f, "signature mismatch"),
164        }
165    }
166}
167
168impl std::error::Error for VerifyError {}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    const DATE: &str = "Thu, 15 Oct 2026 12:00:00 GMT";
175
176    fn now() -> SystemTime {
177        httpdate::parse_http_date(DATE).unwrap()
178    }
179
180    fn keys() -> Vec<EncoreAuthKey> {
181        vec![
182            EncoreAuthKey {
183                key_id: 1,
184                data: Box::new(b"old".to_vec()),
185            },
186            EncoreAuthKey {
187                key_id: 2,
188                data: Box::new(b"new".to_vec()),
189            },
190        ]
191    }
192
193    fn cron() -> Signed<'static> {
194        Signed {
195            date: DATE,
196            method: "POST",
197            service: Some("email"),
198            path: "/internal/welcome%20email",
199            query: None,
200        }
201    }
202
203    #[test]
204    fn a_signed_request_verifies_with_its_key() {
205        let header = sign(2, b"new", &cron());
206        assert!(header.starts_with("v2."), "{header}");
207        verify(&keys(), &header, &cron(), now()).unwrap();
208        let older = sign(1, b"old", &cron());
209        verify(&keys(), &older, &cron(), now()).unwrap();
210    }
211
212    #[test]
213    fn the_signature_covers_method_service_path_and_query() {
214        let header = sign(2, b"new", &cron());
215        let changed = [
216            Signed {
217                method: "GET",
218                ..cron()
219            },
220            Signed {
221                service: Some("billing"),
222                ..cron()
223            },
224            Signed {
225                service: None,
226                ..cron()
227            },
228            Signed {
229                path: "/internal/other",
230                ..cron()
231            },
232            Signed {
233                query: Some("all=true"),
234                ..cron()
235            },
236            Signed {
237                date: "Thu, 15 Oct 2026 12:00:01 GMT",
238                ..cron()
239            },
240        ];
241        for req in changed {
242            let err = verify(&keys(), &header, &req, now()).unwrap_err();
243            assert!(
244                matches!(err, VerifyError::SignatureMismatch),
245                "{req:?}: {err}"
246            );
247        }
248    }
249
250    #[test]
251    fn the_path_is_compared_decoded() {
252        let header = sign(2, b"new", &cron());
253        let decoded = Signed {
254            path: "/internal/welcome email",
255            ..cron()
256        };
257        verify(&keys(), &header, &decoded, now()).unwrap();
258    }
259
260    #[test]
261    fn the_path_is_signed_as_its_decoded_bytes() {
262        // As the platform signs it: the bytes `%FF` decodes to, which are not
263        // UTF-8, as they are.
264        let req = Signed {
265            path: "/a%FF",
266            ..cron()
267        };
268        let header = sign(2, b"new", &req);
269        let mut want = HmacSha256::new_from_slice(b"new").unwrap();
270        want.update(b"v2\0Thu, 15 Oct 2026 12:00:00 GMT\0POST\0email\0/a\xff\0");
271        let raw = STANDARD_NO_PAD
272            .decode(header.strip_prefix("v2.").unwrap())
273            .unwrap();
274        assert_eq!(raw[4..], want.finalize().into_bytes()[..]);
275
276        // So a path differing only there does not verify with it.
277        let other = Signed {
278            path: "/a%FE",
279            ..cron()
280        };
281        let err = verify(&keys(), &header, &other, now()).unwrap_err();
282        assert!(matches!(err, VerifyError::SignatureMismatch), "{err}");
283    }
284
285    #[test]
286    fn a_query_cannot_be_moved_into_the_path() {
287        // The decoded path is the one field that can hold the separator.
288        let header = sign(
289            2,
290            b"new",
291            &Signed {
292                path: "/b",
293                query: Some("c"),
294                ..cron()
295            },
296        );
297        let moved = Signed {
298            path: "/b%00c",
299            query: None,
300            ..cron()
301        };
302        let err = verify(&keys(), &header, &moved, now()).unwrap_err();
303        assert!(matches!(err, VerifyError::SignatureMismatch), "{err}");
304    }
305
306    #[test]
307    fn a_v1_signature_is_refused() {
308        // The v1 form: the bare base64 of the key id and a MAC over the date
309        // and path.
310        let mut mac = HmacSha256::new_from_slice(b"new").unwrap();
311        mac.update(DATE.as_bytes());
312        mac.update(b"\0");
313        mac.update(b"/internal/welcome email");
314        let mut raw = 2u32.to_be_bytes().to_vec();
315        raw.extend_from_slice(&mac.finalize().into_bytes());
316        let v1 = STANDARD_NO_PAD.encode(raw);
317        let err = verify(&keys(), &v1, &cron(), now()).unwrap_err();
318        assert!(matches!(err, VerifyError::NotV2), "{err}");
319    }
320
321    #[test]
322    fn a_request_outside_the_skew_is_refused() {
323        let header = sign(2, b"new", &cron());
324        for offset in [MAX_SKEW, Duration::from_secs(1)] {
325            verify(&keys(), &header, &cron(), now() + offset).unwrap();
326            verify(&keys(), &header, &cron(), now() - offset).unwrap();
327        }
328        let late = now() + MAX_SKEW + Duration::from_secs(1);
329        let err = verify(&keys(), &header, &cron(), late).unwrap_err();
330        assert!(matches!(err, VerifyError::DateSkew), "{err}");
331        let early = now() - MAX_SKEW - Duration::from_secs(1);
332        let err = verify(&keys(), &header, &cron(), early).unwrap_err();
333        assert!(matches!(err, VerifyError::DateSkew), "{err}");
334    }
335
336    #[test]
337    fn unknown_keys_and_garbage_are_refused() {
338        let header = sign(7, b"new", &cron());
339        let err = verify(&keys(), &header, &cron(), now()).unwrap_err();
340        assert!(matches!(err, VerifyError::UnknownKey(7)), "{err}");
341
342        let forged = sign(2, b"guess", &cron());
343        let err = verify(&keys(), &forged, &cron(), now()).unwrap_err();
344        assert!(matches!(err, VerifyError::SignatureMismatch), "{err}");
345
346        for garbage in ["v2.", "v2.!!", "v2.AAA", "v3.AAAAAAAA", ""] {
347            assert!(
348                verify(&keys(), garbage, &cron(), now()).is_err(),
349                "{garbage:?}"
350            );
351        }
352
353        let no_date = Signed {
354            date: "yesterday",
355            ..cron()
356        };
357        let err = verify(&keys(), &header, &no_date, now()).unwrap_err();
358        assert!(matches!(err, VerifyError::InvalidDate), "{err}");
359    }
360}