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
30const MEMORY_ENTRIES: u64 = 10_000;
32
33pub(crate) struct State {
35 pub(crate) settings: Hallmark,
36 pub(crate) guesses: RateLimiter,
38 pub(crate) recently_used: moka::future::Cache<i64, ()>,
40 pub(crate) accepted: moka::future::Cache<String, ()>,
43 pub(crate) first_party: std::sync::OnceLock<stateful::FirstParty>,
45 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
72pub trait HallmarkExt: Sized {
75 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 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
131async fn csrf_cookie() -> http::StatusCode {
133 http::StatusCode::NO_CONTENT
134}
135
136async 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
154struct PasswordListener;
158
159fn 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 && tokens.rebind(change.user_id, id).await? == 0
190 {
191 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
235pub mod migrations {
271 use smeltery_core::Result;
272 use smeltery_core::db::migration::Schema;
273
274 use crate::TABLE;
275
276 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 pub async fn down(schema: &Schema) -> Result<()> {
305 schema.drop_if_exists(TABLE).await
306 }
307}