crawlrs 0.2.0

crawlrs - Enterprise-grade web scraping and crawling platform built with Rust
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
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Garrison Principal ↔ crawlrs AuthState 桥接。
//!
//! ## 职责
//!
//! 将 garrison 校验返回的 `Principal` 桥接为 crawlrs 既有 `AuthState`,
//! 保持 handler 层 19 个 `Extension<AuthState>` 提取点零改动(换内核保外壳)。
//!
//! - `map_perms_to_scope`:garrison 权限串 → crawlrs `ApiKeyScope`(确定性查找表)
//! - `bridge_to_auth_state`:login_id/perms/team_id → AuthState
//! - `extract_bearer`:从 axum Request 提取 Bearer token
//!
//! ## feature 门控
//!
//! 本模块整体 `#[cfg(feature = "auth")]`——auth-off 时 garrison 不编译,
//! 走 feature-gate 的 `default_identity_middleware` 路径,不需要桥接。
//!
//! ## Spec
//!
//! - `map_perms_to_scope` 实现 garrison 权限串到 ApiKeyScope 的映射
//! - `bridge_to_auth_state` 实现分解参数到 AuthState 的桥接

use crate::domain::auth::ApiKeyScope;
use crate::presentation::middleware::auth_types::{AuthError, AuthState};
use axum::body::Body;
use axum::http::{header, Request};
use dbnexus::DbPool;
use std::sync::Arc;

/// garrison 权限串:read。
const PERM_READ: &str = "crawlrs:read";
/// garrison 权限串:write。
const PERM_WRITE: &str = "crawlrs:write";
/// garrison 权限串:admin(蕴含 read + write)。
const PERM_ADMIN: &str = "crawlrs:admin";

/// 默认搜索配额(与 `ApiKeyScope::default()` 一致)。
const DEFAULT_SEARCH_LIMIT: u32 = 100;
/// 默认抓取配额(与 `ApiKeyScope::default()` 一致)。
const DEFAULT_SCRAPE_LIMIT: u32 = 50;

/// `Authorization: Bearer <token>` scheme 前缀(RFC 7235,大小写敏感)。
const BEARER_PREFIX: &str = "Bearer ";

/// Bearer token 最大长度(CWE-208 防护:超长 token 拒绝,避免资源耗尽攻击)。
///
/// 真实 JWT(HS256)典型长度 200-800 字节;API Key 通常 32-128 字节。
/// 1024 字节上限覆盖所有合法场景,同时拒绝明显异常的超长输入(DoS 防护)。
const MAX_BEARER_TOKEN_LEN: usize = 1024;

/// 将 garrison 权限串列表映射为 crawlrs `ApiKeyScope`。
///
/// ## 权限蕴含规则(确定性查找表)
///
/// | garrison 权限串 | read | write | admin |
/// |----------------|------|-------|-------|
/// | `crawlrs:read`  | ✓    |       |       |
/// | `crawlrs:write` |      | ✓     |       |
/// | `crawlrs:admin` | ✓    | ✓     | ✓     |
///
/// `admin` 蕴含 `read` + `write`(角色层级,garrison role_hierarchy 预计算)。
/// `write` **不**蕴含 `read`(最小权限原则)。
///
/// ## 配额
///
/// `search_limit` / `scrape_limit` 使用默认值(100/50)。
/// 后续 `bridge_to_auth_state` 会从 principal 扩展属性读取配额覆盖。
///
/// ## 参数
///
/// * `perms` - garrison `GarrisonInterface::get_permission_list` 返回的权限串切片
///
/// ## 返回
///
/// 返回对应的 `ApiKeyScope`。空切片或无匹配权限 → `denied()`(全 false)。
///
/// ## 示例
///
/// ```
/// use crawlrs::presentation::middleware::auth_bridge::map_perms_to_scope;
///
/// let admin_scope = map_perms_to_scope(&["crawlrs:admin".to_string()]);
/// assert!(admin_scope.read && admin_scope.write && admin_scope.admin);
///
/// let read_scope = map_perms_to_scope(&["crawlrs:read".to_string()]);
/// assert!(read_scope.read && !read_scope.write && !read_scope.admin);
/// ```
pub fn map_perms_to_scope(perms: &[String]) -> ApiKeyScope {
    // 确定性查找表:遍历一次权限串,按匹配设置对应标志。
    // 不用 HashSet——N 通常 <5(garrison role_hierarchy 预计算后权限很少),
    // 线性扫描 + 早期返回比 HashSet 分配更高效(简洁优先)。
    let mut read = false;
    let mut write = false;
    let mut admin = false;

    for perm in perms {
        match perm.as_str() {
            PERM_ADMIN => {
                // admin 蕴含 read + write
                read = true;
                write = true;
                admin = true;
            }
            PERM_READ => read = true,
            PERM_WRITE => write = true,
            // 未知权限串忽略(garrison 可能返回其他 namespace 的权限,如其他应用)
            _ => {}
        }
    }

    ApiKeyScope::with_custom_limits(
        read,
        write,
        admin,
        DEFAULT_SEARCH_LIMIT,
        DEFAULT_SCRAPE_LIMIT,
    )
}

