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
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
//! TOML configuration support for ACL rules.
//!
//! This module provides structures for loading ACL rules from TOML configuration,
//! either compiled-in at build time or read from a file at runtime.
//!
//! # Example TOML Format
//!
//! ```toml
//! [settings]
//! default_action = "deny"
//!
//! [[rules]]
//! role = "admin"
//! endpoint = "*"
//! action = "allow"
//! description = "Admins have full access"
//!
//! [[rules]]
//! role = "user"
//! endpoint = "/api/**"
//! time = { start = 9, end = 17, days = [0,1,2,3,4] }
//! action = "allow"
//!
//! [[rules]]
//! role = "*"
//! endpoint = "/blocked/**"
//! action = { type = "error", code = 403, message = "Access forbidden" }
//! ```
//!
//! # Usage
//!
//! ## Compile-time embedded config
//!
//! ```ignore
//! use axum_acl::AclTable;
//!
//! // Embed at compile time
//! const ACL_CONFIG: &str = include_str!("../acl.toml");
//!
//! let table = AclTable::from_toml(ACL_CONFIG).unwrap();
//! ```
//!
//! ## Runtime file loading
//!
//! ```ignore
//! use axum_acl::AclTable;
//!
//! let table = AclTable::from_toml_file("config/acl.toml").unwrap();
//! ```

use crate::rule::{AclAction, AclRuleFilter, EndpointPattern, IpMatcher, RuleMatcher, TimeWindow};
use crate::table::{AclRule, AclTable};
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::sync::Arc;

/// Configuration file structure.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AclConfig {
    /// Global settings.
    #[serde(default)]
    pub settings: ConfigSettings,
    /// List of ACL rules.
    #[serde(default)]
    pub rules: Vec<RuleConfig>,
}

/// Global configuration settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigSettings {
    /// Default action when no rules match.
    #[serde(default = "default_action")]
    pub default_action: ActionConfig,
}

fn default_action() -> ActionConfig {
    ActionConfig::Simple(SimpleAction::Deny)
}

impl Default for ConfigSettings {
    fn default() -> Self {
        Self {
            default_action: default_action(),
        }
    }
}

/// A single rule configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuleConfig {
    /// Role bitmask. Use 0xFFFFFFFF for all roles, or specific bits like 0b11.
    /// Can be decimal (e.g., 3), hex (e.g., "0x3"), or binary string.
    #[serde(default = "default_role_mask")]
    pub role_mask: RoleMaskConfig,

    /// ID to match. Use "*" for any ID.
    #[serde(default = "default_id")]
    pub id: String,

    /// Endpoint pattern to match.
    /// - "*" or "any" for all endpoints
    /// - "/path/" (trailing slash) for prefix match
    /// - "/path/**" for glob match
    /// - "/path" for exact match
    #[serde(default = "default_endpoint")]
    pub endpoint: String,

    /// HTTP methods to match (optional). Empty means all methods.
    #[serde(default)]
    pub methods: Vec<String>,

    /// Time window configuration (optional).
    #[serde(default)]
    pub time: Option<TimeConfig>,

    /// IP address/CIDR to match (optional). "*" or omitted means any IP.
    #[serde(default)]
    pub ip: Option<String>,

    /// Action to take when rule matches.
    pub action: ActionConfig,

    /// Optional description for logging/debugging.
    #[serde(default)]
    pub description: Option<String>,

    /// Priority (lower = higher priority). Rules are sorted by priority.
    #[serde(default = "default_priority")]
    pub priority: i32,

    /// Custom matcher configuration (for use with `MatcherRegistry`).
    /// When present and a registry is provided, this is used instead of
    /// `role_mask`/`id`/`ip`/`time` for building the matcher.
    #[serde(default)]
    pub matcher: Option<MatcherConfig>,
}

/// Role mask configuration - can be a number or string.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RoleMaskConfig {
    /// Numeric role mask.
    Number(u32),
    /// String role mask (can be hex like "0xFF" or "*" for all).
    String(String),
}

