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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
//! The machine-facing route groups: [`Principal`], [`ApiAuth`], JSON [`ApiError`]s, [`Cors`] and the
//! rate limiter. `App::api` / `App::public` wrap their routes with these (and never with sessions or CSRF).
//!
//! ```
//! use ryuk::api::{ApiAuth, ApiError};
//!
//! async fn list(ApiAuth(p): ApiAuth) -> Result<&'static str, ApiError> {
//!     p.require("posts:read")?;
//!     Ok("[]")
//! }
//! ```
use crate::{health::BoxFuture, proxy::ClientIp};
use axum::{
    Json, Router,
    extract::{FromRequestParts, Request, State},
    http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header, request::Parts},
    middleware::{Next, from_fn, from_fn_with_state},
    response::{IntoResponse, Response},
};
use serde_json::json;
use std::{
    collections::{BTreeMap, HashMap},
    sync::{Arc, Mutex},
    time::{Duration, Instant},
};
use tower_http::cors::{AllowOrigin, CorsLayer};

/// What kind of credential produced a [`Principal`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PrincipalKind {
    ApiKey,
    OAuthToken,
    OAuthClient,
}

/// The authenticated caller of an api route.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Principal {
    pub kind: PrincipalKind,
    pub id: String,
    pub user_id: Option<i64>,
    pub client_id: Option<String>,
    pub scopes: Vec<String>,
    pub name: Option<String>,
}

impl Principal {
    /// Exact scope, `*`, or an `area:*` wildcard (`posts:*` grants `posts:read` and `posts:comments:write`).
    ///
    /// ```
    /// use ryuk::api::{Principal, PrincipalKind};
    /// let p = Principal { kind: PrincipalKind::ApiKey, id: "1".into(), user_id: None, client_id: None,
    ///     scopes: vec!["posts:*".into()], name: None };
    /// assert!(p.has("posts:read") && !p.has("users:read"));
    /// ```
    pub fn has(&self, scope: &str) -> bool {
        self.scopes.iter().any(|g| {
            g == scope
                || g == "*"
                || g.strip_suffix('*')
                    .is_some_and(|area| area.ends_with(':') && scope.starts_with(area))
        })
    }

    /// `Ok` when [`has`](Self::has), else a 403 `insufficient_scope` error.
    pub fn require(&self, scope: &str) -> Result<(), ApiError> {
        if self.has(scope) {
            Ok(())
        } else {
            Err(ApiError::forbidden(scope))
        }
    }
}

/// JSON error `{"error":{"code","message"}}`; return it from api handlers.
#[derive(Clone, Debug)]
pub struct ApiError {
    pub status: StatusCode,
    pub code: &'static str,
    pub message: String,
}

impl ApiError {
    fn new(status: StatusCode, code: &'static str, message: impl Into<String>) -> Self {
        ApiError {
            status,
            code,
            message: message.into(),
        }
    }
    /// 401 with `WWW-Authenticate: Bearer`.
    pub fn unauthorized() -> Self {
        Self::new(
            StatusCode::UNAUTHORIZED,
            "unauthorized",
            "Authentication required",
        )
    }
    /// 403 `insufficient_scope`.
    pub fn forbidden(scope: &str) -> Self {
        Self::new(
            StatusCode::FORBIDDEN,
            "insufficient_scope",
            format!("Missing scope: {scope}"),
        )
    }
    pub fn not_found() -> Self {
        Self::new(StatusCode::NOT_FOUND, "not_found", "Not found")
    }
    pub fn bad_request(msg: impl Into<String>) -> Self {
        Self::new(StatusCode::BAD_REQUEST, "bad_request", msg)
    }
    /// 422; the message lists `field: reason` pairs.
    pub fn validation(errors: BTreeMap<String, Vec<String>>) -> Self {
        let list: Vec<_> = errors
            .iter()
            .flat_map(|(f, m)| m.iter().map(move |m| format!("{f}: {m}")))
            .collect();
        Self::new(
            StatusCode::UNPROCESSABLE_ENTITY,
            "validation_failed",
            list.join("; "),
        )
    }
    /// Generic 500; log the detail yourself.
    pub fn internal() -> Self {
        Self::new(
            StatusCode::INTERNAL_SERVER_ERROR,
            "internal_error",
            "Internal server error",
        )
    }
}

