axum-acl 0.3.0

Flexible ACL middleware for axum 0.8 with 5-tuple rule matching (endpoint, role, id, ip, time)
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
//! Role and ID extraction from HTTP requests.
//!
//! This module provides traits for extracting user identity from requests:
//! - [`RoleExtractor`]: Extract roles as a `u32` bitmask (up to 32 roles)
//! - [`IdExtractor`]: Extract user/resource ID as a `String`
//!
//! ## Custom Role Translation
//!
//! If your system uses a different role scheme (e.g., string roles, enums),
//! implement `RoleExtractor` to translate to u32 bitmask:
//!
//! ```
//! use axum_acl::{RoleExtractor, RoleExtractionResult};
//! use http::Request;
//!
//! // Your role enum
//! enum Role { Admin, User, Guest }
//!
//! // Define bit positions
//! const ROLE_ADMIN: u32 = 1 << 0;
//! const ROLE_USER: u32 = 1 << 1;
//! const ROLE_GUEST: u32 = 1 << 2;
//!
//! fn roles_to_mask(roles: &[Role]) -> u32 {
//!     roles.iter().fold(0u32, |mask, role| {
//!         mask | match role {
//!             Role::Admin => ROLE_ADMIN,
//!             Role::User => ROLE_USER,
//!             Role::Guest => ROLE_GUEST,
//!         }
//!     })
//! }
//! ```
//!
//! ## Path Parameter ID Matching
//!
//! For paths like `/api/boat/{id}/size`, the `{id}` is matched against
//! the user's ID from `IdExtractor`. This enables ownership-based access:
//!
//! ```text
//! Rule: /api/boat/{id}/**  role=USER, id={id}  -> allow
//! User: id="boat-123", roles=USER
//! Path: /api/boat/boat-123/size  -> ALLOWED (id matches)
//! Path: /api/boat/boat-456/size  -> DENIED (id doesn't match)
//! ```

use crate::rule::BitmaskAuth;
use http::Request;
use std::sync::Arc;

/// Result of role extraction.
#[derive(Debug, Clone)]
pub enum RoleExtractionResult {
    /// Roles were successfully extracted (u32 bitmask).
    Roles(u32),
    /// No role could be extracted (user is anonymous/guest).
    Anonymous,
    /// An error occurred during extraction.
    Error(String),
}

impl RoleExtractionResult {
    /// Get the roles bitmask, returning a default for anonymous users.
    pub fn roles_or(&self, default: u32) -> u32 {
        match self {
            Self::Roles(roles) => *roles,
            Self::Anonymous => default,
            Self::Error(_) => default,
        }
    }

    /// Get the roles, returning 0 (no roles) for anonymous users.
    pub fn roles_or_none(&self) -> u32 {
        self.roles_or(0)
    }
}

/// Trait for extracting roles from HTTP requests.
///
/// Implement this trait to customize how roles are determined from incoming
/// requests. This allows integration with various authentication systems.
///
/// Roles are represented as `u32` bitmasks, allowing multiple roles per user.
///
/// The trait is synchronous because role extraction typically involves
/// reading headers or request extensions, which doesn't require async.
///
/// # Example
/// ```
/// use axum_acl::{RoleExtractor, RoleExtractionResult};
/// use http::Request;
///
/// const ROLE_ADMIN: u32 = 0b001;
/// const ROLE_USER: u32 = 0b010;
///
/// /// Extract roles from a custom header as a bitmask.
/// struct CustomRolesExtractor;
///
/// impl<B> RoleExtractor<B> for CustomRolesExtractor {
///     fn extract_roles(&self, request: &Request<B>) -> RoleExtractionResult {
///         match request.headers().get("X-Roles") {
///             Some(value) => {
///                 match value.to_str() {
///                     Ok(s) => {
///                         // Parse comma-separated role names to bitmask
///                         let mut mask = 0u32;
///                         for role in s.split(',') {
///                             match role.trim() {
///                                 "admin" => mask |= ROLE_ADMIN,
///                                 "user" => mask |= ROLE_USER,
///                                 _ => {}
///                             }
///                         }
///                         RoleExtractionResult::Roles(mask)
///                     }
///                     Err(_) => RoleExtractionResult::Anonymous,
///                 }
///             }
///             None => RoleExtractionResult::Anonymous,
///         }
///     }
/// }
/// ```
pub trait RoleExtractor<B>: Send + Sync {
    /// Extract the roles bitmask from an HTTP request.
    fn extract_roles(&self, request: &Request<B>) -> RoleExtractionResult;
}

