umbral-core 0.0.12

umbral internals: ORM, migrations, routing, DB backends, the Plugin trait. Do not depend on this directly; use the `umbral` facade.
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! The authentication identity contract — who is the caller?
//!
//! [`Identity`] and [`Authentication`] are the two types every auth
//! backend and every permission class speaks. They live here in
//! `umbral-core` (re-exported from the `umbral` facade at `umbral::auth`)
//! so that `umbral-auth` and `umbral-rest` both depend *inward* on core
//! rather than one depending on the other.
//!
//! This is the architectural fix for gaps2 #76: previously
//! `umbral-auth` depended on `umbral-rest` to get `Identity` and
//! `Authentication`, which forced REST into every app that used auth —
//! even REST-free HTML apps. After this move, `umbral-auth` names
//! `umbral::auth::*` (the facade path), and `umbral-rest` re-exports the
//! same types from here rather than defining them itself.
//!
//! ## Built-ins
//!
//! - [`NoAuthentication`] — always returns `None`. The default; every
//!   request looks anonymous. Pair with `AllowAny` for fully open
//!   endpoints.
//! - [`FnAuthentication`] — wraps an async closure of your shape.
//!   The escape hatch for session-cookie auth (against
//!   `umbral_auth::current_user`), HTTP Basic Auth, API key,
//!   JWT, and anything else.
//! - [`ChainAuthentication`] — try multiple backends in order; first
//!   success wins.
//!
//! Session / Basic / Token / JWT specifics aren't baked into the
//! crate — they're 5-line `FnAuthentication` wrappers in your app
//! code, which avoids forcing a transitive dep on every auth scheme
//! onto users who only need one of them.

use std::pin::Pin;
use std::sync::Arc;

use async_trait::async_trait;
use base64::Engine;
use serde::{Deserialize, Serialize};

use crate::web::{HeaderMap, header};

/// [`Identity::pk`] could not convert the stringified key back to its type.
///
/// In a correctly-configured app this cannot happen — the string was produced by
/// `Display` on that very key type — which is exactly why hand-writing the parse (and its
/// error branch) at every call site is waste.
#[derive(Debug, Clone)]
pub struct IdentityPkError {
    /// The value that would not parse.
    pub value: String,
    /// The Rust type it was asked to become.
    pub target: &'static str,
}

impl std::fmt::Display for IdentityPkError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "umbral: identity primary key `{}` is not a valid `{}` — the active user model's \
             key type and the session's stored key disagree",
            self.value, self.target
        )
    }
}

impl std::error::Error for IdentityPkError {}

/// Who the request belongs to, after authentication.
///
/// The shape is intentionally narrow: `user_id`, `is_staff`, and
/// `is_superuser` cover most permission checks. An `extras` map carries
/// app-specific bits (role names, organisation id, scope strings) for
/// custom permission impls.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Identity {
    /// The authenticated user's primary key, stringified so the same `Identity` shape
    /// works whether the active user model has an `i64`, `String`, or UUID primary key.
    /// The framework's own permissions plugin and session store speak strings.
    ///
    /// **To get the typed key back, use [`Identity::pk`] — not `.parse()`.** This
    /// doc-comment used to say "parse on demand (`identity.user_id.parse::<i64>()`)",
    /// and a live consumer duly wrote that expression ~19 times, each with its own
    /// bespoke error branch for a failure that cannot happen. Documentation that hands
    /// you a snippet is documentation that decides your code; this one was teaching the
    /// boilerplate it should have been replacing. (gaps3 #57.)
    ///
    /// In a handler, prefer not to touch this field at all — the
    /// `RequireAuth<T>` / `RequireStaff` extractors hand you the typed key in the
    /// signature, so a handler that forgot to authenticate cannot be written.
    pub user_id: String,
    /// Staff flag. Used by the
    /// built-in `IsStaff` permission class in `umbral-rest`.
    pub is_staff: bool,
    /// Superuser flag. A
    /// superuser bypasses all permission checks in the built-in
    /// permission classes; custom permission impls can consult this
    /// field to grant unconditional access.
    #[serde(default)]
    pub is_superuser: bool,
    /// App-specific extras a permission check might want to consult.
    /// `umbral-auth` doesn't populate this; user-defined auth backends
    /// can stuff role names, organisation ids, etc. here.
    #[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
    pub extras: std::collections::HashMap<String, serde_json::Value>,
}

