garrison 0.9.0

Garrison - 面向 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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! 账号安全能力 Prometheus 指标(`metrics-prometheus` feature):4 个指标——凭证验证 / 策略校验 /
//! 认证流程执行耗时 Histogram + 锁定触发 Counter,指标名分别为
//! `garrison_credential_verify_duration_seconds` / `garrison_policy_validate_duration_seconds` /
//! `garrison_authflow_execute_duration_seconds` / `garrison_lockout_triggered_total`。
//!
//! 集成点:`UserLockoutStrategy::record_failure` 触发锁定时 `record_lockout`;`PasswordPolicyEngine::validate`
//! 每条规则后 `observe_policy_validate`;`AuthExecutor::execute_with_metrics` 计流程与 Login/Mfa 凭证验证耗时。
//!
//! 与 `crate::observability::GarrisonMetrics` 一致:未启用 `metrics-prometheus` 时 `AccountMetrics`
//! 为 `()` 别名,调用方使用 `Option<Arc<AccountMetrics>>` 仍可编译。

#[cfg(feature = "metrics-prometheus")]
use std::time::Duration;

/// 账号安全能力 Prometheus 指标集合(模式与 `crate::observability::GarrisonMetrics` 一致):
/// 4 个指标注册到指定 registry,经 `with_metrics` builder 注入 `UserLockoutStrategy` /
/// `PasswordPolicyEngine`,或作为 `AuthExecutor::execute_with_metrics` 的参数传入(保持五字段约束)。
///
/// # 使用示例
///
/// ```ignore
/// use garrison::account::metrics::AccountMetrics;
/// use std::sync::Arc;
/// use std::time::Duration;
///
/// let metrics = Arc::new(AccountMetrics::new());
/// metrics.observe_credential_verify("password", Duration::from_millis(5));
/// metrics.record_lockout(true);
/// let output = metrics.gather();
/// assert!(output.contains("garrison_credential_verify_duration_seconds"));
/// ```
#[cfg(feature = "metrics-prometheus")]
#[derive(Clone)]
pub struct AccountMetrics {
    /// 凭证验证耗时 Histogram(标签:credential_type)。
    credential_verify_duration: prometheus::HistogramVec,
    /// 密码策略校验耗时 Histogram(标签:rule_name)。
    policy_validate_duration: prometheus::HistogramVec,
    /// 锁定触发次数 Counter(标签:lockout_type=temporary|permanent)。
    lockout_triggered_total: prometheus::CounterVec,
    /// 认证流程执行耗时 Histogram(标签:flow_name)。
    authflow_execute_duration: prometheus::HistogramVec,
}

#[cfg(feature = "metrics-prometheus")]
impl AccountMetrics {
    /// 创建新的指标集合,注册到默认 registry(进程级单例,OnceLock 缓存)。
    ///
    /// 本方法不会 panic:默认 registry 已存在同名指标时(重复 `new` / 与 `register_to(default_registry)`
    /// 混用),`tracing::warn` 后返回未注册的本地实例(`observe_*` / `record_*` / `gather()` 均可用,仅默认
    /// registry 不再新增采集,已注册实例不受影响);生产环境建议用 [`Self::register_to`] 注册到自定义 registry。
    pub fn new() -> Self {
        use std::sync::OnceLock;
        static INSTANCE: OnceLock<AccountMetrics> = OnceLock::new();
        INSTANCE.get_or_init(Self::init_default).clone()
    }

