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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Unified authentication middleware with scope support.
//!
//! ## 重构(决策 1-4)
//!
//! 本模块在完成 DTO 化与 garrison 桥接:
//! - `AuthState` / `AuthError` 抽出到 `super::auth_types`(决策 3:解决循环依赖)
//! - 删除 `ApiKeyCache` / `AuthRateLimiter` / `validate_api_key_from_db` 等死代码(决策 1)
//! - 限速仅依赖 garrison firewall(决策 2),crawlrs 侧不再做暴力破解防护
//! - 新增 `TeamIdCache`(api_key_id → team_id LRU,容量 4096,TTL 60s,决策 4)
//! - `inject_auth_state` 注入 SHA-256 hash 而非裸 token(CWE-532 防护)
//!
//! ## feature 门控
//!
//! - `auth` 启用:`auth_middleware_inner` 走 garrison RBAC 路径
//! - `auth` 关闭:`default_identity_middleware` 注入默认身份模板(单租户降级)

#[cfg(not(feature = "auth"))]
use crate::common::constants::default_identity::DEFAULT_IDENTITY_TOKEN_HASH;
use crate::domain::auth::{ApiKeyScope, ScopePermission};
use crate::domain::services::audit_service::AuditServiceTrait;
#[cfg(feature = "auth")]
use crate::infrastructure::database::entities::api_key;
// Re-export 共享类型(决策 3:从 auth_types 导入,避免循环依赖)。
// auth-off 构建面(web-axum)同样需要 AuthState——default_identity_middleware 注入它。
pub use crate::presentation::middleware::auth_types::{AuthError, AuthState};
use axum::extract::State;
#[cfg(feature = "auth")]
use axum::response::IntoResponse;
use axum::{
    body::Body,
    http::{Request, StatusCode},
    middleware::Next,
    response::Response,
};
#[cfg(feature = "auth")]
use dbnexus::sea_orm::EntityTrait;
#[cfg(feature = "auth")]
use dbnexus::DbPool;
#[cfg(feature = "auth")]
use log::debug;
#[cfg(feature = "auth")]
use lru::LruCache;
#[cfg(feature = "auth")]
use parking_lot::RwLock as ParkRwLock;
#[cfg(feature = "auth")]
use sha2::{Digest, Sha256};
#[cfg(feature = "auth")]
use std::num::NonZeroUsize;
use std::sync::Arc;
#[cfg(feature = "auth")]
use std::sync::LazyLock;
#[cfg(feature = "auth")]
use std::time::{Duration, Instant};

/// Team ID 缓存容量(决策 4:4096 条目覆盖典型多租户规模)。
#[cfg(feature = "auth")]
const TEAM_ID_CACHE_CAPACITY: usize = 4096;

/// Team ID 缓存 TTL(决策 4:60 秒,平衡 DB 查询压力与 team_id 变更生效延迟)。
#[cfg(feature = "auth")]
const TEAM_ID_CACHE_TTL: Duration = Duration::from_secs(60);

/// 全局 `api_key_id → team_id` LRU 缓存(决策 4)。
///
/// ## 设计
///
/// - 容量 4096(`TEAM_ID_CACHE_CAPACITY`),TTL 60s(`TEAM_ID_CACHE_TTL`)
/// - Key: `api_key_id` (crate::domain::id::Id),Value: `(team_id, cached_at)`
/// - 命中时检查 TTL,过期则 evict 并回查 DB
/// - 使用 `parking_lot::RwLock` 同步锁(不跨 await,避免死锁)
///
/// ## 安全
///
/// 缓存 `team_id` 映射不引入越权风险——`team_id` 由 crawlrs DB 持有,
/// garrison 吊销 key 后 crawlrs DB 行可能被删除,此时缓存 TTL 过期后
/// 回查返回 `None` → `AuthError::KeyNotFound`,拒绝访问。
#[cfg(feature = "auth")]
static TEAM_ID_CACHE: LazyLock<
    ParkRwLock<LruCache<crate::domain::id::Id, (crate::domain::id::Id, Instant)>>,
> = LazyLock::new(|| {
    ParkRwLock::new(LruCache::new(
        NonZeroUsize::new(TEAM_ID_CACHE_CAPACITY).expect("TEAM_ID_CACHE_CAPACITY must be > 0"),
    ))
});

/// 获取 `api_key_id → team_id` 缓存的命中数(监控/测试用)。
#[cfg(feature = "auth")]
pub fn team_id_cache_len() -> usize {
    TEAM_ID_CACHE.read().len()
}

/// 清空 `api_key_id → team_id` 缓存(测试用)。
#[cfg(all(any(test, feature = "test-mocks"), feature = "auth"))]
pub fn reset_team_id_cache() {
    TEAM_ID_CACHE.write().clear();
}

