zenith-web 0.1.0

Zenith Web 应用框架:编译期 Trie 路由、类型化 Extractor、中间件 DAG、静态文件服务、统一错误处理
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
//! 统一错误处理
//!
//! 提供 WebError 类型、错误响应格式化、panic 保护。

use zenith_api::CanonicalResponse;

use crate::server::ServerError;

/// Web 错误类型
///
/// 注:本类型不再派发 `Clone`——`Internal` 变体持有 `Box<dyn std::error::Error>`,
/// 泛型错误无法克隆;workspace 内亦无 `WebError` 的 `clone()` 调用点。
#[derive(Debug)]
pub enum WebError {
    /// 400 Bad Request
    BadRequest(String),
    /// 401 Unauthorized
    Unauthorized(String),
    /// 403 Forbidden
    Forbidden(String),
    /// 404 Not Found
    NotFound(String),
    /// 405 Method Not Allowed
    MethodNotAllowed(String),
    /// 409 Conflict
    Conflict(String),
    /// 422 Unprocessable Entity
    UnprocessableEntity(String),
    /// 429 Too Many Requests
    TooManyRequests(String),
    /// 500 Internal Server Error
    InternalError(String),
    /// 结构化内部错误(保留完整错误链,fail-closed 不向客户端泄露内部细节)
    Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
    /// 501 Not Implemented
    NotImplemented(String),
    /// 503 Service Unavailable
    ServiceUnavailable(String),
    /// 自定义错误(带状态码)
    Custom {
        /// HTTP 状态码
        status: u16,
        /// 错误消息
        message: String,
    },
}

impl WebError {
    /// 返回 HTTP 状态码
    pub fn status_code(&self) -> u16 {
        match self {
            WebError::BadRequest(_) => 400,
            WebError::Unauthorized(_) => 401,
            WebError::Forbidden(_) => 403,
            WebError::NotFound(_) => 404,
            WebError::MethodNotAllowed(_) => 405,
            WebError::Conflict(_) => 409,
            WebError::UnprocessableEntity(_) => 422,
            WebError::TooManyRequests(_) => 429,
            WebError::InternalError(_) => 500,
            WebError::Internal(_) => 500,
            WebError::NotImplemented(_) => 501,
            WebError::ServiceUnavailable(_) => 503,
            WebError::Custom { status, .. } => *status,
        }
    }

    /// 返回错误消息
    pub fn message(&self) -> &str {
        match self {
            WebError::BadRequest(msg) => msg,
            WebError::Unauthorized(msg) => msg,
            WebError::Forbidden(msg) => msg,
            WebError::NotFound(msg) => msg,
            WebError::MethodNotAllowed(msg) => msg,
            WebError::Conflict(msg) => msg,
            WebError::UnprocessableEntity(msg) => msg,
            WebError::TooManyRequests(msg) => msg,
            WebError::InternalError(msg) => msg,
            WebError::Internal(_) => "internal server error",
            WebError::NotImplemented(msg) => msg,
            WebError::ServiceUnavailable(msg) => msg,
            WebError::Custom { message, .. } => message,
        }
    }

    /// 转换为 CanonicalResponse
    pub fn into_response(self) -> CanonicalResponse {
        let status = self.status_code();
        let message = self.message().to_string();

        let mut response = CanonicalResponse::new(status);
        let _ = response
            .add_header(b"content-type", b"application/json");

        // JSON 转义 message:防止 message 中的 `"` / `\` / 控制字符
        // 破坏 JSON 结构或注入额外键值对(响应拆分/JSON 注入防护)
        let escaped = escape_json_string(&message);
        let body = format!(
            r#"{{"error":true,"status":{},"message":"{}"}}"#,
            status, escaped
        );
        response.set_body(body.into_bytes());
        response
    }
}

impl std::fmt::Display for WebError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Error {}: {}", self.status_code(), self.message())
    }
}

impl std::error::Error for WebError {}

impl From<WebError> for CanonicalResponse {
    fn from(err: WebError) -> Self {
        err.into_response()
    }
}

impl From<String> for WebError {
    fn from(msg: String) -> Self {
        WebError::InternalError(msg)
    }
}