impl RoleMaskConfig {
    /// Convert to u32 bitmask.
    pub fn to_mask(&self) -> u32 {
        match self {
            RoleMaskConfig::Number(n) => *n,
            RoleMaskConfig::String(s) => {
                let s = s.trim();
                if s == "*" || s.eq_ignore_ascii_case("all") {
                    u32::MAX
                } else if let Some(hex) = s.strip_prefix("0x") {
                    u32::from_str_radix(hex, 16).unwrap_or(u32::MAX)
                } else if let Some(bin) = s.strip_prefix("0b") {
                    u32::from_str_radix(bin, 2).unwrap_or(u32::MAX)
                } else {
                    s.parse().unwrap_or(u32::MAX)
                }
            }
        }
    }
}

fn default_role_mask() -> RoleMaskConfig {
    RoleMaskConfig::Number(u32::MAX)
}

fn default_id() -> String {
    "*".to_string()
}

fn default_endpoint() -> String {
    "*".to_string()
}

fn default_priority() -> i32 {
    100
}

/// Time window configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimeConfig {
    /// Start hour (0-23).
    #[serde(default)]
    pub start: Option<u32>,
    /// End hour (0-23).
    #[serde(default)]
    pub end: Option<u32>,
    /// Days of week (0=Monday, 6=Sunday). Empty means all days.
    #[serde(default)]
    pub days: Vec<u32>,
}

/// Action configuration - can be simple string or complex object.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ActionConfig {
    /// Simple action: "allow", "deny"
    Simple(SimpleAction),
    /// Complex action with parameters
    Complex(ComplexAction),
}

/// Simple action types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SimpleAction {
    /// Allow the request.
    Allow,
    /// Deny with 403 Forbidden.
    Deny,
    /// Block (same as deny, alias).
    Block,
}

/// Complex action with additional parameters.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum ComplexAction {
    /// Allow the request.
    Allow,
    /// Deny with 403.
    Deny,
    /// Block (alias for deny).
    Block,
    /// Return a custom error response.
    Error {
        /// HTTP status code.
        #[serde(default = "default_error_code")]
        code: u16,
        /// Error message body.
        #[serde(default)]
        message: Option<String>,
    },
    /// Reroute to a different path.
    Reroute {
        /// Target path to reroute to.
        target: String,
        /// Whether to preserve the original path as a header.
        #[serde(default)]
        preserve_path: bool,
    },
    /// Rate limit the request.
    RateLimit {
        /// Maximum requests per window.
        max_requests: u32,
        /// Window duration in seconds.
        window_secs: u64,
    },
    /// Log and allow (for monitoring).
    Log {
        /// Log level: "trace", "debug", "info", "warn", "error"
        #[serde(default = "default_log_level")]
        level: String,
        /// Custom log message.
        #[serde(default)]
        message: Option<String>,
    },
}

/// Configuration for a custom matcher (used with `MatcherRegistry`).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MatcherConfig {
    /// A named matcher reference (e.g., `"authenticated"`).
    Named(String),
    /// A parameterized matcher (e.g., `{ type = "scoped_role", param = "id" }`).
    Parameterized {
        /// The matcher type name.
        #[serde(rename = "type")]
        matcher_type: String,
        /// Optional parameter name (e.g., path parameter to bind to).
        #[serde(default)]
        param: Option<String>,
    },
}

/// Registry that resolves `MatcherConfig` values into `RuleMatcher<A>` instances.
pub trait MatcherRegistry<A>: Send + Sync {
    /// Resolve a matcher config into a boxed `RuleMatcher`.
    fn resolve(&self, config: &MatcherConfig) -> Result<Arc<dyn RuleMatcher<A>>, ConfigError>;
}

fn default_error_code() -> u16 {
    403
}

fn default_log_level() -> String {
    "info".to_string()
}

