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

//! AuditLogBuilder — 用于构建 [`AuditLogEntry`] 的 builder 模式实现。
//!
//! 从 `audit_service.rs` 拆出(架构单文件混合 Service + Builder + Error
//! 三个独立 concern,违反单一职责原则)。本文件只包含 builder 本身,
//! Service / Error 仍保留在 `audit_service.rs` 中。

use crate::domain::auth::{ApiKeyScope, AuditDecision, AuditLogEntry};

/// Builder for creating audit log entries
#[derive(Clone, Debug)]
pub struct AuditLogBuilder {
    pub api_key_id: Option<crate::domain::id::Id>,
    pub team_id: Option<crate::domain::id::Id>,
    pub requested_action: String,
    pub decision: AuditDecision,
    pub denial_reason: Option<String>,
    pub scope_used: Option<ApiKeyScope>,
    pub ip_address: Option<std::net::IpAddr>,
    pub trace_id: Option<crate::domain::id::Id>,
    pub user_agent: Option<String>,
    pub request_path: Option<String>,
    pub request_method: Option<String>,
    pub metadata: serde_json::Value,
}

impl AuditLogBuilder {
    /// Create a new builder
    pub fn new(action: impl Into<String>, decision: AuditDecision) -> Self {
        Self {
            api_key_id: None,
            team_id: None,
            requested_action: action.into(),
            decision,
            denial_reason: None,
            scope_used: None,
            ip_address: None,
            trace_id: None,
            user_agent: None,
            request_path: None,
            request_method: None,
            metadata: serde_json::Value::Object(serde_json::Map::new()),
        }
    }

    /// Set API Key ID
    pub fn with_api_key_id(mut self, id: crate::domain::id::Id) -> Self {
        self.api_key_id = Some(id);
        self
    }

    /// Set team ID
    pub fn with_team_id(mut self, id: crate::domain::id::Id) -> Self {
        self.team_id = Some(id);
        self
    }

    /// Set denial reason
    pub fn with_denial_reason(mut self, reason: impl Into<String>) -> Self {
        self.denial_reason = Some(reason.into());
        self
    }

    /// Set scope used
    pub fn with_scope(mut self, scope: ApiKeyScope) -> Self {
        self.scope_used = Some(scope);
        self
    }

    /// Conditionally set API Key ID.
    ///
    /// 当 `id` 为 `None`(如未认证请求被拒绝)时保持字段为 `None`,
    /// 避免 `unwrap_or_default()` 写入 nil UUID (`00000000-...`)。
    /// nil UUID 与 NULL 在数据库中语义不同:
    /// - NULL 表示"未知/不适用"
    /// - nil UUID 会被 `find_by_api_key_id(nil_uuid)` 误匹配,混淆真实 API key 的审计日志
    pub fn maybe_with_api_key_id(mut self, id: Option<crate::domain::id::Id>) -> Self {
        // nil UUID 归一为 None:注释承诺的「不写 nil」由实现保证,而非调用方自觉
        self.api_key_id = id.filter(|id| !id.is_nil());
        self
    }

    /// Conditionally set team ID(语义同 `maybe_with_api_key_id`)。
    pub fn maybe_with_team_id(mut self, id: Option<crate::domain::id::Id>) -> Self {
        self.team_id = id.filter(|id| !id.is_nil());
        self
    }

    /// Conditionally set scope used(语义同 `maybe_with_api_key_id`)。
    pub fn maybe_with_scope(mut self, scope: Option<ApiKeyScope>) -> Self {
        self.scope_used = scope;
        self
    }

    /// Set IP address
    pub fn with_ip_address(mut self, ip: impl Into<std::net::IpAddr>) -> Self {
        self.ip_address = Some(ip.into());
        self
    }

    /// Set trace ID
    pub fn with_trace_id(mut self, id: crate::domain::id::Id) -> Self {
        self.trace_id = Some(id);
        self
    }

    /// Set user agent
    pub fn with_user_agent(mut self, ua: impl Into<String>) -> Self {
        self.user_agent = Some(ua.into());
        self
    }