impl From<&str> for WebError {
    fn from(msg: &str) -> Self {
        WebError::InternalError(msg.to_string())
    }
}

impl From<ServerError> for WebError {
    /// 将服务器全链路错误映射为 Web 错误,保留类型分类(ENG-007):
    /// 客户端可归因的协议/规范化错误 → 4xx;服务器内部错误 → 结构化 `Internal`。
    fn from(err: ServerError) -> Self {
        match err {
            ServerError::Normalize(e) => WebError::BadRequest(e.to_string()),
            ServerError::Http1(e) => WebError::BadRequest(e.to_string()),
            ServerError::Protocol(m) => WebError::BadRequest(m),
            ServerError::ConnectionClosed => {
                WebError::BadRequest("connection closed before complete request".to_string())
            }
            ServerError::Accept(e) => WebError::ServiceUnavailable(e.to_string()),
            ServerError::Timeout => {
                WebError::ServiceUnavailable("operation timed out".to_string())
            }
            // 服务器内部错误:保留结构化错误链(分类 + 日志),
            // 响应体不泄露内部细节(`message()` 返回通用文案)。
            other => WebError::Internal(Box::new(other)),
        }
    }
}

// ---------------------------------------------------------------------------
// RouterError 路由错误(fail-closed)
// ---------------------------------------------------------------------------

/// 路由操作错误类型(fail-closed:任何错误都拒绝请求)
#[derive(Debug, Clone)]
pub enum RouterError {
    /// 路由未找到(404)
    NotFound(String),
    /// 方法不允许(405)
    MethodNotAllowed(String),
    /// 路由冲突
    Conflict(String),
    /// 内部路由错误(500)
    Internal(String),
}

impl std::fmt::Display for RouterError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RouterError::NotFound(msg) => write!(f, "Route not found: {}", msg),
            RouterError::MethodNotAllowed(msg) => write!(f, "Method not allowed: {}", msg),
            RouterError::Conflict(msg) => write!(f, "Route conflict: {}", msg),
            RouterError::Internal(msg) => write!(f, "Router internal error: {}", msg),
        }
    }
}

impl std::error::Error for RouterError {}

impl From<RouterError> for WebError {
    fn from(err: RouterError) -> Self {
        match err {
            RouterError::NotFound(msg) => WebError::NotFound(msg),
            RouterError::MethodNotAllowed(msg) => WebError::MethodNotAllowed(msg),
            RouterError::Conflict(msg) => WebError::Conflict(msg),
            RouterError::Internal(msg) => WebError::InternalError(msg),
        }
    }
}

impl From<RouterError> for CanonicalResponse {
    fn from(err: RouterError) -> Self {
        WebError::from(err).into_response()
    }
}

// ---------------------------------------------------------------------------
// MiddlewareError 中间件错误(fail-closed)
// ---------------------------------------------------------------------------

/// 中间件操作错误类型(fail-closed:任何错误都拒绝请求)
#[derive(Debug, Clone)]
pub enum MiddlewareError {
    /// 中间件短路响应(正常流程,带响应)
    ShortCircuit(Box<CanonicalResponse>),
    /// 中间件内部错误(500)
    Internal(String),
    /// 认证失败(401)
    Unauthorized(String),
    /// 权限不足(403)
    Forbidden(String),
    /// 请求被拒绝(421 Misdirected Request)
    Misdirected(String),
}

impl std::fmt::Display for MiddlewareError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MiddlewareError::ShortCircuit(_) => write!(f, "Middleware short circuit"),
            MiddlewareError::Internal(msg) => write!(f, "Middleware internal error: {}", msg),
            MiddlewareError::Unauthorized(msg) => write!(f, "Unauthorized: {}", msg),
            MiddlewareError::Forbidden(msg) => write!(f, "Forbidden: {}", msg),
            MiddlewareError::Misdirected(msg) => write!(f, "Misdirected Request: {}", msg),
        }
    }
}

impl std::error::Error for MiddlewareError {}