// Implement for Arc<T> where T: RoleExtractor
impl<B, T: RoleExtractor<B>> RoleExtractor<B> for Arc<T> {
    fn extract_roles(&self, request: &Request<B>) -> RoleExtractionResult {
        (**self).extract_roles(request)
    }
}

// Implement for Box<T> where T: RoleExtractor
impl<B, T: RoleExtractor<B> + ?Sized> RoleExtractor<B> for Box<T> {
    fn extract_roles(&self, request: &Request<B>) -> RoleExtractionResult {
        (**self).extract_roles(request)
    }
}

/// Extract roles bitmask from an HTTP header.
///
/// The header value is parsed as a u32 bitmask directly, or you can use
/// a custom parser function to convert header values to bitmasks.
///
/// # Example
/// ```
/// use axum_acl::HeaderRoleExtractor;
///
/// // Extract roles bitmask directly from X-Roles header (as decimal or hex)
/// let extractor = HeaderRoleExtractor::new("X-Roles");
///
/// // With a custom default roles bitmask for missing headers
/// let extractor = HeaderRoleExtractor::new("X-Roles")
///     .with_default_roles(0b100);  // guest role
/// ```
#[derive(Debug, Clone)]
pub struct HeaderRoleExtractor {
    header_name: String,
    default_roles: u32,
}

impl HeaderRoleExtractor {
    /// Create a new header role extractor.
    pub fn new(header_name: impl Into<String>) -> Self {
        Self {
            header_name: header_name.into(),
            default_roles: 0,
        }
    }

    /// Set default roles bitmask to use when the header is missing.
    pub fn with_default_roles(mut self, roles: u32) -> Self {
        self.default_roles = roles;
        self
    }
}

impl<B> RoleExtractor<B> for HeaderRoleExtractor {
    fn extract_roles(&self, request: &Request<B>) -> RoleExtractionResult {
        match request.headers().get(&self.header_name) {
            Some(value) => match value.to_str() {
                Ok(s) if !s.is_empty() => {
                    // Try parsing as decimal first, then hex (with 0x prefix)
                    let trimmed = s.trim();
                    if let Ok(roles) = trimmed.parse::<u32>() {
                        RoleExtractionResult::Roles(roles)
                    } else if let Some(hex) = trimmed.strip_prefix("0x") {
                        u32::from_str_radix(hex, 16)
                            .map(RoleExtractionResult::Roles)
                            .unwrap_or_else(|_| {
                                if self.default_roles != 0 {
                                    RoleExtractionResult::Roles(self.default_roles)
                                } else {
                                    RoleExtractionResult::Anonymous
                                }
                            })
                    } else if self.default_roles != 0 {
                        RoleExtractionResult::Roles(self.default_roles)
                    } else {
                        RoleExtractionResult::Anonymous
                    }
                }
                _ => {
                    if self.default_roles != 0 {
                        RoleExtractionResult::Roles(self.default_roles)
                    } else {
                        RoleExtractionResult::Anonymous
                    }
                }
            },
            None => {
                if self.default_roles != 0 {
                    RoleExtractionResult::Roles(self.default_roles)
                } else {
                    RoleExtractionResult::Anonymous
                }
            }
        }
    }
}