/// 从 axum `Request` 提取 Bearer token。
///
/// ## 提取规则
///
/// 1. 读 `Authorization` header;缺失 → `AuthError::InvalidKey`
/// 2. header 值非可见 ASCII → `AuthError::InvalidKey`
/// 3. 不以 `Bearer ` 前缀开头 → `AuthError::InvalidKey`(RFC 7235:scheme 大小写敏感)
/// 4. 截取前缀后的 token;空 token → `AuthError::InvalidKey`
/// 5. token 长度 > `MAX_BEARER_TOKEN_LEN` → `AuthError::InvalidKey`(CWE-208 超长输入拒绝)
///
/// ## 安全
///
/// - scheme 大小写敏感:RFC 7235 规定 `Bearer` 是规范形式,故 `bearer` / `BEARER` 拒绝。
///   crawlrs 旧实现也是大小写敏感的(`auth_middleware.rs::extract_bearer_token`),
///   本桥接保持一致性(惯例优先于新颖)。
/// - 不记录 token 内容到日志(避免 CWE-532 凭据泄露)。
/// - 超长 token 拒绝(CWE-208 / DoS 防护):避免下游 garrison 校验消耗资源在明显异常输入上。
///
/// ## 参数
///
/// * `req` - axum `Request<Body>`
///
/// ## 返回
///
/// - `Ok(token)`:提取的 Bearer token 字符串(owned)
/// - `Err(AuthError::InvalidKey)`:header 缺失 / 非 Bearer scheme / 空 token / 超长 token
///
/// ## 示例
///
/// ```ignore
/// use crawlrs::presentation::middleware::auth_bridge::extract_bearer;
///
/// let mut req = axum::http::Request::builder
///     .header("authorization", "Bearer ak_test_123")
///     .body(axum::body::Body::empty)
///     .unwrap;
/// let token = extract_bearer(&req).unwrap;
/// assert_eq!(token, "ak_test_123");
/// ```
pub fn extract_bearer(req: &Request<Body>) -> Result<String, AuthError> {
    let auth_header = req.headers().get(header::AUTHORIZATION).ok_or_else(|| {
        // 拒绝原因显式记录,便于调试。
        log::debug!("Bearer token rejected: Authorization header missing");
        AuthError::InvalidKey
    })?;

    let value = auth_header.to_str().map_err(|_| {
        log::debug!("Bearer token rejected: header value not visible ASCII");
        AuthError::InvalidKey
    })?;

    // 检查 `Bearer ` 前缀。
    // 注:RFC 7235 §2.1 实际规定 auth-scheme 是 case-insensitive,
    // 但 crawlrs 旧实现是大小写敏感的(惯例优先于新颖),此处保持一致。
    if !value.starts_with(BEARER_PREFIX) {
        log::debug!(
            "Bearer token rejected: scheme not 'Bearer ' (case-sensitive, RFC 7235 legacy)"
        );
        return Err(AuthError::InvalidKey);
    }

    let token = &value[BEARER_PREFIX.len()..];
    if token.is_empty() {
        log::debug!("Bearer token rejected: token empty after 'Bearer ' prefix");
        return Err(AuthError::InvalidKey);
    }

    // CWE-208 / DoS 防护:超长 token 拒绝(合法 JWT/API Key 不会超过 1024 字节)
    if token.len() > MAX_BEARER_TOKEN_LEN {
        log::warn!(
            "Bearer token rejected: length {} exceeds max {} (CWE-208)",
            token.len(),
            MAX_BEARER_TOKEN_LEN
        );
        return Err(AuthError::InvalidKey);
    }

    Ok(token.to_string())
}