/// Error type for configuration parsing.
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    /// TOML parsing error.
    #[error("Failed to parse TOML: {0}")]
    TomlParse(#[from] toml::de::Error),

    /// File I/O error.
    #[error("Failed to read config file: {0}")]
    FileRead(#[from] std::io::Error),

    /// Invalid configuration.
    #[error("Invalid configuration: {0}")]
    Invalid(String),

    /// Invalid IP pattern.
    #[error("Invalid IP pattern '{0}': {1}")]
    InvalidIp(String, String),

    /// Invalid action configuration.
    #[error("Invalid action configuration: {0}")]
    InvalidAction(String),
}

impl AclConfig {
    /// Parse configuration from a TOML string.
    ///
    /// # Example
    /// ```
    /// use axum_acl::TomlConfig;
    ///
    /// let toml = r#"
    /// [settings]
    /// default_action = "deny"
    ///
    /// [[rules]]
    /// role = "admin"
    /// endpoint = "*"
    /// action = "allow"
    /// "#;
    ///
    /// let config = TomlConfig::from_toml(toml).unwrap();
    /// ```
    pub fn from_toml(toml_str: &str) -> Result<Self, ConfigError> {
        let config: AclConfig = toml::from_str(toml_str)?;
        config.validate()?;
        Ok(config)
    }

    /// Load configuration from a TOML file.
    ///
    /// # Example
    /// ```ignore
    /// use axum_acl::AclConfig;
    ///
    /// let config = AclConfig::from_file("config/acl.toml").unwrap();
    /// ```
    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
        let contents = std::fs::read_to_string(path)?;
        Self::from_toml(&contents)
    }

    /// Validate the configuration.
    fn validate(&self) -> Result<(), ConfigError> {
        for (i, rule) in self.rules.iter().enumerate() {
            // Validate IP pattern if provided
            if let Some(ref ip) = rule.ip {
                if ip != "*" && !ip.eq_ignore_ascii_case("any") {
                    IpMatcher::parse(ip)
                        .map_err(|e| ConfigError::InvalidIp(ip.clone(), e))?;
                }
            }

            // Validate time config
            if let Some(ref time) = rule.time {
                if let Some(start) = time.start {
                    if start > 23 {
                        return Err(ConfigError::Invalid(format!(
                            "Rule {}: start hour {} is invalid (must be 0-23)",
                            i, start
                        )));
                    }
                }
                if let Some(end) = time.end {
                    if end > 23 {
                        return Err(ConfigError::Invalid(format!(
                            "Rule {}: end hour {} is invalid (must be 0-23)",
                            i, end
                        )));
                    }
                }
                for &day in &time.days {
                    if day > 6 {
                        return Err(ConfigError::Invalid(format!(
                            "Rule {}: day {} is invalid (must be 0-6)",
                            i, day
                        )));
                    }
                }
            }
        }
        Ok(())
    }

    /// Convert configuration to an AclTable.
    ///
    /// # Example
    /// ```
    /// use axum_acl::TomlConfig;
    ///
    /// let toml = r#"
    /// [[rules]]
    /// role_mask = 1
    /// endpoint = "*"
    /// action = "allow"
    /// "#;
    ///
    /// let config = TomlConfig::from_toml(toml).unwrap();
    /// let table = config.into_table();
    /// ```
    pub fn into_table(self) -> AclTable {
        let default_action = action_config_to_action(&self.settings.default_action);

        // Sort rules by priority (lower = higher priority)
        let mut rules: Vec<(i32, RuleConfig)> = self
            .rules
            .into_iter()
            .map(|r| (r.priority, r))
            .collect();
        rules.sort_by_key(|(p, _)| *p);

        // Build the table using the builder
        let mut builder = AclTable::builder().default_action(default_action);

        for (_, rule_config) in rules {
            let endpoint = EndpointPattern::parse(&rule_config.endpoint);
            let filter = rule_config_to_filter(rule_config);

            // Add to appropriate collection based on endpoint type
            match endpoint {
                EndpointPattern::Exact(path) => {
                    builder = builder.add_exact(path, filter);
                }
                pattern => {
                    builder = builder.add_pattern(pattern, filter);
                }
            }
        }

        builder.build()
    }
}

/// Convert ActionConfig to AclAction.
fn action_config_to_action(config: &ActionConfig) -> AclAction {
    match config {
        ActionConfig::Simple(simple) => match simple {
            SimpleAction::Allow => AclAction::Allow,
            SimpleAction::Deny | SimpleAction::Block => AclAction::Deny,
        },
        ActionConfig::Complex(complex) => match complex {
            ComplexAction::Allow => AclAction::Allow,
            ComplexAction::Deny | ComplexAction::Block => AclAction::Deny,
            ComplexAction::Error { code, message } => AclAction::Error {
                code: *code,
                message: message.clone(),
            },
            ComplexAction::Reroute {
                target,
                preserve_path,
            } => AclAction::Reroute {
                target: target.clone(),
                preserve_path: *preserve_path,
            },
            ComplexAction::RateLimit {
                max_requests,
                window_secs,
            } => AclAction::RateLimit {
                max_requests: *max_requests,
                window_secs: *window_secs,
            },
            ComplexAction::Log { level, message } => AclAction::Log {
                level: level.clone(),
                message: message.clone(),
            },
        },
    }
}