impl Identity {
    /// The user's primary key, typed (gaps3 #57).
    ///
    /// `user_id` is a `String` because the framework supports `i64`, `String` and UUID
    /// primary keys behind one `Identity` shape. This converts it back:
    ///
    /// ```ignore
    /// let uid: i64 = identity.pk()?;
    /// ```
    ///
    /// `Err` carries the unparseable value, which is the only useful thing to say about
    /// it — but note that in a correctly-configured app this cannot fail: the string was
    /// produced by `Display` on that very key type. That is precisely why hand-writing
    /// `.parse::<i64>().map_err(|_| some_500())?` at every call site is waste: it is an
    /// error branch for an impossible state, repeated once per handler.
    pub fn pk<T: std::str::FromStr>(&self) -> Result<T, IdentityPkError> {
        self.user_id.parse::<T>().map_err(|_| IdentityPkError {
            value: self.user_id.clone(),
            target: std::any::type_name::<T>(),
        })
    }

    /// Convenience constructor for a non-staff user. Accepts any
    /// stringifiable PK — `Identity::user(42)`, `Identity::user("42")`,
    /// or `Identity::user(uuid.to_string())` all work because the
    /// argument is `impl ToString`.
    pub fn user(user_id: impl ToString) -> Self {
        Self {
            user_id: user_id.to_string(),
            is_staff: false,
            is_superuser: false,
            extras: Default::default(),
        }
    }

    /// Promote to staff. Chainable.
    pub fn staff(mut self) -> Self {
        self.is_staff = true;
        self
    }

    /// Set the staff flag explicitly. Chainable.
    pub fn with_staff(mut self, is_staff: bool) -> Self {
        self.is_staff = is_staff;
        self
    }

    /// Set the superuser flag explicitly. Chainable.
    pub fn with_superuser(mut self, is_superuser: bool) -> Self {
        self.is_superuser = is_superuser;
        self
    }

    /// Insert an extras entry. Chainable.
    pub fn with_extra(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.extras.insert(key.into(), value);
        self
    }

    /// Parse the stringified [`user_id`](Self::user_id) back into the caller's
    /// primary-key type.
    ///
    /// **Deprecated: use [`pk`](Self::pk).** `user_pk` and `pk` do the same
    /// parse; they differ only in the error type. `user_pk` returns the bare
    /// `T::Err`, which carries no context about *what* failed to parse, while
    /// [`pk`](Self::pk) returns a structured [`IdentityPkError`] that names the
    /// unparseable value and the target type. Two methods for one operation is
    /// the confusion this collapses — `pk` is canonical; `user_pk` is retained
    /// only so existing callers keep compiling and is slated for removal.
    ///
    /// `Identity::user_id` is a `String` — the lowest common denominator across
    /// `i64` / `String` / UUID user models. Generic over any `T: FromStr`, so it
    /// works for numeric, string, and UUID keys alike.
    #[deprecated(note = "use `Identity::pk` for a structured `IdentityPkError`")]
    pub fn user_pk<T: std::str::FromStr>(&self) -> Result<T, T::Err> {
        self.user_id.parse()
    }
}

