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
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
//! Machine-to-machine API keys (table `api_keys`, self-created, SQLite/PostgreSQL/MySQL).
//!
//! A key looks like `ryk_<8 char prefix>_<43 char secret>`; the secret is 256 bits from the OS RNG.
//! The plaintext is returned once by [`ApiKeys::issue`]; only the sha256 of the whole key is stored.
//! [`ApiKeys::verify`] finds the row by its unique prefix and compares hashes in constant time.
//!
//! ```ignore
//! let keys = ApiKeys::new(db);
//! keys.ensure_tables().await?;
//! let k = keys.issue(Some(user.id), "ci", &["posts:read"], None).await?;
//! // show k.plaintext to the user once; later, from a request:
//! if let Some(principal) = keys.verify(bearer).await { /* principal.has("posts:read") */ }
//! // or register it: app.api_verifier(keys)
//! ```
use crate::api::{Principal, PrincipalKind, TokenVerifier};
use crate::health::BoxFuture;
use sea_orm::entity::prelude::*;
use sea_orm::sea_query::Expr;
use sea_orm::{
    ActiveValue::Set, Condition, ConnectionTrait, DatabaseConnection, DbErr, QueryFilter,
    QueryOrder, QuerySelect, Schema,
};
use sha2::{Digest, Sha256};
use std::time::Duration;

/// `api_keys` table.
pub mod api_keys {
    use sea_orm::entity::prelude::*;
    /// One hashed API key.
    #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "api_keys")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i64,
        /// Owning user id; `None` = system key.
        pub owner_id: Option<i64>,
        #[sea_orm(column_type = "Text")]
        pub name: String,
        /// Public, unique lookup part of the key.
        #[sea_orm(unique, column_type = "String(StringLen::N(16))")]
        pub prefix: String,
        /// Lowercase hex sha256 of the whole key.
        #[sea_orm(column_type = "String(StringLen::N(64))")]
        pub secret_hash: String,
        /// Space-separated scopes.
        #[sea_orm(column_type = "Text")]
        pub scopes: String,
        /// Unix seconds.
        pub created_at: i64,
        pub last_used_at: Option<i64>,
        pub expires_at: Option<i64>,
        pub revoked_at: Option<i64>,
    }
    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}
    impl ActiveModelBehavior for ActiveModel {}
}
use api_keys::{Column, Entity, Model};

const PREFIX_LEN: usize = 8;
const SECRET_LEN: usize = 43;
const KEY_LEN: usize = 4 + PREFIX_LEN + 1 + SECRET_LEN;
/// `last_used_at` is written at most this often per key.
const LAST_USED_EVERY: i64 = 60;

/// API key failure.
#[derive(Debug, thiserror::Error)]
pub enum ApiKeyError {
    /// Database error.
    #[error("database: {0}")]
    Db(#[from] DbErr),
    /// The OS random number generator failed.
    #[error("OS random number generator failed")]
    Rng,
    /// Rejected input (name, scopes or ttl).
    #[error("invalid api key input: {0}")]
    Invalid(&'static str),
}

/// A freshly issued key. `plaintext` is the only copy; it cannot be recovered later.
#[derive(Clone)]
pub struct NewKey {
    /// Row id.
    pub id: i64,
    /// Public prefix (safe to show).
    pub prefix: String,
    /// The full key, shown once.
    pub plaintext: String,
}

impl std::fmt::Debug for NewKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NewKey")
            .field("id", &self.id)
            .field("prefix", &self.prefix)
            .field("plaintext", &"<redacted>")
            .finish()
    }
}

/// A key as listed to its owner (never the secret).
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct ApiKeyInfo {
    /// Row id.
    pub id: i64,
    /// Label.
    pub name: String,
    /// Public prefix.
    pub prefix: String,
    /// Granted scopes.
    pub scopes: Vec<String>,
    /// Unix seconds.
    pub created_at: i64,
    /// Last successful use (at most 60 s stale).
    pub last_used_at: Option<i64>,
    /// Expiry, if any.
    pub expires_at: Option<i64>,
    /// Revocation time, if revoked.
    pub revoked_at: Option<i64>,
}