/// 按 `api_key_id` 反查 crawlrs `api_keys` 表获取 `team_id`。
///
/// ## 缓存策略(决策 4)
///
/// 先查 `TEAM_ID_CACHE`(LRU + TTL 60s);命中且未过期则直接返回,
/// 未命中或过期则回查 DB 并填充缓存。
///
/// ## 设计
///
/// garrison 管理 API Key 的校验/吊销/哈希存储,但不持有 `api_key_id → team_id` 映射。
/// crawlrs 保留 `api_keys` 表的 `id`/`team_id` 列供反查。
///
/// ## 参数
///
/// * `pool` - crawlrs 数据库连接池
/// * `api_key_id` - 从 garrison `login_id` 解析得到的 API Key crate::domain::id::Id
///
/// ## 返回
///
/// - `Ok(Some(team_id))`:找到映射
/// - `Ok(None)`:`api_key_id` 不在 `api_keys` 表中
/// - `Err(AuthError::InternalError)`:dbnexus `DbError`(连接池/会话获取失败)
/// - `Err(AuthError::DatabaseError)`:sea-orm 查询失败(`DbErr`)
//
// teams feature 关闭时,`auth_middleware_inner` 直接使用 DEFAULT_TEAM_ID,
// 此函数不被调用。用 `cfg_attr(not(feature = "teams"), allow(dead_code))`
// 显式声明 teams-off 时 unused 是预期行为(Rust 条件编译 unused 的标准处理)。
#[cfg(feature = "auth")]
#[cfg_attr(not(feature = "teams"), allow(dead_code))]
async fn fetch_team_id_by_api_key_id(
    pool: &Arc<DbPool>,
    api_key_id: crate::domain::id::Id,
) -> Result<Option<crate::domain::id::Id>, AuthError> {
    // 1. 查缓存。 `LruCache::get` 需 `&mut self` 更新 LRU 访问顺序,
    // 故必须用 write 锁(非读锁)。debug! 已移到锁外,避免锁内 I/O。
    // 长期优化建议:换用 `moka::Cache`(concurrent LRU,无锁读路径)。
    let cached_hit = {
        let mut cache = TEAM_ID_CACHE.write();
        if let Some((team_id, cached_at)) = cache.get(&api_key_id) {
            if cached_at.elapsed() < TEAM_ID_CACHE_TTL {
                Some(*team_id)
            } else {
                // 过期:evict
                cache.pop(&api_key_id);
                None
            }
        } else {
            None
        }
    };
    if let Some(team_id) = cached_hit {
        debug!(
            "TEAM_ID_CACHE hit: api_key_id={} team_id={}",
            api_key_id, team_id
        );
        return Ok(Some(team_id));
    }

    // 2. 缓存未命中或过期:回查 DB
    let session = pool
        .get_session("admin")
        .await
        .map_err(|e| AuthError::InternalError(format!("db session: {}", e)))?;
    let conn = session
        .connection()
        .map_err(|e| AuthError::InternalError(format!("db conn: {}", e)))?;
    let result = api_key::Entity::find_by_id(api_key_id.to_uuid_v8())
        .one(conn)
        .await?;

    // 3. 填充缓存(仅当找到映射时)。 debug! 移到锁外。
    if let Some(ref model) = result {
        let team_id: crate::domain::id::Id = model.team_id.into();
        {
            let mut cache = TEAM_ID_CACHE.write();
            cache.push(api_key_id, (team_id, Instant::now()));
        }
        debug!(
            "TEAM_ID_CACHE miss→fill: api_key_id={} team_id={}",
            api_key_id, team_id
        );
    }

    Ok(result.map(|m| m.team_id.into()))
}

/// 计算 token 的 SHA-256 hash(hex 编码,带 `sha256:` 前缀)。
///
/// ## 安全(CWE-532)
///
/// 将裸 token 转为 hash 后注入 extensions,避免下游日志/审计泄露明文 token。
/// `sha256:` 前缀与 crawlrs 旧 `ApiKeyCache` 的 key 格式保持一致(惯例优先)。
#[cfg(feature = "auth")]
fn hash_token(token: &str) -> String {
    let digest = Sha256::digest(token.as_bytes());
    format!("sha256:{}", hex::encode(digest))
}

/// Inject auth state into request extensions.
///
/// ## 安全(CWE-532)
///
/// 注入的 `token_hash` 是 SHA-256 hash(`sha256:...`),非裸 token。
/// 下游 `limiteron_rate_limit_middleware` 的 `Extension<String>` 提取器拿到的是 hash,
/// 不会在限速日志中泄露明文 token。
fn inject_auth_state(req: &mut Request<Body>, auth_state: AuthState, token_hash: &str) {
    // 注意:`team_id` 和 `api_key_id` 均为 `crate::domain::id::Id` 类型,若同时 `insert` 会发生类型冲突
    // (后者覆盖前者)。生产代码通过 `Extension<AuthState>` 读取,无需裸 `crate::domain::id::Id` 扩展。
    // 此处仅注入 `AuthState`(包含 team_id/api_key_id/scope)+ `token_hash`(限速器消费)。
    req.extensions_mut().insert(auth_state);
    req.extensions_mut().insert(token_hash.to_string());
}

