ryuk 0.1.0

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
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
//! Passkey (WebAuthn/FIDO2) registration and discoverable sign-in (table `passkeys`,
//! self-created, SQLite/PostgreSQL/MySQL). Wraps Kanidm's `webauthn-rs`: no hand-rolled
//! CBOR/COSE/attestation parsing. Feature `passkey` needs `auth`, `db`, `sessions`.
//!
//! Build one [`Webauthn`] per app (one `rp_id` + origin, from `APP_URL`) with
//! [`webauthn_from_env`] and share it as an `Arc` with every [`Passkeys`]:
//!
//! ```
//! use std::sync::Arc;
//! # async fn f() -> Result<(), Box<dyn std::error::Error>> {
//! let webauthn = Arc::new(ryuk::passkey::webauthn_from_url("https://example.com")?);
//! let db = ryuk::db::connect("sqlite::memory:").await?;
//! let passkeys = ryuk::passkey::Passkeys::new(db, webauthn);
//! passkeys.ensure_tables().await?;
//! # Ok(()) }
//! ```
//!
//! # Registration (the user is already signed in some other way)
//! ```ignore
//! let exclude = passkeys.credential_ids(user.id).await?;
//! let (challenge, reg_state) = passkeys.start_registration(user.id, &user.email, &user.name, &exclude)?;
//! session.insert("passkey_reg", &reg_state).await.ok(); // JSON-encode `challenge` for the browser
//! // ... browser: navigator.credentials.create(options), POST the result back as `response` ...
//! let reg_state = session.remove("passkey_reg").await.ok().flatten().ok_or(PasskeyError::BadState)?;
//! passkeys.finish_registration(user.id, "MacBook Touch ID", &reg_state, &response).await?;
//! ```
//!
//! # Discoverable sign-in (no email typed first)
//! ```ignore
//! let (challenge, auth_state) = passkeys.start_discoverable_authentication()?;
//! session.insert("passkey_auth", &auth_state).await.ok(); // JSON-encode `challenge` for the browser
//! // ... browser: navigator.credentials.get({ mediation: "conditional", publicKey: challenge }) ...
//! let auth_state = session.remove("passkey_auth").await.ok().flatten().ok_or(PasskeyError::BadState)?;
//! let owner_id = passkeys.finish_discoverable_authentication(&auth_state, &response).await?;
//! // ryuk::auth::login(&session, owner_id).await?;
//! ```
//!
//! The in-progress ceremony state ([`PasskeyRegistration`] / [`DiscoverableAuthentication`]) is
//! not safe to round-trip through the client: it is JSON-serialized into the [`Session`] between
//! `start_*` and `finish_*` (same idea as the CSRF token and flash messages), the same way the
//! examples above do, and removed on first use so a replayed `finish_*` call finds nothing.
//!
//! # Shortcuts
//! - User ids are packed into the WebAuthn user handle as `Uuid::from_u128(id as u128)`: lossless
//!   for any positive `i64` (every auto-increment id), which is all this library assumes.
//! - Discoverable sign-in uses webauthn-rs's `conditional-ui` preview API: the only primitive in
//!   0.5.x that authenticates without a username typed first. Revisit when it stabilises upstream.
//! - No attestation policy beyond webauthn-rs's own default for `start_passkey_registration`
//!   (`AttestationConveyancePreference::None`): this library does not vet authenticator
//!   makes/models. Add attestation CA checking yourself if that matters for your threat model.
use sea_orm::entity::prelude::*;
use sea_orm::sea_query::Expr;
use sea_orm::{
    ActiveValue::Set, ConnectionTrait, DatabaseConnection, DbErr, QueryFilter, QueryOrder, Schema,
};
use std::sync::Arc;
pub use webauthn_rs::prelude::{
    CreationChallengeResponse, CredentialID, DiscoverableAuthentication, DiscoverableKey, Passkey,
    PasskeyRegistration, PublicKeyCredential, RegisterPublicKeyCredential,
    RequestChallengeResponse, Url, Uuid, Webauthn, WebauthnBuilder,
};