/// Issues, lists, revokes and verifies API keys.
#[derive(Clone)]
pub struct ApiKeys {
    db: DatabaseConnection,
}

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

fn hash(key: &str) -> String {
    Sha256::digest(key.as_bytes())
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

/// Constant-time equality (length is public: always 64 hex chars).
fn ct_eq(a: &[u8], b: &[u8]) -> bool {
    a.len() == b.len()
        && std::hint::black_box(a.iter().zip(b).fold(0u8, |d, (x, y)| d | (x ^ y))) == 0
}

fn random<const N: usize>() -> Result<[u8; N], ApiKeyError> {
    use rand::TryRng;
    let mut raw = [0u8; N];
    rand::rngs::SysRng
        .try_fill_bytes(&mut raw)
        .map_err(|_| ApiKeyError::Rng)?;
    Ok(raw)
}

/// base64url without padding (32 bytes -> 43 chars).
fn b64url(bytes: &[u8]) -> String {
    const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    let mut out = String::with_capacity(bytes.len() * 4 / 3 + 3);
    for c in bytes.chunks(3) {
        let n = (c[0] as u32) << 16
            | (*c.get(1).unwrap_or(&0) as u32) << 8
            | *c.get(2).unwrap_or(&0) as u32;
        for i in 0..=c.len() {
            out.push(A[(n >> (18 - 6 * i) & 63) as usize] as char);
        }
    }
    out
}

/// Prefix of a well-formed key, `None` for anything else (cheap shape check, no secrets involved).
fn parse(key: &str) -> Option<&str> {
    let b = key.as_bytes();
    let ok = b.len() == KEY_LEN
        && key.starts_with("ryk_")
        && b[4 + PREFIX_LEN] == b'_'
        && b[4..4 + PREFIX_LEN].iter().all(u8::is_ascii_alphanumeric)
        && b[5 + PREFIX_LEN..]
            .iter()
            .all(|c| c.is_ascii_alphanumeric() || *c == b'-' || *c == b'_');
    ok.then(|| &key[4..4 + PREFIX_LEN])
}

fn valid_scope(s: &str) -> bool {
    !s.is_empty()
        && s.len() <= 64
        && s.bytes()
            .all(|c| matches!(c, b'a'..=b'z' | b'0'..=b'9' | b':' | b'_' | b'*' | b'.' | b'-'))
}

fn split_scopes(s: &str) -> Vec<String> {
    s.split_whitespace().map(String::from).collect()
}

fn info(m: Model) -> ApiKeyInfo {
    ApiKeyInfo {
        id: m.id,
        scopes: split_scopes(&m.scopes),
        name: m.name,
        prefix: m.prefix,
        created_at: m.created_at,
        last_used_at: m.last_used_at,
        expires_at: m.expires_at,
        revoked_at: m.revoked_at,
    }
}

impl ApiKeys {
    /// New key store over `db`.
    pub fn new(db: DatabaseConnection) -> Self {
        Self { db }
    }

    /// Create `api_keys` 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(())
    }

    /// Mint a key. `name` is 1..=100 chars; up to 20 scopes of `[a-z0-9:_*.-]`, 64 chars each;
    /// `ttl`, if given, must be non-zero.
    pub async fn issue(
        &self,
        owner: Option<i64>,
        name: &str,
        scopes: &[&str],
        ttl: Option<Duration>,
    ) -> Result<NewKey, ApiKeyError> {
        if !(1..=100).contains(&name.chars().count()) {
            return Err(ApiKeyError::Invalid("name must be 1 to 100 characters"));
        }
        if scopes.len() > 20 || !scopes.iter().all(|s| valid_scope(s)) {
            return Err(ApiKeyError::Invalid("at most 20 scopes of [a-z0-9:_*.-]+"));
        }
        if ttl == Some(Duration::ZERO) {
            return Err(ApiKeyError::Invalid("ttl must be greater than zero"));
        }
        const ALNUM: &[u8; 62] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        // shortcut: a prefix collision (47 bits) is pre-checked then left to the unique index, no retry on a lost race.
        let prefix = loop {
            let p: String = random::<PREFIX_LEN>()?
                .iter()
                .map(|b| ALNUM[*b as usize % 62] as char)
                .collect();
            if Entity::find()
                .filter(Column::Prefix.eq(p.as_str()))
                .one(&self.db)
                .await?
                .is_none()
            {
                break p;
            }
        };
        let plaintext = format!("ryk_{prefix}_{}", b64url(&random::<32>()?));
        let t = now();
        let row = api_keys::ActiveModel {
            owner_id: Set(owner),
            name: Set(name.into()),
            prefix: Set(prefix.clone()),
            secret_hash: Set(hash(&plaintext)),
            scopes: Set(scopes.join(" ")),
            created_at: Set(t),
            expires_at: Set(
                ttl.map(|d| t.saturating_add(d.as_secs().min(i64::MAX as u64 / 2) as i64))
            ),
            ..Default::default()
        }
        .insert(&self.db)
        .await?;
        Ok(NewKey {
            id: row.id,
            prefix,
            plaintext,
        })
    }

    /// The owner's keys, newest first (revoked ones included, never the secret).
    pub async fn list(&self, owner: i64) -> Result<Vec<ApiKeyInfo>, ApiKeyError> {
        Ok(Entity::find()
            .filter(Column::OwnerId.eq(owner))
            .order_by_desc(Column::Id)
            .all(&self.db)
            .await?
            .into_iter()
            .map(info)
            .collect())
    }

    /// Revoke a key the `owner` owns; `false` if it is not theirs, unknown or already revoked.
    pub async fn revoke(&self, owner: i64, id: i64) -> Result<bool, ApiKeyError> {
        let live = Entity::find_by_id(id)
            .filter(Column::OwnerId.eq(owner))
            .filter(Column::RevokedAt.is_null())
            .one(&self.db)
            .await?
            .is_some();
        if live {
            // The row count is not used: MySQL reports matched rows, not changed ones.
            Entity::update_many()
                .col_expr(Column::RevokedAt, Expr::value(now()))
                .filter(Column::Id.eq(id))
                .filter(Column::OwnerId.eq(owner))
                .filter(Column::RevokedAt.is_null())
                .exec(&self.db)
                .await?;
        }
        Ok(live)
    }

    /// Revoke every live key of `owner` (account deletion, password reset); returns how many were live.
    pub async fn revoke_all(&self, owner: i64) -> Result<u64, ApiKeyError> {
        let live = Entity::find()
            .filter(Column::OwnerId.eq(owner))
            .filter(Column::RevokedAt.is_null())
            .count(&self.db)
            .await?;
        // The row count is not used: MySQL reports matched rows, not changed ones.
        Entity::update_many()
            .col_expr(Column::RevokedAt, Expr::value(now()))
            .filter(Column::OwnerId.eq(owner))
            .filter(Column::RevokedAt.is_null())
            .exec(&self.db)
            .await?;
        Ok(live)
    }

    /// Delete keys that are expired, or were revoked more than `retention` ago; returns how many
    /// were selected for deletion. A verify racing the delete just sees an unknown key.
    ///
    /// shortcut: `owner_id` has no index (revoke_all/list scan); add one when the table is large.
    pub async fn prune(&self, retention: Duration) -> Result<u64, ApiKeyError> {
        let t = now();
        let old = t - retention.as_secs().min(i64::MAX as u64 / 4) as i64;
        let dead = Condition::any()
            .add(Column::ExpiresAt.lte(t))
            .add(Column::RevokedAt.lte(old));
        let mut n = 0u64;
        loop {
            let ids: Vec<i64> = Entity::find()
                .filter(dead.clone())
                .limit(500)
                .all(&self.db)
                .await?
                .into_iter()
                .map(|r| r.id)
                .collect();
            n += ids.len() as u64;
            let full = ids.len() == 500;
            Entity::delete_many()
                .filter(Column::Id.is_in(ids))
                .exec(&self.db)
                .await?;
            if !full {
                return Ok(n);
            }
        }
    }

    /// The principal behind a presented key; `None` if malformed, unknown, wrong, revoked or
    /// expired (and on database errors: fail closed). An unknown prefix costs the same hash and
    /// comparison as a known one.
    pub async fn verify(&self, key: &str) -> Option<Principal> {
        let prefix = parse(key)?;
        let row = match Entity::find()
            .filter(Column::Prefix.eq(prefix))
            .one(&self.db)
            .await
        {
            Ok(r) => r,
            Err(e) => {
                tracing::error!("api key lookup failed: {e}");
                return None;
            }
        };
        let presented = hash(key);
        // Dummy of the same shape so the unknown-prefix path does the same work.
        let stored = row
            .as_ref()
            .map_or("0".repeat(64), |r| r.secret_hash.clone());
        let hash_ok = ct_eq(presented.as_bytes(), stored.as_bytes());
        let r = row?;
        let t = now();
        if !hash_ok || r.revoked_at.is_some() || r.expires_at.is_some_and(|e| e <= t) {
            return None;
        }
        if r.last_used_at.is_none_or(|l| l <= t - LAST_USED_EVERY) {
            let touched = Entity::update_many()
                .col_expr(Column::LastUsedAt, Expr::value(t))
                .filter(Column::Id.eq(r.id))
                .exec(&self.db)
                .await;
            if let Err(e) = touched {
                tracing::warn!("api key last_used update failed: {e}");
            }
        }
        Some(Principal {
            kind: PrincipalKind::ApiKey,
            id: r.id.to_string(),
            user_id: r.owner_id,
            client_id: None,
            scopes: split_scopes(&r.scopes),
            name: Some(r.name),
        })
    }
}