/// Unified authentication middleware (garrison RBAC path).
///
/// ## 职责
///
/// 1. 提取 Bearer token(`extract_bearer`,来自 `auth_bridge`)
/// 2. 在 `with_current_token` 作用域内调用 garrison `GarrisonUtil::check_api_key` 校验
///    API Key(含 CWE-916 哈希、CWE-307 IP 限速),并提取 `login_id` / `perms`
/// 3. 解析 `login_id` → `api_key_id` (crate::domain::id::Id)(约定)
/// 4. 反查 crawlrs `api_keys` 表获取 `team_id`(garrison 不持有此映射,带 LRU 缓存)
/// 5. 桥接为 `AuthState`(`bridge_to_auth_state`,来自 `auth_bridge`)
/// 6. 复用 `inject_auth_state` 注入 extensions(token_hash 用 SHA-256 hash,CWE-532)
///
/// ## 失败映射(显性化)
///
/// | 失败点 | 映射 | HTTP 状态码 |
/// |--------|------|-------------|
/// | 全局态未初始化 | `StatusCode::INTERNAL_SERVER_ERROR` | 500 |
/// | 公开端点 | `next.run(req)`(跳过) | 200 |
/// | `extract_bearer` 失败 | `AuthError::InvalidKey` | 401 |
/// | garrison 校验失败 | `AuthError::from_garrison(...)` | 401/403/429/500 |
/// | `login_id` 非 crate::domain::id::Id | `AuthError::InvalidLoginId` | 400 |
/// | `api_key_id` 反查未命中 | `AuthError::KeyNotFound` | 400 |
/// | DB 查询失败 | `AuthError::DatabaseError` | 500 |
/// | 桥接失败 | 透传 `AuthError` | 400 |
///
/// ## Security
///
/// - garrison `check_api_key` 负责 CWE-916 哈希校验和 CWE-307 IP 限速
/// - token 不记录到日志(CWE-532);注入 extensions 的是 SHA-256 hash
/// - `login_id` 解析失败不静默回退 `crate::domain::id::Id::nil()`(避免越权)
///
/// 可信代理配置的进程级快照(bootstrap 从 Settings 注入一次)。
///
/// 与限流中间件使用同一 XFF 解析(最右非可信跳),避免认证失败计数按
/// 反代直连 IP 聚合——否则攻击者可用 6 次错误 Key 封禁整台代理 IP。
static TRUSTED_PROXY_CONFIG: std::sync::OnceLock<
    std::sync::Arc<crate::infrastructure::security::secure_ip::TrustedProxyConfig>,
> = std::sync::OnceLock::new();

/// bootstrap 调用一次:注入 `[trusted_proxies]` 配置。
pub fn configure_trusted_proxies(settings: &crate::config::settings::Settings) {
    let config = std::sync::Arc::new(
        crate::infrastructure::security::secure_ip::TrustedProxyConfig::from_settings(
            settings.trusted_proxies.enabled,
            settings.trusted_proxies.proxies.clone(),
        ),
    );
    if TRUSTED_PROXY_CONFIG.set(config).is_err() {
        log::debug!("trusted proxy config already initialized; keeping first value");
    }
}

/// 将客户端 IP 注入 garrison task-local(`garrison::stp::with_current_ip`)。
///
/// garrison firewall-bruteforce 的 IP 级失败计数读取 `garrison::stp::current_ip()`,
/// 按 garrison 契约该值由 Web 框架中间件注入;缺失时 fail-open(IP 限速不启用)。
/// IP 来源与限流中间件一致:`get_secure_client_ip`(可信代理 + 最右非可信跳)。
/// 须挂载于认证中间件**外侧**,保证 `auth_middleware_inner` 运行时 task-local 已就位。
#[cfg(feature = "auth")]
pub async fn garrison_ip_context_middleware(req: axum::extract::Request, next: Next) -> Response {
    let trusted = TRUSTED_PROXY_CONFIG.get().cloned().unwrap_or_else(|| {
        std::sync::Arc::new(
            crate::infrastructure::security::secure_ip::TrustedProxyConfig::default(),
        )
    });
    let ip = crate::infrastructure::security::secure_ip::get_secure_client_ip(&req, &trusted);
    match ip.as_str() {
        "unknown" | "" => next.run(req).await,
        _ => garrison::stp::with_current_ip(ip, next.run(req)).await,
    }
}

