modo-rs 0.8.0

Rust web framework for small monolithic apps
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
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Wake};

use crate::{Error, Result};

use super::{TenantId, traits::TenantStrategy};

/// Extract Host header value, strip port if present.
fn host_from_parts(parts: &http::request::Parts) -> Result<String> {
    let host = parts
        .headers
        .get(http::header::HOST)
        .ok_or_else(|| Error::bad_request("missing Host header"))?
        .to_str()
        .map_err(|_| Error::bad_request("invalid Host header"))?;

    // Strip port
    let host = match host.rfind(':') {
        Some(pos) if host[pos + 1..].bytes().all(|b| b.is_ascii_digit()) => &host[..pos],
        _ => host,
    };

    Ok(host.to_lowercase())
}

// ---------------------------------------------------------------------------
// Strategy 1: Subdomain
// ---------------------------------------------------------------------------

/// Extracts tenant slug from a single-level subdomain relative to a base domain.
///
/// Created by [`subdomain()`]. Produces [`TenantId::Slug`].
///
/// Multi-level subdomains (e.g., `a.b.base.com`) and bare base-domain
/// requests are rejected with 400 Bad Request.
pub struct SubdomainStrategy {
    base_domain: String,
}

impl SubdomainStrategy {
    fn new(base_domain: &str) -> Self {
        Self {
            base_domain: base_domain.to_lowercase(),
        }
    }
}

impl TenantStrategy for SubdomainStrategy {
    fn extract(&self, parts: &mut http::request::Parts) -> Result<TenantId> {
        let host = host_from_parts(parts)?;
        let suffix = format!(".{}", self.base_domain);

        if !host.ends_with(&suffix) {
            return Err(Error::bad_request("host is not a subdomain of base domain"));
        }

        let subdomain = &host[..host.len() - suffix.len()];

        if subdomain.is_empty() {
            return Err(Error::bad_request("no subdomain in host"));
        }

        // Only one level allowed
        if subdomain.contains('.') {
            return Err(Error::bad_request("multi-level subdomains not allowed"));
        }

        Ok(TenantId::Slug(subdomain.to_string()))
    }
}

/// Returns a strategy that extracts the tenant slug from a subdomain of `base_domain`.
pub fn subdomain(base_domain: &str) -> SubdomainStrategy {
    SubdomainStrategy::new(base_domain)
}

// ---------------------------------------------------------------------------
// Strategy 2: Domain
// ---------------------------------------------------------------------------

/// Extracts tenant identifier from the full domain name in the `Host` header.
///
/// Created by [`domain()`]. Produces [`TenantId::Domain`].
pub struct DomainStrategy;

impl TenantStrategy for DomainStrategy {
    fn extract(&self, parts: &mut http::request::Parts) -> Result<TenantId> {
        let host = host_from_parts(parts)?;
        Ok(TenantId::Domain(host))
    }
}

/// Returns a strategy that uses the full domain as the tenant identifier.
pub fn domain() -> DomainStrategy {
    DomainStrategy
}

// ---------------------------------------------------------------------------
// Strategy 3: Subdomain or Domain
// ---------------------------------------------------------------------------

/// Extracts tenant from subdomain (as slug) or falls back to the full domain (as custom domain).
///
/// Created by [`subdomain_or_domain()`]. Produces [`TenantId::Slug`] or [`TenantId::Domain`].
///
/// - Single-level subdomain of base -> [`TenantId::Slug`]
/// - Unrelated host -> [`TenantId::Domain`] (custom domain)
/// - Base domain exactly -> 400 Bad Request
/// - Multi-level subdomain -> 400 Bad Request
pub struct SubdomainOrDomainStrategy {
    base_domain: String,
}

impl SubdomainOrDomainStrategy {
    fn new(base_domain: &str) -> Self {
        Self {
            base_domain: base_domain.to_lowercase(),
        }
    }
}

