limiteron 0.3.0-rc.7

Unified flow control framework for 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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT
//! Admin API configuration

use ahash::AHashMap as HashMap;
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Admin API configuration validation error
///
/// 双轨:Display 英文规范串 + [`crate::i18n::LocalizedMsg`](键
/// `admin-config-*`,已英文错误对齐补键)。
#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("API key is required when admin API is enabled")]
    ApiKeyRequired,
    #[error("API key must be at least 16 characters, got {0}")]
    ApiKeyTooShort(usize),
}

impl crate::i18n::LocalizedMsg for ConfigError {
    fn message_key(&self) -> &'static str {
        match self {
            ConfigError::ApiKeyRequired => "admin-config-api-key-required",
            ConfigError::ApiKeyTooShort(_) => "admin-config-api-key-too-short",
        }
    }

    fn message_args(&self) -> Vec<(&'static str, String)> {
        match self {
            ConfigError::ApiKeyRequired => vec![],
            ConfigError::ApiKeyTooShort(length) => vec![("length", length.to_string())],
        }
    }
}

/// 管理面角色
///
/// - `Admin`:读写全部端点(封禁增删、配额修改、热更新等)
/// - `Viewer`:只读端点(status / circuit-breaker / 探针自省查询等)
///
/// 越权(角色不足以访问目标端点)返回 403,与凭证无效的 401 区分。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AdminRole {
    /// 管理员:全部端点
    Admin,
    /// 只读观察者:仅 GET/HEAD 端点
    Viewer,
}

impl AdminRole {
    /// 角色名(诊断/日志用)
    pub fn as_str(&self) -> &'static str {
        match self {
            AdminRole::Admin => "admin",
            AdminRole::Viewer => "viewer",
        }
    }

    /// 是否允许访问只读请求(GET/HEAD)
    pub fn allows_read(&self) -> bool {
        true
    }

    /// 是否允许访问写请求(POST/PUT/DELETE 等)
    pub fn allows_write(&self) -> bool {
        matches!(self, AdminRole::Admin)
    }
}

/// Admin API configuration
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AdminApiConfig {
    /// Listening host
    #[serde(default = "default_host")]
    pub host: String,
    /// Listening port
    #[serde(default = "default_port")]
    pub port: u16,
    /// API Key for authentication (required when enabled)
    pub api_key: String,
    /// Whether to enable the admin API
    #[serde(default = "default_enabled")]
    pub enabled: bool,
    /// API key → operator identity mapping (vuln-0001 修复)
    ///
    /// 当管理员通过不同 API key 鉴权时,绑定到对应的 operator 身份,
    /// 防止客户端在 JSON body 中伪造 `operator` 字段。mapping 为空时
    /// 回退到默认 `"admin-api"` 并记录 warn 日志(向后兼容)。
    #[serde(default)]
    pub api_key_operators: HashMap<String, String>,
    /// API key → 角色映射(RBAC)
    ///
    /// 配置后,鉴权中间件按 key 解析角色并执行端点级授权:
    /// viewer 访问写端点返回 403。**未在此映射中的合法 key**(含主
    /// `api_key`)默认 `Admin`,保持既有单 key 部署的行为逐位一致。
    #[serde(default)]
    pub api_key_roles: HashMap<String, AdminRole>,
    /// 按路径分组的速率限制配置 (vuln-0002 修复)
    ///
    /// key = 分组名("ban" / "quota" / "default"),value = (max_requests, window_secs)。
    /// middleware 在鉴权之前检查速率限制,超限返回 429 + Retry-After。
    /// 默认:ban=(100,60), quota=(50,60), default=(200,60)。
    #[serde(default = "default_rate_limits")]
    pub rate_limits: HashMap<String, (u64, u64)>,
}