/// Any error becomes a generic 500; the detail is only logged.
impl<E: std::error::Error> From<E> for ApiError {
    fn from(e: E) -> Self {
        tracing::error!("api handler error: {e}");
        ApiError::internal()
    }
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let mut res = (
            self.status,
            Json(json!({"error": {"code": self.code, "message": self.message}})),
        )
            .into_response();
        if self.status == StatusCode::UNAUTHORIZED {
            res.headers_mut()
                .insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer"));
        }
        res
    }
}

/// Turns a bearer token into a [`Principal`]. `App::api_verifier` may be called several times:
/// verifiers are tried in registration order and the first `Some` wins.
pub trait TokenVerifier: Send + Sync + 'static {
    fn verify<'a>(&'a self, bearer: &'a str) -> BoxFuture<'a, Option<Principal>>;
}

/// Set by the api guard; its absence means the route is not in the api group.
#[derive(Clone)]
struct ApiCtx(Option<Principal>);

fn ctx(parts: &Parts) -> Result<Option<Principal>, ApiError> {
    match parts.extensions.get::<ApiCtx>() {
        Some(c) => Ok(c.0.clone()),
        None => {
            tracing::error!("ApiAuth used outside the api group (mount the route with App::api)");
            Err(ApiError::new(
                StatusCode::INTERNAL_SERVER_ERROR,
                "internal_error",
                "ApiAuth used outside the api group",
            ))
        }
    }
}

/// Extractor requiring a valid API key / OAuth token: 401 JSON otherwise.
pub struct ApiAuth(pub Principal);

/// Extractor yielding the principal when a valid credential was sent.
pub struct OptionalApiAuth(pub Option<Principal>);

impl<S: Send + Sync> FromRequestParts<S> for ApiAuth {
    type Rejection = ApiError;
    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, ApiError> {
        ctx(parts)?.map(ApiAuth).ok_or_else(ApiError::unauthorized)
    }
}

impl<S: Send + Sync> FromRequestParts<S> for OptionalApiAuth {
    type Rejection = ApiError;
    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, ApiError> {
        ctx(parts).map(OptionalApiAuth)
    }
}

/// `Authorization: Bearer <t>` or `X-API-Key: <t>`.
fn bearer(h: &HeaderMap) -> Option<&str> {
    let auth = h.get(header::AUTHORIZATION).and_then(|v| v.to_str().ok());
    let tok = match auth.and_then(|a| a.split_once(' ')) {
        Some((s, t)) if s.eq_ignore_ascii_case("bearer") => Some(t.trim()),
        _ => h.get("x-api-key").and_then(|v| v.to_str().ok()),
    };
    tok.filter(|t| !t.is_empty())
}

/// CORS for the api and public groups. Default (no `App::cors`): no cross-origin access.
///
/// ```
/// use ryuk::api::Cors;
/// let c = Cors::allow_origins(&["https://app.example.com"])
///     .allow_headers(&["x-trace"])
///     .max_age(std::time::Duration::from_secs(600));
/// ```
#[derive(Clone, Default)]
pub struct Cors {
    origins: Vec<String>,
    headers: Vec<String>,
    max_age: Option<Duration>,
}

impl Cors {
    /// Allowed origins (`"*"` allows any). Credentials are never allowed: api auth is a bearer token.
    pub fn allow_origins(origins: &[&str]) -> Self {
        Cors {
            origins: origins.iter().map(|o| o.to_string()).collect(),
            ..Default::default()
        }
    }
    /// Extra allowed request headers (Authorization, Content-Type and X-API-Key are always allowed).
    pub fn allow_headers(mut self, headers: &[&str]) -> Self {
        self.headers.extend(headers.iter().map(|h| h.to_string()));
        self
    }
    /// How long browsers may cache a preflight answer.
    pub fn max_age(mut self, d: Duration) -> Self {
        self.max_age = Some(d);
        self
    }