    /// new() 的单例初始化:注册默认 registry,冲突时 warn + 回退本地实例
    /// (与 `credit::metrics::CreditMetrics::new` 修复方式一致)。
    fn init_default() -> Self {
        match Self::register_to(prometheus::default_registry()) {
            Ok(m) => m,
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "{}",
                    crate::i18n::translate_detail(
                        "logs-metrics-already-registered",
                        &[("arg0", "AccountMetrics")]
                    )
                );
                // build() 仅在指标名/帮助文本非法时失败——静态字面量下不可达
                Self::build().expect("AccountMetrics: static metric opts are valid (unreachable)")
            },
        }
    }

    /// 创建并注册到指定 registry(自定义 registry 场景、测试隔离);已注册同名指标返回
    /// `Err(prometheus::Error::AlreadyReg)`。
    pub fn register_to(registry: &prometheus::Registry) -> Result<Self, prometheus::Error> {
        let metrics = Self::build()?;
        registry.register(Box::new(metrics.credential_verify_duration.clone()))?;
        registry.register(Box::new(metrics.policy_validate_duration.clone()))?;
        registry.register(Box::new(metrics.lockout_triggered_total.clone()))?;
        registry.register(Box::new(metrics.authflow_execute_duration.clone()))?;
        Ok(metrics)
    }

    /// 构建指标集合(不注册到任何 registry)。
    fn build() -> Result<Self, prometheus::Error> {
        // Histogram buckets 与 GarrisonMetrics 一致
        let buckets = vec![0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0];

        let credential_verify_duration = prometheus::HistogramVec::new(
            prometheus::HistogramOpts::new(
                "garrison_credential_verify_duration_seconds",
                "Credential verify duration in seconds",
            )
            .buckets(buckets.clone()),
            &["credential_type"],
        )?;
        let policy_validate_duration = prometheus::HistogramVec::new(
            prometheus::HistogramOpts::new(
                "garrison_policy_validate_duration_seconds",
                "Password policy rule validate duration in seconds",
            )
            .buckets(buckets.clone()),
            &["rule_name"],
        )?;
        let lockout_triggered_total = prometheus::CounterVec::new(
            prometheus::Opts::new(
                "garrison_lockout_triggered_total",
                "Total number of lockout triggered (temporary|permanent)",
            ),
            &["lockout_type"],
        )?;
        let authflow_execute_duration = prometheus::HistogramVec::new(
            prometheus::HistogramOpts::new(
                "garrison_authflow_execute_duration_seconds",
                "Authentication flow execute duration in seconds",
            )
            .buckets(buckets),
            &["flow_name"],
        )?;

        Ok(Self {
            credential_verify_duration,
            policy_validate_duration,
            lockout_triggered_total,
            authflow_execute_duration,
        })
    }

    /// 观测一次凭证验证耗时(`credential_type` 标签)。
    pub fn observe_credential_verify(&self, credential_type: &str, duration: Duration) {
        self.credential_verify_duration
            .with_label_values(&[credential_type])
            .observe(duration.as_secs_f64());
    }

    /// 观测一次密码策略规则校验耗时(`rule_name` 标签)。
    pub fn observe_policy_validate(&self, rule_name: &str, duration: Duration) {
        self.policy_validate_duration
            .with_label_values(&[rule_name])
            .observe(duration.as_secs_f64());
    }

    /// 记录一次锁定触发(`permanent` 区分 permanent / temporary 标签)。
    pub fn record_lockout(&self, permanent: bool) {
        let label = if permanent { "permanent" } else { "temporary" };
        self.lockout_triggered_total
            .with_label_values(&[label])
            .inc();
    }

    /// 观测一次认证流程执行耗时(`flow_name` 标签)。
    pub fn observe_authflow_execute(&self, flow_name: &str, duration: Duration) {
        self.authflow_execute_duration
            .with_label_values(&[flow_name])
            .observe(duration.as_secs_f64());
    }

    /// 收集所有指标为 Prometheus 文本格式(供 `/metrics` 端点抓取):直接从自身 4 个字段
    /// (`HistogramVec` / `CounterVec`)调用 `Collector::collect`,不依赖任何外部 registry,
    /// 故注册到 default 或自定义 registry 均能正确返回。
    pub fn gather(&self) -> String {
        use prometheus::core::Collector;
        use prometheus::Encoder;
        let mut metric_families = Vec::new();
        metric_families.extend(self.credential_verify_duration.collect());
        metric_families.extend(self.policy_validate_duration.collect());
        metric_families.extend(self.lockout_triggered_total.collect());
        metric_families.extend(self.authflow_execute_duration.collect());
        let mut buffer = Vec::new();
        let encoder = prometheus::TextEncoder::new();
        // 编码失败显式记录 warn(不中断主流程);返回显式错误标记行(Prometheus 文本注释),
        // 使调用方可区分「无指标记录」与「编码失败」,不静默返回空串
        match encoder.encode(&metric_families, &mut buffer) {
            Ok(()) => String::from_utf8_lossy(&buffer).into_owned(),
            Err(e) => {
                tracing::warn!(error = %e, "AccountMetrics::gather prometheus encode failed");
                format!("# garrison account-metrics gather encode failed: {e}")
            },
        }
    }
}

#[cfg(feature = "metrics-prometheus")]
impl Default for AccountMetrics {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "metrics-prometheus")]
impl std::fmt::Debug for AccountMetrics {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AccountMetrics")
            .field("credential_verify_duration", &"HistogramVec")
            .field("policy_validate_duration", &"HistogramVec")
            .field("lockout_triggered_total", &"CounterVec")
            .field("authflow_execute_duration", &"HistogramVec")
            .finish()
    }
}

