rustango 0.62.0

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Tenant-facing login + session — analog of [`super::operator_console`]
//! but scoped to a single tenant's user pool.
//!
//! The tenant admin (built via [`crate::tenancy::admin::TenantAdminBuilder`])
//! opts in by calling `with_session(SessionSecret)`. With the opt-in:
//!
//! * `GET  /__login` / `POST /__login` — tenant login form, verified
//!   against `rustango_users` in the resolved tenant's storage.
//! * `POST /__logout` — clear cookie.
//! * `GET  /__static__/rustango.png` — embedded brand image.
//! * Every other path requires a valid session cookie. Anon traffic
//!   gets `303 → /__login?next=<sanitized-path>`.
//! * Authenticated **superusers** get full read/write admin.
//! * Authenticated **non-superusers** get a `read_only_all` admin —
//!   list/detail views render but every mutating route returns 403
//!   and write-buttons are hidden.
//!
//! ## Cookie shape
//!
//! Cookie name `rustango_tenant_session`. Payload + HMAC-SHA256
//! signature, same wire format as the operator console
//! (`<base64url(payload)>.<base64url(hmac)>`). Payload includes the
//! tenant `slug` so a cookie minted for `acme` can't authenticate at
//! `globex` even if the browser somehow forwards it.

use serde::{Deserialize, Serialize};

use super::session::SessionError;
pub use super::session::{PasswordFingerprint, SessionSecret};

/// Signature domain of this token kind: it never verifies as another kind.
const TENANT_DOMAIN_TAG: &[u8] = b"rustango-tenant-session-v1";

/// Default tenant cookie name. Distinct from the operator console's
/// `rustango_op_session` so the two never collide on a host that
/// serves both UIs.
pub const COOKIE_NAME: &str = "rustango_tenant_session";

/// Default lifetime — 7 days, matches the operator console.
pub const SESSION_TTL_SECS: i64 = 7 * 24 * 60 * 60;

/// Default lifetime for an *impersonation* session (operator
/// "Open admin as superuser →"). 1 hour by default — short
/// enough that an idle operator gets dropped before they can
/// forget they're impersonating, long enough for a debugging
/// session. Override via `RUSTANGO_OPERATOR_IMPERSONATION_TTL_SECS`.
/// (#78, v0.27.8)
pub const IMPERSONATION_TTL_SECS: i64 = 60 * 60;

/// Embedded brand image, served at `/__static__/rustango.png`.
pub(crate) const RUSTANGO_PNG: &[u8] = include_bytes!("static/rustango.png");

/// Principal payload carried inside the cookie. Compact field names
/// (`uid`, `slug`, `exp`) keep the cookie short.
///
/// The `slug` field binds the session to a single tenant — the
/// middleware rejects with [`SessionError::WrongTenant`] if the
/// resolved org's slug doesn't match.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TenantSessionPayload {
    /// `rustango_users.id` in the tenant's storage. For
    /// **impersonation** cookies (#78), this is `0` — the
    /// operator is acting as a synthetic principal that doesn't
    /// correspond to any real tenant user. The middleware
    /// branches on `imp.is_some()` rather than `uid`.
    pub uid: i64,
    /// Tenant slug the cookie was minted for.
    pub slug: String,
    /// Org id the cookie was minted for, so a tenant that reuses the slug refuses it.
    /// Required: a cookie without it fails to parse rather than reading as org 0.
    pub org: i64,
    /// Expiry as Unix seconds.
    pub exp: i64,
    /// `Some(operator_id)` when this cookie was minted by the
    /// operator console's "Open admin as superuser →" flow
    /// (#78). The tenant admin treats it as superuser, renders
    /// an impersonation banner, and tags audit-log entries with
    /// `source = "operator:<id>:impersonating"`. `None` for
    /// regular tenant-user logins.
    ///
    /// `#[serde(default)]` keeps cookies minted on pre-0.27.8
    /// servers parseable when the user upgrades.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub imp: Option<i64>,
    /// Issued-at as Unix seconds. A session issued before
    /// `rustango_users.password_changed_at` is rejected. `0` for
    /// cookies minted on pre-0.28.4 servers.
    #[serde(default)]
    pub iat: i64,
    /// Fingerprint of the user's `password_hash` at login, or of the
    /// operator's for impersonation. A password change ends the session.
    #[serde(default)]
    pub pwf: PasswordFingerprint,
    /// An impersonation's id, its handoff `jti`: ending it revokes this id (#2038).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sid: Option<String>,
}

