wordval-web 1.0.13

Wordval web layer: router, middleware, extractors, responses, session-based authentication
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
//! 路由策略表
//!
//! 统一汇总路由策略的两个来源——路由守卫(`#[wordval::get(path, permission =
//! "...", audit = "...", public)]` 与 `App` 构建器注册的 `RouteGuard`)、
//! 配置 `auth.ignore_paths` / `permission.rules`——生成最终策略表,
//! 启动阶段输出策略表并 fail-fast 校验冲突,收敛"路径字符串绕过 +
//! 全局路径扫描"的多个事实来源。
//!
//! 策略的事实来源是 route metadata 本身(宏/构建器注册时生成),
//! 因此不存在"策略指向已改名的路径"这类静默失效。

use crate::middleware::auth::{
    is_api_path, join_route_path, match_path_pattern, normalize_path, PathPattern,
};
use crate::router::RouteEntry;

/// 路由认证要求
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RouteAuthRequirement {
    /// 免认证(公开路由,如登录/注册)
    Public,
    /// 必须登录
    Required,
}

impl RouteAuthRequirement {
    fn as_str(&self) -> &'static str {
        match self {
            RouteAuthRequirement::Public => "public",
            RouteAuthRequirement::Required => "required",
        }
    }
}

/// 单条路由策略(method 为空 = 所有 HTTP 方法)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RoutePolicy {
    /// 规范化后的最终路径(已拼接全局前缀)
    pub path: String,
    /// HTTP 方法(空 = 所有方法)
    pub method: String,
    /// 认证要求
    pub auth: RouteAuthRequirement,
    /// 权限标识(None = 无权限要求)
    pub permission: Option<String>,
}

impl RoutePolicy {
    fn is_permission_required(&self) -> bool {
        self.permission.is_some()
    }
}

/// 冲突检测的单条预编译数据(启动期每条策略构建一次,配对阶段零分配)。
///
/// 替代历史上每对策略各调两次 [`match_path_pattern`] 的写法——那会在
/// O(P²) 内层循环里反复 normalize + 重新编译模式字符串(每对最多 4 次
/// 分配),路由数上千时启动校验明显变慢。
struct CompiledPolicy {
    /// 规范化后的路径(与 `match_path_pattern` 内部 normalize 一致)
    norm: String,
    /// 预编译模式
    pattern: PathPattern,
    /// 纯段模式的段数(尾部通配为 None)
    seg_count: Option<usize>,
    /// 小写方法集(None = 所有方法)
    methods: Option<Vec<String>>,
}

impl CompiledPolicy {
    fn compile(p: &RoutePolicy) -> Self {
        let norm = normalize_path(&p.path);
        let pattern = PathPattern::compile_normalized(&norm);
        let seg_count = match &pattern {
            PathPattern::Segments(segs) => Some(segs.len()),
            PathPattern::TailWildcard(_) => None,
        };
        let methods = if p.method.is_empty() {
            None
        } else {
            Some(p.method.split(',').map(|m| m.to_ascii_lowercase()).collect())
        };
        Self {
            norm: norm.to_string(),
            pattern,
            seg_count,
            methods,
        }
    }

    /// 与历史双向 `match_path_pattern` 调用语义完全一致:
    /// `a.norm == b.norm || a.pattern 匹配 b.norm || b.pattern 匹配 a.norm`,
    /// 但全部输入已预编译,配对阶段零分配。
    fn overlaps(a: &Self, b: &Self) -> bool {
        Self::matches_into(a, b) || Self::matches_into(b, a)
    }

    /// 单向版本:与 `match_path_pattern(&a.path, &b.path)` 等价
    /// (重复注册检测的历史语义即单向)。
    fn matches_into(a: &Self, b: &Self) -> bool {
        if a.norm == b.norm {
            return true;
        }
        // 双方均为纯段模式且段数不同:匹配要求段数相等,字符串等价已
        // 先行排除,直接短路。路由表中不同段数的配对占绝大多数,
        // 该分支使常见路由表的实际复杂度近似 O(P)。
        if a.seg_count.is_some() && b.seg_count.is_some() && a.seg_count != b.seg_count {
            return false;
        }
        a.pattern.matches_normalized(&b.norm)
    }