#[cfg(feature = "auth")]
pub async fn auth_middleware_inner(
    State(pool): State<Arc<DbPool>>,
    mut req: axum::http::Request<Body>,
    next: Next,
) -> Response {
    use crate::presentation::middleware::auth_bridge::extract_bearer;

    let path = req.uri().path().to_string();
    debug!("AuthMiddleware (garrison) processing path: {}", path);

    // 1. 公开端点跳过认证(与限流共用同一谓词;尾部斜杠已归一化)
    if crate::presentation::middleware::is_public_endpoint(&path) {
        debug!("Public endpoint {}, skipping auth", path);
        return next.run(req).await;
    }

    // 2. 提取 Bearer token
    let raw = match extract_bearer(&req) {
        Ok(t) => t,
        Err(e) => return e.into_response(),
    };

    // 3. garrison 校验 + 提取 login_id / scopes
    let (login_id, perms) = match verify_api_key_scopes(&raw).await {
        Ok(credentials) => credentials,
        Err(e) => return e.into_response(),
    };

    // 4-7. 解析身份并注入 extensions
    if let Some(response) =
        resolve_and_inject_auth_state(&pool, login_id, perms, &raw, &mut req).await
    {
        return response;
    }

    debug!("API Key authentication successful (garrison path)");

    next.run(req).await
}

/// 4-7. login_id → api_key_id → team_id → AuthState,并注入 extensions。
///
/// 反查 crawlrs DB 获取 team_id(带 LRU 缓存,决策 4)。
///
/// teams feature 关闭时(单租户模式),强制使用 DEFAULT_TEAM_ID,不查 DB。
/// teams-on 时保持原逻辑从 DB 反查。
#[cfg(feature = "auth")]
async fn resolve_and_inject_auth_state(
    pool: &Arc<DbPool>,
    login_id: String,
    perms: Vec<String>,
    raw: &str,
    req: &mut axum::http::Request<Body>,
) -> Option<Response> {
    use crate::presentation::middleware::auth_bridge::bridge_to_auth_state;

    // 4. 解析 login_id → api_key_id (crate::domain::id::Id)
    let api_key_id = match login_id.parse::<crate::domain::id::Id>() {
        Ok(u) => u,
        Err(_) => return Some(AuthError::InvalidLoginId(login_id).into_response()),
    };

    // 5. 反查 crawlrs DB 获取 team_id(带 LRU 缓存,决策 4)
    #[cfg(feature = "teams")]
    let team_id = match fetch_team_id_by_api_key_id(pool, api_key_id).await {
        Ok(Some(tid)) => tid,
        Ok(None) => return Some(AuthError::KeyNotFound(api_key_id).into_response()),
        Err(e) => return Some(e.into_response()),
    };
    #[cfg(not(feature = "teams"))]
    let team_id = crate::common::constants::default_identity::DEFAULT_TEAM_ID;

    // 6. 桥接为 AuthState(传 api_key_id 而非 login_id,消除重复 crate::domain::id::Id 解析)
    let auth_state = match bridge_to_auth_state(pool.clone(), api_key_id, &perms, team_id).await {
        Ok(s) => s,
        Err(e) => return Some(e.into_response()),
    };

    // 7. 注入 extensions(token_hash 用 SHA-256 hash,CWE-532 防护)
    let token_hash = hash_token(raw);
    inject_auth_state(req, auth_state, &token_hash);

    None
}

/// 3. garrison 校验 + 提取 login_id / scopes。
///
/// ## 决策:直接用 `ApiKeyHandler::verify_with_namespace` 而非 `stp::check_api_key`
///
/// garrison 0.8.x 的 `check_api_key("crawlrs")` 内部用 verify 验证后丢弃
/// `ApiKeyInfo`,不写入 TokenSession(ApiKey 与 Password/JWT 是两套会话机制)。
/// 后续 `get_login_id()` → `session.get_token_session(token)` 因没有 session 而
/// 返回 `None` → auth_middleware 误报 `NotLogin("login_id missing")` → 401。
///
/// 跳过 stp 会话层的中间间接查询,
/// 直接 `handler.verify_with_namespace(raw, "crawlrs")` 一步拿到
/// `ApiKeyInfo { login_id, scopes, expire_at, ... }`,避免 O(3) DAO roundtrip
/// 且消除 session/notfound 误报。
///
/// CWE-307 保护(firewall-bruteforce)保留:在 verify 前后显式调用。
///
/// DAO 来源优先级:优先 `get_garrison_dao()`(bootstrap 注入的全局共享 DAO),
/// 与 GarrisonManager::init 传入的 dao 是同一 Arc 实例(services.rs
/// init_garrison_auth: `set_garrison_dao(Arc::clone(&dao))`;`GarrisonManager::init(dao,...)`)。
#[cfg(feature = "auth")]
async fn verify_api_key_scopes(raw: &str) -> Result<(String, Vec<String>), AuthError> {
    use garrison::protocol::apikey::ApiKeyHandler;

    let dao = match crate::infrastructure::auth::get_garrison_dao() {
        Some(d) => d,
        None => {
            let e = garrison::error::GarrisonError::Session(
                "auth-middleware: garrison dao not initialized".to_string(),
            );
            return Err(AuthError::from_garrison(e));
        }
    };

    // CWE-307: IP 级暴力破解防护(对齐 check_api_key 内部实现,fail-open 兼容)
    // garrison firewall-bruteforce feature: 若编译期类型缺失则在运行时零成本失效。
    let ip_ctx = garrison::stp::current_ip();
    if let Some(ip) = &ip_ctx {
        if let Some(err) = check_ip_blocked(&dao, ip).await {
            return Err(err);
        }
    }

    let handler = ApiKeyHandler::new(Arc::clone(&dao));
    let info = match handler.verify_with_namespace(raw, "crawlrs").await {
        Ok(i) => i,
        Err(e) => {
            if let Some(ip) = &ip_ctx {
                if let Some(err) = record_failure_and_check_block(&dao, ip).await {
                    return Err(err);
                }
            }
            return Err(AuthError::from_garrison(e));
        }
    };
    Ok((info.login_id, info.scopes))
}