impl TenantStrategy for SubdomainOrDomainStrategy {
    fn extract(&self, parts: &mut http::request::Parts) -> Result<TenantId> {
        let host = host_from_parts(parts)?;
        let suffix = format!(".{}", self.base_domain);

        if host == self.base_domain {
            return Err(Error::bad_request(
                "base domain is not a valid tenant identifier",
            ));
        }

        if host.ends_with(&suffix) {
            let subdomain = &host[..host.len() - suffix.len()];
            if subdomain.is_empty() {
                return Err(Error::bad_request("no subdomain in host"));
            }
            if subdomain.contains('.') {
                return Err(Error::bad_request("multi-level subdomains not allowed"));
            }
            Ok(TenantId::Slug(subdomain.to_string()))
        } else {
            Ok(TenantId::Domain(host))
        }
    }
}

/// Returns a strategy that extracts from a subdomain, falling back to the full domain.
pub fn subdomain_or_domain(base_domain: &str) -> SubdomainOrDomainStrategy {
    SubdomainOrDomainStrategy::new(base_domain)
}

// ---------------------------------------------------------------------------
// Strategy 4: Header
// ---------------------------------------------------------------------------

/// Extracts tenant identifier from a named request header.
///
/// Created by [`header()`]. Produces [`TenantId::Id`].
pub struct HeaderStrategy {
    header_name: http::HeaderName,
}

impl HeaderStrategy {
    fn new(name: &str) -> Self {
        Self {
            header_name: http::HeaderName::from_bytes(name.as_bytes())
                .expect("invalid header name"),
        }
    }
}

impl TenantStrategy for HeaderStrategy {
    fn extract(&self, parts: &mut http::request::Parts) -> Result<TenantId> {
        let value = parts
            .headers
            .get(&self.header_name)
            .ok_or_else(|| Error::bad_request(format!("missing {} header", self.header_name)))?
            .to_str()
            .map_err(|_| {
                Error::bad_request(format!("invalid {} header value", self.header_name))
            })?;
        Ok(TenantId::Id(value.to_string()))
    }
}

/// Returns a strategy that reads the tenant identifier from the given request header.
///
/// # Panics
///
/// Panics if `name` is not a valid HTTP header name.
pub fn header(name: &str) -> HeaderStrategy {
    HeaderStrategy::new(name)
}

// ---------------------------------------------------------------------------
// Strategy 5: API Key Header
// ---------------------------------------------------------------------------

/// Extracts tenant API key from a named request header.
///
/// Created by [`api_key_header()`]. Produces [`TenantId::ApiKey`], which is
/// **redacted** in `Display` and `Debug` output.
pub struct ApiKeyHeaderStrategy {
    header_name: http::HeaderName,
}

impl ApiKeyHeaderStrategy {
    fn new(name: &str) -> Self {
        Self {
            header_name: http::HeaderName::from_bytes(name.as_bytes())
                .expect("invalid header name"),
        }
    }
}

impl TenantStrategy for ApiKeyHeaderStrategy {
    fn extract(&self, parts: &mut http::request::Parts) -> Result<TenantId> {
        let value = parts
            .headers
            .get(&self.header_name)
            .ok_or_else(|| Error::bad_request(format!("missing {} header", self.header_name)))?
            .to_str()
            .map_err(|_| {
                Error::bad_request(format!("invalid {} header value", self.header_name))
            })?;
        Ok(TenantId::ApiKey(value.to_string()))
    }
}

/// Returns a strategy that reads an API key from the given request header.
///
/// # Panics
///
/// Panics if `name` is not a valid HTTP header name.
pub fn api_key_header(name: &str) -> ApiKeyHeaderStrategy {
    ApiKeyHeaderStrategy::new(name)
}

// ---------------------------------------------------------------------------
// Strategy 6: Path Prefix
// ---------------------------------------------------------------------------