    fn layer(&self) -> CorsLayer {
        let origin = if self.origins.iter().any(|o| o == "*") {
            AllowOrigin::any()
        } else {
            AllowOrigin::list(self.origins.iter().map(|o| {
                o.parse::<HeaderValue>()
                    .unwrap_or_else(|_| panic!("Cors: `{o}` is not a valid origin"))
            }))
        };
        let name = |s: &str| {
            s.parse::<HeaderName>()
                .unwrap_or_else(|_| panic!("Cors: `{s}` is not a valid header name"))
        };
        let headers = ["authorization", "content-type", "x-api-key"]
            .into_iter()
            .map(name)
            .chain(self.headers.iter().map(|h| name(h)))
            .collect::<Vec<_>>();
        let expose = [
            "x-ratelimit-limit",
            "x-ratelimit-remaining",
            "x-ratelimit-reset",
            "retry-after",
            "x-request-id",
        ]
        .map(name);
        let l = CorsLayer::new()
            .allow_origin(origin)
            .allow_methods([
                Method::GET,
                Method::POST,
                Method::PUT,
                Method::PATCH,
                Method::DELETE,
                Method::HEAD,
                Method::OPTIONS,
            ])
            .allow_headers(headers)
            .expose_headers(expose);
        match self.max_age {
            Some(d) => l.max_age(d),
            None => l,
        }
    }
}

/// Outcome of one [`RateLimitStore::hit`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RateStatus {
    /// The request is over the limit (429).
    pub limited: bool,
    /// Hits left in the current window.
    pub remaining: u32,
    /// Time until the window resets.
    pub reset_in: Duration,
}

/// A rate limit store failure (a database outage, say). See `App::api_rate_limit_fail_closed`.
#[derive(Debug, thiserror::Error)]
#[error("rate limit store: {0}")]
pub struct RateError(pub String);

/// Counts hits per key in a fixed window. [`MemoryRateLimit`] is the default; `DbRateLimit` (features
/// `api` + `db`) shares the counters between instances.
///
/// ```
/// use ryuk::api::{MemoryRateLimit, RateLimitStore};
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let s = MemoryRateLimit::default();
/// let w = std::time::Duration::from_secs(60);
/// let st = s.hit("k", 1, w).await.unwrap();
/// assert!(!st.limited && st.remaining == 0);
/// assert!(s.hit("k", 1, w).await.unwrap().limited);
/// # });
/// ```
pub trait RateLimitStore: Send + Sync + 'static {
    /// Counts one hit for `key` against `limit` per `window`.
    fn hit<'a>(
        &'a self,
        key: &'a str,
        limit: u32,
        window: Duration,
    ) -> BoxFuture<'a, Result<RateStatus, RateError>>;
}

/// Fixed-window counters in process memory (the default store).
// shortcut: per process, so N instances allow N times the limit; use `DbRateLimit` when scaling out.
#[derive(Default)]
pub struct MemoryRateLimit {
    hits: Mutex<HashMap<String, (Instant, u32)>>,
}

impl RateLimitStore for MemoryRateLimit {
    fn hit<'a>(
        &'a self,
        key: &'a str,
        limit: u32,
        window: Duration,
    ) -> BoxFuture<'a, Result<RateStatus, RateError>> {
        let now = Instant::now();
        let mut m = self.hits.lock().unwrap_or_else(|e| e.into_inner());
        if m.len() > 10_000 {
            m.retain(|_, (start, _)| now.duration_since(*start) < window);
        }
        let e = m.entry(key.to_owned()).or_insert((now, 0));
        if now.duration_since(e.0) >= window {
            *e = (now, 0);
        }
        let reset_in = window.saturating_sub(now.duration_since(e.0));
        let limited = e.1 >= limit;
        if !limited {
            e.1 += 1;
        }
        let remaining = if limited { 0 } else { limit - e.1 };
        Box::pin(std::future::ready(Ok(RateStatus {
            limited,
            remaining,
            reset_in,
        })))
    }
}

/// `api_rate_limits` table.
#[cfg(feature = "db")]
pub mod api_rate_limits {
    use sea_orm::entity::prelude::*;
    /// Counter for one rate limit key (`principal:<kind>:<id>` or `ip:<addr>`).
    #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "api_rate_limits")]
    pub struct Model {
        #[sea_orm(
            primary_key,
            auto_increment = false,
            column_type = "String(StringLen::N(255))"
        )]
        pub key: String,
        pub hits: i64,
        /// Unix seconds when the current window ends.
        pub reset_at: i64,
    }
    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}
    impl ActiveModelBehavior for ActiveModel {}
}

/// Rate limit counters shared through the database (SQLite, PostgreSQL, MySQL).
///
/// ```ignore
/// let store = DbRateLimit::new(db);
/// store.ensure_tables().await?;
/// let app = app.api_rate_limit_store(store);
/// ```
#[cfg(feature = "db")]
#[derive(Clone)]
pub struct DbRateLimit {
    db: sea_orm::DatabaseConnection,
}