impl From<MiddlewareError> for WebError {
    fn from(err: MiddlewareError) -> Self {
        match err {
            MiddlewareError::ShortCircuit(resp) => {
                let status = resp.status_code;
                let body = String::from_utf8_lossy(resp.body()).to_string();
                WebError::Custom { status, message: body }
            }
            MiddlewareError::Internal(msg) => WebError::InternalError(msg),
            MiddlewareError::Unauthorized(msg) => WebError::Unauthorized(msg),
            MiddlewareError::Forbidden(msg) => WebError::Forbidden(msg),
            MiddlewareError::Misdirected(msg) => WebError::Custom {
                status: 421,
                message: msg,
            },
        }
    }
}

impl From<MiddlewareError> for CanonicalResponse {
    fn from(err: MiddlewareError) -> Self {
        match err {
            MiddlewareError::ShortCircuit(resp) => *resp,
            other => WebError::from(other).into_response(),
        }
    }
}

// ---------------------------------------------------------------------------
// JSON 转义(防止 message 中的特殊字符破坏 JSON 结构 / 注入)
// ---------------------------------------------------------------------------

/// 转义 JSON 字符串内容(RFC 8259 §7)
///
/// 转义 `"` / `\` / 控制字符(`\n` `\r` `\t` 及其他 < 0x20 的控制字符为 `\uXXXX`)。
/// 防止用户可控的 message 字段破坏 JSON 响应结构或注入额外键值对。
pub(crate) fn escape_json_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => {
                out.push_str(&format!("\\u{:04x}", c as u32));
            }
            c => out.push(c),
        }
    }
    out
}

// ---------------------------------------------------------------------------
// Panic 保护
// ---------------------------------------------------------------------------

/// 捕获 panic 并转换为 500 响应
pub fn catch_panic<F>(f: F) -> CanonicalResponse
where
    F: FnOnce() -> CanonicalResponse,
{
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
    match result {
        Ok(response) => response,
        Err(_) => WebError::InternalError("Internal server error (panic recovered)".to_string())
            .into_response(),
    }
}

// ---------------------------------------------------------------------------
// 常用错误快捷构造
// ---------------------------------------------------------------------------

/// 400 Bad Request
pub fn bad_request(msg: impl Into<String>) -> WebError {
    WebError::BadRequest(msg.into())
}

/// 401 Unauthorized
pub fn unauthorized(msg: impl Into<String>) -> WebError {
    WebError::Unauthorized(msg.into())
}

/// 403 Forbidden
pub fn forbidden(msg: impl Into<String>) -> WebError {
    WebError::Forbidden(msg.into())
}

/// 404 Not Found
pub fn not_found(msg: impl Into<String>) -> WebError {
    WebError::NotFound(msg.into())
}

/// 405 Method Not Allowed
pub fn method_not_allowed(msg: impl Into<String>) -> WebError {
    WebError::MethodNotAllowed(msg.into())
}

/// 409 Conflict
pub fn conflict(msg: impl Into<String>) -> WebError {
    WebError::Conflict(msg.into())
}

/// 422 Unprocessable Entity
pub fn unprocessable(msg: impl Into<String>) -> WebError {
    WebError::UnprocessableEntity(msg.into())
}

/// 429 Too Many Requests
pub fn too_many_requests(msg: impl Into<String>) -> WebError {
    WebError::TooManyRequests(msg.into())
}

/// 500 Internal Server Error
pub fn internal_error(msg: impl Into<String>) -> WebError {
    WebError::InternalError(msg.into())
}

/// 501 Not Implemented
pub fn not_implemented(msg: impl Into<String>) -> WebError {
    WebError::NotImplemented(msg.into())
}