/// 指标集合的 feature-gated 别名:启用 `metrics-prometheus` 时解析为 [`AccountMetrics`],
/// 未启用时解析为 `()` unit type(调用方使用 `Option<Arc<AccountMetrics>>` 仍可编译)。
#[cfg(not(feature = "metrics-prometheus"))]
pub type AccountMetrics = ();

#[cfg(all(test, feature = "metrics-prometheus"))]
mod tests {
    use super::*;
    use serial_test::serial;

    /// 测试 AccountMetrics 创建并注册到自定义 registry 成功,4 个指标名都出现在 gather 输出中。
    #[test]
    #[serial]
    fn account_metrics_register_to_custom_registry() {
        let registry = prometheus::Registry::new();
        let metrics = AccountMetrics::register_to(&registry).expect("注册到自定义 registry 失败");
        // 先观测/记录一次,确保 HistogramVec/CounterVec 在 gather 输出中可见
        metrics.observe_credential_verify("password", Duration::from_millis(1));
        metrics.observe_policy_validate("length", Duration::from_millis(1));
        metrics.record_lockout(false);
        metrics.observe_authflow_execute("login", Duration::from_millis(1));

        let gathered = prometheus::TextEncoder::new()
            .encode_to_string(&registry.gather())
            .expect("encode 失败");
        assert!(
            gathered.contains("garrison_credential_verify_duration_seconds"),
            "missing credential_verify_duration: {}",
            gathered
        );
        assert!(
            gathered.contains("garrison_policy_validate_duration_seconds"),
            "missing policy_validate_duration: {}",
            gathered
        );
        assert!(
            gathered.contains("garrison_lockout_triggered_total"),
            "missing lockout_triggered_total: {}",
            gathered
        );
        assert!(
            gathered.contains("garrison_authflow_execute_duration_seconds"),
            "missing authflow_execute_duration: {}",
            gathered
        );
    }

    /// 测试 observe_credential_verify 记录 credential_type 标签 + count。
    #[test]
    #[serial]
    fn credential_verify_duration_registered_and_observed() {
        let registry = prometheus::Registry::new();
        let metrics = AccountMetrics::register_to(&registry).unwrap();
        metrics.observe_credential_verify("password", Duration::from_millis(5));
        metrics.observe_credential_verify("password", Duration::from_millis(10));
        metrics.observe_credential_verify("totp", Duration::from_millis(3));

        let output = prometheus::TextEncoder::new()
            .encode_to_string(&registry.gather())
            .unwrap();
        assert!(
            output.contains("garrison_credential_verify_duration_seconds"),
            "missing metric name: {}",
            output
        );
        assert!(
            output.contains("credential_type=\"password\""),
            "missing password label: {}",
            output
        );
        assert!(
            output.contains("credential_type=\"totp\""),
            "missing totp label: {}",
            output
        );
        assert!(
            output.contains(
                "garrison_credential_verify_duration_seconds_count{credential_type=\"password\"} 2"
            ),
            "password count should be 2: {}",
            output
        );
    }

    /// 测试 observe_policy_validate 记录 rule_name 标签 + count。
    #[test]
    #[serial]
    fn policy_validate_duration_registered_and_observed() {
        let registry = prometheus::Registry::new();
        let metrics = AccountMetrics::register_to(&registry).unwrap();
        metrics.observe_policy_validate("length", Duration::from_millis(2));
        metrics.observe_policy_validate("complexity", Duration::from_millis(4));

        let output = prometheus::TextEncoder::new()
            .encode_to_string(&registry.gather())
            .unwrap();
        assert!(
            output.contains("garrison_policy_validate_duration_seconds"),
            "missing metric name: {}",
            output
        );
        assert!(
            output.contains("rule_name=\"length\""),
            "missing length label: {}",
            output
        );
        assert!(
            output.contains("rule_name=\"complexity\""),
            "missing complexity label: {}",
            output
        );
        assert!(
            output.contains(
                "garrison_policy_validate_duration_seconds_count{rule_name=\"length\"} 1"
            ),
            "length count should be 1: {}",
            output
        );
    }

    /// 测试 record_lockout 分别递增 temporary / permanent 标签。
    #[test]
    #[serial]
    fn lockout_triggered_total_registered_and_recorded() {
        let registry = prometheus::Registry::new();
        let metrics = AccountMetrics::register_to(&registry).unwrap();
        metrics.record_lockout(false); // temporary
        metrics.record_lockout(false); // temporary
        metrics.record_lockout(true); // permanent

        let output = prometheus::TextEncoder::new()
            .encode_to_string(&registry.gather())
            .unwrap();
        assert!(
            output.contains("garrison_lockout_triggered_total"),
            "missing metric name: {}",
            output
        );
        assert!(
            output.contains("lockout_type=\"temporary\""),
            "missing temporary label: {}",
            output
        );
        assert!(
            output.contains("lockout_type=\"permanent\""),
            "missing permanent label: {}",
            output
        );
        assert!(
            output.contains("garrison_lockout_triggered_total{lockout_type=\"temporary\"} 2"),
            "temporary count should be 2: {}",
            output
        );
        assert!(
            output.contains("garrison_lockout_triggered_total{lockout_type=\"permanent\"} 1"),
            "permanent count should be 1: {}",
            output
        );
    }