    /// 方法集是否重叠(None = 所有方法;与逐对 split 比较语义一致)
    fn methods_overlap(a: &Self, b: &Self) -> bool {
        match (&a.methods, &b.methods) {
            (None, _) | (_, None) => true,
            (Some(x), Some(y)) => x.iter().any(|m| y.contains(m)),
        }
    }
}

/// 最终路由策略表
#[derive(Debug, Default)]
pub struct RoutePolicyTable {
    /// 策略条目
    pub policies: Vec<RoutePolicy>,
}

impl RoutePolicyTable {
    /// 从路由守卫与配置规则构建统一策略表(路径统一拼接全局前缀)。
    ///
    /// - 守卫策略(`public` / `permission`)属于强制策略,不受配置开关控制;
    /// - 配置 `auth.ignore_paths` 仅在实际启用 auth 时才有意义;
    /// - 配置 `permission.rules` 受 `permission.enabled` 控制。
    pub fn build(
        prefix: &str,
        routes: &[RouteEntry],
        auth_enabled: bool,
        config_ignore_paths: &[String],
        permission_enabled: bool,
        config_rules: &[wordval_config::PermissionRule],
    ) -> Self {
        let mut policies: Vec<RoutePolicy> = Vec::new();

        // 路由守卫:`public` / `permission`(同一条路由两者都声明时交由 conflicts 报错)
        for r in routes {
            if !r.guard.public && r.guard.permission.is_none() {
                continue;
            }
            policies.push(RoutePolicy {
                path: join_route_path(prefix, &r.path),
                method: r.method.clone(),
                auth: if r.guard.public {
                    RouteAuthRequirement::Public
                } else {
                    RouteAuthRequirement::Required
                },
                permission: r.guard.permission.clone(),
            });
        }

        // 配置:`auth.ignore_paths`(等同于全方法免认证)
        if auth_enabled {
            for path in config_ignore_paths {
                policies.push(RoutePolicy {
                    path: join_route_path(prefix, path),
                    method: String::new(),
                    auth: RouteAuthRequirement::Public,
                    permission: None,
                });
            }
        }

        // 配置:`permission.rules`(method 空 = 所有方法)
        if permission_enabled {
            for rule in config_rules {
                policies.push(RoutePolicy {
                    path: join_route_path(prefix, &rule.path),
                    method: rule.methods.join(","),
                    auth: RouteAuthRequirement::Required,
                    permission: Some(rule.permission.clone()),
                });
            }
        }

        Self { policies }
    }