/// The authentication contract. Inspect headers, return an `Identity`
/// if recognised. Async because most real backends hit the DB.
///
/// Object-safe via `async-trait`'s `Pin<Box<...>>` desugaring; that's
/// what makes `Arc<dyn Authentication>` work in `RestPlugin`.
#[async_trait]
pub trait Authentication: Send + Sync + 'static {
    /// Try to identify the caller. `None` means "anonymous"; the
    /// permission check decides whether to allow that.
    ///
    /// Returning an error isn't part of the contract — auth backends
    /// should silently return `None` on invalid credentials and let
    /// the permission check produce a 403. The alternative
    /// (returning a typed error) leaks "which credential you tried"
    /// information to the client.
    async fn authenticate(&self, headers: &HeaderMap) -> Option<Identity>;

    /// OpenAPI `securitySchemes` entry this backend contributes —
    /// `Some((name, scheme_value))` for documented schemes, `None`
    /// to skip.
    ///
    /// `name` is the key under
    /// `components.securitySchemes.<name>`; consumers also reference
    /// it from operation-level `security: [{<name>: []}]` entries.
    /// `scheme_value` is the [OpenAPI 3.0 Security Scheme Object][1]
    /// serialised as a `serde_json::Value`.
    ///
    /// Default `None` — anonymous / no-auth backends contribute
    /// nothing. Concrete classes can override when they want to
    /// document their shape.
    ///
    /// [1]: https://spec.openapis.org/oas/v3.0.3#security-scheme-object
    fn security_scheme(&self) -> Option<(String, serde_json::Value)> {
        None
    }

    /// All `securitySchemes` entries the backend (and any children
    /// it might wrap) contributes. The default impl returns
    /// `self.security_scheme().into_iter().collect()` — fine for
    /// every leaf backend. `ChainAuthentication` overrides to walk
    /// every child so the OpenAPI plugin can publish the full list.
    fn security_schemes_all(&self) -> Vec<(String, serde_json::Value)> {
        self.security_scheme().into_iter().collect()
    }

    /// True when this backend never identifies anyone — every request is
    /// anonymous ([`NoAuthentication`]). Used only by the boot-time
    /// security warning (WEB-1); defaults to `false` so a real backend is
    /// never mistaken for the no-op.
    fn is_anonymous(&self) -> bool {
        false
    }
}

// =========================================================================
// Built-in: NoAuthentication — default. Always anonymous.
// =========================================================================

/// The do-nothing authenticator. Always returns `None`, so the
/// permission check sees anonymous. Default for `RestPlugin`
/// — opt in to real auth via `RestPlugin::authenticate`.
#[derive(Debug, Default, Clone, Copy)]
pub struct NoAuthentication;

#[async_trait]
impl Authentication for NoAuthentication {
    async fn authenticate(&self, _headers: &HeaderMap) -> Option<Identity> {
        None
    }

    fn is_anonymous(&self) -> bool {
        true
    }
}

// =========================================================================
// Built-in: FnAuthentication — wrap any closure.
// =========================================================================

/// `Authentication` from a user-supplied async closure. Keeps the
/// shape pluggable without dragging session / basic / JWT crates into
/// `umbral-rest` itself.
///
/// ```ignore
/// // Session-cookie auth via umbral-sessions:
/// RestPlugin::default().authenticate(FnAuthentication::new(|headers| async move {
///     let user = umbral_auth::current_user(&headers).await.ok().flatten()?;
///     Some(Identity::user(user.id).with_staff(user.is_staff))
/// }));
///
/// // HTTP Basic Auth against umbral-auth:
/// RestPlugin::default().authenticate(FnAuthentication::new(|headers| async move {
///     let (user, pass) = umbral::auth::parse_basic_credentials(&headers)?;
///     let auth_user = umbral_auth::authenticate(&user, &pass).await.ok()?;
///     Some(Identity::user(auth_user.id).with_staff(auth_user.is_staff))
/// }));
/// ```
///
/// The closure takes an owned `HeaderMap` (cheap, internal Bytes
/// references). That lets the future capture the headers without
/// fighting lifetimes.
#[derive(Clone)]
pub struct FnAuthentication {
    f: Arc<
        dyn Fn(HeaderMap) -> Pin<Box<dyn std::future::Future<Output = Option<Identity>> + Send>>
            + Send
            + Sync,
    >,
}

impl std::fmt::Debug for FnAuthentication {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FnAuthentication").finish_non_exhaustive()
    }
}

impl FnAuthentication {
    /// Wrap an async closure as an `Authentication`. The closure
    /// receives a cloned `HeaderMap` and returns `Option<Identity>`.
    pub fn new<F, Fut>(f: F) -> Self
    where
        F: Fn(HeaderMap) -> Fut + Send + Sync + 'static,
        Fut: std::future::Future<Output = Option<Identity>> + Send + 'static,
    {
        Self {
            f: Arc::new(move |headers| Box::pin(f(headers))),
        }
    }
}

