Skip to main content

rustango_cms/
preview_token.rs

1//! Signed preview tokens for decoupled / headless frontends.
2//!
3//! The public API serves **published** pages only (404 on drafts). A
4//! preview token lets an authorized decoupled frontend fetch a page's
5//! **draft** content: the admin mints a short-lived signed token for a
6//! page, the frontend appends it to its API request
7//! (`/api/v2/pages/{id}/?preview_token=…`), and the API serves the
8//! page regardless of status when the token verifies.
9//!
10//! Token shape: `"{page_id}.{expires_unix}.{sig}"`, where `sig` is the
11//! first 16 hex chars of HMAC-SHA256 over
12//! `"{tenant_slug}:{page_id}.{expires_unix}"` keyed by
13//! [`crate::signing::secret`]. The expiry is signed, so it can't be
14//! extended by tampering. The tenant is signed but not carried: every
15//! tenant numbers its pages from 1, so a token must verify only on the
16//! tenant that minted it.
17
18/// Mint a preview token for `page_id` that expires at `expires_unix`
19/// (UNIX seconds).
20#[must_use]
21pub fn mint(tenant_slug: &str, page_id: i64, expires_unix: i64) -> String {
22    mint_with_key(crate::signing::secret(), tenant_slug, page_id, expires_unix)
23}
24
25/// Verify `token` for `tenant_slug` at `now_unix`; returns the page id
26/// when the signature is valid for this tenant AND the token hasn't
27/// expired. `None` when the token is malformed/forged, was minted for
28/// another tenant, or has expired.
29#[must_use]
30pub fn verify(tenant_slug: &str, token: &str, now_unix: i64) -> Option<i64> {
31    verify_with_key(crate::signing::secret(), tenant_slug, token, now_unix)
32}
33
34fn mint_with_key(key: &[u8], tenant_slug: &str, page_id: i64, expires_unix: i64) -> String {
35    let payload = format!("{page_id}.{expires_unix}");
36    let sig = signature(key, tenant_slug, &payload);
37    format!("{payload}.{sig}")
38}
39
40fn verify_with_key(key: &[u8], tenant_slug: &str, token: &str, now_unix: i64) -> Option<i64> {
41    let mut parts = token.splitn(3, '.');
42    let page_id: i64 = parts.next()?.parse().ok()?;
43    let expires: i64 = parts.next()?.parse().ok()?;
44    let sig = parts.next()?;
45    if now_unix > expires {
46        return None; // expired
47    }
48    let payload = format!("{page_id}.{expires}");
49    let expected = signature(key, tenant_slug, &payload);
50    if crate::signing::constant_time_eq(sig.as_bytes(), expected.as_bytes()) {
51        Some(page_id)
52    } else {
53        None
54    }
55}
56
57/// 16-hex (64-bit) MAC over the payload — short + URL-friendly, ample
58/// against forgery for a short-lived token.
59fn signature(key: &[u8], tenant_slug: &str, payload: &str) -> String {
60    let signed = format!("{tenant_slug}:{payload}");
61    crate::signing::hmac_sha256_hex(key, signed.as_bytes())[..16].to_owned()
62}
63
64#[cfg(test)]
65mod tests {
66    use super::{mint_with_key, verify_with_key};
67
68    const KEY: &[u8] = b"test-secret";
69
70    #[test]
71    fn round_trips_within_expiry() {
72        let token = mint_with_key(KEY, "acme", 42, 2_000);
73        assert_eq!(verify_with_key(KEY, "acme", &token, 1_000), Some(42));
74        // exactly at expiry is still valid (now <= expires).
75        assert_eq!(verify_with_key(KEY, "acme", &token, 2_000), Some(42));
76    }
77
78    #[test]
79    fn rejects_expired() {
80        let token = mint_with_key(KEY, "acme", 7, 1_000);
81        assert_eq!(verify_with_key(KEY, "acme", &token, 1_001), None);
82    }
83
84    #[test]
85    fn rejects_wrong_key_and_tamper() {
86        let token = mint_with_key(KEY, "acme", 7, 9_999);
87        assert_eq!(verify_with_key(b"other-key", "acme", &token, 0), None);
88        // Tampering the page id breaks the signature (no privilege
89        // escalation to another page).
90        let forged = token.replacen("7.", "8.", 1);
91        assert_eq!(verify_with_key(KEY, "acme", &forged, 0), None);
92        // Extending the expiry breaks the signature.
93        let extended = mint_with_key(KEY, "acme", 7, 9_999).replace("9999", "999999");
94        assert_eq!(verify_with_key(KEY, "acme", &extended, 50_000), None);
95    }
96
97    #[test]
98    fn a_token_minted_on_one_tenant_does_not_verify_on_another() {
99        // Page ids restart at 1 per tenant, so "page 7" exists on both.
100        let token = mint_with_key(KEY, "acme", 7, 9_999);
101        assert_eq!(verify_with_key(KEY, "acme", &token, 0), Some(7));
102        assert_eq!(verify_with_key(KEY, "globex", &token, 0), None);
103    }
104
105    #[test]
106    fn rejects_malformed() {
107        assert_eq!(verify_with_key(KEY, "acme", "garbage", 0), None);
108        assert_eq!(verify_with_key(KEY, "acme", "7.notanumber.abc", 0), None);
109        assert_eq!(verify_with_key(KEY, "acme", "7.1000", 0), None); // missing sig
110    }
111}