/// `passkeys` table.
pub mod passkeys {
    use sea_orm::entity::prelude::*;
    /// One registered WebAuthn credential.
    #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "passkeys")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i64,
        /// Owning user id; the app's own user table, not enforced here (see `apikey::api_keys`).
        pub owner_id: i64,
        /// base64url of the raw WebAuthn credential id.
        #[sea_orm(unique, column_type = "String(StringLen::N(512))")]
        pub credential_id: String,
        /// Serialized [`super::Passkey`] (JSON). Overwritten after every successful authentication
        /// so the stored signature counter advances; this is what makes clone detection work.
        #[sea_orm(column_type = "Text")]
        pub passkey_json: String,
        /// User-chosen label, e.g. "MacBook Touch ID".
        #[sea_orm(column_type = "Text")]
        pub name: String,
        /// Unix seconds.
        pub created_at: i64,
        pub last_used_at: Option<i64>,
    }
    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}
    impl ActiveModelBehavior for ActiveModel {}
}
use passkeys::{Column, Entity};

/// Passkey ceremony failure. Verification failures never leak detail (logged instead via
/// `tracing::error!`); see the module docs for why.
#[derive(Debug, thiserror::Error)]
pub enum PasskeyError {
    /// Database error.
    #[error("database: {0}")]
    Db(#[from] DbErr),
    /// The ceremony state in the session was missing (expired, already used, or never started).
    #[error("the sign-in attempt expired or was already used; please try again")]
    BadState,
    /// Registration or authentication did not cryptographically verify, or the credential/user is
    /// unknown. Deliberately generic: detail is only ever in the log.
    #[error("the passkey could not be verified")]
    Verification,
}

fn now() -> i64 {
    chrono::Utc::now().timestamp()
}

/// shortcut: packs the id directly into the WebAuthn user handle; see the module docs.
fn user_uuid(user_id: i64) -> Uuid {
    Uuid::from_u128(user_id as u128)
}

fn uuid_user_id(id: Uuid) -> i64 {
    id.as_u128() as i64
}

fn encode_id(id: &[u8]) -> String {
    use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD as B64};
    B64.encode(id)
}

/// Build the shared [`Webauthn`] relying party from `APP_URL`: its host is the relying party id,
/// the URL itself the allowed origin. Call once at startup and share the result as an `Arc` with
/// every [`Passkeys`].
///
/// WebAuthn requires `rp_id` to be a real domain, never a bare IP, so the default here is
/// `http://localhost:3000` rather than the `http://127.0.0.1:3000` the rest of the framework
/// falls back to (`social`, `storage`): point a browser at `localhost`, not `127.0.0.1`, to test
/// passkeys locally, or set `APP_URL` to a real hostname.
///
/// ```
/// let webauthn = ryuk::passkey::webauthn_from_env().unwrap();
/// ```
pub fn webauthn_from_env() -> Result<Webauthn, String> {
    webauthn_from_url(&std::env::var("APP_URL").unwrap_or_else(|_| "http://localhost:3000".into()))
}

/// [`webauthn_from_env`] with an explicit `APP_URL`-shaped origin (tests, or any other config path).
///
/// ```
/// let webauthn = ryuk::passkey::webauthn_from_url("https://example.com").unwrap();
/// ```
pub fn webauthn_from_url(app_url: &str) -> Result<Webauthn, String> {
    let origin = Url::parse(app_url).map_err(|e| format!("APP_URL is not a valid URL: {e}"))?;
    let rp_id = origin
        .host_str()
        .ok_or_else(|| "APP_URL has no host".to_string())?
        .to_string();
    WebauthnBuilder::new(&rp_id, &origin)
        .map_err(|e| format!("invalid WebAuthn relying party config: {e}"))?
        .build()
        .map_err(|e| format!("failed to build Webauthn: {e}"))
}