    /// 是否包含冲突(允许启动前校验;空表视为无冲突)
    pub fn conflicts(&self) -> Vec<String> {
        let mut conflicts = Vec::new();

        // 1. 公开路由携带权限要求:公开路由没有 CurrentUser,权限层会恒 403,
        //    属于策略矛盾,必须启动失败而不是运行期才暴露。
        for p in &self.policies {
            if p.auth == RouteAuthRequirement::Public && p.is_permission_required() {
                conflicts.push(format!(
                    "公开路由不可携带权限要求: {} {} (permission={})",
                    method_display(&p.method),
                    p.path,
                    p.permission.as_deref().unwrap_or("")
                ));
            }
        }

        // 1b. 公开路由与权限路由跨条目重叠:
        //     同一方法/路径既免认证又要求权限,策略矛盾。
        //     配对前一次性预编译全部策略(见 CompiledPolicy),内层零分配。
        let compiled: Vec<CompiledPolicy> = self
            .policies
            .iter()
            .map(CompiledPolicy::compile)
            .collect();
        for (i, p) in self.policies.iter().enumerate() {
            if p.auth != RouteAuthRequirement::Public {
                continue;
            }
            for (j, q) in self.policies.iter().enumerate() {
                if !q.is_permission_required() {
                    continue;
                }
                if CompiledPolicy::overlaps(&compiled[i], &compiled[j])
                    && CompiledPolicy::methods_overlap(&compiled[i], &compiled[j])
                {
                    conflicts.push(format!(
                        "公开路由与权限路由重叠: {} {} 与 {} {} (permission={})",
                        method_display(&p.method),
                        p.path,
                        method_display(&q.method),
                        q.path,
                        q.permission.as_deref().unwrap_or("")
                    ));
                }
            }
        }

        // 2. 同一 (method, path) 重复注册不同权限:无法确定应执行哪一条策略。
        for (i, a) in self.policies.iter().enumerate() {
            if !a.is_permission_required() {
                continue;
            }
            for (j, b) in self.policies.iter().enumerate().skip(i + 1) {
                if !b.is_permission_required() {
                    continue;
                }
                if !CompiledPolicy::overlaps(&compiled[i], &compiled[j]) {
                    continue;
                }
                if !CompiledPolicy::methods_overlap(&compiled[i], &compiled[j]) {
                    continue;
                }
                if a.permission != b.permission {
                    conflicts.push(format!(
                        "同一路由重复注册不同权限: {} {} -> {} vs {}",
                        method_display(&a.method),
                        a.path,
                        a.permission.as_deref().unwrap_or(""),
                        b.permission.as_deref().unwrap_or("")
                    ));
                }
            }
        }

        conflicts
    }

    /// 启动阶段校验:存在冲突时返回结构化错误(fail-fast)。
    pub fn validate(&self) -> std::result::Result<(), String> {
        let conflicts = self.conflicts();
        if conflicts.is_empty() {
            Ok(())
        } else {
            Err(format!(
                "路由策略存在冲突(共 {} 处):
  - {}",
                conflicts.len(),
                conflicts.join(
                    "
  - "
                )
            ))
        }
    }

    /// 输出最终策略表(info 摘要 + debug 明细),供启动审计。
    ///
    /// 摘要统计基于**全部已注册路由**(与路由列表总数一致),
    /// 公开/需登录按 [`classify_route_auth`] 的 AuthLayer 运行时语义判定;
    /// 策略规则明细仍按 debug 级别输出。
    pub fn log(
        &self,
        prefix: &str,
        routes: &[RouteEntry],
        config_ignore_paths: &[String],
        api_prefixes: &[String],
        auth_enabled: bool,
    ) {
        let (public, required) = classify_route_auth(
            prefix,
            routes,
            config_ignore_paths,
            api_prefixes,
            auth_enabled,
        );
        tracing::info!(
            "路由策略表: 已注册 {} 条(公开 {} / 需登录 {})",
            routes.len(),
            public,
            required
        );
        // fail-open 审计:点名仅因不在 api_prefixes 前缀内而默认免鉴权的路由,
        // 避免「启用 auth 后非 /api 路由静默免鉴权」无感知(可配 api_prefixes=[] 强制全覆盖)
        let exempt = prefix_exempt_routes(
            prefix,
            routes,
            config_ignore_paths,
            api_prefixes,
            auth_enabled,
        );
        if !exempt.is_empty() {
            tracing::warn!(
                "以下 {} 条路由不在 api_prefixes {:?} 内且未标 public 守卫,启用 auth 后仍默认免鉴权(fail-open);\
                 如需强制鉴权请将其纳入前缀或显式配置 api_prefixes=[]:",
                exempt.len(),
                api_prefixes
            );
            for (method, path) in &exempt {
                tracing::warn!("  [免鉴权] {} {}", method_display(method), path);
            }
        }
        for p in &self.policies {
            tracing::debug!(
                "  route-policy: {} {} auth={} permission={}",
                method_display(&p.method),
                p.path,
                p.auth.as_str(),
                p.permission.as_deref().unwrap_or("-")
            );
        }
    }
}