/// Extract roles from a request extension.
///
/// This extractor looks for roles that were set by a previous middleware
/// (e.g., an authentication middleware) as a request extension.
///
/// # Example
/// ```
/// use axum_acl::ExtensionRoleExtractor;
///
/// // The authentication middleware should insert a Roles struct into extensions
/// #[derive(Clone)]
/// struct UserRoles(u32);
///
/// let extractor = ExtensionRoleExtractor::<UserRoles>::new(|roles| roles.0);
/// ```
pub struct ExtensionRoleExtractor<T> {
    extract_fn: Box<dyn Fn(&T) -> u32 + Send + Sync>,
}

impl<T> ExtensionRoleExtractor<T> {
    /// Create a new extension role extractor.
    ///
    /// The `extract_fn` converts the extension type to a roles bitmask.
    pub fn new<F>(extract_fn: F) -> Self
    where
        F: Fn(&T) -> u32 + Send + Sync + 'static,
    {
        Self {
            extract_fn: Box::new(extract_fn),
        }
    }
}

impl<T> std::fmt::Debug for ExtensionRoleExtractor<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ExtensionRoleExtractor")
            .field("type", &std::any::type_name::<T>())
            .finish()
    }
}

impl<B, T: Clone + Send + Sync + 'static> RoleExtractor<B> for ExtensionRoleExtractor<T> {
    fn extract_roles(&self, request: &Request<B>) -> RoleExtractionResult {
        match request.extensions().get::<T>() {
            Some(ext) => RoleExtractionResult::Roles((self.extract_fn)(ext)),
            None => RoleExtractionResult::Anonymous,
        }
    }
}

/// A roles extractor that always returns fixed roles.
///
/// Useful for testing or for routes that should always use specific roles.
#[derive(Debug, Clone)]
pub struct FixedRoleExtractor {
    roles: u32,
}

impl FixedRoleExtractor {
    /// Create a new fixed roles extractor.
    pub fn new(roles: u32) -> Self {
        Self { roles }
    }
}

impl<B> RoleExtractor<B> for FixedRoleExtractor {
    fn extract_roles(&self, _request: &Request<B>) -> RoleExtractionResult {
        RoleExtractionResult::Roles(self.roles)
    }
}

/// A role extractor that always returns anonymous (no roles).
#[derive(Debug, Clone, Default)]
pub struct AnonymousRoleExtractor;

impl AnonymousRoleExtractor {
    /// Create a new anonymous role extractor.
    pub fn new() -> Self {
        Self
    }
}

impl<B> RoleExtractor<B> for AnonymousRoleExtractor {
    fn extract_roles(&self, _request: &Request<B>) -> RoleExtractionResult {
        RoleExtractionResult::Anonymous
    }
}

/// A composite extractor that tries multiple extractors in order.
///
/// Returns the first successful roles extraction, or anonymous if all fail.
/// Roles from multiple extractors are NOT combined - only the first match is used.
pub struct ChainedRoleExtractor<B> {
    extractors: Vec<Box<dyn RoleExtractor<B>>>,
}

// ============================================================================
// ID Extraction
// ============================================================================

/// Result of ID extraction.
#[derive(Debug, Clone)]
pub enum IdExtractionResult {
    /// ID was successfully extracted.
    Id(String),
    /// No ID could be extracted (anonymous user).
    Anonymous,
    /// An error occurred during extraction.
    Error(String),
}

impl IdExtractionResult {
    /// Get the ID, returning a default for anonymous users.
    pub fn id_or(&self, default: impl Into<String>) -> String {
        match self {
            Self::Id(id) => id.clone(),
            Self::Anonymous => default.into(),
            Self::Error(_) => default.into(),
        }
    }

    /// Get the ID, returning "*" (wildcard) for anonymous users.
    pub fn id_or_wildcard(&self) -> String {
        self.id_or("*")
    }
}