impl TenantSessionPayload {
    /// `pwf` is the [`PasswordFingerprint`] of the user's current hash.
    #[must_use]
    pub fn new(
        user_id: i64,
        tenant: &crate::tenancy::TenantSlug,
        ttl_secs: i64,
        pwf: PasswordFingerprint,
    ) -> Self {
        let now = chrono::Utc::now().timestamp();
        Self {
            uid: user_id,
            slug: tenant.slug.clone(),
            org: tenant.org_id,
            exp: now + ttl_secs,
            imp: None,
            iat: now,
            pwf,
            sid: None,
        }
    }

    /// Mint an impersonation payload — operator-as-superuser
    /// for the named tenant. Distinct from [`Self::new`] so
    /// the call site reads as intent. (#78) `pwf` is the
    /// operator's [`PasswordFingerprint`]; `sid` names the session so it
    /// can be revoked alone (#2038).
    #[must_use]
    pub fn impersonation(
        operator_id: i64,
        tenant: &crate::tenancy::TenantSlug,
        ttl_secs: i64,
        pwf: PasswordFingerprint,
        sid: impl Into<String>,
    ) -> Self {
        let now = chrono::Utc::now().timestamp();
        Self {
            uid: 0,
            slug: tenant.slug.clone(),
            org: tenant.org_id,
            exp: now + ttl_secs,
            imp: Some(operator_id),
            iat: now,
            pwf,
            sid: Some(sid.into()),
        }
    }

    /// `true` for impersonation payloads (operator opened the
    /// tenant admin from the operator console). The middleware
    /// uses this to switch on the auth path. (#78)
    #[must_use]
    pub fn is_impersonation(&self) -> bool {
        self.imp.is_some()
    }
}

impl crate::session::Expiring for TenantSessionPayload {
    fn is_expired_at(&self, now: i64) -> bool {
        now >= self.exp
    }
}

/// Serialize and sign a tenant session payload.
#[must_use]
pub fn encode(secret: &SessionSecret, payload: &TenantSessionPayload) -> String {
    crate::session::SealedToken::seal(secret.key(), TENANT_DOMAIN_TAG, payload)
}

/// Verify, deserialize, and tenant-bind-check a cookie value.
///
/// `tenant` is the resolved tenant — the cookie's `slug` and `org` must
/// match, so a cookie from another tenant, or from a purged tenant whose
/// slug was reused, is refused.
///
/// # Errors
/// * [`SessionError::Malformed`] — bad split, non-base64, bad JSON.
/// * [`SessionError::BadSignature`] — HMAC mismatch.
/// * [`SessionError::Expired`] — `exp` in the past.
/// * [`SessionError::WrongTenant`] — another slug or org id.
pub fn decode(
    secret: &SessionSecret,
    tenant: &crate::tenancy::TenantSlug,
    value: &str,
) -> Result<TenantSessionPayload, SessionError> {
    let payload: TenantSessionPayload =
        crate::session::SealedToken::open(secret.key(), TENANT_DOMAIN_TAG, value)?;
    if !tenant.binds(&payload.slug, payload.org) {
        return Err(SessionError::WrongTenant);
    }
    Ok(payload)
}

#[cfg(test)]
mod tests {
    use super::*;
    use base64::Engine as _;

    fn key() -> SessionSecret {
        SessionSecret::from_bytes(b"a-test-secret-thirty-two-bytes-x".to_vec())
    }

