Skip to main content

smeltery_hallmark/
lib.rs

1#![doc = include_str!("../README.md")]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3
4mod abilities;
5mod console;
6mod extract;
7mod guard;
8mod issue;
9mod settings;
10mod stateful;
11pub mod testing;
12mod tokens;
13
14use std::sync::atomic::AtomicU64;
15
16use smeltery_core::auth::{CredentialListener, CredentialsChanged};
17use smeltery_core::cache::RateLimiter;
18use smeltery_core::db::migration::Schema;
19use smeltery_core::{App, AppBuilder, BoxFuture, Error, Result};
20
21pub use abilities::{MAX_ABILITIES, MAX_ABILITY_LEN, valid_ability};
22pub use extract::CurrentToken;
23pub use guard::GUARD;
24pub use issue::{CODE_INVALID, CODE_REQUIRED, FAILED, issue_for_credentials, revoke_current};
25pub use settings::Hallmark;
26pub use tokens::{
27    AccessToken, HasApiTokens, MAX_NAME_LEN, NewToken, PlainToken, TABLE, TOKEN_PREFIX, Tokens,
28};
29
30/// The memory of recently used tokens and of blocked clients: at most this many entries each.
31const MEMORY_ENTRIES: u64 = 10_000;
32
33/// Hallmark's state in an app (a service).
34pub(crate) struct State {
35    pub(crate) settings: Hallmark,
36    /// Invalid bearer tokens per client a minute (the app's cache store, shared by its processes).
37    pub(crate) guesses: RateLimiter,
38    /// Tokens whose `last_used_at` this process wrote in the last minute.
39    pub(crate) recently_used: moka::future::Cache<i64, ()>,
40    /// SHA-256 hashes of tokens this process accepted in the last five minutes: while their client is blocked they
41    /// still get the full check.
42    pub(crate) accepted: moka::future::Cache<String, ()>,
43    /// The first-party rule when SPA mode is on (made at boot, from the final `APP_URL`).
44    pub(crate) first_party: std::sync::OnceLock<stateful::FirstParty>,
45    /// When a `last_used_at` failure was last logged (Unix seconds).
46    pub(crate) last_warned: AtomicU64,
47}
48
49impl State {
50    fn new(settings: Hallmark) -> Self {
51        Self {
52            first_party: std::sync::OnceLock::new(),
53            guesses: RateLimiter::new(
54                "hallmark.guesses",
55                settings.guesses_per_minute(),
56                guard::GUESS_WINDOW,
57            ),
58            recently_used: moka::future::Cache::builder()
59                .max_capacity(MEMORY_ENTRIES)
60                .time_to_live(std::time::Duration::from_secs(60))
61                .build(),
62            accepted: moka::future::Cache::builder()
63                .max_capacity(MEMORY_ENTRIES)
64                .time_to_live(std::time::Duration::from_secs(300))
65                .build(),
66            last_warned: AtomicU64::new(0),
67            settings,
68        }
69    }
70}
71
72/// Installs Hallmark on an [`AppBuilder`]: `.hallmark(Hallmark::new())` in `bootstrap/app.rs`, after
73/// `.auth::<User>()`.
74pub trait HallmarkExt: Sized {
75    /// Install Hallmark: the guard `hallmark` (routes use `auth:hallmark`), the middleware families `abilities:`
76    /// (every listed ability) and `ability:` (at least one), the [`Tokens`] service, the credential listener that
77    /// deletes a user's tokens when the password changes, and the console command `hallmark:prune-expired`.
78    /// The app stops at boot when no user model is registered (`.auth::<User>()`); `serve` logs an error when the
79    /// `personal_access_tokens` table is missing.
80    fn hallmark(self, hallmark: Hallmark) -> Self;
81}
82
83impl HallmarkExt for AppBuilder {
84    fn hallmark(self, hallmark: Hallmark) -> Self {
85        let spa = hallmark.is_spa();
86        let stateful = hallmark.stateful_origins().join(",");
87        let builder = if spa {
88            self.xsrf_cookie().routes(|r| {
89                r.get("/hallmark/csrf-cookie", csrf_cookie)
90                    .name("hallmark.csrf-cookie");
91            })
92        } else {
93            self
94        };
95        builder
96            .service(State::new(hallmark))
97            .guard(guard::HallmarkGuard)
98            .global_middleware(guard::response_headers)
99            .middleware_family("abilities", |args, _route| {
100                abilities::family(abilities::Need::All, "abilities", args)
101            })
102            .middleware_family("ability", |args, _route| {
103                abilities::family(abilities::Need::Any, "ability", args)
104            })
105            .credential_listener(PasswordListener)
106            .commands(|c| {
107                c.add(console::PruneExpired);
108            })
109            .on_boot(move |app| async move {
110                if spa {
111                    // An invalid `HALLMARK_STATEFUL` entry stops the app here.
112                    let rule = stateful::FirstParty::new(&app.settings().url, &stateful)?;
113                    if let Some(state) = app.service::<State>() {
114                        let _ = state.first_party.set(rule);
115                    }
116                }
117                if app.auth_model().is_none() {
118                    return Err(Error::internal(
119                        "Hallmark needs a user model: call `.auth::<User>()` in bootstrap/app.rs",
120                    ));
121                }
122                Ok(())
123            })
124            .on_serve(|app| async move {
125                check_table(&app).await;
126                Ok(())
127            })
128    }
129}
130
131/// `GET /hallmark/csrf-cookie` (SPA mode): 204; the web stack sets the `XSRF-TOKEN` cookie on it.
132async fn csrf_cookie() -> http::StatusCode {
133    http::StatusCode::NO_CONTENT
134}
135
136/// Log one error when the tokens table is missing (`serve` still starts: every token is refused).
137async fn check_table(app: &App) {
138    let Ok(db) = app.db() else {
139        tracing::error!("hallmark: API tokens need a database (DATABASE_URL)");
140        return;
141    };
142    match Schema::new(&db).has_table(TABLE).await {
143        Ok(true) => {}
144        Ok(false) => tracing::error!(
145            table = TABLE,
146            "hallmark: the API tokens table is missing; add its migration and run `migrate`"
147        ),
148        Err(e) => {
149            tracing::error!(error = %e, "hallmark: the API tokens table could not be checked")
150        }
151    }
152}
153
154/// Deletes a user's tokens when the password changes (a reset, another device signed out, a new password),
155/// except the Hallmark token of the request that made the change, which is bound to the new password so it keeps
156/// working. Core publishes the revocation of every credential, so nothing is published here.
157struct PasswordListener;
158
159/// The id of the Hallmark token that a [`CredentialsChanged::except`] names: the key of this
160/// guard's token (core's [`credential_key`](smeltery_core::auth::credential_key)), rebuilt and compared
161/// whole, so another guard's key never matches.
162fn kept_token(except: Option<&str>) -> Option<i64> {
163    let key = except?;
164    let (_, id) = key.rsplit_once(':')?;
165    if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) {
166        return None;
167    }
168    let id = id.parse::<i64>().ok()?;
169    (tokens::token_key(id) == key).then_some(id)
170}
171
172impl CredentialListener for PasswordListener {
173    fn credentials_changed<'a>(
174        &'a self,
175        app: &'a App,
176        change: &'a CredentialsChanged,
177    ) -> BoxFuture<'a, Result<()>> {
178        Box::pin(async move {
179            let tokens = Tokens::of(app)?;
180            let keep = kept_token(change.except.as_deref());
181            let extra = keep.map(|id| {
182                use sea_orm::sea_query::{Alias, Expr, ExprTrait};
183                Expr::col(Alias::new("id")).ne(id)
184            });
185            tokens.delete_where(change.user_id, extra).await?;
186            if let Some(id) = keep
187                // The new password hash is stored before listeners run: bind the kept token to it, or its next
188                // request would find the old binding and end it.
189                && tokens.rebind(change.user_id, id).await? == 0
190            {
191                // A request of the same token that ran between the new hash and this rebind found the old binding
192                // and ended the token: the caller must know it was not kept.
193                return Err(Error::http(
194                    http::StatusCode::UNAUTHORIZED,
195                    "The token that changed the password was signed out meanwhile; sign in again.",
196                ));
197            }
198            Ok(())
199        })
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::kept_token;
206
207    #[test]
208    fn the_kept_token_is_read_from_the_key() {
209        let key = crate::tokens::token_key(7);
210        assert_eq!(kept_token(Some(&key)), Some(7));
211        let session = smeltery_core::auth::Principal::new(
212            3,
213            smeltery_core::auth::WEB_GUARD,
214            smeltery_core::auth::Credential::session("ab"),
215        )
216        .key();
217        let other_guard = smeltery_core::auth::Principal::new(
218            3,
219            "demo",
220            smeltery_core::auth::Credential::token::<String>(7, []),
221        )
222        .key();
223        for other in [
224            None,
225            Some(session.as_str()),
226            Some(other_guard.as_str()),
227            Some("7"),
228            Some("x:+7"),
229        ] {
230            assert_eq!(kept_token(other), None, "{other:?}");
231        }
232    }
233}
234
235/// The `personal_access_tokens` table, for the app's migration.
236///
237/// ```
238/// use smeltery::Result;
239/// use smeltery::db::migration::{Migration, Schema};
240///
241/// pub struct CreatePersonalAccessTokensTable;
242///
243/// impl Migration for CreatePersonalAccessTokensTable {
244///     fn name(&self) -> &'static str {
245///         "2026_10_05_000000_create_personal_access_tokens_table"
246///     }
247///
248///     async fn up(&self, schema: &Schema) -> Result<()> {
249///         smeltery::hallmark::migrations::up(schema).await
250///     }
251///
252///     async fn down(&self, schema: &Schema) -> Result<()> {
253///         smeltery::hallmark::migrations::down(schema).await
254///     }
255/// }
256/// ```
257///
258/// | Column | Type |
259/// |---|---|
260/// | `id` | 64-bit auto-increment primary key |
261/// | `user_id` | the user (`users.id`, deleted with the user), indexed |
262/// | `name` | `varchar(255)` |
263/// | `token_hash` | `varchar(64)`, unique: the SHA-256 (hex) of the token |
264/// | `binding` | `varchar(64)`: a hash of the user's password hash when the token was created |
265/// | `abilities` | text: a JSON array |
266/// | `last_used_at` | timestamp, nullable |
267/// | `expires_at` | timestamp, nullable, indexed |
268/// | `created_at` | timestamp |
269/// | `updated_at` | timestamp, nullable |
270pub mod migrations {
271    use smeltery_core::Result;
272    use smeltery_core::db::migration::Schema;
273
274    use crate::TABLE;
275
276    /// Create the `personal_access_tokens` table.
277    ///
278    /// # Errors
279    /// The table exists already, `users` does not, or a statement fails.
280    pub async fn up(schema: &Schema) -> Result<()> {
281        schema
282            .create(TABLE, |t| {
283                t.id();
284                t.foreign_id("user_id")
285                    .constrained("users")
286                    .cascade_on_delete()
287                    .index();
288                t.string("name");
289                t.string_len("token_hash", 64).unique();
290                t.string_len("binding", 64);
291                t.text("abilities");
292                t.datetime("last_used_at").nullable();
293                t.datetime("expires_at").nullable().index();
294                t.datetime("created_at");
295                t.datetime("updated_at").nullable();
296            })
297            .await
298    }
299
300    /// Drop the table.
301    ///
302    /// # Errors
303    /// A statement fails.
304    pub async fn down(schema: &Schema) -> Result<()> {
305        schema.drop_if_exists(TABLE).await
306    }
307}