/// 对全部已注册路由按认证策略分类统计,返回 (公开数, 需登录数)。
///
/// 判定语义与 `AuthLayer` 运行时完全一致:
/// - 路由守卫声明 `public`,或命中配置 `auth.ignore_paths` → 公开;
/// - 不在 `auth.api_prefixes` 前缀内的页面路径 → 公开(AuthLayer 的 is_page 放行);
/// - 其余 → 需登录;`auth_enabled=false` 时 AuthLayer 未装配,全部视为公开。
pub fn classify_route_auth(
    prefix: &str,
    routes: &[RouteEntry],
    config_ignore_paths: &[String],
    api_prefixes: &[String],
    auth_enabled: bool,
) -> (usize, usize) {
    if !auth_enabled {
        return (routes.len(), 0);
    }
    // 规则与路由路径统一拼接全局前缀(与 AuthLayer 装配时的 join 保持一致)
    let ignore_rules: Vec<String> = config_ignore_paths
        .iter()
        .map(|p| join_route_path(prefix, p))
        .collect();

    let public = routes
        .iter()
        .filter(|r| {
            let joined = join_route_path(prefix, &r.path);
            let path = normalize_path(&joined);
            r.guard.public
                || ignore_rules.iter().any(|p| match_path_pattern(p, &path))
                || !is_api_path(&path, api_prefixes)
        })
        .count();
    (public, routes.len() - public)
}

/// 列出**仅因不在 `api_prefixes` 前缀内**而免鉴权的路由(fail-open 启动审计)。
///
/// 这些路由既未命中路由守卫的 `public` / `auth.ignore_paths` 显式公开规则,
/// 也不在任一 API 前缀下,被 AuthLayer 的 `is_page` 语义默认放行。启用 auth 后
/// 它们默认免鉴权,启动期点名便于运维确认是否漏配前缀或漏标 `public`。
///
/// 判定语义与 [`classify_route_auth`] 完全一致(含全局前缀拼接);
/// `auth_enabled=false`(AuthLayer 未装配)或 `api_prefixes` 为空(fail-closed,
/// 全部路径强制鉴权)时返回空列表。
pub fn prefix_exempt_routes(
    prefix: &str,
    routes: &[crate::router::RouteEntry],
    config_ignore_paths: &[String],
    api_prefixes: &[String],
    auth_enabled: bool,
) -> Vec<(String, String)> {
    if !auth_enabled || api_prefixes.is_empty() {
        return Vec::new();
    }
    let ignore_rules: Vec<String> = config_ignore_paths
        .iter()
        .map(|p| join_route_path(prefix, p))
        .collect();
    routes
        .iter()
        .filter_map(|r| {
            let joined = join_route_path(prefix, &r.path);
            let path = normalize_path(&joined);
            let explicit_public = r.guard.public
                || ignore_rules.iter().any(|p| match_path_pattern(p, &path));
            if !explicit_public && !is_api_path(&path, api_prefixes) {
                Some((r.method.clone(), path.into_owned()))
            } else {
                None
            }
        })
        .collect()
}