#[cfg(feature = "db")]
impl DbRateLimit {
    pub fn new(db: sea_orm::DatabaseConnection) -> Self {
        Self { db }
    }

    /// Create `api_rate_limits` if missing (a new table: nothing to upgrade).
    pub async fn ensure_tables(&self) -> Result<(), sea_orm::DbErr> {
        use sea_orm::{ConnectionTrait, Schema};
        let mut t = Schema::new(self.db.get_database_backend())
            .create_table_from_entity(api_rate_limits::Entity);
        self.db.execute(t.if_not_exists()).await?;
        Ok(())
    }

    /// Delete counters whose window is over; returns how many.
    pub async fn prune(&self) -> Result<u64, sea_orm::DbErr> {
        use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};
        let r = api_rate_limits::Entity::delete_many()
            .filter(api_rate_limits::Column::ResetAt.lte(chrono::Utc::now().timestamp()))
            .exec(&self.db)
            .await?;
        Ok(r.rows_affected)
    }

    /// Four single statements, each atomic: insert-if-absent (hits 0), reset an ended window, `hits = hits + 1`,
    /// read back. Nothing depends on affected-row counts (MySQL reports matched rows).
    ///
    /// shortcut: not one transaction and windows are whole seconds (min 1s). Increments are never lost; the
    /// read-back may include concurrent hits, so a burst can be limited slightly early, never late.
    async fn hit_db(
        &self,
        key: &str,
        limit: u32,
        window: Duration,
    ) -> Result<RateStatus, sea_orm::DbErr> {
        use api_rate_limits::{ActiveModel, Column, Entity};
        use sea_orm::sea_query::Expr;
        use sea_orm::{ActiveValue::Set, ColumnTrait, EntityTrait, ExprTrait, QueryFilter};
        if key.len() > 255 {
            return Err(sea_orm::DbErr::Custom(
                "rate limit key over 255 bytes".into(),
            ));
        }
        let now = chrono::Utc::now().timestamp();
        let win = std::cmp::max(window.as_secs(), 1) as i64;
        Entity::insert(ActiveModel {
            key: Set(key.into()),
            hits: Set(0),
            reset_at: Set(now + win),
        })
        .on_conflict_do_nothing()
        .exec_without_returning(&self.db)
        .await?;
        Entity::update_many()
            .col_expr(Column::Hits, Expr::value(0i64))
            .col_expr(Column::ResetAt, Expr::value(now + win))
            .filter(Column::Key.eq(key))
            .filter(Column::ResetAt.lte(now))
            .exec(&self.db)
            .await?;
        Entity::update_many()
            .col_expr(Column::Hits, Expr::col(Column::Hits).add(1))
            .filter(Column::Key.eq(key))
            .exec(&self.db)
            .await?;
        // A concurrent prune can delete the row between statements: count it as a fresh window.
        let (hits, reset_at) = match Entity::find_by_id(key).one(&self.db).await? {
            Some(r) => (r.hits, r.reset_at),
            None => (1, now + win),
        };
        Ok(RateStatus {
            limited: hits > limit as i64,
            remaining: std::cmp::max(limit as i64 - hits, 0) as u32,
            reset_in: Duration::from_secs(std::cmp::max(reset_at - now, 1) as u64),
        })
    }
}

#[cfg(feature = "db")]
impl RateLimitStore for DbRateLimit {
    fn hit<'a>(
        &'a self,
        key: &'a str,
        limit: u32,
        window: Duration,
    ) -> BoxFuture<'a, Result<RateStatus, RateError>> {
        Box::pin(async move {
            self.hit_db(key, limit, window)
                .await
                .map_err(|e| RateError(e.to_string()))
        })
    }
}

/// Rate limit settings the guard needs.
#[derive(Clone)]
pub(crate) struct RateCfg {
    pub store: Arc<dyn RateLimitStore>,
    pub max: u32,
    pub per: Duration,
    pub fail_closed: bool,
}

/// Dotted integers (`1.10.0`), a `-beta` / `+build` suffix ignored, missing components 0. `None` on anything else.
fn parse_version(s: &str) -> Option<Vec<u64>> {
    let core = s.trim().split(['-', '+']).next()?;
    let parts: Vec<u64> = core
        .split('.')
        .map(|p| {
            if p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()) {
                return None;
            }
            p.parse().ok()
        })
        .collect::<Option<_>>()?;
    (parts.len() <= 8).then_some(parts)
}

