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. The feature is **off** until a
17//! secret is configured (`RCMS_SECRET_KEY` or
18//! [`crate::signing::set_secret`]).
19
20/// Mint a preview token for `page_id` that expires at `expires_unix`
21/// (UNIX seconds). Returns `None` when no signing secret is configured.
22#[must_use]
23pub fn mint(tenant_slug: &str, page_id: i64, expires_unix: i64) -> Option<String> {
24    let key = crate::signing::secret()?;
25    Some(mint_with_key(key, tenant_slug, page_id, expires_unix))
26}
27
28/// Verify `token` for `tenant_slug` at `now_unix`; returns the page id
29/// when the signature is valid for this tenant AND the token hasn't
30/// expired. `None` when the secret is unset, the token is
31/// malformed/forged, was minted for another tenant, or has expired.
32#[must_use]
33pub fn verify(tenant_slug: &str, token: &str, now_unix: i64) -> Option<i64> {
34    let key = crate::signing::secret()?;
35    verify_with_key(key, tenant_slug, token, now_unix)
36}
37
38fn mint_with_key(key: &[u8], tenant_slug: &str, page_id: i64, expires_unix: i64) -> String {
39    let payload = format!("{page_id}.{expires_unix}");
40    let sig = signature(key, tenant_slug, &payload);
41    format!("{payload}.{sig}")
42}
43
44fn verify_with_key(key: &[u8], tenant_slug: &str, token: &str, now_unix: i64) -> Option<i64> {
45    let mut parts = token.splitn(3, '.');
46    let page_id: i64 = parts.next()?.parse().ok()?;
47    let expires: i64 = parts.next()?.parse().ok()?;
48    let sig = parts.next()?;
49    if now_unix > expires {
50        return None; // expired
51    }
52    let payload = format!("{page_id}.{expires}");
53    let expected = signature(key, tenant_slug, &payload);
54    if crate::signing::constant_time_eq(sig.as_bytes(), expected.as_bytes()) {
55        Some(page_id)
56    } else {
57        None
58    }
59}
60
61/// 16-hex (64-bit) MAC over the payload — short + URL-friendly, ample
62/// against forgery for a short-lived token.
63fn signature(key: &[u8], tenant_slug: &str, payload: &str) -> String {
64    let signed = format!("{tenant_slug}:{payload}");
65    crate::signing::hmac_sha256_hex(key, signed.as_bytes())[..16].to_owned()
66}
67
68#[cfg(test)]
69mod tests {
70    use super::{mint_with_key, verify_with_key};
71
72    const KEY: &[u8] = b"test-secret";
73
74    #[test]
75    fn round_trips_within_expiry() {
76        let token = mint_with_key(KEY, "acme", 42, 2_000);
77        assert_eq!(verify_with_key(KEY, "acme", &token, 1_000), Some(42));
78        // exactly at expiry is still valid (now <= expires).
79        assert_eq!(verify_with_key(KEY, "acme", &token, 2_000), Some(42));
80    }
81
82    #[test]
83    fn rejects_expired() {
84        let token = mint_with_key(KEY, "acme", 7, 1_000);
85        assert_eq!(verify_with_key(KEY, "acme", &token, 1_001), None);
86    }
87
88    #[test]
89    fn rejects_wrong_key_and_tamper() {
90        let token = mint_with_key(KEY, "acme", 7, 9_999);
91        assert_eq!(verify_with_key(b"other-key", "acme", &token, 0), None);
92        // Tampering the page id breaks the signature (no privilege
93        // escalation to another page).
94        let forged = token.replacen("7.", "8.", 1);
95        assert_eq!(verify_with_key(KEY, "acme", &forged, 0), None);
96        // Extending the expiry breaks the signature.
97        let extended = mint_with_key(KEY, "acme", 7, 9_999).replace("9999", "999999");
98        assert_eq!(verify_with_key(KEY, "acme", &extended, 50_000), None);
99    }
100
101    #[test]
102    fn a_token_minted_on_one_tenant_does_not_verify_on_another() {
103        // Page ids restart at 1 per tenant, so "page 7" exists on both.
104        let token = mint_with_key(KEY, "acme", 7, 9_999);
105        assert_eq!(verify_with_key(KEY, "acme", &token, 0), Some(7));
106        assert_eq!(verify_with_key(KEY, "globex", &token, 0), None);
107    }
108
109    #[test]
110    fn rejects_malformed() {
111        assert_eq!(verify_with_key(KEY, "acme", "garbage", 0), None);
112        assert_eq!(verify_with_key(KEY, "acme", "7.notanumber.abc", 0), None);
113        assert_eq!(verify_with_key(KEY, "acme", "7.1000", 0), None); // missing sig
114    }
115}