/// Convert RuleConfig to AclRuleFilter.
fn rule_config_to_filter(config: RuleConfig) -> AclRuleFilter {
    let time = config.time.map(|t| {
        if t.start.is_none() && t.end.is_none() && t.days.is_empty() {
            TimeWindow::any()
        } else {
            TimeWindow {
                start: t.start.and_then(|h| chrono::NaiveTime::from_hms_opt(h, 0, 0)),
                end: t.end.and_then(|h| chrono::NaiveTime::from_hms_opt(h, 0, 0)),
                days: t.days,
            }
        }
    }).unwrap_or_else(TimeWindow::any);

    let ip = config
        .ip
        .map(|s| IpMatcher::parse(&s).unwrap_or(IpMatcher::Any))
        .unwrap_or(IpMatcher::Any);

    let action = action_config_to_action(&config.action);

    let methods: Vec<http::Method> = config
        .methods
        .iter()
        .filter_map(|m| m.parse::<http::Method>().ok())
        .collect();

    let mut filter = AclRuleFilter::new()
        .id(config.id)
        .role_mask(config.role_mask.to_mask())
        .methods(methods)
        .time(time)
        .ip(ip)
        .action(action);

    if let Some(desc) = config.description {
        filter = filter.description(desc);
    }

    filter
}

impl AclConfig {
    /// Convert configuration into a generic `AclTable<A>` using a `MatcherRegistry`.
    ///
    /// Rules with a `matcher` field are resolved via the registry.
    /// Rules without a `matcher` field are skipped (they only work with the
    /// bitmask-based `into_table()` method).
    pub fn into_generic_table<A: Send + Sync + 'static>(
        self,
        registry: &dyn MatcherRegistry<A>,
    ) -> Result<AclTable<A>, ConfigError> {
        let default_action = action_config_to_action(&self.settings.default_action);

        let mut rules: Vec<(i32, RuleConfig)> = self
            .rules
            .into_iter()
            .map(|r| (r.priority, r))
            .collect();
        rules.sort_by_key(|(p, _)| *p);

        let mut exact_rules: std::collections::HashMap<String, Vec<AclRule<A>>> =
            std::collections::HashMap::new();
        let mut pattern_rules: Vec<(EndpointPattern, Vec<AclRule<A>>)> = Vec::new();

        for (_, rule_config) in rules {
            let Some(ref matcher_config) = rule_config.matcher else {
                continue;
            };

            let matcher = registry.resolve(matcher_config)?;

            let methods: Vec<http::Method> = rule_config
                .methods
                .iter()
                .filter_map(|m| m.parse::<http::Method>().ok())
                .collect();

            let action = action_config_to_action(&rule_config.action);

            let rule = if methods.is_empty() {
                AclRule::from_matcher(matcher)
            } else {
                AclRule::from_matcher_with_methods(matcher, methods, action)
            };

            let endpoint = EndpointPattern::parse(&rule_config.endpoint);
            match endpoint {
                EndpointPattern::Exact(path) => {
                    exact_rules.entry(path).or_default().push(rule);
                }
                pattern => {
                    let mut found = false;
                    for (existing, rules) in &mut pattern_rules {
                        let is_match = match (existing, &pattern) {
                            (EndpointPattern::Any, EndpointPattern::Any) => true,
                            (EndpointPattern::Prefix(a), EndpointPattern::Prefix(b)) => a == b,
                            (EndpointPattern::Glob(a), EndpointPattern::Glob(b)) => a == b,
                            (EndpointPattern::Exact(a), EndpointPattern::Exact(b)) => a == b,
                            _ => false,
                        };
                        if is_match {
                            rules.push(rule.clone());
                            found = true;
                            break;
                        }
                    }
                    if !found {
                        pattern_rules.push((pattern, vec![rule]));
                    }
                }
            }
        }

        Ok(AclTable {
            exact_rules,
            pattern_rules,
            default_action,
        })
    }
}