/// Extracts tenant slug from a path prefix and rewrites the URI.
///
/// Created by [`path_prefix()`]. Produces [`TenantId::Slug`].
///
/// Strips the prefix and tenant slug from the URI before the request reaches
/// handlers, preserving the query string. For example, with prefix `/org`,
/// a request to `/org/acme/settings?tab=billing` becomes `/settings?tab=billing`
/// and the slug `acme` is extracted.
pub struct PathPrefixStrategy {
    prefix: String,
}

impl PathPrefixStrategy {
    fn new(prefix: &str) -> Self {
        Self {
            prefix: prefix.to_string(),
        }
    }
}

impl TenantStrategy for PathPrefixStrategy {
    fn extract(&self, parts: &mut http::request::Parts) -> Result<TenantId> {
        let path = parts.uri.path();

        if !path.starts_with(&self.prefix) {
            return Err(Error::bad_request(format!(
                "path does not start with prefix '{}'",
                self.prefix
            )));
        }

        let after_prefix = &path[self.prefix.len()..];

        // Must have /slug after prefix
        let after_prefix = after_prefix
            .strip_prefix('/')
            .ok_or_else(|| Error::bad_request("no tenant segment after prefix"))?;

        if after_prefix.is_empty() {
            return Err(Error::bad_request("no tenant segment after prefix"));
        }

        // Split slug from remaining path
        let (slug, remaining) = match after_prefix.find('/') {
            Some(pos) => (&after_prefix[..pos], &after_prefix[pos..]),
            None => (after_prefix, "/"),
        };

        if slug.is_empty() {
            return Err(Error::bad_request("empty tenant slug in path"));
        }

        // Collect into owned values before reassigning parts.uri
        let slug = slug.to_string();
        let remaining = remaining.to_string();

        // Rewrite URI -- preserve query string
        let new_path_and_query = match parts.uri.query() {
            Some(q) => format!("{remaining}?{q}"),
            None => remaining,
        };
        let new_uri = http::Uri::builder()
            .path_and_query(new_path_and_query)
            .build()
            .map_err(|e| Error::internal(format!("failed to rewrite URI: {e}")))?;
        parts.uri = new_uri;

        Ok(TenantId::Slug(slug))
    }
}

/// Returns a strategy that extracts a tenant slug from a path prefix and rewrites the URI.
pub fn path_prefix(prefix: &str) -> PathPrefixStrategy {
    PathPrefixStrategy::new(prefix)
}

// ---------------------------------------------------------------------------
// Strategy 7: Path Parameter
// ---------------------------------------------------------------------------

/// Extracts tenant slug from a named axum path parameter.
///
/// Created by [`path_param()`]. Produces [`TenantId::Slug`].
///
/// This strategy requires `.route_layer()` instead of `.layer()` because
/// axum path parameters are only available after route matching.
pub struct PathParamStrategy {
    param_name: String,
}

impl PathParamStrategy {
    fn new(name: &str) -> Self {
        Self {
            param_name: name.to_string(),
        }
    }
}

/// A no-op `Wake` implementation used to synchronously poll trivially-ready futures.
struct NoopWaker;

impl Wake for NoopWaker {
    fn wake(self: std::sync::Arc<Self>) {}
}

impl TenantStrategy for PathParamStrategy {
    fn extract(&self, parts: &mut http::request::Parts) -> Result<TenantId> {
        // `RawPathParams::from_request_parts` is async in signature but performs
        // no actual I/O -- it reads from extensions synchronously. We poll it
        // once with a noop waker; it is always immediately ready.
        use axum::extract::FromRequestParts;
        use axum::extract::RawPathParams;

        let waker = std::sync::Arc::new(NoopWaker).into();
        let mut cx = Context::from_waker(&waker);

        let mut fut = pin!(RawPathParams::from_request_parts(parts, &()));

        let raw_params = match fut.as_mut().poll(&mut cx) {
            Poll::Ready(Ok(params)) => params,
            Poll::Ready(Err(_)) => {
                return Err(Error::internal(
                    "path parameters not available (use route_layer instead of layer)",
                ));
            }
            Poll::Pending => {
                return Err(Error::internal(
                    "unexpected pending state extracting path params",
                ));
            }
        };

        for (key, value) in &raw_params {
            if key == self.param_name {
                return Ok(TenantId::Slug(value.to_string()));
            }
        }

        Err(Error::internal(format!(
            "path parameter '{}' not found in route",
            self.param_name
        )))
    }
}