/// 将 garrison 校验返回的分解参数桥接为 crawlrs `AuthState`。
///
/// ## 桥接逻辑
///
/// 1. `perms` → `scope`:调用 [`map_perms_to_scope`] 映射为 `ApiKeyScope`
/// 2. 构造 `AuthState::new(pool, team_id, api_key_id, scope)`(DTO 化后仅 4 字段)
///
/// ## 参数
///
/// * `pool` - crawlrs 数据库连接池(`Arc<DbPool>`,`DbPool` 内部 `Arc`,clone 廉价)
/// * `api_key_id` - 已从 garrison `login_id` 解析的 API Key crate::domain::id::Id(调用方负责解析)
/// * `perms` - garrison `GarrisonUtil::get_permission_list` 返回的权限串切片(借用)
/// * `team_id` - 由中间件反查 crawlrs `api_keys` 表获取的 team_id(步骤 4)
///
/// ## 返回
///
/// - `Ok(AuthState)`:成功构造的 AuthState,可注入到请求 extensions
///
/// ## 设计说明
///
/// 签名改为接收 `api_key_id: crate::domain::id::Id` 而非 `login_id: String`,
/// 消除调用方与函数内部的重复 crate::domain::id::Id 解析;`perms` 改为 `&[String]` 借用而非 owned。
pub async fn bridge_to_auth_state(
    pool: Arc<DbPool>,
    api_key_id: crate::domain::id::Id,
    perms: &[String],
    team_id: crate::domain::id::Id,
) -> Result<AuthState, AuthError> {
    // 权限映射(确定性查找表)
    let scope = map_perms_to_scope(perms);

    // 构造 AuthState(DTO 化后仅 4 字段)
    Ok(AuthState::new(pool, team_id, api_key_id, scope))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::auth::ScopePermission;

    // map_perms_to_scope 测试

    /// admin 权限 → read/write/admin 全 true
    #[test]
    fn test_map_perms_admin_grants_all() {
        let perms = vec!["crawlrs:admin".to_string()];
        let scope = map_perms_to_scope(&perms);
        assert!(scope.read, "admin should grant read");
        assert!(scope.write, "admin should grant write");
        assert!(scope.admin, "admin should grant admin");
    }

    /// read 权限 → 仅 read
    #[test]
    fn test_map_perms_read_grants_only_read() {
        let perms = vec!["crawlrs:read".to_string()];
        let scope = map_perms_to_scope(&perms);
        assert!(scope.read, "read should grant read");
        assert!(!scope.write, "read should NOT grant write");
        assert!(!scope.admin, "read should NOT grant admin");
    }

    /// write 权限 → 仅 write(不蕴含 read,最小权限原则)
    #[test]
    fn test_map_perms_write_grants_only_write() {
        let perms = vec!["crawlrs:write".to_string()];
        let scope = map_perms_to_scope(&perms);
        assert!(!scope.read, "write should NOT grant read (least privilege)");
        assert!(scope.write, "write should grant write");
        assert!(!scope.admin, "write should NOT grant admin");
    }

    /// read + write → read + write(admin 不被授予)
    #[test]
    fn test_map_perms_read_and_write_grants_read_write() {
        let perms = vec!["crawlrs:read".to_string(), "crawlrs:write".to_string()];
        let scope = map_perms_to_scope(&perms);
        assert!(scope.read, "read+write should grant read");
        assert!(scope.write, "read+write should grant write");
        assert!(!scope.admin, "read+write should NOT grant admin");
    }

    /// 空权限 → denied(全 false)
    #[test]
    fn test_map_perms_empty_denies_all() {
        let perms: Vec<String> = vec![];
        let scope = map_perms_to_scope(&perms);
        assert!(!scope.read, "empty perms should deny read");
        assert!(!scope.write, "empty perms should deny write");
        assert!(!scope.admin, "empty perms should deny admin");
    }

    /// 未知权限串 → denied(全 false,忽略其他 namespace)
    #[test]
    fn test_map_perms_unknown_perm_denies_all() {
        let perms = vec!["otherapp:read".to_string(), "foo:admin".to_string()];
        let scope = map_perms_to_scope(&perms);
        assert!(!scope.read, "unknown perm should deny read");
        assert!(!scope.write, "unknown perm should deny write");
        assert!(!scope.admin, "unknown perm should deny admin");
    }

    /// admin + read → admin 蕴含 read,去重后全 true
    #[test]
    fn test_map_perms_admin_and_read_dedup() {
        let perms = vec!["crawlrs:admin".to_string(), "crawlrs:read".to_string()];
        let scope = map_perms_to_scope(&perms);
        assert!(scope.read, "admin+read should grant read");
        assert!(scope.write, "admin+read should grant write");
        assert!(scope.admin, "admin+read should grant admin");
    }

    /// 大小写敏感("Crawlrs:admin" ≠ "crawlrs:admin")
    #[test]
    fn test_map_perms_case_sensitive() {
        let perms = vec!["Crawlrs:admin".to_string(), "CRAWLRS:READ".to_string()];
        let scope = map_perms_to_scope(&perms);
        assert!(!scope.read, "wrong case should deny read");
        assert!(!scope.write, "wrong case should deny write");
        assert!(!scope.admin, "wrong case should deny admin");
    }

    /// search_limit/scrape_limit 使用默认值(100/50)
    #[test]
    fn test_map_perms_default_limits() {
        let perms = vec!["crawlrs:admin".to_string()];
        let scope = map_perms_to_scope(&perms);
        assert_eq!(
            scope.search_limit, 100,
            "search_limit should be default 100"
        );
        assert_eq!(scope.scrape_limit, 50, "scrape_limit should be default 50");
    }

    /// 混合权限(read + 未知 + admin)→ admin 蕴含全 true
    #[test]
    fn test_map_perms_mixed_with_unknown() {
        let perms = vec![
            "crawlrs:read".to_string(),
            "otherapp:write".to_string(),
            "crawlrs:admin".to_string(),
        ];
        let scope = map_perms_to_scope(&perms);
        assert!(scope.read, "mixed with admin should grant read");
        assert!(scope.write, "mixed with admin should grant write");
        assert!(scope.admin, "mixed with admin should grant admin");
    }

    /// 常量一致性验证
    #[test]
    fn test_perm_constants() {
        assert_eq!(PERM_READ, "crawlrs:read");
        assert_eq!(PERM_WRITE, "crawlrs:write");
        assert_eq!(PERM_ADMIN, "crawlrs:admin");
        assert_eq!(DEFAULT_SEARCH_LIMIT, 100);
        assert_eq!(DEFAULT_SCRAPE_LIMIT, 50);
        assert_eq!(BEARER_PREFIX, "Bearer ");
    }

    // extract_bearer 测试

    /// 构造测试用 Request(含指定 Authorization header)
    fn make_request(auth_header: Option<&str>) -> Request<Body> {
        let mut req = axum::http::Request::builder()
            .uri("/")
            .body(Body::empty())
            .unwrap();
        if let Some(value) = auth_header {
            req.headers_mut()
                .insert(header::AUTHORIZATION, value.parse().unwrap());
        }
        req
    }

    /// 合法 Bearer token 提取成功
    #[test]
    fn test_extract_bearer_valid_token() {
        let req = make_request(Some("Bearer ak_test_12345"));
        let result = extract_bearer(&req);
        assert!(result.is_ok(), "valid Bearer should be Ok");
        assert_eq!(result.unwrap(), "ak_test_12345");
    }

    /// Authorization header 缺失 → InvalidKey
    #[test]
    fn test_extract_bearer_missing_header() {
        let req = make_request(None);
        let result = extract_bearer(&req);
        assert!(result.is_err(), "missing header should be Err");
        match result.unwrap_err() {
            AuthError::InvalidKey => {}
            other => panic!("expected InvalidKey, got {:?}", other),
        }
    }

    /// 非 Bearer scheme → InvalidKey
    #[test]
    fn test_extract_bearer_wrong_scheme() {
        let req = make_request(Some("Basic abc123"));
        let result = extract_bearer(&req);
        assert!(result.is_err(), "non-Bearer scheme should be Err");
        match result.unwrap_err() {
            AuthError::InvalidKey => {}
            other => panic!("expected InvalidKey, got {:?}", other),
        }
    }

    /// Bearer 后 token 为空 → InvalidKey
    #[test]
    fn test_extract_bearer_empty_token() {
        let req = make_request(Some("Bearer "));
        let result = extract_bearer(&req);
        assert!(result.is_err(), "empty token should be Err");
        match result.unwrap_err() {
            AuthError::InvalidKey => {}
            other => panic!("expected InvalidKey, got {:?}", other),
        }
    }

    /// scheme 大小写敏感(`bearer` ≠ `Bearer`)
    #[test]
    fn test_extract_bearer_case_sensitive_scheme() {
        let req = make_request(Some("bearer ak_test"));
        let result = extract_bearer(&req);
        assert!(result.is_err(), "lowercase 'bearer' should be Err");
        match result.unwrap_err() {
            AuthError::InvalidKey => {}
            other => panic!("expected InvalidKey, got {:?}", other),
        }
    }

    /// header 值含非 ASCII 字节 → InvalidKey
    #[test]
    fn test_extract_bearer_non_ascii_header() {
        let mut req = axum::http::Request::builder()
            .uri("/")
            .body(Body::empty())
            .unwrap();
        // 构造一个非 ASCII header 值(0x80 字节)
        let non_ascii_value = axum::http::HeaderValue::from_bytes(b"Bearer \x80abc").unwrap();
        req.headers_mut()
            .insert(header::AUTHORIZATION, non_ascii_value);
        let result = extract_bearer(&req);
        assert!(result.is_err(), "non-ASCII header should be Err");
        match result.unwrap_err() {
            AuthError::InvalidKey => {}
            other => panic!("expected InvalidKey, got {:?}", other),
        }
    }

    /// 含特殊字符但合法的 token(含 `=` / `.`)
    #[test]
    fn test_extract_bearer_token_with_special_chars() {
        let req = make_request(Some("Bearer ak.test_key=123"));
        let result = extract_bearer(&req);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "ak.test_key=123");
    }

    // bridge_to_auth_state 测试

    /// 构造测试用 `Arc<DbPool>`(跳过 `TEST_DATABASE_URL` 缺失场景)。
    ///
    /// `DbPool` 在 dbnexus 0.4 无 Default 实现,必须连真实 PostgreSQL。
    /// `bridge_to_auth_state` 内部只调用 `AuthState::new(pool, ...)` 把 pool
    /// 存进 `Arc<DbPool>` 字段,不执行任何 DB 操作,故任何 `Arc<DbPool>` 即可。
    async fn make_test_pool() -> Option<Arc<DbPool>> {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return None;
        }
        Some(crate::common::test_helpers::create_test_db_pool())
    }

    /// 合法 api_key_id + admin perms → 全 true scope + 正确字段
    #[tokio::test]
    async fn test_bridge_to_auth_state_admin_perms() {
        let pool = match make_test_pool().await {
            Some(p) => p,
            None => {
                eprintln!(
                    "[skip] TEST_DATABASE_URL not set — test requires real DbPool for AuthState::new"
                );
                return;
            }
        };
        let api_key_id = crate::domain::id::Id::generate();
        let perms = vec!["crawlrs:admin".to_string()];
        let team_id = crate::domain::id::Id::generate();

        let auth_state = bridge_to_auth_state(pool, api_key_id, &perms, team_id)
            .await
            .expect("admin bridge should succeed");

        assert_eq!(auth_state.api_key_id, api_key_id);
        assert_eq!(auth_state.team_id, team_id);
        assert!(auth_state.scope.read);
        assert!(auth_state.scope.write);
        assert!(auth_state.scope.admin);
        assert!(auth_state.scope.has_permission(ScopePermission::Admin));
    }

    /// 合法 api_key_id + read perms → 仅 read scope
    #[tokio::test]
    async fn test_bridge_to_auth_state_read_perms() {
        let pool = match make_test_pool().await {
            Some(p) => p,
            None => {
                eprintln!(
                    "[skip] TEST_DATABASE_URL not set — test requires real DbPool for AuthState::new"
                );
                return;
            }
        };
        let api_key_id = crate::domain::id::Id::generate();
        let perms = vec!["crawlrs:read".to_string()];
        let team_id = crate::domain::id::Id::generate();

        let auth_state = bridge_to_auth_state(pool, api_key_id, &perms, team_id)
            .await
            .expect("read bridge should succeed");

        assert_eq!(auth_state.api_key_id, api_key_id);
        assert_eq!(auth_state.team_id, team_id);
        assert!(auth_state.scope.read);
        assert!(!auth_state.scope.write);
        assert!(!auth_state.scope.admin);
    }

    /// 空 perms → denied scope(全 false),但 AuthState 构造成功
    #[tokio::test]
    async fn test_bridge_to_auth_state_empty_perms_denied_scope() {
        let pool = match make_test_pool().await {
            Some(p) => p,
            None => {
                eprintln!(
                    "[skip] TEST_DATABASE_URL not set — test requires real DbPool for AuthState::new"
                );
                return;
            }
        };
        let api_key_id = crate::domain::id::Id::generate();
        let perms: Vec<String> = vec![];
        let team_id = crate::domain::id::Id::generate();

        let auth_state = bridge_to_auth_state(pool, api_key_id, &perms, team_id)
            .await
            .expect("empty perms should still bridge successfully");

        // 空 perms → denied scope(全 false),但 AuthState 字段正确填充
        assert_eq!(auth_state.api_key_id, api_key_id);
        assert_eq!(auth_state.team_id, team_id);
        assert!(!auth_state.scope.read);
        assert!(!auth_state.scope.write);
        assert!(!auth_state.scope.admin);
    }

    /// 未知 perms → denied scope(与空 perms 等价)
    #[tokio::test]
    async fn test_bridge_to_auth_state_unknown_perms_denied_scope() {
        let pool = match make_test_pool().await {
            Some(p) => p,
            None => {
                eprintln!(
                    "[skip] TEST_DATABASE_URL not set — test requires real DbPool for AuthState::new"
                );
                return;
            }
        };
        let api_key_id = crate::domain::id::Id::generate();
        let perms = vec!["otherapp:admin".to_string(), "foo:read".to_string()];
        let team_id = crate::domain::id::Id::generate();

        let auth_state = bridge_to_auth_state(pool, api_key_id, &perms, team_id)
            .await
            .expect("unknown perms should still bridge successfully");

        assert!(!auth_state.scope.read);
        assert!(!auth_state.scope.write);
        assert!(!auth_state.scope.admin);
    }

    // AuthError::from_garrison 测试

    /// 401 错误 → InvalidKey
    #[test]
    fn test_from_garrison_401_to_invalid_key() {
        let cases = vec![
            garrison::error::GarrisonError::NotLogin("test".to_string()),
            garrison::error::GarrisonError::InvalidToken("test".to_string()),
            garrison::error::GarrisonError::TokenRevoked("test".to_string()),
            garrison::error::GarrisonError::ExpiredToken("test".to_string()),
        ];
        for err in cases {
            let auth_err = AuthError::from_garrison(err);
            match auth_err {
                AuthError::InvalidKey => {}
                other => panic!("expected InvalidKey, got {:?}", other),
            }
        }
    }

    /// 403 DISABLE_SERVICE → InactiveKey
    #[test]
    fn test_from_garrison_403_disable_service_to_inactive_key() {
        let err = garrison::error::GarrisonError::DisableService {
            service: "default".to_string(),
            until: None,
        };
        let auth_err = AuthError::from_garrison(err);
        match auth_err {
            AuthError::InactiveKey => {}
            other => panic!("expected InactiveKey, got {:?}", other),
        }
    }

    /// 403 其他(NOT_PERMISSION / NOT_ROLE / SMS_CHANNEL_RECYCLED)→ Forbidden
    #[test]
    fn test_from_garrison_403_others_to_forbidden() {
        let cases = vec![
            garrison::error::GarrisonError::NotPermission("test".to_string()),
            garrison::error::GarrisonError::NotRole("test".to_string()),
            garrison::error::GarrisonError::SmsChannelRecycled,
        ];
        for err in cases {
            let auth_err = AuthError::from_garrison(err);
            match auth_err {
                AuthError::Forbidden(_) => {}
                other => panic!("expected Forbidden, got {:?}", other),
            }
        }
    }

    /// FirewallBlocked → RateLimited(429)。
    /// IP 暴力破解封禁在 crawlrs API 面对外语义为 429(RFC 6585),
    /// 与 garrison 上游 403 契约解耦(`AuthError::from_garrison`)。
    #[test]
    fn test_from_garrison_firewall_blocked_to_rate_limited() {
        let auth_err = AuthError::from_garrison(garrison::error::GarrisonError::FirewallBlocked(
            "bruteforce".to_string(),
        ));
        match auth_err {
            AuthError::RateLimited => {}
            other => panic!("expected RateLimited, got {:?}", other),
        }
    }

    /// 429 SMS_RATE_LIMIT_EXCEEDED → RateLimited
    #[test]
    fn test_from_garrison_429_to_rate_limited() {
        let err = garrison::error::GarrisonError::SmsRateLimitExceeded {
            window: "hourly".to_string(),
        };
        let auth_err = AuthError::from_garrison(err);
        match auth_err {
            AuthError::RateLimited => {}
            other => panic!("expected RateLimited, got {:?}", other),
        }
    }

    /// 502 NETWORK_ERROR → NetworkError
    #[test]
    fn test_from_garrison_502_to_network_error() {
        let err = garrison::error::GarrisonError::Network("test".to_string());
        let auth_err = AuthError::from_garrison(err);
        match auth_err {
            AuthError::NetworkError(_) => {}
            other => panic!("expected NetworkError, got {:?}", other),
        }
    }

    /// 501 NOT_IMPLEMENTED → NotImplemented
    #[test]
    fn test_from_garrison_501_to_not_implemented() {
        let err = garrison::error::GarrisonError::NotImplemented("test".to_string());
        let auth_err = AuthError::from_garrison(err);
        match auth_err {
            AuthError::NotImplemented(_) => {}
            other => panic!("expected NotImplemented, got {:?}", other),
        }
    }

    /// 400(INVALID_PARAM / NOT_SAFE / SMS_VERIFY_MAX_ATTEMPTS / SMS_CODE_NOT_FOUND)→ InvalidParam
    #[test]
    fn test_from_garrison_400_to_invalid_param() {
        let cases = vec![
            garrison::error::GarrisonError::InvalidParam("test".to_string()),
            garrison::error::GarrisonError::NotSafe {
                reason: "MFA_TOTP_REQUIRED".to_string(),
            },
            garrison::error::GarrisonError::SmsVerifyMaxAttempts,
            garrison::error::GarrisonError::SmsCodeNotFound,
        ];
        for err in cases {
            let auth_err = AuthError::from_garrison(err);
            match auth_err {
                AuthError::InvalidParam(_) => {}
                other => panic!("expected InvalidParam, got {:?}", other),
            }
        }
    }

    /// 500(DAO_ERROR / CONFIG_ERROR / INTERNAL_ERROR / SESSION_ERROR / ANNOTATION_ERROR / CONTEXT_ERROR / OAUTH2_ERROR / INVALID_STATE_TRANSITION)→ InternalError
    #[test]
    fn test_from_garrison_500_to_internal_error() {
        let cases = vec![
            garrison::error::GarrisonError::Dao("test".to_string()),
            garrison::error::GarrisonError::Config("test".to_string()),
            garrison::error::GarrisonError::Internal("test".to_string()),
            garrison::error::GarrisonError::Session("test".to_string()),
            garrison::error::GarrisonError::Annotation("test".to_string()),
            garrison::error::GarrisonError::Context("test".to_string()),
            garrison::error::GarrisonError::OAuth2("test".to_string()),
            garrison::error::GarrisonError::InvalidStateTransition {
                from: "A".to_string(),
                to: "B".to_string(),
            },
        ];
        for err in cases {
            let auth_err = AuthError::from_garrison(err);
            match auth_err {
                AuthError::InternalError(_) => {}
                other => panic!("expected InternalError, got {:?}", other),
            }
        }
    }

    /// Exception(code=-1) → InvalidKey(401)
    #[test]
    fn test_from_garrison_exception_code_neg1_to_invalid_key() {
        let err = garrison::error::GarrisonError::Exception(Box::new(
            garrison::exception::GarrisonException::new(-1, "test"),
        ));
        let auth_err = AuthError::from_garrison(err);
        match auth_err {
            AuthError::InvalidKey => {}
            other => panic!("expected InvalidKey, got {:?}", other),
        }
    }

    /// Exception(code=-2) → Forbidden(403)
    #[test]
    fn test_from_garrison_exception_code_neg2_to_forbidden() {
        let err = garrison::error::GarrisonError::Exception(Box::new(
            garrison::exception::GarrisonException::new(-2, "test"),
        ));
        let auth_err = AuthError::from_garrison(err);
        match auth_err {
            AuthError::Forbidden(_) => {}
            other => panic!("expected Forbidden, got {:?}", other),
        }
    }

    /// Exception(其他 code) → InternalError(500,fail-safe)
    #[test]
    fn test_from_garrison_exception_other_code_to_internal_error() {
        let err = garrison::error::GarrisonError::Exception(Box::new(
            garrison::exception::GarrisonException::new(100, "test"),
        ));
        let auth_err = AuthError::from_garrison(err);
        match auth_err {
            AuthError::InternalError(_) => {}
            other => panic!("expected InternalError, got {:?}", other),
        }
    }
}