#[async_trait]
impl Authentication for FnAuthentication {
    async fn authenticate(&self, headers: &HeaderMap) -> Option<Identity> {
        (self.f)(headers.clone()).await
    }
}

// =========================================================================
// Built-in: ChainAuthentication — first-success wins.
// =========================================================================

/// Try multiple authentications in order. The first one that returns
/// `Some(Identity)` wins; if none succeed, the request is anonymous.
///
/// Common case: session-cookie for browsers, HTTP Basic Auth for
/// curl-style API consumers. Build via [`Self::new`]:
///
/// ```ignore
/// let auth = ChainAuthentication::new(vec![
///     Arc::new(session_auth) as Arc<dyn Authentication>,
///     Arc::new(basic_auth)   as Arc<dyn Authentication>,
/// ]);
/// RestPlugin::default().authenticate(auth);
/// ```
#[derive(Clone)]
pub struct ChainAuthentication {
    backends: Vec<Arc<dyn Authentication>>,
}

impl std::fmt::Debug for ChainAuthentication {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ChainAuthentication")
            .field("backends_count", &self.backends.len())
            .finish()
    }
}

impl ChainAuthentication {
    /// Build a chain. Order matters — first to succeed wins.
    pub fn new(backends: Vec<Arc<dyn Authentication>>) -> Self {
        Self { backends }
    }
}

#[async_trait]
impl Authentication for ChainAuthentication {
    async fn authenticate(&self, headers: &HeaderMap) -> Option<Identity> {
        for backend in &self.backends {
            if let Some(id) = backend.authenticate(headers).await {
                return Some(id);
            }
        }
        None
    }

    fn security_scheme(&self) -> Option<(String, serde_json::Value)> {
        // Returns the first child's contribution for callers that
        // only want one. The full walk lives on
        // `security_schemes_all` below — the OpenAPI plugin uses
        // that path so the spec publishes every scheme the chain
        // accepts.
        self.backends.iter().find_map(|b| b.security_scheme())
    }

    fn security_schemes_all(&self) -> Vec<(String, serde_json::Value)> {
        self.backends
            .iter()
            .flat_map(|b| b.security_schemes_all())
            .collect()
    }
}

// =========================================================================
// The app-wide default authentication backend (gaps4 #42).
// =========================================================================

/// The backend [`AppBuilder::authentication`](crate::app::AppBuilder)
/// published at build time, if any.
static DEFAULT_AUTH: std::sync::OnceLock<Arc<dyn Authentication>> = std::sync::OnceLock::new();

/// Publish the app-wide default [`Authentication`] backend. Called once by
/// `App::build()` (Phase 3, before plugin routes are collected) when the
/// app used `AppBuilder::authentication`. Second calls are ignored with a
/// warning — one app, one default.
pub fn set_default_authentication(auth: Arc<dyn Authentication>) {
    if DEFAULT_AUTH.set(auth).is_err() {
        tracing::warn!(
            "umbral: a default authentication backend is already installed; \
             ignoring this one (AppBuilder::authentication may only be used once)"
        );
    }
}

/// The app-wide default [`Authentication`] backend, if the app installed
/// one via `AppBuilder::authentication` (gaps4 #42).
///
/// Plugins that authenticate requests (REST, GraphQL, realtime) fall back
/// to this when no per-plugin backend was configured, so ONE builder line
/// serves every surface — the alternative was pasting the same
/// `ChainAuthentication` block into each plugin, where forgetting one copy
/// silently made that surface anonymous. A per-plugin `.authenticate(...)`
/// still overrides it.
pub fn default_authentication() -> Option<Arc<dyn Authentication>> {
    DEFAULT_AUTH.get().cloned()
}

// =========================================================================
// Helper: HTTP Basic Auth credential extraction.
// =========================================================================

