inklog 0.1.6

Enterprise-grade Rust logging infrastructure
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
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! # 错误类型模块
//!
//! 定义 Inklog 项目中使用的所有错误类型。
//!
//! ## 概述
//!
//! 使用 `thiserror` 派生实现的错误枚举,提供类型安全且用户友好的错误消息。
//!
//! ## 错误类型
//!
//! | 变体 | 描述 |
//! |------|------|
//! | `ConfigError` | 配置相关错误 |
//! | `IoError` | I/O 操作错误 |
//! | `SerializationError` | JSON/TOML 序列化错误 |
//! | `DatabaseError` | 数据库操作错误 |
//! | `EncryptionError` | 加密/解密错误 |
//! | `Shutdown` | 关闭过程中的错误 |
//! | `ChannelError` | 通道通信错误 |
//! | `CompressionError` | 压缩/解压错误 |
//! | `RuntimeError` | 运行时错误 |
//! | `HttpServerError` | HTTP 服务器错误 |
//! | `Unknown` | 未知错误 |
//!
//! ## 使用示例
//!
//! ```rust
//! use inklog::InklogError;
//!
//! fn example() -> Result<(), InklogError> {
//!     // 配置错误
//!     Err(InklogError::ConfigError("Invalid log level".to_string()))
//! }
//!
//! // 使用 ? 操作符传播错误
//! fn read_config() -> Result<(), InklogError> {
//!     let content = std::fs::read_to_string("config.toml")?;
//!     Ok(())
//! }
//! ```

use thiserror::Error;

/// Sensitive pattern redaction rules for error messages.
/// Each tuple contains (pattern, replacement).
const SENSITIVE_PATTERNS: &[(&str, &str)] = &[
    // AWS Access Key ID pattern (20 characters, starts with AKIA, ABIA, ACCA, ASIA)
    (
        "(?i)(AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}\\b",
        "[AWS_ACCESS_KEY_ID]",
    ),
    // AWS Secret Key pattern (40 characters, base64-like with word boundary)
    ("[0-9a-zA-Z+/]{40}={0,2}\\b", "[AWS_SECRET_ACCESS_KEY]"),
    // JWT Token pattern (with word boundaries)
    (
        "\\beyJ[a-zA-Z0-9_-]+\\.[a-zA-Z0-9_-]+\\.[a-zA-Z0-9_-]+\\b",
        "[JWT_TOKEN]",
    ),
    // Database connection strings (postgres, mysql, sqlite)
    ("(?i)(postgres|postgresql)://[^@]+:[^@]+@", "$1://***:***@"),
    ("(?i)mysql://[^@]+:[^@]+@", "mysql://***:***@"),
    ("(?i)sqlite://[^?]*\\?[^&]*", "sqlite://***"),
    // API keys (generic pattern)
    (
        "(?i)(api[_-]?key|access[_-]?key|secret[_-]?key)[\"']?\\s*[=:]\\s*[\"']?[a-zA-Z0-9_\\-]{20,}",
        "$1=***REDACTED***",
    ),
    // Bearer tokens
    (
        "(?i)(bearer|authorization)\\s*:\\s*[a-zA-Z0-9_\\-\\.]+",
        "$1: ***REDACTED***",
    ),
    // Sensitive paths
    ("/home/[a-zA-Z0-9_-]+/", "[USER_HOME_PATH]"),
    ("/etc/inklog/", "[CONFIG_PATH]"),
    ("/run/secrets/", "[SECRETS_PATH]"),
    // Passwords in URLs
    ("(?i)(password|passwd|pwd)=[^&\\s]+", "$1=***"),
    // Email addresses
    (
        "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}",
        "***@***.***",
    ),
    // Phone numbers (Chinese)
    ("\\b1[3-9]\\d{9}\\b", "***-****-****"),
    // Credit card numbers (basic pattern)
    (
        "\\b\\d{4}[ -]?\\d{4}[ -]?\\d{4}[ -]?\\d{4}\\b",
        "****-****-****-****",
    ),
];

/// Sanitizes a message by removing sensitive information.
/// Uses regex pattern matching to detect and redact common sensitive patterns.
fn sanitize_message(msg: &str) -> String {
    let mut result = msg.to_string();

    // 使用正则表达式进行更精确的匹配
    for (pattern, replacement) in SENSITIVE_PATTERNS {
        if let Ok(re) = regex::Regex::new(pattern) {
            result = re.replace_all(&result, *replacement).to_string();
        }
    }

    result
}