impl TokenVerifier for ApiKeys {
    fn verify<'a>(&'a self, bearer: &'a str) -> BoxFuture<'a, Option<Principal>> {
        Box::pin(ApiKeys::verify(self, bearer))
    }
}

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

    #[test]
    fn helpers() {
        assert!(ct_eq(b"abc", b"abc") && !ct_eq(b"abc", b"abd") && !ct_eq(b"abc", b"ab"));
        assert_eq!(b64url(&[0u8; 32]).len(), SECRET_LEN);
        let k = format!("ryk_AbCd1234_{}", b64url(&[7u8; 32]));
        assert_eq!(k.len(), KEY_LEN);
        assert_eq!(parse(&k), Some("AbCd1234"));
        for bad in [
            "",
            "ryk_",
            "ryk_AbCd1234_short",
            &k.replace("ryk_", "xyz_"),
            &format!("{k}x"),
            &k.replace('_', "!"),
        ] {
            assert_eq!(parse(bad), None, "{bad}");
        }
        assert!(valid_scope("posts:read") && valid_scope("*") && valid_scope("a.b-c_d"));
        assert!(!valid_scope("") && !valid_scope("Up") && !valid_scope("a b"));
        assert!(!valid_scope(&"a".repeat(65)));
    }

    #[cfg(feature = "sqlite")]
    /// A SQLite file DB plus external servers when configured.
    async fn dbs() -> Vec<(&'static str, 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-apikey-{ns}.db"));
        let mut v = vec![(
            "sqlite",
            sea_orm::Database::connect(format!("sqlite://{}?mode=rwc", path.display()))
                .await
                .unwrap(),
        )];
        for (name, var) in [
            ("postgres", "TEST_POSTGRES_URL"),
            ("mysql", "TEST_MYSQL_URL"),
        ] {
            if let Ok(url) = std::env::var(var) {
                v.push((name, sea_orm::Database::connect(url).await.unwrap()));
            }
        }
        v
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn lifecycle_all_backends() {
        for (name, db) in dbs().await {
            let k = ApiKeys::new(db.clone());
            k.ensure_tables().await.unwrap();
            k.ensure_tables().await.unwrap();
            // shared DBs keep rows between runs: a per-run owner keeps assertions exact
            let owner = chrono::Utc::now().timestamp_nanos_opt().unwrap();
            let other = owner + 1;

            let n = k
                .issue(Some(owner), "ci", &["posts:read", "posts:*"], None)
                .await
                .unwrap();
            assert_eq!(n.plaintext.len(), KEY_LEN, "{name}");
            assert!(n.plaintext.starts_with(&format!("ryk_{}_", n.prefix)));
            let p = k.verify(&n.plaintext).await.expect(name);
            assert_eq!(p.kind, PrincipalKind::ApiKey);
            assert_eq!(p.id, n.id.to_string());
            assert_eq!(p.user_id, Some(owner));
            assert_eq!(p.name.as_deref(), Some("ci"));
            assert_eq!(p.scopes, ["posts:read", "posts:*"]);
            assert!(TokenVerifier::verify(&k, &n.plaintext).await.is_some());

            // hash at rest
            let secret = &n.plaintext[13..];
            let row = Entity::find_by_id(n.id).one(&db).await.unwrap().unwrap();
            assert_eq!(row.secret_hash, hash(&n.plaintext));
            assert!(!format!("{row:?}").contains(secret), "{name}");
            assert!(!format!("{n:?}").contains(secret));

            // malformed, unknown prefix, right prefix + wrong secret
            assert!(k.verify("garbage").await.is_none());
            assert!(k.verify("").await.is_none());
            let unknown = format!("ryk_ZZZZZZZZ_{secret}");
            assert!(k.verify(&unknown).await.is_none(), "{name}");
            let wrong = format!("ryk_{}_{}", n.prefix, b64url(&[1u8; 32]));
            assert!(k.verify(&wrong).await.is_none(), "{name}");

            // last_used throttled to once per minute
            let used = || async {
                Entity::find_by_id(n.id)
                    .one(&db)
                    .await
                    .unwrap()
                    .unwrap()
                    .last_used_at
            };
            let dbr = &db;
            let set = |v: i64| async move {
                Entity::update_many()
                    .col_expr(Column::LastUsedAt, Expr::value(v))
                    .filter(Column::Id.eq(n.id))
                    .exec(dbr)
                    .await
                    .unwrap();
            };
            let first = used().await.expect("set on first use");
            set(first - 10).await;
            k.verify(&n.plaintext).await.unwrap();
            assert_eq!(used().await, Some(first - 10), "{name}: within 60s");
            set(first - 100).await;
            k.verify(&n.plaintext).await.unwrap();
            assert!(used().await.unwrap() >= first, "{name}: refreshed");

            // list never exposes the secret; owner isolation on revoke
            let theirs = k.issue(Some(other), "x", &[], None).await.unwrap();
            let l = k.list(owner).await.unwrap();
            assert_eq!(l.len(), 1);
            assert_eq!(l[0].prefix, n.prefix);
            assert!(!format!("{l:?}").contains(secret));
            assert!(!k.revoke(owner, theirs.id).await.unwrap(), "{name}");
            assert!(k.verify(&theirs.plaintext).await.is_some());
            assert!(k.revoke(owner, n.id).await.unwrap(), "{name}");
            assert!(!k.revoke(owner, n.id).await.unwrap(), "{name}: twice");
            assert!(k.verify(&n.plaintext).await.is_none(), "{name}: revoked");
            assert!(k.list(owner).await.unwrap()[0].revoked_at.is_some());

            // expiry enforced server-side; a system key has no owner
            let ttl = Some(Duration::from_secs(3600));
            let e = k.issue(None, "sys", &[], ttl).await.unwrap();
            assert_eq!(k.verify(&e.plaintext).await.unwrap().user_id, None);
            Entity::update_many()
                .col_expr(Column::ExpiresAt, Expr::value(now() - 1))
                .filter(Column::Id.eq(e.id))
                .exec(&db)
                .await
                .unwrap();
            assert!(k.verify(&e.plaintext).await.is_none(), "{name}: expired");
        }
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn revoke_all_and_prune() {
        for (name, db) in dbs().await {
            let k = ApiKeys::new(db.clone());
            k.ensure_tables().await.unwrap();
            let owner = chrono::Utc::now().timestamp_nanos_opt().unwrap();
            let other = owner + 1;
            let hour = Duration::from_secs(3600);
            let set = |id: i64, c: Column, v: i64| {
                let db = db.clone();
                async move {
                    Entity::update_many()
                        .col_expr(c, Expr::value(v))
                        .filter(Column::Id.eq(id))
                        .exec(&db)
                        .await
                        .unwrap();
                }
            };
            let there = |id: i64| {
                let db = db.clone();
                async move { Entity::find_by_id(id).one(&db).await.unwrap().is_some() }
            };
            let mut mine = Vec::new();
            for i in 0..3 {
                mine.push(
                    k.issue(Some(owner), &format!("k{i}"), &["a"], None)
                        .await
                        .unwrap(),
                );
            }
            let theirs = k.issue(Some(other), "t", &[], None).await.unwrap();
            assert!(k.revoke(owner, mine[0].id).await.unwrap());
            assert_eq!(k.revoke_all(owner).await.unwrap(), 2, "{name}");
            assert_eq!(k.revoke_all(owner).await.unwrap(), 0, "{name}");
            for m in &mine {
                assert!(k.verify(&m.plaintext).await.is_none(), "{name}");
            }
            assert!(
                k.verify(&theirs.plaintext).await.is_some(),
                "{name}: other owner"
            );

            // revoked just now: kept for the retention; revoked long ago or expired: deleted
            assert!(k.prune(hour).await.is_ok());
            assert!(there(mine[1].id).await, "{name}");
            set(mine[0].id, Column::RevokedAt, now() - 7200).await;
            set(mine[2].id, Column::ExpiresAt, now() - 1).await;
            set(mine[2].id, Column::RevokedAt, now()).await;
            let expired = k.issue(Some(other), "e", &[], Some(hour)).await.unwrap();
            set(expired.id, Column::ExpiresAt, now() - 1).await;
            assert!(k.prune(hour).await.unwrap() >= 3, "{name}");
            assert!(
                !there(mine[0].id).await && !there(mine[2].id).await && !there(expired.id).await,
                "{name}"
            );
            assert!(there(mine[1].id).await && there(theirs.id).await, "{name}");
            assert!(
                k.verify(&theirs.plaintext).await.is_some(),
                "{name}: live key survives prune"
            );
            // retention zero drops the freshly revoked one
            k.prune(Duration::ZERO).await.unwrap();
            assert!(!there(mine[1].id).await && there(theirs.id).await, "{name}");
        }
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn issue_validates_input() {
        let (_, db) = dbs().await.remove(0);
        let k = ApiKeys::new(db);
        k.ensure_tables().await.unwrap();
        let many = vec!["a"; 21];
        let long = "n".repeat(101);
        for (name, scopes, ttl) in [
            ("", vec![], None),
            (long.as_str(), vec![], None),
            ("ok", vec!["Bad Scope"], None),
            ("ok", vec![""], None),
            ("ok", many, None),
            ("ok", vec![], Some(Duration::ZERO)),
        ] {
            let r = k.issue(None, name, &scopes, ttl).await;
            assert!(matches!(r, Err(ApiKeyError::Invalid(_))), "{name:?}");
        }
        let max = k.issue(None, &"é".repeat(100), &["a"; 20], None).await;
        assert!(max.is_ok());
    }
}