/// Parse a `Basic <base64(user:pass)>` Authorization header into
/// `(username, password)`. Returns `None` if the header is missing,
/// malformed, or not Basic.
///
/// Provided as a free function so user-supplied `FnAuthentication`
/// closures (the recommended way to ship HTTP Basic Auth) can reach
/// it without re-implementing the boring base64 + colon-split logic.
pub fn parse_basic_credentials(headers: &HeaderMap) -> Option<(String, String)> {
    let header = headers.get(header::AUTHORIZATION)?.to_str().ok()?;
    let encoded = header.strip_prefix("Basic ")?;
    let decoded = base64::engine::general_purpose::STANDARD
        .decode(encoded)
        .ok()?;
    let decoded = String::from_utf8(decoded).ok()?;
    let (user, pass) = decoded.split_once(':')?;
    Some((user.to_string(), pass.to_string()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::web::header::AUTHORIZATION;

    fn headers_with(name: &str, value: &str) -> HeaderMap {
        let mut h = HeaderMap::new();
        h.insert(
            crate::web::header::HeaderName::from_bytes(name.as_bytes()).unwrap(),
            value.parse().unwrap(),
        );
        h
    }

    #[tokio::test]
    async fn no_authentication_always_returns_none() {
        let headers = HeaderMap::new();
        assert!(NoAuthentication.authenticate(&headers).await.is_none());
    }

    #[tokio::test]
    async fn fn_authentication_invokes_closure() {
        let auth = FnAuthentication::new(|_headers| async move { Some(Identity::user(42)) });
        let id = auth.authenticate(&HeaderMap::new()).await.unwrap();
        assert_eq!(id.user_id, "42");
        assert!(!id.is_staff);
    }

    #[tokio::test]
    async fn chain_authentication_first_success_wins() {
        let first = FnAuthentication::new(|_| async move { None });
        let second = FnAuthentication::new(|_| async move { Some(Identity::user(7).staff()) });
        let third = FnAuthentication::new(|_| async move { Some(Identity::user(99)) });
        let chain = ChainAuthentication::new(vec![
            Arc::new(first) as Arc<dyn Authentication>,
            Arc::new(second) as Arc<dyn Authentication>,
            Arc::new(third) as Arc<dyn Authentication>,
        ]);
        let id = chain.authenticate(&HeaderMap::new()).await.unwrap();
        // Second wins, third never runs.
        assert_eq!(id.user_id, "7");
        assert!(id.is_staff);
    }

    #[tokio::test]
    async fn chain_authentication_returns_none_when_all_fail() {
        let chain = ChainAuthentication::new(vec![
            Arc::new(NoAuthentication) as Arc<dyn Authentication>,
            Arc::new(NoAuthentication) as Arc<dyn Authentication>,
        ]);
        assert!(chain.authenticate(&HeaderMap::new()).await.is_none());
    }

    #[test]
    fn parse_basic_credentials_extracts_user_and_pass() {
        // "alice:secret" base64-encoded
        let headers = headers_with(AUTHORIZATION.as_str(), "Basic YWxpY2U6c2VjcmV0");
        let (user, pass) = parse_basic_credentials(&headers).unwrap();
        assert_eq!(user, "alice");
        assert_eq!(pass, "secret");
    }

    #[test]
    fn parse_basic_credentials_returns_none_for_missing_header() {
        assert!(parse_basic_credentials(&HeaderMap::new()).is_none());
    }

    #[test]
    fn parse_basic_credentials_returns_none_for_wrong_scheme() {
        let headers = headers_with(AUTHORIZATION.as_str(), "Bearer abc");
        assert!(parse_basic_credentials(&headers).is_none());
    }

    #[test]
    fn parse_basic_credentials_returns_none_for_invalid_base64() {
        let headers = headers_with(AUTHORIZATION.as_str(), "Basic !!!notbase64");
        assert!(parse_basic_credentials(&headers).is_none());
    }

    #[test]
    #[allow(deprecated)] // exercising `user_pk` specifically; `pk` is the canonical replacement.
    fn user_pk_parses_the_stringified_pk_into_the_requested_type() {
        // i64 PK — the common case that consumers hand-parse today.
        let id = Identity::user(42);
        assert_eq!(id.user_pk::<i64>().expect("i64 pk"), 42);
        // Non-i64 PK models (String / UUID codenames) ride the same FromStr path.
        let named = Identity::user("codename-x");
        assert_eq!(named.user_pk::<String>().expect("string pk"), "codename-x");
        // A PK that can't parse into the requested type is an `Err`, never a panic.
        assert!(Identity::user("not-a-number").user_pk::<i64>().is_err());
    }
}