    /// Set request path
    pub fn with_request_path(mut self, path: impl Into<String>) -> Self {
        self.request_path = Some(path.into());
        self
    }

    /// Set request method
    pub fn with_request_method(mut self, method: impl Into<String>) -> Self {
        self.request_method = Some(method.into());
        self
    }

    /// Add metadata
    pub fn with_metadata(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        if let serde_json::Value::Object(map) = &mut self.metadata {
            map.insert(key.into(), value);
        }
        self
    }

    /// Build the audit log entry
    pub fn build(self) -> AuditLogEntry {
        AuditLogEntry {
            id: crate::domain::id::Id::generate(),
            api_key_id: self.api_key_id,
            team_id: self.team_id,
            requested_action: self.requested_action,
            decision: self.decision,
            denial_reason: self.denial_reason,
            scope_used: self.scope_used,
            ip_address: self.ip_address,
            trace_id: self.trace_id,
            user_agent: self.user_agent,
            request_path: self.request_path,
            request_method: self.request_method,
            metadata: self.metadata,
            created_at: chrono::Utc::now(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::net::Ipv4Addr;

    #[test]
    fn test_audit_log_builder_new() {
        let builder = AuditLogBuilder::new("test_action", AuditDecision::Allow);
        assert_eq!(builder.requested_action, "test_action");
        assert_eq!(builder.decision, AuditDecision::Allow);
    }

    #[test]
    fn test_audit_log_builder_with_api_key_id() {
        let api_key_id = crate::domain::id::Id::generate();
        let builder =
            AuditLogBuilder::new("test_action", AuditDecision::Allow).with_api_key_id(api_key_id);
        assert_eq!(builder.api_key_id, Some(api_key_id));
    }

    #[test]
    fn test_audit_log_builder_with_team_id() {
        let team_id = crate::domain::id::Id::generate();
        let builder =
            AuditLogBuilder::new("test_action", AuditDecision::Allow).with_team_id(team_id);
        assert_eq!(builder.team_id, Some(team_id));
    }

    #[test]
    fn test_maybe_with_nil_ids_normalizes_to_none() {
        let nil = crate::domain::id::Id::nil();
        let builder = AuditLogBuilder::new("test_action", AuditDecision::Allow)
            .maybe_with_api_key_id(Some(nil))
            .maybe_with_team_id(Some(nil));
        assert_eq!(builder.api_key_id, None, "nil api key id must be dropped");
        assert_eq!(builder.team_id, None, "nil team id must be dropped");
    }

    #[test]
    fn test_maybe_with_non_nil_ids_keeps_values() {
        let api_key_id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let builder = AuditLogBuilder::new("test_action", AuditDecision::Allow)
            .maybe_with_api_key_id(Some(api_key_id))
            .maybe_with_team_id(Some(team_id));
        assert_eq!(builder.api_key_id, Some(api_key_id));
        assert_eq!(builder.team_id, Some(team_id));
    }

    #[test]
    fn test_audit_log_builder_with_denial_reason() {
        let builder = AuditLogBuilder::new("test_action", AuditDecision::Deny)
            .with_denial_reason("insufficient permissions");
        assert_eq!(
            builder.denial_reason,
            Some("insufficient permissions".to_string())
        );
    }

    #[test]
    fn test_audit_log_builder_with_ip_address() {
        let ip: std::net::IpAddr = Ipv4Addr::new(192, 168, 1, 1).into();
        let builder = AuditLogBuilder::new("test_action", AuditDecision::Allow).with_ip_address(ip);
        assert!(builder.ip_address.is_some());
    }

    #[test]
    fn test_audit_log_builder_with_trace_id() {
        let trace_id = crate::domain::id::Id::generate();
        let builder =
            AuditLogBuilder::new("test_action", AuditDecision::Allow).with_trace_id(trace_id);
        assert_eq!(builder.trace_id, Some(trace_id));
    }

    #[test]
    fn test_audit_log_builder_with_user_agent() {
        let builder = AuditLogBuilder::new("test_action", AuditDecision::Allow)
            .with_user_agent("Test Agent/1.0");
        assert_eq!(builder.user_agent, Some("Test Agent/1.0".to_string()));
    }

    #[test]
    fn test_audit_log_builder_with_request_path() {
        let builder = AuditLogBuilder::new("test_action", AuditDecision::Allow)
            .with_request_path("/api/v1/test");
        assert_eq!(builder.request_path, Some("/api/v1/test".to_string()));
    }

    #[test]
    fn test_audit_log_builder_with_request_method() {
        let builder =
            AuditLogBuilder::new("test_action", AuditDecision::Allow).with_request_method("POST");
        assert_eq!(builder.request_method, Some("POST".to_string()));
    }

    #[test]
    fn test_audit_log_builder_with_metadata() {
        let builder = AuditLogBuilder::new("test_action", AuditDecision::Allow)
            .with_metadata("key1", json!("value1"))
            .with_metadata("key2", json!(123));

        match &builder.metadata {
            serde_json::Value::Object(map) => {
                assert_eq!(map.get("key1"), Some(&json!("value1")));
                assert_eq!(map.get("key2"), Some(&json!(123)));
            }
            _ => panic!("Expected object metadata"),
        }
    }

    #[test]
    fn test_audit_log_builder_build_returns_entry() {
        let api_key_id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let trace_id = crate::domain::id::Id::generate();
        let ip: std::net::IpAddr = Ipv4Addr::new(10, 0, 0, 1).into();

        let entry = AuditLogBuilder::new("test_action", AuditDecision::Allow)
            .with_api_key_id(api_key_id)
            .with_team_id(team_id)
            .with_trace_id(trace_id)
            .with_ip_address(ip)
            .with_request_path("/api/test")
            .with_request_method("GET")
            .build();

        assert_eq!(entry.requested_action, "test_action");
        assert_eq!(entry.decision, AuditDecision::Allow);
        assert_eq!(entry.api_key_id, Some(api_key_id));
        assert_eq!(entry.team_id, Some(team_id));
        assert_eq!(entry.trace_id, Some(trace_id));
        assert_eq!(entry.request_path, Some("/api/test".to_string()));
        assert_eq!(entry.request_method, Some("GET".to_string()));
        assert!(entry.id != crate::domain::id::Id::nil());
        assert!(entry.created_at <= chrono::Utc::now());
    }

    #[test]
    fn test_audit_log_builder_with_scope() {
        let scope = ApiKeyScope::default();
        let builder =
            AuditLogBuilder::new("test_action", AuditDecision::Allow).with_scope(scope.clone());
        assert_eq!(builder.scope_used, Some(scope));
    }

    // maybe_with_* methods (preserve None semantics)

    #[test]
    fn test_maybe_with_api_key_id_none_preserves_none() {
        // None must stay None — writing NULL to DB, not nil UUID.
        let builder =
            AuditLogBuilder::new("anon.deny", AuditDecision::Deny).maybe_with_api_key_id(None);
        assert_eq!(builder.api_key_id, None);
    }

    #[test]
    fn test_maybe_with_api_key_id_some_sets_value() {
        let id = crate::domain::id::Id::generate();
        let builder = AuditLogBuilder::new("authed.deny", AuditDecision::Deny)
            .maybe_with_api_key_id(Some(id));
        assert_eq!(builder.api_key_id, Some(id));
    }

    #[test]
    fn test_maybe_with_team_id_none_preserves_none() {
        let builder =
            AuditLogBuilder::new("anon.deny", AuditDecision::Deny).maybe_with_team_id(None);
        assert_eq!(builder.team_id, None);
    }

    #[test]
    fn test_maybe_with_team_id_some_sets_value() {
        let id = crate::domain::id::Id::generate();
        let builder =
            AuditLogBuilder::new("team.deny", AuditDecision::Deny).maybe_with_team_id(Some(id));
        assert_eq!(builder.team_id, Some(id));
    }

    #[test]
    fn test_maybe_with_scope_none_preserves_none() {
        let builder = AuditLogBuilder::new("anon.deny", AuditDecision::Deny).maybe_with_scope(None);
        assert_eq!(builder.scope_used, None);
    }

    #[test]
    fn test_maybe_with_scope_some_sets_value() {
        let scope = ApiKeyScope::full_access();
        let builder = AuditLogBuilder::new("authed.deny", AuditDecision::Deny)
            .maybe_with_scope(Some(scope.clone()));
        assert_eq!(builder.scope_used, Some(scope));
    }

    #[test]
    fn test_maybe_with_methods_build_entry_with_none_fields() {
        // End-to-end: maybe_with_* None must produce an entry whose fields are None,
        // not nil UUID / default scope. This is the regression guard.
        let entry = AuditLogBuilder::new("anonymous.action", AuditDecision::Deny)
            .maybe_with_api_key_id(None)
            .maybe_with_team_id(None)
            .with_denial_reason("auth required")
            .maybe_with_scope(None)
            .build();

        assert_eq!(entry.decision, AuditDecision::Deny);
        assert_eq!(entry.api_key_id, None);
        assert_eq!(entry.team_id, None);
        assert_eq!(entry.scope_used, None);
        assert_eq!(entry.denial_reason.as_deref(), Some("auth required"));
        // ID must still be a fresh UUID, not nil
        assert_ne!(entry.id, crate::domain::id::Id::nil());
    }

    #[test]
    fn test_maybe_with_methods_build_entry_with_some_fields() {
        let api_key_id = crate::domain::id::Id::generate();
        let team_id = crate::domain::id::Id::generate();
        let scope = ApiKeyScope::read_only();

        let entry = AuditLogBuilder::new("authed.action", AuditDecision::Deny)
            .maybe_with_api_key_id(Some(api_key_id))
            .maybe_with_team_id(Some(team_id))
            .with_denial_reason("insufficient scope")
            .maybe_with_scope(Some(scope.clone()))
            .build();

        assert_eq!(entry.api_key_id, Some(api_key_id));
        assert_eq!(entry.team_id, Some(team_id));
        assert_eq!(entry.scope_used, Some(scope));
    }

    #[test]
    fn test_maybe_with_overrides_previous_with_value() {
        // maybe_with_* should override a prior with_* call (last-write-wins),
        // including clearing back to None.
        let id = crate::domain::id::Id::generate();
        let builder = AuditLogBuilder::new("action", AuditDecision::Allow)
            .with_api_key_id(id)
            .maybe_with_api_key_id(None);
        assert_eq!(builder.api_key_id, None);
    }

    #[test]
    fn test_audit_log_builder_build_includes_metadata_and_scope() {
        let scope = ApiKeyScope::full_access();
        let entry = AuditLogBuilder::new("delete_resource", AuditDecision::Deny)
            .with_denial_reason("no permission")
            .with_scope(scope.clone())
            .with_metadata("resource_id", json!("res-123"))
            .with_user_agent("AuditClient/2.0")
            .build();

        assert_eq!(entry.decision, AuditDecision::Deny);
        assert_eq!(entry.denial_reason.as_deref(), Some("no permission"));
        assert_eq!(entry.scope_used, Some(scope));
        assert_eq!(entry.user_agent.as_deref(), Some("AuditClient/2.0"));
        match &entry.metadata {
            serde_json::Value::Object(map) => {
                assert_eq!(map.get("resource_id"), Some(&json!("res-123")));
            }
            _ => panic!("Expected object metadata"),
        }
    }

    #[test]
    fn test_audit_log_builder_with_metadata_after_non_object_is_noop() {
        // Start with default (Object). Verify metadata insertion works.
        let builder = AuditLogBuilder::new("test_action", AuditDecision::Allow)
            .with_metadata("k1", json!("v1"));
        // The builder always starts with Object metadata, so insertion should succeed
        match &builder.metadata {
            serde_json::Value::Object(map) => {
                assert_eq!(map.get("k1"), Some(&json!("v1")));
            }
            _ => panic!("Expected object metadata"),
        }
    }
}