impl AclTable {
    /// Create an AclTable from a TOML configuration string.
    ///
    /// This is the recommended way to load embedded configuration.
    ///
    /// # Example
    /// ```
    /// use axum_acl::AclTable;
    ///
    /// // Compile-time embedded config
    /// const CONFIG: &str = r#"
    /// [settings]
    /// default_action = "deny"
    ///
    /// [[rules]]
    /// role_mask = 1
    /// endpoint = "*"
    /// action = "allow"
    ///
    /// [[rules]]
    /// role_mask = 2
    /// endpoint = "/api/**"
    /// action = "allow"
    /// "#;
    ///
    /// let table = AclTable::from_toml(CONFIG).unwrap();
    /// ```
    pub fn from_toml(toml_str: &str) -> Result<Self, ConfigError> {
        let config = AclConfig::from_toml(toml_str)?;
        Ok(config.into_table())
    }

    /// Create an AclTable from a TOML configuration file.
    ///
    /// # Example
    /// ```ignore
    /// use axum_acl::AclTable;
    ///
    /// let table = AclTable::from_toml_file("config/acl.toml").unwrap();
    /// ```
    pub fn from_toml_file(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
        let config = AclConfig::from_file(path)?;
        Ok(config.into_table())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::IpAddr;
    use crate::rule::RequestContext;

    #[test]
    fn test_parse_simple_config() {
        let toml = r#"
[settings]
default_action = "deny"

[[rules]]
role_mask = 1
endpoint = "*"
action = "allow"
description = "Admin access"

[[rules]]
role_mask = 2
endpoint = "/api/**"
action = "allow"
"#;

        let config = AclConfig::from_toml(toml).unwrap();
        assert_eq!(config.rules.len(), 2);

        let table = config.into_table();
        // Check the table has pattern rules (since endpoints use * and **)
        assert!(!table.pattern_rules().is_empty());
    }

    #[test]
    fn test_parse_complex_actions() {
        let toml = r#"
[[rules]]
endpoint = "/error"
action = { type = "error", code = 418, message = "I'm a teapot" }

[[rules]]
endpoint = "/redirect"
action = { type = "reroute", target = "/new-path", preserve_path = true }
"#;

        let config = AclConfig::from_toml(toml).unwrap();
        assert_eq!(config.rules.len(), 2);

        let table = config.into_table();
        // Check error action is returned for /error path
        let ip: IpAddr = "127.0.0.1".parse().unwrap();
        let ctx = RequestContext::new(u32::MAX, ip, "*");
        let action = table.evaluate("/error", &ctx);
        match action {
            AclAction::Error { code, message } => {
                assert_eq!(code, 418);
                assert_eq!(message.as_deref(), Some("I'm a teapot"));
            }
            _ => panic!("Expected Error action"),
        }
    }

    #[test]
    fn test_parse_time_config() {
        let toml = r#"
[[rules]]
role_mask = 2
endpoint = "/api/**"
time = { start = 9, end = 17, days = [0, 1, 2, 3, 4] }
action = "allow"
"#;

        let config = AclConfig::from_toml(toml).unwrap();
        let table = config.into_table();

        // The table should have pattern rules with time config
        assert!(!table.pattern_rules().is_empty());
    }

    #[test]
    fn test_parse_ip_config() {
        let toml = r#"
[[rules]]
endpoint = "/internal/**"
ip = "192.168.1.0/24"
action = "allow"
"#;

        let config = AclConfig::from_toml(toml).unwrap();
        let table = config.into_table();

        // Verify IP filtering works via evaluation
        let internal_ip: IpAddr = "192.168.1.50".parse().unwrap();
        let external_ip: IpAddr = "10.0.0.1".parse().unwrap();
        let ctx_internal = RequestContext::new(u32::MAX, internal_ip, "*");
        let ctx_external = RequestContext::new(u32::MAX, external_ip, "*");

        assert_eq!(table.evaluate("/internal/foo", &ctx_internal), AclAction::Allow);
        assert_eq!(table.evaluate("/internal/foo", &ctx_external), AclAction::Deny);
    }

    #[test]
    fn test_role_mask_formats() {
        let toml = r#"
[[rules]]
role_mask = 3
endpoint = "/decimal"
action = "allow"

[[rules]]
role_mask = "0xFF"
endpoint = "/hex"
action = "allow"

[[rules]]
role_mask = "*"
endpoint = "/all"
action = "allow"
"#;

        let config = AclConfig::from_toml(toml).unwrap();
        assert_eq!(config.rules[0].role_mask.to_mask(), 3);
        assert_eq!(config.rules[1].role_mask.to_mask(), 0xFF);
        assert_eq!(config.rules[2].role_mask.to_mask(), u32::MAX);
    }
}