fn version_lt(a: &[u64], b: &[u64]) -> bool {
    let at = |v: &[u64], i| v.get(i).copied().unwrap_or(0);
    (0..a.len().max(b.len()))
        .map(|i| (at(a, i), at(b, i)))
        .find(|(x, y)| x != y)
        .is_some_and(|(x, y)| x < y)
}

/// `App::min_app_version` settings: (platform, min string, parsed min).
#[derive(Clone, Default)]
pub(crate) struct VersionGate {
    pub min: Vec<(String, String, Vec<u64>)>,
    pub require_headers: bool,
}

impl VersionGate {
    pub(crate) fn set(&mut self, platform: &str, min: &str) {
        let parsed = parse_version(min)
            .unwrap_or_else(|| panic!("App::min_app_version: `{min}` is not a dotted version"));
        let p = platform.trim().to_ascii_lowercase();
        self.min.retain(|(q, ..)| *q != p);
        self.min.push((p, min.to_owned(), parsed));
    }
    fn active(&self) -> bool {
        !self.min.is_empty() || self.require_headers
    }
}

/// 426 for an app older than the configured minimum; 400 for missing headers when required.
async fn version_gate(State(g): State<Arc<VersionGate>>, req: Request, next: Next) -> Response {
    match upgrade_error(&g, req.headers()) {
        Some(res) => res,
        None => next.run(req).await,
    }
}

fn upgrade_error(g: &VersionGate, h: &HeaderMap) -> Option<Response> {
    let hv = |n: &str| h.get(n).and_then(|v| v.to_str().ok());
    let (platform, ver) = (
        hv("x-app-platform"),
        hv("x-app-version").and_then(parse_version),
    );
    if g.require_headers && (platform.is_none() || ver.is_none()) {
        return Some(
            ApiError::bad_request("X-App-Platform and X-App-Version headers are required")
                .into_response(),
        );
    }
    let (p, v) = (platform?.trim().to_ascii_lowercase(), ver?);
    let (_, min, minv) = g.min.iter().find(|(q, ..)| *q == p)?;
    if !version_lt(&v, minv) {
        return None;
    }
    let mut r = (
        StatusCode::UPGRADE_REQUIRED,
        Json(json!({"error": {
            "code": "upgrade_required",
            "message": format!("Update the app to {min} or newer"),
            "min_version": min, "platform": p,
        }})),
    )
        .into_response();
    if let Ok(h) = HeaderValue::from_str(min) {
        r.headers_mut().insert("x-min-app-version", h);
    }
    Some(r)
}

type Verifiers = Arc<Vec<Arc<dyn TokenVerifier>>>;

#[derive(Clone)]
struct Guard {
    verifiers: Verifiers,
    limit: RateCfg,
    public: bool,
}

/// Rate limit key: the principal, else the client's IP bucket (the public group has its own `public:` space).
fn limit_key(p: Option<&Principal>, ip: Option<std::net::IpAddr>, public: bool) -> String {
    let pre = if public { "public:" } else { "" };
    match (p, ip) {
        (Some(p), _) => format!("principal:{:?}:{}", p.kind, p.id),
        (None, Some(ip)) => format!("{pre}ip:{}", crate::proxy::ip_bucket(ip)),
        (None, None) => format!("{pre}ip:unknown"),
    }
}