// 手动实现 Debug 并脱敏 api_key(F5):派生的 Debug 会以明文打印
// `api_key`,误用 `println!("{config:?}")` 即泄露管理凭证
impl std::fmt::Debug for AdminApiConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AdminApiConfig")
            .field("host", &self.host)
            .field("port", &self.port)
            .field(
                "api_key",
                &format!("<redacted; {} chars>", self.api_key.len()),
            )
            .field("enabled", &self.enabled)
            .field("api_key_operators", &self.api_key_operators)
            .field("api_key_roles", &self.api_key_roles)
            .field("rate_limits", &self.rate_limits)
            .finish()
    }
}

/// 默认速率限制配置:ban=100/min, quota=50/min, default=200/min
fn default_rate_limits() -> HashMap<String, (u64, u64)> {
    let mut m = HashMap::new();
    m.insert("ban".to_string(), (100, 60));
    m.insert("quota".to_string(), (50, 60));
    m.insert("default".to_string(), (200, 60));
    m
}

fn default_host() -> String {
    "127.0.0.1".to_string()
}

fn default_port() -> u16 {
    9090
}

fn default_enabled() -> bool {
    false
}

impl Default for AdminApiConfig {
    fn default() -> Self {
        Self {
            host: default_host(),
            port: default_port(),
            api_key: String::new(),
            enabled: default_enabled(),
            api_key_operators: HashMap::new(),
            api_key_roles: HashMap::new(),
            rate_limits: default_rate_limits(),
        }
    }
}