/// CWE-307 预检:IP 已封禁则返回 `FirewallBlocked`;查询故障 fail-open。
#[cfg(feature = "auth")]
async fn check_ip_blocked(
    dao: &Arc<dyn garrison::prelude::GarrisonDao>,
    ip: &str,
) -> Option<AuthError> {
    use garrison::strategy::firewall::brute_force::{BruteForceConfig, BruteForceStrategy};
    use garrison::strategy::firewall::FirewallContext;
    let strategy = BruteForceStrategy::new(BruteForceConfig::default(), Arc::clone(dao));
    let fw_ctx = FirewallContext::new(ip);
    match strategy.is_blocked(&fw_ctx).await {
        Ok(true) => {
            let e = garrison::error::GarrisonError::FirewallBlocked(format!(
                "auth-middleware-ip-blocked::{}",
                ip
            ));
            Some(AuthError::from_garrison(e))
        }
        Ok(false) | Err(_) => None,
    }
}

/// 认证失败后记录 IP 失败计数;达到阈值时立即返回 `FirewallBlocked`。
///
/// 达到 max_attempts 的本次请求即返回 429(而非等下一次请求的
/// 预检才发现被封禁):record_failure 在计数越过阈值时落封禁
/// 记录,这里立即复查一次,命中则拒绝当前请求。
#[cfg(feature = "auth")]
async fn record_failure_and_check_block(
    dao: &Arc<dyn garrison::prelude::GarrisonDao>,
    ip: &str,
) -> Option<AuthError> {
    use garrison::strategy::firewall::brute_force::{BruteForceConfig, BruteForceStrategy};
    use garrison::strategy::firewall::FirewallContext;
    let strategy = BruteForceStrategy::new(BruteForceConfig::default(), Arc::clone(dao));
    let fw_ctx = FirewallContext::new(ip);
    if let Err(rec_err) = strategy.record_failure(&fw_ctx).await {
        debug!(
            "brute force record_failure failed (ip={}, err={})",
            ip, rec_err
        );
    }
    match strategy.is_blocked(&fw_ctx).await {
        Ok(true) => {
            let e = garrison::error::GarrisonError::FirewallBlocked(format!(
                "auth-middleware-ip-blocked::{}",
                ip
            ));
            Some(AuthError::from_garrison(e))
        }
        Ok(false) | Err(_) => None,
    }
}

/// auth-off protected routes 的显式放行开关(默认 `false` = 默认拒绝 401)。
///
/// 语义恢复自 v0.2.0-rc.1(0.2.0-rc.2 路由装配重构时意外丢失,见 CHANGELOG):
/// 未显式 opt-in 时,protected 请求一律 `401`——auth-off 降级模式也不应在
/// 未确认安全边界的情况下放行请求。
#[cfg(not(feature = "auth"))]
static ALLOW_UNAUTHENTICATED: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);
#[cfg(not(feature = "auth"))]
static DENY_LOG_ONCE: std::sync::OnceLock<()> = std::sync::OnceLock::new();
#[cfg(not(feature = "auth"))]
static ALLOW_LOG_ONCE: std::sync::OnceLock<()> = std::sync::OnceLock::new();

/// 显式放行未鉴权请求(auth-off 面 opt-in;语义恢复自 v0.2.0-rc.1)。
///
/// 调用后 protected routes 以**匿名受限身份**(模板 scope,见
/// `build_default_identity_template`)放行;未调用时默认 `401`。
/// 一次性 `error!` 日志声明安全语义降级——此模式仅限受信任内网部署,
/// 多租户或公开 API 场景必须启用 `auth` feature。
#[cfg(not(feature = "auth"))]
pub fn allow_unauthenticated_protected() {
    ALLOW_LOG_ONCE.get_or_init(|| {
        log::error!(
            "{}",
            crate::i18n::tr_log("auth-allow-unauthenticated-enabled")
        );
    });
    ALLOW_UNAUTHENTICATED.store(true, std::sync::atomic::Ordering::SeqCst);
}