#[derive(Error, Debug)]
pub enum InklogError {
    #[error("Configuration error: {0}")]
    ConfigError(String),

    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),

    #[error("Serialization error: {0}")]
    SerializationError(#[from] serde_json::Error),

    #[error("Database error: {0}")]
    DatabaseError(String),

    #[error("Cache error: {0}")]
    CacheError(String),

    #[error("Encryption error: {0}")]
    EncryptionError(String),

    #[error("Shutdown error: {0}")]
    Shutdown(String),

    #[error("Channel error: {0}")]
    ChannelError(String),

    #[error("Compression error: {0}")]
    CompressionError(String),

    #[error("Runtime error: {0}")]
    RuntimeError(String),

    #[error("HTTP server error: {0}")]
    HttpServerError(String),

    #[error("Unknown error: {0}")]
    Unknown(String),
}

impl From<toml::de::Error> for InklogError {
    fn from(err: toml::de::Error) -> Self {
        InklogError::ConfigError(err.to_string())
    }
}

impl InklogError {
    /// Returns a sanitized error message that does not contain sensitive information.
    ///
    /// This method is useful for logging and displaying errors to users
    /// where sensitive data (like passwords, keys, paths) should not be exposed.
    ///
    /// # Example
    ///
    /// ```rust
    /// use inklog::InklogError;
    ///
    /// let error = InklogError::ConfigError(
    ///     "Failed to load AKIA1234567890EXAMPLE from /home/user/.aws/credentials".to_string()
    /// );
    /// let safe = error.safe_message();
    /// // Returns: "Configuration error: Failed to load [AWS_ACCESS_KEY_ID] from [USER_HOME_PATH]/.aws/credentials"
    /// ```
    pub fn safe_message(&self) -> String {
        match self {
            InklogError::ConfigError(msg) => {
                format!("Configuration error: {}", sanitize_message(msg))
            }
            InklogError::IoError(e) => {
                format!("IO error: {}", sanitize_message(&e.to_string()))
            }
            InklogError::SerializationError(e) => {
                format!("Serialization error: {}", sanitize_message(&e.to_string()))
            }
            InklogError::DatabaseError(msg) => {
                format!("Database error: {}", sanitize_message(msg))
            }
            InklogError::CacheError(msg) => {
                format!("Cache error: {}", sanitize_message(msg))
            }
            InklogError::EncryptionError(msg) => {
                format!("Encryption error: {}", sanitize_message(msg))
            }
            InklogError::Shutdown(msg) => {
                format!("Shutdown error: {}", sanitize_message(msg))
            }
            InklogError::ChannelError(msg) => {
                format!("Channel error: {}", sanitize_message(msg))
            }
            InklogError::CompressionError(msg) => {
                format!("Compression error: {}", sanitize_message(msg))
            }
            InklogError::RuntimeError(msg) => {
                format!("Runtime error: {}", sanitize_message(msg))
            }
            InklogError::HttpServerError(msg) => {
                format!("HTTP server error: {}", sanitize_message(msg))
            }
            InklogError::Unknown(msg) => {
                format!("Unknown error: {}", sanitize_message(msg))
            }
        }
    }
}

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

    #[test]
    fn test_safe_message_redacts_aws_keys() {
        let error = InklogError::ConfigError(
            "Failed to load AKIAIOSFODNN7EXAMPLE from credentials".to_string(),
        );
        let msg = error.safe_message();
        assert!(
            msg.contains("[AWS_ACCESS_KEY_ID]") || msg.contains("***"),
            "Message: {}",
            msg
        );
        assert!(!msg.contains("AKIAIOSFODNN7EXAMPLE"));
    }

    #[test]
    fn test_safe_message_redacts_jwt_tokens() {
        let error = InklogError::ConfigError(
            "prefix.eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.suffix".to_string(),
        );
        let msg = error.safe_message();
        assert!(
            msg.contains("[JWT_TOKEN]") || msg.contains("***"),
            "Message: {}",
            msg
        );
    }

    #[test]
    fn test_safe_message_redacts_database_urls() {
        let error = InklogError::ConfigError(
            "Connection failed: postgres://user:secret@localhost:5432/db".to_string(),
        );
        let msg = error.safe_message();
        assert!(
            msg.contains("***") || !msg.contains("secret"),
            "Message: {}",
            msg
        );
    }

    #[test]
    fn test_safe_message_redacts_user_paths() {
        let error = InklogError::ConfigError(
            "Config not found at /home/user/.config/inklog.yaml".to_string(),
        );
        let msg = error.safe_message();
        assert!(
            msg.contains("[USER_HOME_PATH]") || msg.contains("***"),
            "Message: {}",
            msg
        );
        assert!(!msg.contains("/home/user/"));
    }

    #[test]
    fn test_safe_message_redacts_bearer_tokens() {
        let error = InklogError::HttpServerError(
            "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0".to_string(),
        );
        let msg = error.safe_message();
        assert!(
            msg.contains("REDACTED") || msg.contains("***"),
            "Message: {}",
            msg
        );
    }

    #[test]
    fn test_safe_message_preserves_non_sensitive() {
        let error = InklogError::ConfigError("Configuration file not found".to_string());
        let msg = error.safe_message();
        assert!(msg.contains("Configuration file not found"));
    }

    #[test]
    fn test_safe_message_redacts_passwords() {
        let error =
            InklogError::ConfigError("Failed to connect: password=mysecretpassword".to_string());
        let msg = error.safe_message();
        assert!(
            !msg.contains("mysecretpassword") || msg.contains("***"),
            "Message: {}",
            msg
        );
    }

    #[test]
    fn test_safe_message_all_variants() {
        // 验证所有错误变体的 safe_message() 都返回正确前缀
        assert!(
            InklogError::ConfigError("x".into())
                .safe_message()
                .contains("Configuration error:")
        );
        assert!(
            InklogError::DatabaseError("x".into())
                .safe_message()
                .contains("Database error:")
        );
        assert!(
            InklogError::CacheError("x".into())
                .safe_message()
                .contains("Cache error:")
        );
        assert!(
            InklogError::EncryptionError("x".into())
                .safe_message()
                .contains("Encryption error:")
        );
        assert!(
            InklogError::Shutdown("x".into())
                .safe_message()
                .contains("Shutdown error:")
        );
        assert!(
            InklogError::ChannelError("x".into())
                .safe_message()
                .contains("Channel error:")
        );
        assert!(
            InklogError::CompressionError("x".into())
                .safe_message()
                .contains("Compression error:")
        );
        assert!(
            InklogError::RuntimeError("x".into())
                .safe_message()
                .contains("Runtime error:")
        );
        assert!(
            InklogError::Unknown("x".into())
                .safe_message()
                .contains("Unknown error:")
        );
    }

    #[test]
    fn test_safe_message_io_error() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
        let error = InklogError::IoError(io_err);
        let msg = error.safe_message();
        assert!(msg.contains("IO error:"));
        assert!(msg.contains("file missing"));
    }

    #[test]
    fn test_safe_message_serialization_error() {
        let json_err = serde_json::from_str::<String>("invalid").unwrap_err();
        let error = InklogError::SerializationError(json_err);
        let msg = error.safe_message();
        assert!(msg.contains("Serialization error:"));
    }

    #[test]
    fn test_from_io_error() {
        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
        let inklog_err: InklogError = io_err.into();
        assert!(matches!(inklog_err, InklogError::IoError(_)));
    }

    #[test]
    fn test_from_serde_json_error() {
        let json_err = serde_json::from_str::<i32>("not a number").unwrap_err();
        let inklog_err: InklogError = json_err.into();
        assert!(matches!(inklog_err, InklogError::SerializationError(_)));
    }

    #[test]
    fn test_from_toml_de_error() {
        let toml_err: toml::de::Error =
            toml::from_str::<toml::Value>("invalid = = toml").unwrap_err();
        let inklog_err: InklogError = toml_err.into();
        assert!(matches!(inklog_err, InklogError::ConfigError(_)));
    }

    #[test]
    fn test_safe_message_redacts_email() {
        let error = InklogError::ConfigError("Contact admin@example.com for help".to_string());
        let msg = error.safe_message();
        assert!(!msg.contains("admin@example.com"));
    }

    #[test]
    fn test_safe_message_redacts_phone() {
        let error = InklogError::ConfigError("Call 13812345678 for support".to_string());
        let msg = error.safe_message();
        assert!(!msg.contains("13812345678"));
    }

    #[test]
    fn test_safe_message_redacts_credit_card() {
        let error = InklogError::ConfigError("Card: 4111111111111111".to_string());
        let msg = error.safe_message();
        assert!(!msg.contains("4111111111111111"));
    }

    #[test]
    fn test_error_display_format() {
        // 验证 Display trait 实现
        assert_eq!(
            InklogError::ConfigError("test".into()).to_string(),
            "Configuration error: test"
        );
        assert_eq!(
            InklogError::ChannelError("closed".into()).to_string(),
            "Channel error: closed"
        );
    }
}

/// Convenience `Result` type alias using [`InklogError`] as the error type.
pub type InklogResult<T> = std::result::Result<T, InklogError>;