impl AdminApiConfig {
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            host: default_host(),
            port: default_port(),
            api_key: api_key.into(),
            enabled: true,
            api_key_operators: HashMap::new(),
            api_key_roles: HashMap::new(),
            rate_limits: default_rate_limits(),
        }
    }

    pub fn with_host(mut self, host: impl Into<String>) -> Self {
        self.host = host.into();
        self
    }

    pub fn with_port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }

    pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
        self.api_key = api_key.into();
        self
    }

    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// 添加 API key → operator 映射(vuln-0001 修复)
    pub fn with_api_key_operator(
        mut self,
        api_key: impl Into<String>,
        operator: impl Into<String>,
    ) -> Self {
        self.api_key_operators
            .insert(api_key.into(), operator.into());
        self
    }

    /// 批量设置 API key → operator 映射
    pub fn with_api_key_operators(mut self, mapping: HashMap<String, String>) -> Self {
        self.api_key_operators = mapping;
        self
    }

    /// 添加 API key → 角色映射(RBAC)
    ///
    /// # 示例
    ///
    /// ```rust
    /// use limiteron::admin::{AdminApiConfig, AdminRole};
    ///
    /// let config = AdminApiConfig::new("primary-key-16chars!!!")
    ///     .with_api_key_role("viewer-key-16chars!!", AdminRole::Viewer);
    /// ```
    pub fn with_api_key_role(mut self, api_key: impl Into<String>, role: AdminRole) -> Self {
        self.api_key_roles.insert(api_key.into(), role);
        self
    }

    /// 解析 API key 的角色
    ///
    /// 未在映射中的 key 默认 `Admin`——保持既有单 key 部署(主 key 即
    /// 管理员)的行为不变。
    pub fn role_for_api_key(&self, api_key: &str) -> AdminRole {
        self.api_key_roles
            .get(api_key)
            .copied()
            .unwrap_or(AdminRole::Admin)
    }

    /// 判定 key 是否为合法凭证(多 key 支持)
    ///
    /// 主 `api_key` 恒合法;`api_key_roles` 中登记的 key 亦合法。
    pub fn is_valid_api_key(&self, api_key: &str) -> bool {
        api_key == self.api_key || self.api_key_roles.contains_key(api_key)
    }

    /// 查找 API key 对应的 operator 身份
    ///
    /// 返回 `Some(operator)` 表示配置中存在显式映射;
    /// 返回 `None` 表示未配置映射,调用方应回退到默认 `"admin-api"` 并记录 warn。
    pub fn operator_for_api_key(&self, api_key: &str) -> Option<&str> {
        self.api_key_operators.get(api_key).map(|s| s.as_str())
    }

    /// 设置指定分组的速率限制 (vuln-0002 修复)
    ///
    /// # 参数
    /// - `group`: 分组名("ban" / "quota" / "default")
    /// - `max`: 窗口内最大请求数
    /// - `window_secs`: 窗口时长(秒)
    pub fn with_rate_limit(mut self, group: &str, max: u64, window_secs: u64) -> Self {
        self.rate_limits
            .insert(group.to_string(), (max, window_secs));
        self
    }

    pub fn address(&self) -> String {
        format!("{}:{}", self.host, self.port)
    }

    pub fn validate(&self) -> Result<(), ConfigError> {
        if self.enabled && self.api_key.is_empty() {
            return Err(ConfigError::ApiKeyRequired);
        }
        if !self.api_key.is_empty() && self.api_key.len() < 16 {
            return Err(ConfigError::ApiKeyTooShort(self.api_key.len()));
        }
        Ok(())
    }
}

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

    #[test]
    fn test_default_values() {
        let config = AdminApiConfig::default();
        assert_eq!(config.host, "127.0.0.1");
        assert_eq!(config.port, 9090);
        assert!(config.api_key.is_empty());
        assert!(!config.enabled);
    }

    #[test]
    fn test_new_sets_api_key_and_enabled() {
        let config = AdminApiConfig::new("my-secure-api-key-32chars");
        assert_eq!(config.api_key, "my-secure-api-key-32chars");
        assert!(config.enabled);
        assert_eq!(config.host, "127.0.0.1");
        assert_eq!(config.port, 9090);
    }

    #[test]
    fn test_builder_methods() {
        let config = AdminApiConfig::new("initial-api-key-32chars!!")
            .with_host("0.0.0.0")
            .with_port(8080)
            .with_api_key("replacement-api-key-32ch")
            .with_enabled(false);
        assert_eq!(config.host, "0.0.0.0");
        assert_eq!(config.port, 8080);
        assert_eq!(config.api_key, "replacement-api-key-32ch");
        assert!(!config.enabled);
    }

    #[test]
    fn test_address_format() {
        let config = AdminApiConfig::new("my-secure-api-key-32chars")
            .with_host("192.168.1.1")
            .with_port(3000);
        assert_eq!(config.address(), "192.168.1.1:3000");
    }

    #[test]
    fn test_validate_enabled_empty_key_returns_api_key_required() {
        let config = AdminApiConfig {
            api_key: String::new(),
            enabled: true,
            ..Default::default()
        };
        match config.validate() {
            Err(ConfigError::ApiKeyRequired) => {}
            other => panic!("expected ApiKeyRequired, got {:?}", other),
        }
    }

    #[test]
    fn test_validate_short_key_returns_too_short_with_length() {
        let config = AdminApiConfig {
            api_key: "short".to_string(),
            enabled: true,
            ..Default::default()
        };
        match config.validate() {
            Err(ConfigError::ApiKeyTooShort(5)) => {}
            other => panic!("expected ApiKeyTooShort(5), got {:?}", other),
        }
    }

    #[test]
    fn test_validate_disabled_empty_key_ok() {
        let config = AdminApiConfig {
            api_key: String::new(),
            enabled: false,
            ..Default::default()
        };
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_validate_valid_config_ok() {
        let config = AdminApiConfig::new("this-is-a-valid-api-key-32ch");
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_error_display_messages() {
        assert_eq!(
            ConfigError::ApiKeyRequired.to_string(),
            "API key is required when admin API is enabled"
        );
        assert_eq!(
            ConfigError::ApiKeyTooShort(10).to_string(),
            "API key must be at least 16 characters, got 10"
        );
    }

    // ========================================================================
    // vuln-0001 修复测试:api_key_operators 映射
    // ========================================================================

    #[test]
    fn test_default_config_has_empty_api_key_operators() {
        let config = AdminApiConfig::default();
        assert!(config.api_key_operators.is_empty());
    }

    #[test]
    fn test_with_api_key_operator_adds_mapping() {
        let config = AdminApiConfig::new("my-secure-api-key-32chars")
            .with_api_key_operator("my-secure-api-key-32chars", "admin-alice");
        assert_eq!(
            config.operator_for_api_key("my-secure-api-key-32chars"),
            Some("admin-alice")
        );
    }

    #[test]
    fn test_with_api_key_operators_replaces_mapping() {
        let mut mapping = HashMap::new();
        mapping.insert("key-a-16chars-long".to_string(), "admin-a".to_string());
        mapping.insert("key-b-16chars-long".to_string(), "admin-b".to_string());
        let config = AdminApiConfig::new("primary-key-16chars!!!").with_api_key_operators(mapping);
        assert_eq!(
            config.operator_for_api_key("key-a-16chars-long"),
            Some("admin-a")
        );
        assert_eq!(
            config.operator_for_api_key("key-b-16chars-long"),
            Some("admin-b")
        );
        // primary key 未在 mapping 中 → None(回退到默认 "admin-api")
        assert_eq!(config.operator_for_api_key("primary-key-16chars!!!"), None);
    }

    #[test]
    fn test_operator_for_api_key_returns_none_when_not_configured() {
        let config = AdminApiConfig::new("my-secure-api-key-32chars");
        // 未配置 mapping → 任何 key 都返回 None
        assert_eq!(
            config.operator_for_api_key("my-secure-api-key-32chars"),
            None
        );
    }

    #[test]
    fn test_operator_for_api_key_returns_none_for_unknown_key() {
        let config = AdminApiConfig::new("my-secure-api-key-32chars")
            .with_api_key_operator("my-secure-api-key-32chars", "admin-alice");
        // 未在 mapping 中的 key → None
        assert_eq!(config.operator_for_api_key("unknown-key"), None);
    }
}

// ========================================================================
// RBAC 角色矩阵
// ========================================================================

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

    #[test]
    fn test_t605_role_for_api_key_defaults_to_admin() {
        let config = AdminApiConfig::new("primary-key-16chars!!!");
        assert_eq!(
            config.role_for_api_key("primary-key-16chars!!!"),
            AdminRole::Admin
        );
        assert_eq!(config.role_for_api_key("anything"), AdminRole::Admin);
    }

    #[test]
    fn test_t605_with_api_key_role_maps_viewer() {
        let config = AdminApiConfig::new("primary-key-16chars!!!")
            .with_api_key_role("viewer-key-16chars!!", AdminRole::Viewer);
        assert_eq!(
            config.role_for_api_key("viewer-key-16chars!!"),
            AdminRole::Viewer
        );
        assert_eq!(
            config.role_for_api_key("primary-key-16chars!!!"),
            AdminRole::Admin
        );
    }

    #[test]
    fn test_t605_is_valid_api_key_accepts_registered_keys() {
        let config = AdminApiConfig::new("primary-key-16chars!!!")
            .with_api_key_role("viewer-key-16chars!!", AdminRole::Viewer);
        assert!(config.is_valid_api_key("primary-key-16chars!!!"));
        assert!(config.is_valid_api_key("viewer-key-16chars!!"));
        assert!(!config.is_valid_api_key("rogue-key"));
    }

    #[test]
    fn test_t605_role_permissions_matrix() {
        // viewer:只读放行、写入拒绝
        assert!(AdminRole::Viewer.allows_read());
        assert!(!AdminRole::Viewer.allows_write());
        // admin:读写全部
        assert!(AdminRole::Admin.allows_read());
        assert!(AdminRole::Admin.allows_write());
    }

    #[test]
    fn test_t605_role_serde_lowercase() {
        assert_eq!(
            serde_json::to_string(&AdminRole::Viewer).unwrap(),
            "\"viewer\""
        );
        assert_eq!(
            serde_json::to_string(&AdminRole::Admin).unwrap(),
            "\"admin\""
        );
        let role: AdminRole = serde_json::from_str("\"viewer\"").unwrap();
        assert_eq!(role, AdminRole::Viewer);
    }
}