/// 测试用:重置 opt-in 开关(避免跨用例污染)。
#[cfg(all(test, not(feature = "auth")))]
pub(crate) fn _reset_unauthenticated_for_test() {
    ALLOW_UNAUTHENTICATED.store(false, std::sync::atomic::Ordering::SeqCst);
}

/// 单租户降级模式下的默认身份中间件(`auth` feature 关闭时启用)。
///
/// 当 `auth` feature 关闭时,此中间件替代真实 `auth_middleware`:
/// 不校验 API Key、不查 DB、不做暴力破解防护。
///
/// **默认拒绝**:未调用 [`allow_unauthenticated_protected`] 时,protected
/// 请求一律 `401`;一次性 `error!` 日志提示运维存在未鉴权路径。
/// opt-in 后注入预构建的 `AuthState` 模板(匿名受限身份)并放行。
///
/// # Security
///
/// 此中间件仅适用于受信任的内部部署(单租户、无外部用户)。
/// 在多租户或公开 API 场景下必须启用 `auth` feature。
#[cfg(not(feature = "auth"))]
pub(crate) async fn default_identity_middleware(
    State(template): State<AuthState>,
    mut req: Request<Body>,
    next: Next,
) -> Response {
    use axum::response::IntoResponse as _;
    if !ALLOW_UNAUTHENTICATED.load(std::sync::atomic::Ordering::SeqCst) {
        DENY_LOG_ONCE.get_or_init(|| {
            log::error!(
                "{}",
                crate::i18n::tr_log("auth-disabled-unauthenticated-denied")
            );
        });
        return (StatusCode::UNAUTHORIZED, "authentication required").into_response();
    }
    inject_auth_state(&mut req, template, DEFAULT_IDENTITY_TOKEN_HASH);
    next.run(req).await
}

/// Scope validation middleware.
///
/// Validates that the API Key has the required scope for the requested endpoint.
/// This middleware should be used after the main auth middleware.
pub async fn scope_middleware(req: Request<Body>, next: Next) -> Result<Response, StatusCode> {
    let path = req.uri().path().to_string();
    let method = req.method().clone();

    // Determine required scope based on endpoint
    let required_scope = determine_required_scope(&path, method.as_ref());

    if let Some(required) = required_scope {
        let auth_state = req
            .extensions()
            .get::<AuthState>()
            .ok_or(StatusCode::UNAUTHORIZED)?;

        if !auth_state.scope.has_permission(required) {
            // scope denied 是预期事件(合法的授权拒绝),非攻击信号。
            // api_key_id 是 UUID(非敏感),但生产 log level 设为 warn 会产生噪音,改为 info。
            // 详细拒绝事件已通过 audit_service.log_deny 入审计。
            log::info!(
                "Scope denied: API Key {} lacks {:?} for {} {}",
                auth_state.api_key_id,
                required,
                method,
                path
            );

            // Log scope denial to audit service(失败必须显性化)
            if let Some(audit_service) = req.extensions().get::<Arc<dyn AuditServiceTrait>>() {
                let api_key_scope: ApiKeyScope = required.into();
                let reason = format!("Missing required scope: {:?}", required);
                if let Err(e) = audit_service
                    .log_deny(
                        "scope.denied".to_string(),
                        Some(auth_state.api_key_id),
                        Some(auth_state.team_id),
                        reason,
                        Some(api_key_scope),
                    )
                    .await
                {
                    // 审计失败不阻塞拒绝流程,但必须显性记录(显性化)
                    log::error!(
                        "audit log_deny failed for scope.denied event: api_key_id={} team_id={} err={}",
                        auth_state.api_key_id,
                        auth_state.team_id,
                        e
                    );
                }
            }

            return Err(StatusCode::FORBIDDEN);
        }
    }

    Ok(next.run(req).await)
}

/// Check if a path matches a prefix exactly or has a slash after the prefix.
fn is_path_prefix(path: &str, prefix: &str) -> bool {
    path == prefix || (path.starts_with(prefix) && path[prefix.len()..].starts_with('/'))
}

/// Determine required scope for an endpoint.
fn determine_required_scope(path: &str, method: &str) -> Option<ScopePermission> {
    // Admin endpoints - use precise matching
    if is_path_prefix(path, "/api/v1/teams") || is_path_prefix(path, "/api/v1/billing") {
        return Some(ScopePermission::Admin);
    }

    // Write endpoints (POST, PUT, PATCH, DELETE)
    if method == "POST" || method == "PUT" || method == "PATCH" || method == "DELETE" {
        return Some(ScopePermission::Write);
    }

    // Read endpoints (GET) - always allowed if read scope is present
    None
}