/// Trait for extracting user/resource ID from HTTP requests.
///
/// Implement this trait to customize how user IDs are determined from
/// incoming requests. The ID is used for:
/// - Matching against `{id}` path parameters
/// - Direct ID matching in ACL rules
///
/// # Example: JWT User ID
/// ```
/// use axum_acl::{IdExtractor, IdExtractionResult};
/// use http::Request;
///
/// struct JwtIdExtractor;
///
/// impl<B> IdExtractor<B> for JwtIdExtractor {
///     fn extract_id(&self, request: &Request<B>) -> IdExtractionResult {
///         // In practice, you'd decode the JWT and extract the user ID
///         if let Some(auth) = request.headers().get("Authorization") {
///             if let Ok(s) = auth.to_str() {
///                 // Simplified: extract user ID from token
///                 if s.starts_with("Bearer ") {
///                     return IdExtractionResult::Id("user-123".to_string());
///                 }
///             }
///         }
///         IdExtractionResult::Anonymous
///     }
/// }
/// ```
///
/// # Example: Path-based Resource ID
/// ```
/// use axum_acl::{IdExtractor, IdExtractionResult};
/// use http::Request;
///
/// /// Extract resource ID from path like /api/boat/{id}/...
/// struct PathIdExtractor {
///     prefix: String,  // e.g., "/api/boat/"
/// }
///
/// impl<B> IdExtractor<B> for PathIdExtractor {
///     fn extract_id(&self, request: &Request<B>) -> IdExtractionResult {
///         let path = request.uri().path();
///         if let Some(rest) = path.strip_prefix(&self.prefix) {
///             // Get the next path segment as the ID
///             if let Some(id) = rest.split('/').next() {
///                 if !id.is_empty() {
///                     return IdExtractionResult::Id(id.to_string());
///                 }
///             }
///         }
///         IdExtractionResult::Anonymous
///     }
/// }
/// ```
pub trait IdExtractor<B>: Send + Sync {
    /// Extract the user/resource ID from an HTTP request.
    fn extract_id(&self, request: &Request<B>) -> IdExtractionResult;
}

// Implement for Arc<T> where T: IdExtractor
impl<B, T: IdExtractor<B>> IdExtractor<B> for Arc<T> {
    fn extract_id(&self, request: &Request<B>) -> IdExtractionResult {
        (**self).extract_id(request)
    }
}

// Implement for Box<T> where T: IdExtractor
impl<B, T: IdExtractor<B> + ?Sized> IdExtractor<B> for Box<T> {
    fn extract_id(&self, request: &Request<B>) -> IdExtractionResult {
        (**self).extract_id(request)
    }
}

/// Extract ID from an HTTP header.
///
/// # Example
/// ```
/// use axum_acl::HeaderIdExtractor;
///
/// // Extract user ID from X-User-Id header
/// let extractor = HeaderIdExtractor::new("X-User-Id");
/// ```
#[derive(Debug, Clone)]
pub struct HeaderIdExtractor {
    header_name: String,
}

impl HeaderIdExtractor {
    /// Create a new header ID extractor.
    pub fn new(header_name: impl Into<String>) -> Self {
        Self {
            header_name: header_name.into(),
        }
    }
}

impl<B> IdExtractor<B> for HeaderIdExtractor {
    fn extract_id(&self, request: &Request<B>) -> IdExtractionResult {
        match request.headers().get(&self.header_name) {
            Some(value) => match value.to_str() {
                Ok(s) if !s.is_empty() => IdExtractionResult::Id(s.trim().to_string()),
                _ => IdExtractionResult::Anonymous,
            },
            None => IdExtractionResult::Anonymous,
        }
    }
}

/// Extract ID from a request extension.
///
/// This extractor looks for an ID that was set by a previous middleware
/// (e.g., an authentication middleware) as a request extension.
///
/// # Example
/// ```
/// use axum_acl::ExtensionIdExtractor;
///
/// // The authentication middleware should insert a User struct into extensions
/// #[derive(Clone)]
/// struct AuthenticatedUser {
///     id: String,
///     name: String,
/// }
///
/// let extractor = ExtensionIdExtractor::<AuthenticatedUser>::new(|user| user.id.clone());
/// ```
pub struct ExtensionIdExtractor<T> {
    extract_fn: Box<dyn Fn(&T) -> String + Send + Sync>,
}