/// 503 Service Unavailable
pub fn service_unavailable(msg: impl Into<String>) -> WebError {
    WebError::ServiceUnavailable(msg.into())
}

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

    #[test]
    fn test_web_error_status_codes() {
        assert_eq!(WebError::BadRequest("err".into()).status_code(), 400);
        assert_eq!(WebError::Unauthorized("err".into()).status_code(), 401);
        assert_eq!(WebError::Forbidden("err".into()).status_code(), 403);
        assert_eq!(WebError::NotFound("err".into()).status_code(), 404);
        assert_eq!(WebError::MethodNotAllowed("err".into()).status_code(), 405);
        assert_eq!(WebError::Conflict("err".into()).status_code(), 409);
        assert_eq!(WebError::UnprocessableEntity("err".into()).status_code(), 422);
        assert_eq!(WebError::TooManyRequests("err".into()).status_code(), 429);
        assert_eq!(WebError::InternalError("err".into()).status_code(), 500);
        assert_eq!(WebError::NotImplemented("err".into()).status_code(), 501);
        assert_eq!(WebError::ServiceUnavailable("err".into()).status_code(), 503);
    }

    #[test]
    fn test_custom_error() {
        let err = WebError::Custom {
            status: 418,
            message: "I'm a teapot".to_string(),
        };
        assert_eq!(err.status_code(), 418);
        assert_eq!(err.message(), "I'm a teapot");
    }

    #[test]
    fn test_error_to_response() {
        let err = WebError::NotFound("User not found".to_string());
        let response = err.into_response();
        assert_eq!(response.status_code, 404);
        assert!(response.find_header("content-type").is_some());

        let body = response.body();
        let body_str = String::from_utf8_lossy(body);
        assert!(body_str.contains("User not found"));
        assert!(body_str.contains("404"));
    }

    #[test]
    fn test_error_display() {
        let err = WebError::BadRequest("Invalid input".to_string());
        let display = format!("{}", err);
        assert!(display.contains("400"));
        assert!(display.contains("Invalid input"));
    }

    #[test]
    fn test_error_conversion() {
        let response: CanonicalResponse = WebError::InternalError("oops".to_string()).into();
        assert_eq!(response.status_code, 500);

        let err: WebError = "simple error".into();
        assert_eq!(err.status_code(), 500);
    }

    #[test]
    fn test_panic_recovery() {
        let response = catch_panic(|| {
            panic!("test panic");
        });
        assert_eq!(response.status_code, 500);
        let body = response.body();
        let body_str = String::from_utf8_lossy(body);
        assert!(body_str.contains("panic recovered"));
    }

    #[test]
    fn test_panic_no_panic() {
        let response = catch_panic(|| CanonicalResponse::new(200));
        assert_eq!(response.status_code, 200);
    }

    #[test]
    fn test_helpers() {
        let _ = bad_request("test");
        let _ = unauthorized("test");
        let _ = forbidden("test");
        let _ = not_found("test");
        let _ = method_not_allowed("test");
        let _ = conflict("test");
        let _ = unprocessable("test");
        let _ = too_many_requests("test");
        let _ = internal_error("test");
        let _ = not_implemented("test");
        let _ = service_unavailable("test");
    }

    #[test]
    fn test_from_server_error_protocol_is_bad_request() {
        // 客户端可归因的协议错误 → 400
        let err: WebError = ServerError::Protocol("bad framing".into()).into();
        assert_eq!(err.status_code(), 400);
        assert_eq!(err.message(), "bad framing");
    }

    #[test]
    fn test_from_server_error_http2_is_internal() {
        // 服务器内部/连接级协议错误 → 结构化 Internal(500)
        let err: WebError = ServerError::Http2(
            zenith_http2::error::Http2Error::ProtocolError("conn reset".into()),
        )
        .into();
        assert_eq!(err.status_code(), 500);
        // 不泄露内部错误细节
        assert_eq!(err.message(), "internal server error");
    }

    #[test]
    fn test_from_server_error_timeout_is_service_unavailable() {
        let err: WebError = ServerError::Timeout.into();
        assert_eq!(err.status_code(), 503);
    }

    #[test]
    fn test_internal_variant_does_not_leak_details() {
        let err = WebError::Internal(Box::new(std::io::Error::new(
            std::io::ErrorKind::Other,
            "secret internal path",
        )));
        assert_eq!(err.status_code(), 500);
        assert_eq!(err.message(), "internal server error");
        let body = String::from_utf8_lossy(err.into_response().body()).to_string();
        assert!(!body.contains("secret"), "不应向客户端泄露内部错误细节");
    }
}