/// A passkey as listed to its owner (never the key material).
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct PasskeyInfo {
    /// Row id (pass to [`Passkeys::delete`]).
    pub id: i64,
    /// Label.
    pub name: String,
    /// Unix seconds.
    pub created_at: i64,
    /// Last successful sign-in, if any.
    pub last_used_at: Option<i64>,
}

/// Registers, lists, revokes and authenticates passkeys for one app.
///
/// ```ignore
/// let passkeys = Passkeys::new(db, webauthn);
/// passkeys.ensure_tables().await?;
/// ```
#[derive(Clone)]
pub struct Passkeys {
    db: DatabaseConnection,
    webauthn: Arc<Webauthn>,
}

impl Passkeys {
    /// New store over `db`, verifying against `webauthn`.
    pub fn new(db: DatabaseConnection, webauthn: Arc<Webauthn>) -> Self {
        Self { db, webauthn }
    }

    /// Create `passkeys` if missing.
    pub async fn ensure_tables(&self) -> Result<(), DbErr> {
        let mut t = Schema::new(self.db.get_database_backend()).create_table_from_entity(Entity);
        self.db.execute(t.if_not_exists()).await?;
        Ok(())
    }

    /// Credential ids already registered to `owner_id`; pass to [`Self::start_registration`]'s
    /// `exclude` so the same authenticator cannot be enrolled twice.
    pub async fn credential_ids(&self, owner_id: i64) -> Result<Vec<CredentialID>, PasskeyError> {
        use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD as B64};
        let rows = Entity::find()
            .filter(Column::OwnerId.eq(owner_id))
            .all(&self.db)
            .await?;
        Ok(rows
            .into_iter()
            .filter_map(|r| B64.decode(r.credential_id).ok())
            .map(CredentialID::from)
            .collect())
    }

    /// The owner's passkeys, newest first (never the key material).
    pub async fn list(&self, owner_id: i64) -> Result<Vec<PasskeyInfo>, PasskeyError> {
        Ok(Entity::find()
            .filter(Column::OwnerId.eq(owner_id))
            .order_by_desc(Column::Id)
            .all(&self.db)
            .await?
            .into_iter()
            .map(|m| PasskeyInfo {
                id: m.id,
                name: m.name,
                created_at: m.created_at,
                last_used_at: m.last_used_at,
            })
            .collect())
    }

    /// Delete one of the owner's passkeys; `false` if it is not theirs or missing. A deleted
    /// passkey stops working for sign-in immediately (the row the lookup uses is gone).
    pub async fn delete(&self, owner_id: i64, id: i64) -> Result<bool, PasskeyError> {
        let r = Entity::delete_many()
            .filter(Column::Id.eq(id))
            .filter(Column::OwnerId.eq(owner_id))
            .exec(&self.db)
            .await?;
        Ok(r.rows_affected == 1)
    }

    /// Delete every passkey of `owner_id` (account deletion); returns how many were removed.
    pub async fn delete_all(&self, owner_id: i64) -> Result<u64, PasskeyError> {
        Ok(Entity::delete_many()
            .filter(Column::OwnerId.eq(owner_id))
            .exec(&self.db)
            .await?
            .rows_affected)
    }

    /// Start registering a new passkey for `user_id`. Stash the returned [`PasskeyRegistration`]
    /// in the session and send the [`CreationChallengeResponse`] to the browser as JSON for
    /// `navigator.credentials.create()`.
    pub fn start_registration(
        &self,
        user_id: i64,
        user_name: &str,
        display_name: &str,
        exclude: &[CredentialID],
    ) -> Result<(CreationChallengeResponse, PasskeyRegistration), PasskeyError> {
        self.webauthn
            .start_passkey_registration(
                user_uuid(user_id),
                user_name,
                display_name,
                Some(exclude.to_vec()),
            )
            .map_err(|e| {
                tracing::error!("passkey registration start failed: {e}");
                PasskeyError::Verification
            })
    }

    /// Verify the browser's registration `response` against `reg_state` and store the new
    /// credential under `user_id` as `name`.
    pub async fn finish_registration(
        &self,
        user_id: i64,
        name: &str,
        reg_state: &PasskeyRegistration,
        response: &RegisterPublicKeyCredential,
    ) -> Result<(), PasskeyError> {
        let passkey = self
            .webauthn
            .finish_passkey_registration(response, reg_state)
            .map_err(|e| {
                tracing::error!("passkey registration verification failed: {e}");
                PasskeyError::Verification
            })?;
        let json = serde_json::to_string(&passkey).map_err(|e| {
            tracing::error!("passkey serialization failed: {e}");
            PasskeyError::Verification
        })?;
        passkeys::ActiveModel {
            owner_id: Set(user_id),
            credential_id: Set(encode_id(passkey.cred_id())),
            passkey_json: Set(json),
            name: Set(name.to_string()),
            created_at: Set(now()),
            last_used_at: Set(None),
            ..Default::default()
        }
        .insert(&self.db)
        .await?;
        Ok(())
    }

    /// Start a discoverable (passwordless) sign-in: no username is needed, the authenticator
    /// picks the credential. Stash the returned [`DiscoverableAuthentication`] in the session and
    /// send the [`RequestChallengeResponse`] to the browser as JSON for
    /// `navigator.credentials.get({ mediation: "conditional", publicKey })`.
    pub fn start_discoverable_authentication(
        &self,
    ) -> Result<(RequestChallengeResponse, DiscoverableAuthentication), PasskeyError> {
        self.webauthn
            .start_discoverable_authentication()
            .map_err(|e| {
                tracing::error!("passkey authentication start failed: {e}");
                PasskeyError::Verification
            })
    }

    /// Verify the browser's discoverable-authentication `response` against `auth_state`. On
    /// success, persists the authenticator's advanced signature counter (so a cloned authenticator
    /// replaying an old counter is rejected next time) and returns the signed-in `owner_id`.
    pub async fn finish_discoverable_authentication(
        &self,
        auth_state: &DiscoverableAuthentication,
        response: &PublicKeyCredential,
    ) -> Result<i64, PasskeyError> {
        let (uuid, cred_id) = self
            .webauthn
            .identify_discoverable_authentication(response)
            .map_err(|e| {
                tracing::error!("passkey authentication rejected: {e}");
                PasskeyError::Verification
            })?;
        let owner_id = uuid_user_id(uuid);
        let row = Entity::find()
            .filter(Column::CredentialId.eq(encode_id(cred_id)))
            .one(&self.db)
            .await?
            .ok_or(PasskeyError::Verification)?;
        if row.owner_id != owner_id {
            // The user handle we get back only ever comes from what we set at registration time
            // (see `user_uuid`): a mismatch here means the credential row and the asserted user
            // handle disagree, which should be impossible without tampering.
            tracing::error!("passkey user handle does not match the credential's owner");
            return Err(PasskeyError::Verification);
        }
        let mut passkey: Passkey = serde_json::from_str(&row.passkey_json).map_err(|e| {
            tracing::error!("stored passkey unreadable: {e}");
            PasskeyError::Verification
        })?;
        let key = DiscoverableKey::from(&passkey);
        let result = self
            .webauthn
            .finish_discoverable_authentication(response, auth_state.clone(), &[key])
            .map_err(|e| {
                tracing::error!("passkey authentication verification failed: {e}");
                PasskeyError::Verification
            })?;
        passkey.update_credential(&result);
        let json = serde_json::to_string(&passkey).map_err(|e| {
            tracing::error!("passkey serialization failed: {e}");
            PasskeyError::Verification
        })?;
        Entity::update_many()
            .col_expr(Column::PasskeyJson, Expr::value(json))
            .col_expr(Column::LastUsedAt, Expr::value(now()))
            .filter(Column::Id.eq(row.id))
            .exec(&self.db)
            .await?;
        Ok(owner_id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn rp() -> Webauthn {
        webauthn_from_url("https://example.test").unwrap()
    }

    #[test]
    fn uuid_round_trip_and_webauthn_from_env() {
        for id in [1i64, 42, i64::MAX] {
            assert_eq!(uuid_user_id(user_uuid(id)), id);
        }
        assert!(webauthn_from_url("not a url").is_err());
        assert!(webauthn_from_url("https://example.test").is_ok());
        // host-less URLs (e.g. `APP_URL=unix:/tmp/x`) are rejected, not panicking.
        assert!(webauthn_from_url("file:///tmp/x").is_err());
    }

    #[test]
    fn start_registration_builds_a_challenge_for_the_right_rp() {
        // `start_registration` never touches the database, so this drives the `Webauthn` RP
        // directly (no `Passkeys` / connection needed) to check the plumbing end to end.
        let w = rp();
        let (ccr, _state) = w
            .start_passkey_registration(user_uuid(1), "a@example.test", "A", None)
            .unwrap();
        assert_eq!(ccr.public_key.rp.id, "example.test");
    }

    #[cfg(feature = "sqlite")]
    async fn db() -> DatabaseConnection {
        let ns = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let path = std::env::temp_dir().join(format!("ryuk-passkey-{ns}.db"));
        sea_orm::Database::connect(format!("sqlite://{}?mode=rwc", path.display()))
            .await
            .unwrap()
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn ensure_tables_is_idempotent_and_crud_is_owner_scoped() {
        let p = Passkeys::new(db().await, Arc::new(rp()));
        p.ensure_tables().await.unwrap();
        p.ensure_tables().await.unwrap();

        // Insert two rows directly (bypassing a real ceremony, which the dedicated integration
        // test below covers with a real authenticator) to exercise list/delete/credential_ids.
        let mk = |owner: i64, cred: &str| passkeys::ActiveModel {
            owner_id: Set(owner),
            credential_id: Set(cred.into()),
            passkey_json: Set("{}".into()),
            name: Set("Device".into()),
            created_at: Set(now()),
            last_used_at: Set(None),
            ..Default::default()
        };
        use sea_orm::ActiveModelTrait;
        let mine = mk(1, "aaaa").insert(&p.db).await.unwrap();
        mk(2, "bbbb").insert(&p.db).await.unwrap();

        assert_eq!(p.list(1).await.unwrap().len(), 1);
        assert_eq!(p.list(2).await.unwrap().len(), 1);
        assert!(!p.delete(2, mine.id).await.unwrap(), "not their row");
        assert!(p.delete(1, mine.id).await.unwrap());
        assert!(p.list(1).await.unwrap().is_empty());
        assert_eq!(p.list(2).await.unwrap().len(), 1);
        assert_eq!(p.delete_all(2).await.unwrap(), 1);
        assert!(p.list(2).await.unwrap().is_empty());
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn exclude_credentials_prevents_the_same_credential_id_twice() {
        // credential_id has a unique index: a second insert with the same id must fail, which is
        // the DB-level backstop behind `exclude_credentials` (the browser-level check lives with
        // the real ceremony, exercised in tests/passkey_ceremony.rs).
        let p = Passkeys::new(db().await, Arc::new(rp()));
        p.ensure_tables().await.unwrap();
        use sea_orm::ActiveModelTrait;
        let row = || passkeys::ActiveModel {
            owner_id: Set(1),
            credential_id: Set("same-id".into()),
            passkey_json: Set("{}".into()),
            name: Set("Device".into()),
            created_at: Set(now()),
            last_used_at: Set(None),
            ..Default::default()
        };
        row().insert(&p.db).await.unwrap();
        assert!(row().insert(&p.db).await.is_err());
    }
}