impl<T> ExtensionIdExtractor<T> {
    /// Create a new extension ID extractor.
    ///
    /// The `extract_fn` converts the extension type to an ID string.
    pub fn new<F>(extract_fn: F) -> Self
    where
        F: Fn(&T) -> String + Send + Sync + 'static,
    {
        Self {
            extract_fn: Box::new(extract_fn),
        }
    }
}

impl<T> std::fmt::Debug for ExtensionIdExtractor<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ExtensionIdExtractor")
            .field("type", &std::any::type_name::<T>())
            .finish()
    }
}

impl<B, T: Clone + Send + Sync + 'static> IdExtractor<B> for ExtensionIdExtractor<T> {
    fn extract_id(&self, request: &Request<B>) -> IdExtractionResult {
        match request.extensions().get::<T>() {
            Some(ext) => IdExtractionResult::Id((self.extract_fn)(ext)),
            None => IdExtractionResult::Anonymous,
        }
    }
}

/// An ID extractor that always returns a fixed ID.
///
/// Useful for testing.
#[derive(Debug, Clone)]
pub struct FixedIdExtractor {
    id: String,
}

impl FixedIdExtractor {
    /// Create a new fixed ID extractor.
    pub fn new(id: impl Into<String>) -> Self {
        Self { id: id.into() }
    }
}

impl<B> IdExtractor<B> for FixedIdExtractor {
    fn extract_id(&self, _request: &Request<B>) -> IdExtractionResult {
        IdExtractionResult::Id(self.id.clone())
    }
}

/// An ID extractor that always returns anonymous (no ID).
#[derive(Debug, Clone, Default)]
pub struct AnonymousIdExtractor;

impl AnonymousIdExtractor {
    /// Create a new anonymous ID extractor.
    pub fn new() -> Self {
        Self
    }
}

impl<B> IdExtractor<B> for AnonymousIdExtractor {
    fn extract_id(&self, _request: &Request<B>) -> IdExtractionResult {
        IdExtractionResult::Anonymous
    }
}

// ============================================================================
// Generic Auth Extraction
// ============================================================================

/// Result of generic auth extraction.
#[derive(Debug, Clone)]
pub enum AuthResult<A> {
    /// Auth context was successfully extracted.
    Auth(A),
    /// No auth could be extracted (anonymous/guest).
    Anonymous,
    /// An error occurred during extraction.
    Error(String),
}

/// Trait for extracting a generic auth context from HTTP requests.
///
/// `A` is the auth type your ACL rules use.
/// `B` is the request body type.
pub trait AuthExtractor<A, B>: Send + Sync {
    /// Extract auth context from the request.
    fn extract_auth(&self, request: &Request<B>) -> AuthResult<A>;
}

/// Adapter that combines a `RoleExtractor` and `IdExtractor` into
/// an `AuthExtractor<BitmaskAuth, B>`.
pub struct BitmaskAuthExtractor<E, I> {
    role_extractor: E,
    id_extractor: I,
    anonymous_roles: u32,
    default_id: String,
}

impl<E, I> BitmaskAuthExtractor<E, I> {
    /// Create a new adapter from existing extractors.
    pub fn new(role_extractor: E, id_extractor: I) -> Self {
        Self {
            role_extractor,
            id_extractor,
            anonymous_roles: 0,
            default_id: "*".to_string(),
        }
    }

    /// Set the roles bitmask to use for anonymous users.
    pub fn with_anonymous_roles(mut self, roles: u32) -> Self {
        self.anonymous_roles = roles;
        self
    }

    /// Set the default ID when the ID extractor returns anonymous.
    pub fn with_default_id(mut self, id: impl Into<String>) -> Self {
        self.default_id = id.into();
        self
    }
}

impl<E: std::fmt::Debug, I: std::fmt::Debug> std::fmt::Debug for BitmaskAuthExtractor<E, I> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BitmaskAuthExtractor")
            .field("role_extractor", &self.role_extractor)
            .field("id_extractor", &self.id_extractor)
            .finish()
    }
}