fn method_display(method: &str) -> &str {
    if method.is_empty() {
        "*"
    } else {
        method
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::router::RouteGuard;
    use wordval_config::PermissionRule;

    fn route(method: &str, path: &str, guard: RouteGuard) -> RouteEntry {
        RouteEntry {
            method: method.to_string(),
            path: path.to_string(),
            guard,
        }
    }

    fn public_route(method: &str, path: &str) -> RouteEntry {
        route(method, path, RouteGuard::public())
    }

    fn perm_route(method: &str, path: &str, permission: &str) -> RouteEntry {
        route(method, path, RouteGuard::permission(permission))
    }

    fn cfg_rule(path: &str, methods: &[&str], permission: &str) -> PermissionRule {
        PermissionRule {
            path: path.to_string(),
            methods: methods.iter().map(|s| s.to_string()).collect(),
            permission: permission.to_string(),
        }
    }

    fn table(routes: &[RouteEntry]) -> RoutePolicyTable {
        RoutePolicyTable::build("", routes, true, &[], true, &[])
    }

    #[test]
    fn guard_public_and_permission_conflicts() {
        // 同一路由既声明 public 又声明 permission:策略矛盾,启动必须失败
        let t = table(&[route(
            "POST",
            "/api/orders",
            RouteGuard {
                permission: Some("order:create".to_string()),
                public: true,
                audit: None,
            },
        )]);
        assert!(!t.conflicts().is_empty());
        assert!(t.validate().is_err());
    }

    #[test]
    fn config_ignore_overlaps_guard_permission() {
        // 配置全方法免认证与守卫权限重叠(按路径模式)同样冲突
        let t = RoutePolicyTable::build(
            "",
            &[perm_route("GET", "/api/public/admin", "admin:access")],
            true,
            &["/api/public/{*rest}".to_string()],
            true,
            &[],
        );
        assert!(!t.conflicts().is_empty());
    }

    #[test]
    fn method_specific_public_does_not_weaken_other_method() {
        // 同路径 GET 公开不会让 POST 也公开
        let t = table(&[
            public_route("GET", "/api/orders"),
            perm_route("POST", "/api/orders", "order:create"),
        ]);
        assert!(t.conflicts().is_empty());
    }

    #[test]
    fn duplicate_permission_with_different_perm_conflicts() {
        let t = RoutePolicyTable::build(
            "",
            &[],
            true,
            &[],
            true,
            &[
                cfg_rule("/api/users", &["GET"], "user:list"),
                cfg_rule("/api/users", &["GET"], "user:admin"),
            ],
        );
        assert!(!t.conflicts().is_empty());
    }

    #[test]
    fn same_route_same_permission_is_fine() {
        // 守卫与配置对同一路由要求同一权限:不冲突
        let t = RoutePolicyTable::build(
            "",
            &[perm_route("GET", "/api/users", "user:list")],
            true,
            &[],
            true,
            &[cfg_rule("/api/users", &["GET"], "user:list")],
        );
        assert!(t.conflicts().is_empty());
    }

    #[test]
    fn distinct_routes_do_not_conflict() {
        let t = table(&[
            public_route("POST", "/api/auth/login"),
            perm_route("GET", "/api/admin/users", "user:list"),
        ]);
        assert!(t.conflicts().is_empty());
    }

    #[test]
    fn global_prefix_joined_into_policy_path() {
        let t = RoutePolicyTable::build(
            "/api",
            &[
                public_route("POST", "/auth/login"),
                perm_route("GET", "/admin/users", "user:list"),
            ],
            true,
            &[],
            true,
            &[],
        );
        assert!(t.policies.iter().any(|p| p.path == "/api/auth/login"));
        assert!(t.policies.iter().any(|p| p.path == "/api/admin/users"));
    }

    #[test]
    fn guard_without_policy_is_not_listed() {
        // 未声明策略的路由不进入策略表(默认语义由中间件层承担)
        let t = table(&[route("GET", "/api/orders", RouteGuard::default())]);
        assert!(t.policies.is_empty());
    }

    #[test]
    fn config_rules_and_ignore_paths_included() {
        let t = RoutePolicyTable::build(
            "",
            &[],
            true,
            &["/health".to_string()],
            true,
            &[cfg_rule("/orders", &["POST"], "order:create")],
        );
        assert_eq!(t.policies.len(), 2);
        let health = t.policies.iter().find(|p| p.path == "/health").unwrap();
        assert_eq!(health.auth, RouteAuthRequirement::Public);
        let order = t.policies.iter().find(|p| p.path == "/orders").unwrap();
        assert_eq!(order.permission.as_deref(), Some("order:create"));
    }

    #[test]
    fn dormant_config_ignored_when_disabled() {
        // 配置开关关闭时,对应配置规则不再进入策略表(守卫策略仍生效)
        let t = RoutePolicyTable::build(
            "",
            &[],
            false,
            &["/health".to_string()],
            false,
            &[cfg_rule("/orders", &["POST"], "order:create")],
        );
        assert!(t.policies.is_empty());
    }

    // ── classify_route_auth:全量路由分类统计(与 AuthLayer 运行时语义一致)──

    #[test]
    fn classify_counts_guard_and_ignore_as_public() {
        let routes = vec![
            public_route("POST", "/api/auth/login"),
            route("GET", "/api/auth/login", RouteGuard::default()),
            route("POST", "/api/orders", RouteGuard::default()),
            route("GET", "/api/orders", RouteGuard::default()),
        ];
        // 守卫 public 只作用于 POST;ignore_paths 全方法公开
        let (public, required) = classify_route_auth(
            "",
            &routes,
            &["/api/orders".to_string()],
            &[],
            true,
        );
        assert_eq!(public, 3);
        assert_eq!(required, 1);
    }

    #[test]
    fn classify_page_paths_outside_api_prefixes_are_public() {
        let routes = vec![
            route("GET", "/api/data", RouteGuard::default()),
            route("GET", "/v1/models", RouteGuard::default()),
            route("GET", "/user_center/page", RouteGuard::default()),
        ];
        // api_prefixes=["/api"]:非 API 前缀的路径按 AuthLayer is_page 语义公开
        let (public, required) =
            classify_route_auth("", &routes, &[], &["/api".to_string()], true);
        assert_eq!(public, 2);
        assert_eq!(required, 1);
    }

    #[test]
    fn classify_auth_disabled_all_public() {
        let routes = vec![
            route("GET", "/api/data", RouteGuard::default()),
            route("POST", "/api/save", RouteGuard::default()),
        ];
        let (public, required) = classify_route_auth("", &routes, &[], &[], false);
        assert_eq!(public, 2);
        assert_eq!(required, 0);
    }

    #[test]
    fn classify_pattern_rules_match_param_paths() {
        let routes = vec![
            route("GET", "/api/public/token/{id}", RouteGuard::default()),
            route("GET", "/api/public/token/{id}/delete", RouteGuard::default()),
        ];
        // `{id}` 只匹配单段:三段路径不会被两段规则命中
        let (public, required) = classify_route_auth(
            "",
            &routes,
            &["/api/public/token/{id}".to_string()],
            &[],
            true,
        );
        assert_eq!(public, 1);
        assert_eq!(required, 1);
    }

    // ── prefix_exempt_routes:fail-open 启动审计 ──

    #[test]
    fn prefix_exempt_names_only_outside_prefix_not_explicit_public() {
        let routes = vec![
            route("GET", "/api/data", RouteGuard::default()), // 前缀内 → 需登录,不点名
            route("GET", "/v1/models", RouteGuard::default()), // 前缀外且无显式公开 → 点名
            public_route("POST", "/internal/sync"), // 前缀外但守卫 public 显式公开 → 不点名
            route("GET", "/health", RouteGuard::default()), // 前缀外但 ignore_paths 公开 → 不点名
        ];
        let exempt = prefix_exempt_routes(
            "",
            &routes,
            &["/health".to_string()],
            &["/api".to_string()],
            true,
        );
        assert_eq!(exempt, vec![("GET".to_string(), "/v1/models".to_string())]);
    }

    #[test]
    fn prefix_exempt_empty_when_fail_closed_or_auth_disabled() {
        let routes = vec![route("GET", "/v1/models", RouteGuard::default())];
        // api_prefixes=[] → fail-closed,全部强制鉴权,无豁免
        assert!(prefix_exempt_routes("", &routes, &[], &[], true).is_empty());
        // auth 未启用 → AuthLayer 未装配,不做豁免审计
        assert!(prefix_exempt_routes("", &routes, &[], &["/api".to_string()], false).is_empty());
    }

    #[test]
    fn classify_counts_global_prefix_prefixed_routes() {
        // 路由元数据只存原始路径,统计时与配置规则一样拼接全局前缀
        let routes = vec![
            public_route("POST", "/auth/login"),
            route("POST", "/orders", RouteGuard::default()),
        ];
        let (public, required) =
            classify_route_auth("/api", &routes, &["/orders".to_string()], &[], true);
        assert_eq!(public, 2);
        assert_eq!(required, 0);
    }
}