    /// 测试 observe_authflow_execute 记录 flow_name 标签 + count。
    #[test]
    #[serial]
    fn authflow_execute_duration_registered_and_observed() {
        let registry = prometheus::Registry::new();
        let metrics = AccountMetrics::register_to(&registry).unwrap();
        metrics.observe_authflow_execute("login", Duration::from_millis(50));
        metrics.observe_authflow_execute("mfa", Duration::from_millis(20));

        let output = prometheus::TextEncoder::new()
            .encode_to_string(&registry.gather())
            .unwrap();
        assert!(
            output.contains("garrison_authflow_execute_duration_seconds"),
            "missing metric name: {}",
            output
        );
        assert!(
            output.contains("flow_name=\"login\""),
            "missing login label: {}",
            output
        );
        assert!(
            output.contains("flow_name=\"mfa\""),
            "missing mfa label: {}",
            output
        );
        assert!(
            output.contains(
                "garrison_authflow_execute_duration_seconds_count{flow_name=\"login\"} 1"
            ),
            "login count should be 1: {}",
            output
        );
    }

    /// 测试 register_to 重复注册返回 AlreadyReg 错误。
    #[test]
    #[serial]
    fn duplicate_register_returns_already_reg_error() {
        let registry = prometheus::Registry::new();
        let _m1 = AccountMetrics::register_to(&registry).expect("首次注册失败");
        let result = AccountMetrics::register_to(&registry);
        assert!(result.is_err(), "重复注册应返回错误");
        match result {
            Err(prometheus::Error::AlreadyReg) => {},
            Err(e) => panic!("期望 AlreadyReg 错误,实际: {:?}", e),
            Ok(_) => panic!("期望错误,实际成功"),
        }
    }

    /// 测试 Clone trait(用于 Arc<AccountMetrics> 在多线程共享场景)。
    #[test]
    #[serial]
    fn account_metrics_clone_shared_underlying_state() {
        let registry = prometheus::Registry::new();
        let m1 = AccountMetrics::register_to(&registry).expect("注册失败");
        let m2 = m1.clone();
        m1.record_lockout(false);
        m2.record_lockout(false);
        // 两个 clone 共享底层 Counter,应都记录
        let output = prometheus::TextEncoder::new()
            .encode_to_string(&registry.gather())
            .unwrap();
        assert!(
            output.contains("garrison_lockout_triggered_total{lockout_type=\"temporary\"} 2"),
            "clone 应共享底层 Counter: {}",
            output
        );
    }

    /// 测试 Debug trait 实现输出字段名与类型名。
    #[test]
    #[serial]
    fn account_metrics_debug_impl() {
        let registry = prometheus::Registry::new();
        let metrics = AccountMetrics::register_to(&registry).expect("注册失败");
        let debug_str = format!("{:?}", metrics);
        assert!(debug_str.contains("AccountMetrics"));
        assert!(debug_str.contains("HistogramVec"));
        assert!(debug_str.contains("CounterVec"));
    }

    /// gather() 返回非空字符串(覆盖 TextEncoder 编码路径)。
    #[test]
    #[serial]
    fn gather_returns_non_empty_string() {
        let registry = prometheus::Registry::new();
        let metrics = AccountMetrics::register_to(&registry).expect("注册失败");
        metrics.observe_credential_verify("password", std::time::Duration::from_millis(10));
        let output = metrics.gather();
        assert!(!output.is_empty(), "gather() 应返回非空字符串");
    }

    /// Default trait 创建与 new() 等价的实例。
    #[test]
    #[serial]
    fn default_creates_instance() {
        let metrics = AccountMetrics::default();
        // 验证实例可用(observe 不 panic)
        metrics.observe_authflow_execute("test_flow", std::time::Duration::from_micros(100));
    }
}

/// 无 feature 时的编译验证测试。
#[cfg(all(test, not(feature = "metrics-prometheus")))]
mod tests_no_feature {
    use super::*;

    /// 未启用 metrics-prometheus 时 AccountMetrics 为 unit type 别名。
    #[test]
    fn no_feature_account_metrics_is_unit() {
        let _: AccountMetrics = ();
    }
}