    /// An operator cookie, handoff token or untagged signature over a
    /// tenant-shaped payload is refused under the same key.
    #[test]
    fn a_token_of_another_kind_is_refused() {
        use base64::Engine;
        let secret = key();
        let json = br#"{"uid":7,"slug":"acme","exp":99999999999}"#;
        let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json);
        let tags: [&[u8]; 2] = [
            b"rustango-operator-session-v1",
            b"rustango-impersonation-handoff-v1",
        ];
        let sigs = tags
            .iter()
            .map(|t| crate::session::sign_tagged(&secret, t, b64.as_bytes()))
            .chain([crate::session::sign(&secret, b64.as_bytes())]);
        for sig in sigs {
            let sig_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sig);
            assert!(matches!(
                decode(&secret, &acme(), &format!("{b64}.{sig_b64}")),
                Err(SessionError::BadSignature)
            ));
        }
    }

    fn acme() -> crate::tenancy::TenantSlug {
        crate::tenancy::TenantSlug::new(1, "acme")
    }

    /// A tenant that reuses a purged tenant's slug refuses its cookies,
    /// impersonation included; a cookie with no `org` is refused too.
    #[test]
    fn rejects_cookie_minted_for_a_purged_tenant_with_the_slug() {
        let secret = key();
        let heir = crate::tenancy::TenantSlug::new(2, "acme");
        for p in [
            TenantSessionPayload::new(7, &acme(), 3600, fp()),
            TenantSessionPayload::impersonation(9, &acme(), 3600, fp(), "s1"),
        ] {
            let err = decode(&secret, &heir, &encode(&secret, &p)).unwrap_err();
            assert!(matches!(err, SessionError::WrongTenant));
        }
        let json = br#"{"uid":7,"slug":"acme","exp":99999999999}"#;
        let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json);
        let sig = crate::session::sign_tagged(&secret, TENANT_DOMAIN_TAG, b64.as_bytes());
        let sig_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sig);
        // No `org`, even for org 0: the cookie does not parse.
        let zero = crate::tenancy::TenantSlug::new(0, "acme");
        let err = decode(&secret, &zero, &format!("{b64}.{sig_b64}")).unwrap_err();
        assert!(matches!(err, SessionError::Malformed));
    }

    fn fp() -> PasswordFingerprint {
        PasswordFingerprint::of(&key(), "$argon2id$test")
    }

    #[test]
    fn round_trip_valid_payload() {
        let secret = key();
        let payload = TenantSessionPayload::new(7, &acme(), 3600, fp());
        let cookie = encode(&secret, &payload);
        let back = decode(&secret, &acme(), &cookie).unwrap();
        assert_eq!(back, payload);
    }

    #[test]
    fn rejects_cookie_minted_for_a_different_tenant() {
        let secret = key();
        let payload = TenantSessionPayload::new(7, &acme(), 3600, fp());
        let cookie = encode(&secret, &payload);
        let err = decode(
            &secret,
            &crate::tenancy::TenantSlug::new(2, "globex"),
            &cookie,
        )
        .unwrap_err();
        assert!(matches!(err, SessionError::WrongTenant));
    }

    // v0.27.8 (#78) — impersonation cookie shape regression
    // tests. Pin the wire format so an upgrade can't silently
    // change `imp` semantics.

    #[test]
    fn impersonation_payload_has_imp_set() {
        let p = TenantSessionPayload::impersonation(42, &acme(), 3600, fp(), "s1");
        assert_eq!(p.uid, 0);
        assert_eq!(p.slug, "acme");
        assert_eq!(p.imp, Some(42));
        assert!(p.is_impersonation());
    }

    #[test]
    fn regular_payload_has_no_imp_field() {
        let p = TenantSessionPayload::new(7, &acme(), 3600, fp());
        assert_eq!(p.imp, None);
        assert!(!p.is_impersonation());
    }

    #[test]
    fn impersonation_round_trip_through_cookie() {
        let secret = key();
        let p = TenantSessionPayload::impersonation(99, &acme(), 3600, fp(), "s1");
        let cookie = encode(&secret, &p);
        let back = decode(&secret, &acme(), &cookie).unwrap();
        assert_eq!(back, p);
        assert_eq!(back.imp, Some(99));
    }

    #[test]
    fn impersonation_cookie_still_pinned_to_slug() {
        // Cross-tenant replay must fail even for impersonation
        // cookies — operator opening tenant A shouldn't have a
        // cookie that authenticates them at tenant B.
        let secret = key();
        let p = TenantSessionPayload::impersonation(99, &acme(), 3600, fp(), "s1");
        let cookie = encode(&secret, &p);
        let err = decode(
            &secret,
            &crate::tenancy::TenantSlug::new(2, "globex"),
            &cookie,
        )
        .unwrap_err();
        assert!(matches!(err, SessionError::WrongTenant));
    }

    #[test]
    fn pre_0_27_8_cookie_without_imp_still_decodes() {
        // Old cookie format omits the `imp` field. `serde_default`
        // must fill in `None` so a server upgrade doesn't sign
        // every operator out.
        let secret = key();
        let json = br#"{"uid":7,"slug":"acme","org":1,"exp":99999999999}"#;
        let payload_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json);
        let sig = crate::session::sign_tagged(&secret, TENANT_DOMAIN_TAG, payload_b64.as_bytes());
        let sig_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sig);
        let cookie = format!("{payload_b64}.{sig_b64}");
        let back = decode(&secret, &acme(), &cookie).unwrap();
        assert_eq!(back.uid, 7);
        assert_eq!(back.imp, None);
    }

    #[test]
    fn rejects_tampered_payload() {
        let secret = key();
        let payload = TenantSessionPayload::new(7, &acme(), 3600, fp());
        let cookie = encode(&secret, &payload);
        let (_, sig) = cookie.split_once('.').unwrap();
        let evil = base64::engine::general_purpose::URL_SAFE_NO_PAD
            .encode(br#"{"uid":999,"slug":"acme","exp":9999999999}"#);
        let tampered = format!("{evil}.{sig}");
        let err = decode(&secret, &acme(), &tampered).unwrap_err();
        assert!(matches!(err, SessionError::BadSignature));
    }

    #[test]
    fn rejects_wrong_secret() {
        let s1 = SessionSecret::from_bytes(b"first-test-secret-thirty-2-bytes".to_vec());
        let s2 = SessionSecret::from_bytes(b"second-test-secret-thirty2-bytes".to_vec());
        let cookie = encode(&s1, &TenantSessionPayload::new(1, &acme(), 3600, fp()));
        let err = decode(&s2, &acme(), &cookie).unwrap_err();
        assert!(matches!(err, SessionError::BadSignature));
    }

    #[test]
    fn rejects_expired() {
        let secret = key();
        let cookie = encode(&secret, &TenantSessionPayload::new(1, &acme(), -10, fp()));
        let err = decode(&secret, &acme(), &cookie).unwrap_err();
        assert!(matches!(err, SessionError::Expired));
    }

    /// v0.28.4 (#77) — `iat` is set on every newly-minted payload.
    #[test]
    fn new_payload_stamps_iat_at_construction_time() {
        let p = TenantSessionPayload::new(7, &acme(), 3600, fp());
        let now = chrono::Utc::now().timestamp();
        // iat lands within ±2s of "now" — wide enough to absorb
        // schedule jitter, tight enough to fail if we forgot to
        // populate it.
        assert!((p.iat - now).abs() < 2, "iat = {} but now = {now}", p.iat);
        assert!(p.iat > 0);
        assert_eq!(p.exp - p.iat, 3600);
    }

    /// Pre-0.28.4 cookies don't carry `iat` or `pwf`. They still parse,
    /// with `iat = 0` and an empty fingerprint that never matches.
    #[test]
    fn legacy_pre_v0_28_4_cookie_decodes_with_iat_zero() {
        // Hand-write a payload JSON without `iat` to simulate a
        // pre-0.28.4 cookie.
        use base64::Engine;
        let secret = key();
        let json = br#"{"uid":7,"slug":"acme","org":1,"exp":99999999999}"#;
        let payload_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json);
        let sig = crate::session::sign_tagged(&secret, TENANT_DOMAIN_TAG, payload_b64.as_bytes());
        let sig_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sig);
        let cookie = format!("{payload_b64}.{sig_b64}");
        let p = decode(&secret, &acme(), &cookie).expect("legacy cookie still parses");
        assert_eq!(p.uid, 7);
        assert_eq!(p.iat, 0, "missing iat should default to 0");
        assert_eq!(p.pwf, PasswordFingerprint::default());
    }
}