/// Authenticates (verifier chain), exposes the principal to extractors, then rate limits.
async fn guard(State(g): State<Guard>, ip: ClientIp, mut req: Request, next: Next) -> Response {
    let mut principal = None;
    if let Some(tok) = bearer(req.headers()).filter(|_| !g.public) {
        for v in g.verifiers.iter() {
            if let Some(p) = v.verify(tok).await {
                principal = Some(p);
                break;
            }
        }
    }
    let key = limit_key(principal.as_ref(), ip.0, g.public);
    if !g.public {
        // ApiAuth in the public group stays the documented developer error
        req.extensions_mut().insert(ApiCtx(principal));
    }
    let st = match g.limit.store.hit(&key, g.limit.max, g.limit.per).await {
        Ok(st) => st,
        Err(e) if g.limit.fail_closed => {
            tracing::error!("{e}: rejecting the request (fail closed)");
            return ApiError::new(
                StatusCode::SERVICE_UNAVAILABLE,
                "rate_limit_unavailable",
                "Service temporarily unavailable",
            )
            .into_response();
        }
        Err(e) => {
            tracing::error!("{e}: letting the request through (fail open)");
            return next.run(req).await;
        }
    };
    let reset = st.reset_in.as_secs_f64().ceil() as u64;
    let mut res = if !st.limited {
        next.run(req).await
    } else {
        let mut r = (
            StatusCode::TOO_MANY_REQUESTS,
            Json(json!({"error": {"code": "rate_limited", "message": "Too many requests"}})),
        )
            .into_response();
        r.headers_mut().insert(header::RETRY_AFTER, reset.into());
        r
    };
    let h = res.headers_mut();
    h.insert("x-ratelimit-limit", g.limit.max.into());
    h.insert("x-ratelimit-remaining", st.remaining.into());
    h.insert("x-ratelimit-reset", reset.into());
    res
}

fn is_json(h: &HeaderMap) -> bool {
    h.get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .is_some_and(|v| v.contains("json"))
}

/// Rewrites every non-JSON 4xx/5xx (router 404/405, extractor rejections, timeouts, panics) as an [`ApiError`].
async fn json_errors(req: Request, next: Next) -> Response {
    let res = next.run(req).await;
    let st = res.status();
    if !(st.is_client_error() || st.is_server_error()) || is_json(res.headers()) {
        return res;
    }
    let (parts, body) = res.into_parts();
    let text = axum::body::to_bytes(body, 1024)
        .await
        .ok()
        .and_then(|b| String::from_utf8(b.to_vec()).ok())
        .unwrap_or_default();
    let reason = st.canonical_reason().unwrap_or("Error");
    let err = match st.as_u16() {
        // `Auth` (session) without a session layer: it is not available here.
        500 if text.contains("SessionManagerLayer") => ApiError::new(
            StatusCode::UNAUTHORIZED,
            "unauthorized",
            "session auth is not available on api routes",
        ),
        c if c >= 500 => ApiError::new(st, "internal_error", reason),
        c => {
            let code = match c {
                400 => "bad_request",
                401 => "unauthorized",
                403 => "forbidden",
                404 => "not_found",
                405 => "method_not_allowed",
                408 => "request_timeout",
                413 => "payload_too_large",
                415 => "unsupported_media_type",
                422 => "unprocessable_entity",
                429 => "rate_limited",
                _ => "error",
            };
            // 4xx rejection text (e.g. which JSON field failed) helps clients; 5xx text never leaves the server.
            ApiError::new(st, code, if text.is_empty() { reason.into() } else { text })
        }
    };
    let mut out = err.into_response();
    for (k, v) in &parts.headers {
        if k != header::CONTENT_TYPE && k != header::CONTENT_LENGTH {
            out.headers_mut().entry(k).or_insert_with(|| v.clone());
        }
    }
    out
}

/// Wraps the (already stateful) api group: CORS, JSON errors, shared hardening (request id), version gate, then auth + rate limit.
pub(crate) fn wrap_api(
    r: Router,
    verifiers: Verifiers,
    limit: RateCfg,
    gate: VersionGate,
    cors: Option<&Cors>,
    harden: impl FnOnce(Router) -> Router,
) -> Router {
    let mut r = r.layer(from_fn_with_state(
        Guard {
            verifiers,
            limit,
            public: false,
        },
        guard,
    ));
    // Outside auth and the limiter, inside the shared hardening (request id).
    if gate.active() {
        r = r.layer(from_fn_with_state(Arc::new(gate), version_gate));
    }
    wrap(harden(r), cors)
}

/// Wraps the public group: like api without authentication, with a per-IP-bucket rate limit.
pub(crate) fn wrap_public(
    r: Router,
    limit: RateCfg,
    cors: Option<&Cors>,
    harden: impl FnOnce(Router) -> Router,
) -> Router {
    let g = Guard {
        verifiers: Arc::new(vec![]),
        limit,
        public: true,
    };
    wrap(harden(r.layer(from_fn_with_state(g, guard))), cors)
}

fn wrap(r: Router, cors: Option<&Cors>) -> Router {
    let r = r.layer(from_fn(json_errors));
    match cors {
        Some(c) => r.layer(c.layer()),
        None => r,
    }
}