/// Create an auth state for testing purposes.
#[cfg(all(test, feature = "auth"))]
pub fn test_auth_state(
    db: Arc<DbPool>,
    team_id: crate::domain::id::Id,
    api_key_id: crate::domain::id::Id,
) -> AuthState {
    AuthState::new(db, team_id, api_key_id, ApiKeyScope::default())
}

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

    // is_path_prefix tests

    #[test]
    fn test_is_path_prefix_exact_match() {
        assert!(is_path_prefix("/api/v1/teams", "/api/v1/teams"));
    }

    #[test]
    fn test_is_path_prefix_with_slash() {
        assert!(is_path_prefix("/api/v1/teams/123", "/api/v1/teams"));
    }

    #[test]
    fn test_is_path_prefix_suffix_without_slash_no_match() {
        assert!(!is_path_prefix("/api/v1/teams-secret", "/api/v1/teams"));
    }

    #[test]
    fn test_is_path_prefix_no_match() {
        assert!(!is_path_prefix("/v1/search", "/api/v1/teams"));
    }

    // determine_required_scope tests

    #[test]
    fn test_determine_required_scope_teams_admin() {
        assert_eq!(
            determine_required_scope("/api/v1/teams", "GET"),
            Some(ScopePermission::Admin)
        );
    }

    #[test]
    fn test_determine_required_scope_teams_subpath_admin() {
        assert_eq!(
            determine_required_scope("/api/v1/teams/123", "GET"),
            Some(ScopePermission::Admin)
        );
    }

    #[test]
    fn test_determine_required_scope_billing_admin() {
        assert_eq!(
            determine_required_scope("/api/v1/billing", "GET"),
            Some(ScopePermission::Admin)
        );
    }

    #[test]
    fn test_determine_required_scope_teams_secret_not_admin() {
        // /api/v1/teams-secret 不匹配 /api/v1/teams 前缀(is_path_prefix 拒绝)
        assert_eq!(
            determine_required_scope("/api/v1/teams-secret", "GET"),
            None
        );
    }

    #[test]
    fn test_determine_required_scope_post_write() {
        assert_eq!(
            determine_required_scope("/v1/search", "POST"),
            Some(ScopePermission::Write)
        );
        assert_eq!(
            determine_required_scope("/v1/scrape", "POST"),
            Some(ScopePermission::Write)
        );
    }

    #[test]
    fn test_determine_required_scope_get_none() {
        assert_eq!(determine_required_scope("/v1/search", "GET"), None);
        assert_eq!(determine_required_scope("/v1/crawl/123", "GET"), None);
    }

    #[test]
    fn test_determine_required_scope_put_delete_patch_write() {
        assert_eq!(
            determine_required_scope("/v1/crawl/123", "PUT"),
            Some(ScopePermission::Write)
        );
        assert_eq!(
            determine_required_scope("/v1/crawl/123", "DELETE"),
            Some(ScopePermission::Write)
        );
        assert_eq!(
            determine_required_scope("/v1/crawl/123", "PATCH"),
            Some(ScopePermission::Write)
        );
    }

    // hash_token tests (CWE-532)
    #[cfg(feature = "auth")]
    mod hash_token_tests {
        use super::*;

        #[test]
        fn test_hash_token_returns_sha256_prefix() {
            let hash = hash_token("test_token");
            assert!(
                hash.starts_with("sha256:"),
                "hash must start with 'sha256:' prefix, got: {hash}"
            );
        }

        #[test]
        fn test_hash_token_is_deterministic() {
            let hash1 = hash_token("same_token");
            let hash2 = hash_token("same_token");
            assert_eq!(hash1, hash2, "same input must produce same hash");
        }

        #[test]
        fn test_hash_token_different_inputs_different_outputs() {
            let hash1 = hash_token("token_a");
            let hash2 = hash_token("token_b");
            assert_ne!(
                hash1, hash2,
                "different inputs must produce different hashes"
            );
        }

        #[test]
        fn test_hash_token_does_not_contain_plaintext() {
            let token = "sensitive_secret_token_12345";
            let hash = hash_token(token);
            assert!(
                !hash.contains(token),
                "hash must not contain plaintext token (CWE-532)"
            );
        }
    }

    // team_id cache tests
    #[cfg(feature = "auth")]
    mod team_id_cache_tests {
        use super::*;
        use std::time::Duration;

        /// 重置 team_id 缓存以避免跨测试污染。
        fn reset_team_id_cache_for_test() {
            reset_team_id_cache();
        }

        #[test]
        fn test_team_id_cache_len_starts_at_zero() {
            reset_team_id_cache_for_test();
            assert_eq!(team_id_cache_len(), 0);
        }

        #[test]
        fn test_team_id_cache_constants() {
            assert_eq!(TEAM_ID_CACHE_CAPACITY, 4096);
            assert_eq!(TEAM_ID_CACHE_TTL, Duration::from_secs(60));
        }
    }

    // default_identity_middleware tests (feature-gate: `auth` off)
    //
    // 这些测试仅在 `--no-default-features`(关闭 `auth` feature)下编译运行,
    // 验证 `default_identity_middleware` 的契约。
    #[cfg(not(feature = "auth"))]
    mod default_identity_tests {
        use super::*;
        use crate::common::constants::default_identity::{DEFAULT_API_KEY_ID, DEFAULT_TEAM_ID};
        use crate::common::test_helpers::create_test_db_pool;
        use axum::{
            middleware::from_fn_with_state, response::IntoResponse, routing::get, Extension, Router,
        };
        use tower::ServiceExt;

        async fn reflect_extensions(
            Extension(auth_state): Extension<AuthState>,
        ) -> impl IntoResponse {
            (
                StatusCode::OK,
                format!(
                    "auth_team={}\nauth_key={}\nread={}\nwrite={}\nadmin={}",
                    auth_state.team_id,
                    auth_state.api_key_id,
                    auth_state.scope.read,
                    auth_state.scope.write,
                    auth_state.scope.admin,
                ),
            )
        }

        fn make_default_identity_router(template: AuthState) -> Router {
            Router::new()
                .route("/v1/echo", get(reflect_extensions))
                .layer(from_fn_with_state(template, default_identity_middleware))
        }

        #[tokio::test]
        async fn default_identity_middleware_denies_by_default_with_401() {
            let _guard = UNAUTH_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
            _reset_unauthenticated_for_test();
            let pool = create_test_db_pool();
            let template = AuthState::new(
                pool,
                DEFAULT_TEAM_ID,
                DEFAULT_API_KEY_ID,
                ApiKeyScope::denied(),
            );

            let response = make_default_identity_router(template)
                .oneshot(
                    Request::builder()
                        .uri("/v1/echo")
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();

            // 恢复 rc.1 语义:auth-off 且未 opt-in 时默认 401(安全收紧不得静默回退)
            assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        }

        #[tokio::test]
        async fn allow_unauthenticated_protected_opt_in_injects_template_identity() {
            let _guard = UNAUTH_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
            _reset_unauthenticated_for_test();
            allow_unauthenticated_protected();
            let pool = create_test_db_pool();
            let template = AuthState::new(
                pool,
                DEFAULT_TEAM_ID,
                DEFAULT_API_KEY_ID,
                ApiKeyScope::denied(),
            );

            let response = make_default_identity_router(template)
                .oneshot(
                    Request::builder()
                        .uri("/v1/echo")
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();

            assert_eq!(response.status(), StatusCode::OK);
            let body = String::from_utf8(
                axum::body::to_bytes(response.into_body(), usize::MAX)
                    .await
                    .unwrap()
                    .to_vec(),
            )
            .unwrap();
            // opt-in 注入的是模板身份(denied scope),不再注入 full_access
            assert!(body.contains(&format!("auth_team={}", DEFAULT_TEAM_ID)));
            assert!(body.contains(&format!("auth_key={}", DEFAULT_API_KEY_ID)));
            assert!(body.contains("read=false"));
            assert!(body.contains("write=false"));
            assert!(body.contains("admin=false"));
            _reset_unauthenticated_for_test();
        }

        /// 串行化 opt-in 开关相关的用例:ALLOW_UNAUTHENTICATED 是进程级静态,
        /// 并行用例互踩会造成偶发假失败。
        static UNAUTH_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

        #[tokio::test]
        async fn default_identity_middleware_passes_without_authorization_header() {
            let _guard = UNAUTH_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
            allow_unauthenticated_protected();
            let pool = create_test_db_pool();
            let template = AuthState::new(
                pool,
                DEFAULT_TEAM_ID,
                DEFAULT_API_KEY_ID,
                ApiKeyScope::denied(),
            );

            let response = make_default_identity_router(template)
                .oneshot(
                    Request::builder()
                        .uri("/v1/echo")
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();

            assert_eq!(response.status(), StatusCode::OK);
            _reset_unauthenticated_for_test();
        }

        #[tokio::test]
        async fn default_identity_middleware_ignores_invalid_authorization_header() {
            let _guard = UNAUTH_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
            allow_unauthenticated_protected();
            let pool = create_test_db_pool();
            let template = AuthState::new(
                pool,
                DEFAULT_TEAM_ID,
                DEFAULT_API_KEY_ID,
                ApiKeyScope::denied(),
            );

            let response = make_default_identity_router(template)
                .oneshot(
                    Request::builder()
                        .uri("/v1/echo")
                        .header("Authorization", "Bearer fake_token_should_be_ignored")
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();

            assert_eq!(response.status(), StatusCode::OK);
            _reset_unauthenticated_for_test();
        }
    }
}