impl<E, I, B> AuthExtractor<BitmaskAuth, B> for BitmaskAuthExtractor<E, I>
where
    E: RoleExtractor<B>,
    I: IdExtractor<B>,
{
    fn extract_auth(&self, request: &Request<B>) -> AuthResult<BitmaskAuth> {
        let roles = self.role_extractor.extract_roles(request).roles_or(self.anonymous_roles);
        let id = self.id_extractor.extract_id(request).id_or(&self.default_id);
        AuthResult::Auth(BitmaskAuth { roles, id })
    }
}

impl<B> ChainedRoleExtractor<B> {
    /// Create a new chained role extractor.
    pub fn new() -> Self {
        Self {
            extractors: Vec::new(),
        }
    }

    /// Add an extractor to the chain.
    pub fn push<E: RoleExtractor<B> + 'static>(mut self, extractor: E) -> Self {
        self.extractors.push(Box::new(extractor));
        self
    }
}

impl<B> Default for ChainedRoleExtractor<B> {
    fn default() -> Self {
        Self::new()
    }
}

impl<B> std::fmt::Debug for ChainedRoleExtractor<B> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ChainedRoleExtractor")
            .field("extractors_count", &self.extractors.len())
            .finish()
    }
}

impl<B> RoleExtractor<B> for ChainedRoleExtractor<B>
where
    B: Send + Sync,
{
    fn extract_roles(&self, request: &Request<B>) -> RoleExtractionResult {
        for extractor in &self.extractors {
            match extractor.extract_roles(request) {
                RoleExtractionResult::Roles(roles) => return RoleExtractionResult::Roles(roles),
                RoleExtractionResult::Error(e) => {
                    tracing::warn!(error = %e, "Role extractor failed, trying next");
                }
                RoleExtractionResult::Anonymous => continue,
            }
        }
        RoleExtractionResult::Anonymous
    }
}

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

    #[test]
    fn test_header_extractor_decimal() {
        let extractor = HeaderRoleExtractor::new("X-Roles");

        let req = Request::builder()
            .header("X-Roles", "5")  // 0b101 = roles 0 and 2
            .body(())
            .unwrap();

        match extractor.extract_roles(&req) {
            RoleExtractionResult::Roles(roles) => assert_eq!(roles, 5),
            _ => panic!("Expected Roles"),
        }
    }

    #[test]
    fn test_header_extractor_hex() {
        let extractor = HeaderRoleExtractor::new("X-Roles");

        let req = Request::builder()
            .header("X-Roles", "0x1F")  // 0b11111 = roles 0-4
            .body(())
            .unwrap();

        match extractor.extract_roles(&req) {
            RoleExtractionResult::Roles(roles) => assert_eq!(roles, 0x1F),
            _ => panic!("Expected Roles"),
        }
    }

    #[test]
    fn test_header_extractor_missing() {
        let extractor = HeaderRoleExtractor::new("X-Roles");

        let req = Request::builder().body(()).unwrap();

        match extractor.extract_roles(&req) {
            RoleExtractionResult::Anonymous => {}
            _ => panic!("Expected Anonymous"),
        }
    }

    #[test]
    fn test_header_extractor_default() {
        let extractor = HeaderRoleExtractor::new("X-Roles")
            .with_default_roles(0b100);  // guest role

        let req = Request::builder().body(()).unwrap();

        match extractor.extract_roles(&req) {
            RoleExtractionResult::Roles(roles) => assert_eq!(roles, 0b100),
            _ => panic!("Expected Roles"),
        }
    }

    #[test]
    fn test_fixed_extractor() {
        let extractor = FixedRoleExtractor::new(0b11);  // admin + user

        let req = Request::builder().body(()).unwrap();

        match extractor.extract_roles(&req) {
            RoleExtractionResult::Roles(roles) => assert_eq!(roles, 0b11),
            _ => panic!("Expected Roles"),
        }
    }
}