/// Route paths registered on `r` (read from its `Debug` output: axum exposes no accessor).
// shortcut: relies on axum's Debug format; the startup-panic tests fail loudly if an axum upgrade changes it.
pub(crate) fn paths<S>(r: &Router<S>) -> Vec<String> {
    let dbg = format!("{r:?}");
    let dbg = dbg.split("fallback_router").next().unwrap_or("");
    let mut out = vec![];
    let mut rest = dbg;
    while let Some(i) = rest.find("): \"") {
        rest = &rest[i + 4..];
        if let Some(end) = rest.find('"') {
            out.push(rest[..end].to_owned());
            rest = &rest[end..];
        }
    }
    out
}

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

    #[test]
    fn limit_key_uses_ip_bucket() {
        let k = |s: &str, public| limit_key(None, Some(s.parse().unwrap()), public);
        assert_eq!(k("2001:db8:1:2::1", false), k("2001:db8:1:2::9", false));
        assert_ne!(k("2001:db8:1:2::1", false), k("2001:db8:1:3::1", false));
        assert_eq!(k("::ffff:1.2.3.4", false), "ip:1.2.3.4");
        assert_eq!(k("1.2.3.4", true), "public:ip:1.2.3.4");
    }

    fn p(scopes: &[&str]) -> Principal {
        Principal {
            kind: PrincipalKind::ApiKey,
            id: "k1".into(),
            user_id: Some(1),
            client_id: None,
            scopes: scopes.iter().map(|s| s.to_string()).collect(),
            name: None,
        }
    }

    #[test]
    fn scope_wildcards() {
        assert!(p(&["posts:read"]).has("posts:read"));
        assert!(!p(&["posts:read"]).has("posts:write"));
        assert!(p(&["*"]).has("anything:at:all"));
        assert!(p(&["posts:*"]).has("posts:write") && p(&["posts:*"]).has("posts:a:b"));
        assert!(!p(&["posts:*"]).has("postsx:write") && !p(&["posts:*"]).has("users:read"));
        assert!(
            !p(&["pos*"]).has("posts:read"),
            "wildcard must end at a colon"
        );
        assert!(!p(&[]).has("x"));
        let e = p(&["a:b"]).require("a:c").unwrap_err();
        assert_eq!(
            (e.status, e.code),
            (StatusCode::FORBIDDEN, "insufficient_scope")
        );
        assert!(p(&["a:*"]).require("a:c").is_ok());
    }

    #[test]
    fn bearer_forms() {
        let h = |k: &str, v: &str| {
            let mut m = HeaderMap::new();
            m.insert(
                HeaderName::from_bytes(k.as_bytes()).unwrap(),
                v.parse().unwrap(),
            );
            m
        };
        assert_eq!(bearer(&h("authorization", "Bearer abc")), Some("abc"));
        assert_eq!(bearer(&h("authorization", "bearer abc")), Some("abc"));
        assert_eq!(bearer(&h("x-api-key", "abc")), Some("abc"));
        assert_eq!(bearer(&h("authorization", "Basic abc")), None);
        assert_eq!(bearer(&h("authorization", "Bearer ")), None);
    }

    #[tokio::test]
    async fn fixed_window() {
        let rl = MemoryRateLimit::default();
        let w = Duration::from_millis(80);
        assert!(!rl.hit("a", 2, w).await.unwrap().limited);
        let s = rl.hit("a", 2, w).await.unwrap();
        assert!(!s.limited && s.remaining == 0);
        assert!(rl.hit("a", 2, w).await.unwrap().limited);
        assert!(
            !rl.hit("b", 2, w).await.unwrap().limited,
            "keys are independent"
        );
        tokio::time::sleep(Duration::from_millis(100)).await;
        assert!(!rl.hit("a", 2, w).await.unwrap().limited, "window reset");
    }

    #[test]
    fn versions() {
        let lt =
            |a: &str, b: &str| version_lt(&parse_version(a).unwrap(), &parse_version(b).unwrap());
        assert!(lt("1.9.3", "1.10.0") && !lt("1.10.0", "1.9.3"));
        assert!(!lt("1.4", "1.4.0") && !lt("1.4.0", "1.4") && lt("1.4", "1.4.1"));
        assert!(!lt("2.0.0-beta.1", "2.0") && !lt("2.0+build7", "2.0.0") && lt("1", "2"));
        for bad in [
            "",
            ".",
            "1..2",
            "a.b",
            "-1",
            "1.-2",
            "1.2.3.4.5.6.7.8.9",
            "99999999999999999999999",
            "\u{0}",
            "\u{ff11}.\u{ff12}",
            "v1.2",
            " ",
        ] {
            assert_eq!(parse_version(bad), None, "{bad:?}");
        }
        // fuzz-ish: arbitrary text never panics
        let mut x = 0x2545F491u32;
        for _ in 0..2000 {
            let n = x % 12;
            let s: String = (0..n)
                .map(|_| {
                    x = x.wrapping_mul(1664525).wrapping_add(1013904223);
                    char::from_u32((x >> 16) % 0x300).unwrap_or('?')
                })
                .collect();
            let _ = parse_version(&s);
        }
    }

    #[cfg(feature = "sqlite")]
    async fn dbs() -> Vec<(&'static str, sea_orm::DatabaseConnection)> {
        let path = std::env::temp_dir().join(format!(
            "ryuk-rate-{}.db",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let url = format!("sqlite://{}?mode=rwc", path.display());
        // `mut` is only needed when a server driver feature adds its URL below.
        #[allow(unused_mut)]
        let mut v = vec![("sqlite", sea_orm::Database::connect(url).await.unwrap())];
        #[cfg(feature = "postgres")]
        if let Ok(url) = std::env::var("TEST_POSTGRES_URL") {
            v.push(("postgres", sea_orm::Database::connect(url).await.unwrap()));
        }
        #[cfg(feature = "mysql")]
        if let Ok(url) = std::env::var("TEST_MYSQL_URL") {
            v.push(("mysql", sea_orm::Database::connect(url).await.unwrap()));
        }
        v
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn db_store_limits_resets_and_counts_concurrent_hits() {
        use sea_orm::{ColumnTrait, EntityTrait, QueryFilter, sea_query::Expr};
        let uniq = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        for (name, db) in dbs().await {
            let s = DbRateLimit::new(db.clone());
            s.ensure_tables().await.unwrap();
            s.ensure_tables().await.unwrap();
            let w = Duration::from_secs(60);
            let k = format!("seq-{name}-{uniq}");
            for i in (0..3).rev() {
                let st = s.hit(&k, 3, w).await.unwrap();
                assert!(!st.limited && st.remaining == i, "{name}");
                assert!((1..=60).contains(&st.reset_in.as_secs()), "{name}");
            }
            let st = s.hit(&k, 3, w).await.unwrap();
            assert!(st.limited && st.remaining == 0, "{name}");
            // window reset: age this key's row
            api_rate_limits::Entity::update_many()
                .col_expr(api_rate_limits::Column::ResetAt, Expr::value(1i64))
                .filter(api_rate_limits::Column::Key.eq(&k))
                .exec(&db)
                .await
                .unwrap();
            let st = s.hit(&k, 3, w).await.unwrap();
            assert!(!st.limited && st.remaining == 2, "{name} window reset");
            // 50 concurrent hits are all counted
            let k = format!("conc-{name}-{uniq}");
            let hs: Vec<_> = (0..50)
                .map(|_| {
                    let (s, k) = (s.clone(), k.clone());
                    tokio::spawn(async move { s.hit(&k, 1000, w).await })
                })
                .collect();
            for h in hs {
                assert!(!h.await.unwrap().unwrap().limited);
            }
            let row = api_rate_limits::Entity::find_by_id(&k)
                .one(&db)
                .await
                .unwrap()
                .unwrap();
            assert_eq!(row.hits, 50, "{name}");
            // prune removes ended windows only
            api_rate_limits::Entity::update_many()
                .col_expr(api_rate_limits::Column::ResetAt, Expr::value(1i64))
                .filter(api_rate_limits::Column::Key.eq(format!("seq-{name}-{uniq}")))
                .exec(&db)
                .await
                .unwrap();
            assert!(s.prune().await.unwrap() >= 1);
            assert!(
                api_rate_limits::Entity::find_by_id(&k)
                    .one(&db)
                    .await
                    .unwrap()
                    .is_some(),
                "{name}"
            );
            // over-long keys error instead of truncating
            assert!(s.hit(&"x".repeat(256), 1, w).await.is_err());
        }
    }
}