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