/// Returns a strategy that reads the tenant slug from a named path parameter.
pub fn path_param(name: &str) -> PathParamStrategy {
    PathParamStrategy::new(name)
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
mod tests {
    use http::StatusCode;

    use super::*;

    fn make_parts(host: Option<&str>, uri: &str) -> http::request::Parts {
        let mut builder = http::Request::builder().uri(uri);
        if let Some(h) = host {
            builder = builder.header("host", h);
        }
        let (parts, _) = builder.body(()).unwrap().into_parts();
        parts
    }

    // -- host_from_parts ----------------------------------------------------

    #[test]
    fn host_strips_port() {
        let parts = make_parts(Some("acme.com:8080"), "/");
        let host = host_from_parts(&parts).unwrap();
        assert_eq!(host, "acme.com");
    }

    #[test]
    fn host_missing_returns_error() {
        let parts = make_parts(None, "/");
        let err = host_from_parts(&parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
        assert!(err.message().contains("missing Host header"));
    }

    // -- SubdomainStrategy --------------------------------------------------

    #[test]
    fn subdomain_valid() {
        let s = subdomain("acme.com");
        let mut parts = make_parts(Some("tenant1.acme.com"), "/");
        let id = s.extract(&mut parts).unwrap();
        assert_eq!(id, TenantId::Slug("tenant1".into()));
    }

    #[test]
    fn subdomain_case_insensitive() {
        let s = subdomain("acme.com");
        let mut parts = make_parts(Some("TENANT1.ACME.COM"), "/");
        let id = s.extract(&mut parts).unwrap();
        assert_eq!(id, TenantId::Slug("tenant1".into()));
    }

    #[test]
    fn subdomain_bare_base_domain_error() {
        let s = subdomain("acme.com");
        let mut parts = make_parts(Some("acme.com"), "/");
        let err = s.extract(&mut parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn subdomain_multi_level_error() {
        let s = subdomain("acme.com");
        let mut parts = make_parts(Some("a.b.acme.com"), "/");
        let err = s.extract(&mut parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
        assert!(err.message().contains("multi-level"));
    }

    #[test]
    fn subdomain_multi_level_base_domain() {
        let s = subdomain("app.acme.com");
        let mut parts = make_parts(Some("tenant1.app.acme.com"), "/");
        let id = s.extract(&mut parts).unwrap();
        assert_eq!(id, TenantId::Slug("tenant1".into()));
    }

    #[test]
    fn subdomain_port_stripped() {
        let s = subdomain("acme.com");
        let mut parts = make_parts(Some("tenant1.acme.com:3000"), "/");
        let id = s.extract(&mut parts).unwrap();
        assert_eq!(id, TenantId::Slug("tenant1".into()));
    }

    #[test]
    fn subdomain_missing_host() {
        let s = subdomain("acme.com");
        let mut parts = make_parts(None, "/");
        let err = s.extract(&mut parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    }

    // -- DomainStrategy -----------------------------------------------------

    #[test]
    fn domain_valid() {
        let s = domain();
        let mut parts = make_parts(Some("custom.example.com"), "/");
        let id = s.extract(&mut parts).unwrap();
        assert_eq!(id, TenantId::Domain("custom.example.com".into()));
    }

    #[test]
    fn domain_strips_port() {
        let s = domain();
        let mut parts = make_parts(Some("custom.example.com:443"), "/");
        let id = s.extract(&mut parts).unwrap();
        assert_eq!(id, TenantId::Domain("custom.example.com".into()));
    }

    #[test]
    fn domain_missing_host() {
        let s = domain();
        let mut parts = make_parts(None, "/");
        let err = s.extract(&mut parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    }

    // -- SubdomainOrDomainStrategy ------------------------------------------

    #[test]
    fn subdomain_or_domain_subdomain_branch() {
        let s = subdomain_or_domain("acme.com");
        let mut parts = make_parts(Some("tenant1.acme.com"), "/");
        let id = s.extract(&mut parts).unwrap();
        assert_eq!(id, TenantId::Slug("tenant1".into()));
    }

    #[test]
    fn subdomain_or_domain_custom_domain_branch() {
        let s = subdomain_or_domain("acme.com");
        let mut parts = make_parts(Some("custom.example.org"), "/");
        let id = s.extract(&mut parts).unwrap();
        assert_eq!(id, TenantId::Domain("custom.example.org".into()));
    }

    #[test]
    fn subdomain_or_domain_base_domain_error() {
        let s = subdomain_or_domain("acme.com");
        let mut parts = make_parts(Some("acme.com"), "/");
        let err = s.extract(&mut parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
        assert!(err.message().contains("base domain"));
    }

    #[test]
    fn subdomain_or_domain_multi_level_error() {
        let s = subdomain_or_domain("acme.com");
        let mut parts = make_parts(Some("a.b.acme.com"), "/");
        let err = s.extract(&mut parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
        assert!(err.message().contains("multi-level"));
    }

    #[test]
    fn subdomain_or_domain_missing_host() {
        let s = subdomain_or_domain("acme.com");
        let mut parts = make_parts(None, "/");
        let err = s.extract(&mut parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    }

    // -- HeaderStrategy -----------------------------------------------------

    #[test]
    fn header_valid() {
        let s = header("x-tenant-id");
        let mut parts = make_parts(Some("localhost"), "/");
        parts
            .headers
            .insert("x-tenant-id", "abc123".parse().unwrap());
        let id = s.extract(&mut parts).unwrap();
        assert_eq!(id, TenantId::Id("abc123".into()));
    }

    #[test]
    fn header_missing_error() {
        let s = header("x-tenant-id");
        let mut parts = make_parts(Some("localhost"), "/");
        let err = s.extract(&mut parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
        assert!(err.message().contains("missing"));
    }

    #[test]
    fn header_non_utf8_error() {
        let s = header("x-tenant-id");
        let mut parts = make_parts(Some("localhost"), "/");
        parts.headers.insert(
            "x-tenant-id",
            http::HeaderValue::from_bytes(&[0x80, 0x81]).unwrap(),
        );
        let err = s.extract(&mut parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
        assert!(err.message().contains("invalid"));
    }

    // -- ApiKeyHeaderStrategy -----------------------------------------------

    #[test]
    fn api_key_header_valid() {
        let s = api_key_header("x-api-key");
        let mut parts = make_parts(Some("localhost"), "/");
        parts
            .headers
            .insert("x-api-key", "sk_live_abc".parse().unwrap());
        let id = s.extract(&mut parts).unwrap();
        assert_eq!(id, TenantId::ApiKey("sk_live_abc".into()));
    }

    #[test]
    fn api_key_header_missing_error() {
        let s = api_key_header("x-api-key");
        let mut parts = make_parts(Some("localhost"), "/");
        let err = s.extract(&mut parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
        assert!(err.message().contains("missing"));
    }

    #[test]
    fn api_key_header_non_utf8_error() {
        let s = api_key_header("x-api-key");
        let mut parts = make_parts(Some("localhost"), "/");
        parts.headers.insert(
            "x-api-key",
            http::HeaderValue::from_bytes(&[0x80, 0x81]).unwrap(),
        );
        let err = s.extract(&mut parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
        assert!(err.message().contains("invalid"));
    }

    // -- PathPrefixStrategy -------------------------------------------------

    #[test]
    fn path_prefix_valid() {
        let s = path_prefix("/org");
        let mut parts = make_parts(Some("localhost"), "/org/acme/dashboard/settings");
        let id = s.extract(&mut parts).unwrap();
        assert_eq!(id, TenantId::Slug("acme".into()));
        assert_eq!(parts.uri.path(), "/dashboard/settings");
    }

    #[test]
    fn path_prefix_only_slug() {
        let s = path_prefix("/org");
        let mut parts = make_parts(Some("localhost"), "/org/acme");
        let id = s.extract(&mut parts).unwrap();
        assert_eq!(id, TenantId::Slug("acme".into()));
        assert_eq!(parts.uri.path(), "/");
    }

    #[test]
    fn path_prefix_wrong_prefix_error() {
        let s = path_prefix("/org");
        let mut parts = make_parts(Some("localhost"), "/api/v1");
        let err = s.extract(&mut parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
        assert!(err.message().contains("prefix"));
    }

    #[test]
    fn path_prefix_no_segment_error() {
        let s = path_prefix("/org");
        let mut parts = make_parts(Some("localhost"), "/org");
        let err = s.extract(&mut parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn path_prefix_no_segment_trailing_slash_error() {
        let s = path_prefix("/org");
        let mut parts = make_parts(Some("localhost"), "/org/");
        let err = s.extract(&mut parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn path_prefix_preserves_query_string() {
        let s = path_prefix("/org");
        let mut parts = make_parts(Some("localhost"), "/org/acme/page?foo=bar&baz=1");
        let id = s.extract(&mut parts).unwrap();
        assert_eq!(id, TenantId::Slug("acme".into()));
        assert_eq!(parts.uri.path(), "/page");
        assert_eq!(parts.uri.query(), Some("foo=bar&baz=1"));
    }

    #[test]
    fn path_prefix_empty_prefix() {
        let s = path_prefix("");
        let mut parts = make_parts(Some("localhost"), "/acme/page");
        let id = s.extract(&mut parts).unwrap();
        assert_eq!(id, TenantId::Slug("acme".into()));
        assert_eq!(parts.uri.path(), "/page");
    }

    // -- PathParamStrategy --------------------------------------------------

    #[tokio::test]
    async fn path_param_extracts_from_route() {
        use axum::Router;
        use axum::routing::get;
        use tower::ServiceExt as _;

        use super::super::middleware as tenant_middleware;
        use super::super::traits::{HasTenantId, TenantResolver};

        #[derive(Clone, Debug)]
        struct TestTenant {
            slug: String,
        }

        impl HasTenantId for TestTenant {
            fn tenant_id(&self) -> &str {
                &self.slug
            }
        }

        struct SlugResolver;
        impl TenantResolver for SlugResolver {
            type Tenant = TestTenant;
            async fn resolve(&self, id: &TenantId) -> crate::Result<TestTenant> {
                Ok(TestTenant {
                    slug: id.as_str().to_string(),
                })
            }
        }

        // Handler is module-level async fn to satisfy axum Handler bounds
        async fn handler(tenant: super::super::Tenant<TestTenant>) -> String {
            format!("tenant:{}", tenant.slug)
        }

        let layer = tenant_middleware(path_param("tenant"), SlugResolver);
        let app = Router::new()
            .route("/{tenant}/action", get(handler))
            .route_layer(layer);

        let req = http::Request::builder()
            .uri("/acme/action")
            .body(axum::body::Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), http::StatusCode::OK);

        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(&body[..], b"tenant:acme");
    }

    #[test]
    fn path_param_missing_returns_error() {
        let s = path_param("tenant");
        let mut parts = make_parts(Some("localhost"), "/whatever");
        // No path params in extensions — should return 500
        let err = s.extract(&mut parts).unwrap_err();
        assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }
}