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
//! 跨协议端到端一致性集成测试
//!
//! 验证 HTTP/1.1、HTTP/2、HTTP/3 的**原始协议字节**经各自解析器 + 规范化引擎后,
//! 生成语义一致的 [`CanonicalRequest`]。
//!
//! # 与 zenith-api/tests/cross_protocol_consistency.rs 的区别
//! - 旧测试仅在 `normalize_request` 语义层比较三协议(已分解的 method/path/headers)。
//! - 本测试覆盖**真实运行时数据通路**:
//!   - HTTP/1.1:原始字节 → `Http1Parser::feed` → `HttpRequest` → `normalize_http1_request`
//!   - HTTP/2:`HpackEncoder` → HPACK 字节 → `HpackDecoder` → `HeaderField` → `normalize_http2_request`
//!   - HTTP/3:`QpackEncoder` → QPACK 字节 → `QpackDecoder` → `(Vec<u8>, Vec<u8>)` → `normalize_http3_request`
//!
//! # 安全意义
//! 此测试守护协议解析层与规范化层之间的语义偏移,防止
//! HPACK/QPACK 解码出的伪头部大小写、Header 合并差异等
//! 在运行时引入跨协议不一致。

use zenith_api::{CanonicalRequest, Method, Protocol, Transport};
use zenith_http1::{Http1Config, Http1Parser};
use zenith_http2::hpack::{HpackDecoder, HpackEncoder, HeaderField};
use zenith_http3::encoder::QpackEncoder;
use zenith_http3::qpack::QpackDecoder;
use zenith_web::{normalize_http1_request, normalize_http2_request, normalize_http3_request};

/// 比较两个 CanonicalRequest 的语义一致字段(method / path / regular headers)。
///
/// # 注意
/// - HTTP/1.1 的 `Host` 头被 `normalize_http1_request` 保留为普通 Header,
///   而 HTTP/2/3 的 `:authority` 伪头部被 `normalize_http2/3_request` 写入
///   `CanonicalRequest::authority` 字段。因此 authority 的比较是间接的:
///   HTTP/1.1 的 host header 值应等于 HTTP/2/3 的 authority_str()。
fn assert_semantically_equal(h1: &CanonicalRequest, h2: &CanonicalRequest, h3: &CanonicalRequest) {
    // 1. Method 一致
    assert_eq!(h1.method, h2.method, "method mismatch h1 vs h2");
    assert_eq!(h1.method, h3.method, "method mismatch h1 vs h3");

    // 2. Path 一致(含 query string,因为 :path 和 request-target 都包含 query)
    assert_eq!(h1.path_str(), h2.path_str(), "path mismatch h1 vs h2");
    assert_eq!(h1.path_str(), h3.path_str(), "path mismatch h1 vs h3");

    // 3. Protocol 字段正确标记
    assert_eq!(h1.protocol, Protocol::Http1);
    assert_eq!(h2.protocol, Protocol::Http2);
    assert_eq!(h3.protocol, Protocol::Http3);

    // 4. 非 Host 的 regular headers 一致
    //    HTTP/1.1 normalizer 将所有 headers(含 host)作为普通 header 存入。
    //    HTTP/2/3 normalizer 将 :authority 写入 authority 字段,不作为普通 header。
    //    因此比较时需跳过 host/authority。
    let skip_headers = |name: &str| name.eq_ignore_ascii_case("host");

    let count_regular = |c: &CanonicalRequest| {
        c.headers_iter()
            .iter()
            .filter(|h| !skip_headers(h.name_str()))
            .count()
    };
    assert_eq!(
        count_regular(h1),
        count_regular(h2),
        "regular header count mismatch h1 vs h2"
    );
    assert_eq!(
        count_regular(h1),
        count_regular(h3),
        "regular header count mismatch h1 vs h3"
    );

    // 逐个比较 regular headers 的值
    for hdr in h1.headers_iter().iter() {
        let name = hdr.name_str();
        if skip_headers(name) {
            continue;
        }
        // HTTP/2
        let h2_hdr = h2
            .find_header(name)
            .unwrap_or_else(|| panic!("header '{name}' missing in h2"));
        assert_eq!(
            hdr.value_str(),
            h2_hdr.value_str(),
            "header '{name}' value mismatch h1 vs h2"
        );
        // HTTP/3
        let h3_hdr = h3
            .find_header(name)
            .unwrap_or_else(|| panic!("header '{name}' missing in h3"));
        assert_eq!(
            hdr.value_str(),
            h3_hdr.value_str(),
            "header '{name}' value mismatch h1 vs h3"
        );
    }

    // 5. Authority 一致性(HTTP/1.1 Host header vs HTTP/2/3 :authority)
    let h1_host = h1
        .find_header("host")
        .map(|h| h.value_str().to_string())
        .unwrap_or_default();
    assert_eq!(
        h2.authority_str(),
        h1_host,
        "authority mismatch: h1 host={h1_host} h2 authority={}",
        h2.authority_str()
    );
    assert_eq!(
        h3.authority_str(),
        h1_host,
        "authority mismatch: h1 host={h1_host} h3 authority={}",
        h3.authority_str()
    );
}

/// 构造同语义请求的三个协议表示,经完整解析+规范化管线后比较。
///
/// 请求语义:
/// ```text
/// GET /api/v1/users?active=true HTTP/1.1
/// Host: example.com
/// Accept: application/json
/// User-Agent: Zenith/1.0
/// ```
fn build_canonical_requests(
    method: &str,
    path: &str,
    host: &str,
    regular_headers: &[(&str, &str)],
    scheme: &str,
) -> (CanonicalRequest, CanonicalRequest, CanonicalRequest) {
    // ─── HTTP/1.1:原始字节 → Http1Parser → normalize_http1_request ───
    let mut raw_h1 = Vec::new();
    raw_h1.extend_from_slice(method.as_bytes());
    raw_h1.extend_from_slice(b" ");
    raw_h1.extend_from_slice(path.as_bytes());
    raw_h1.extend_from_slice(b" HTTP/1.1\r\n");
    raw_h1.extend_from_slice(b"Host: ");
    raw_h1.extend_from_slice(host.as_bytes());
    raw_h1.extend_from_slice(b"\r\n");
    for (name, value) in regular_headers {
        raw_h1.extend_from_slice(name.as_bytes());
        raw_h1.extend_from_slice(b": ");
        raw_h1.extend_from_slice(value.as_bytes());
        raw_h1.extend_from_slice(b"\r\n");
    }
    raw_h1.extend_from_slice(b"\r\n");

    let mut parser = Http1Parser::new(Http1Config::default());
    let (http1_req, consumed) = parser
        .feed(&raw_h1)
        .expect("HTTP/1.1 parse must succeed");
    let http1_req = http1_req.expect("HTTP/1.1 request must be complete");
    assert_eq!(consumed, raw_h1.len(), "HTTP/1.1 parser must consume all bytes");

    let transport_h1 = if scheme == "https" {
        Transport::Tls13
    } else {
        Transport::Plaintext
    };
    let canonical_h1 = normalize_http1_request(&http1_req, transport_h1)
        .expect("HTTP/1.1 normalize must succeed");

    // ─── HTTP/2:HeaderField → HpackEncoder → HPACK 字节 → HpackDecoder → normalize_http2_request ───
    let mut h2_headers: Vec<HeaderField> = Vec::with_capacity(4 + regular_headers.len());
    h2_headers.push(HeaderField::new(":method", method));
    h2_headers.push(HeaderField::new(":path", path));
    h2_headers.push(HeaderField::new(":scheme", scheme));
    h2_headers.push(HeaderField::new(":authority", host));
    for (name, value) in regular_headers {
        h2_headers.push(HeaderField::new(*name, *value));
    }

    // max_table_size=0 禁用动态表,确保 encode/decode roundtrip 自包含
    let mut encoder_h2 = HpackEncoder::new(0);
    let hpack_bytes = encoder_h2
        .encode(&h2_headers)
        .expect("HPACK encode must succeed");

    let mut decoder_h2 = HpackDecoder::new(0);
    let decoded_h2 = decoder_h2
        .decode(&hpack_bytes)
        .expect("HPACK decode must succeed");

    // 验证 HPACK roundtrip 保真
    assert_eq!(
        decoded_h2.len(),
        h2_headers.len(),
        "HPACK roundtrip must preserve header count"
    );

    let canonical_h2 = normalize_http2_request(&decoded_h2, transport_h1)
        .expect("HTTP/2 normalize must succeed");

    // ─── HTTP/3:(Vec<u8>, Vec<u8>) → QpackEncoder → QPACK 字节 → QpackDecoder → normalize_http3_request ───
    let h3_headers: Vec<(Vec<u8>, Vec<u8>)> = {
        let mut v: Vec<(Vec<u8>, Vec<u8>)> = Vec::with_capacity(4 + regular_headers.len());
        v.push((b":method".to_vec(), method.as_bytes().to_vec()));
        v.push((b":path".to_vec(), path.as_bytes().to_vec()));
        v.push((b":scheme".to_vec(), scheme.as_bytes().to_vec()));
        v.push((b":authority".to_vec(), host.as_bytes().to_vec()));
        for (name, value) in regular_headers {
            v.push((name.as_bytes().to_vec(), value.as_bytes().to_vec()));
        }
        v
    };

    // max_capacity=0 + disable_auto_insert 确保仅用静态表+字面量,roundtrip 自包含
    let mut encoder_h3 = QpackEncoder::new(0).disable_auto_insert();
    let (qpack_bytes, _ric, _delta_base) = encoder_h3
        .encode_field_section(&h3_headers)
        .expect("QPACK encode must succeed");

    let decoder_h3 = QpackDecoder::new(0);
    let decoded_h3 = decoder_h3
        .decode_field_section(&qpack_bytes)
        .expect("QPACK decode must succeed");

    // 验证 QPACK roundtrip 保真
    assert_eq!(
        decoded_h3.len(),
        h3_headers.len(),
        "QPACK roundtrip must preserve header count"
    );

    let canonical_h3 = normalize_http3_request(&decoded_h3, transport_h1)
        .expect("HTTP/3 normalize must succeed");

    (canonical_h1, canonical_h2, canonical_h3)
}

// ===========================================================================
// 端到端一致性测试
// ===========================================================================

#[test]
fn test_e2e_simple_get_all_protocols_consistent() {
    let (h1, h2, h3) = build_canonical_requests(
        "GET",
        "/api/v1/users?active=true",
        "example.com",
        &[
            ("accept", "application/json"),
            ("user-agent", "Zenith/1.0"),
        ],
        "https",
    );

    assert_semantically_equal(&h1, &h2, &h3);

    // 验证关键字段:request target 中的 query 必须拆分到 query 字段,
    // 路由只匹配路径部分(`/api/v1/users?active=true` 整体进 path 会击穿路由)
    assert_eq!(h1.method, Method::Get);
    assert_eq!(h1.path_str(), "/api/v1/users");
    assert_eq!(h1.query_str(), "active=true");
}

#[test]
fn test_e2e_post_request_all_protocols_consistent() {
    let (h1, h2, h3) = build_canonical_requests(
        "POST",
        "/api/v1/orders",
        "api.example.com",
        &[
            ("content-type", "application/json"),
            ("accept", "application/json"),
        ],
        "https",
    );

    assert_semantically_equal(&h1, &h2, &h3);
    assert_eq!(h1.method, Method::Post);
}

#[test]
fn test_e2e_plaintext_http_scheme_consistent() {
    let (h1, h2, h3) = build_canonical_requests(
        "GET",
        "/search?q=hello+world",
        "example.com:80",
        &[("accept", "text/html")],
        "http",
    );

    assert_semantically_equal(&h1, &h2, &h3);
    assert_eq!(h1.transport, Transport::Plaintext);
    assert_eq!(h2.transport, Transport::Plaintext);
    assert_eq!(h3.transport, Transport::Plaintext);
}

#[test]
fn test_e2e_delete_request_all_protocols_consistent() {
    let (h1, h2, h3) = build_canonical_requests(
        "DELETE",
        "/api/v1/users/42",
        "example.com",
        &[("authorization", "Bearer token123")],
        "https",
    );

    assert_semantically_equal(&h1, &h2, &h3);
    assert_eq!(h1.method, Method::Delete);
}

#[test]
fn test_e2e_multiple_headers_preserved() {
    let (h1, h2, h3) = build_canonical_requests(
        "GET",
        "/",
        "example.com",
        &[
            ("accept", "text/html,application/xhtml+xml"),
            ("accept-encoding", "gzip, deflate, br"),
            ("accept-language", "en-US,en;q=0.9"),
            ("cache-control", "no-cache"),
            ("x-request-id", "abc-123-def-456"),
        ],
        "https",
    );

    assert_semantically_equal(&h1, &h2, &h3);

    // 验证所有 regular headers 都保留
    assert_eq!(h1.header_count(), 6); // 5 regular + 1 host
    assert_eq!(h2.header_count(), 5); // 5 regular (authority 在独立字段)
    assert_eq!(h3.header_count(), 5); // 5 regular
}

// ===========================================================================
// 协议合规性拒绝测试(验证 normalize 层的安全守护)
// ===========================================================================

#[test]
fn test_h2_forbidden_connection_header_rejected() {
    // HTTP/2 禁止 Connection 头部(RFC 7540 §8.1.2.2)
    let h2_headers = vec![
        HeaderField::new(":method", "GET"),
        HeaderField::new(":path", "/"),
        HeaderField::new(":scheme", "https"),
        HeaderField::new(":authority", "example.com"),
        HeaderField::new("connection", "keep-alive"),
    ];

    let result = normalize_http2_request(&h2_headers, Transport::Tls13);
    assert!(
        result.is_err(),
        "HTTP/2 must reject forbidden 'connection' header"
    );
}

#[test]
fn test_h3_transfer_encoding_rejected() {
    // HTTP/3 禁止 Transfer-Encoding 头部(RFC 9114 §4.3)
    let h3_headers: Vec<(Vec<u8>, Vec<u8>)> = vec![
        (b":method".to_vec(), b"GET".to_vec()),
        (b":path".to_vec(), b"/".to_vec()),
        (b":scheme".to_vec(), b"https".to_vec()),
        (b":authority".to_vec(), b"example.com".to_vec()),
        (b"transfer-encoding".to_vec(), b"chunked".to_vec()),
    ];

    let result = normalize_http3_request(&h3_headers, Transport::Tls13);
    assert!(
        result.is_err(),
        "HTTP/3 must reject forbidden 'transfer-encoding' header"
    );
}

#[test]
fn test_h2_pseudo_after_regular_rejected() {
    // HTTP/2 伪头部必须在普通头部之前(RFC 7540 §8.1.2.1)
    let h2_headers = vec![
        HeaderField::new("content-type", "text/plain"),
        HeaderField::new(":method", "GET"),
        HeaderField::new(":path", "/"),
        HeaderField::new(":scheme", "http"),
    ];

    let result = normalize_http2_request(&h2_headers, Transport::Plaintext);
    assert!(
        result.is_err(),
        "HTTP/2 must reject pseudo-header after regular header"
    );
}

#[test]
fn test_scheme_transport_mismatch_rejected() {
    // :scheme=https 但 transport=Plaintext 应被拒绝(防走私)
    let h2_headers = vec![
        HeaderField::new(":method", "GET"),
        HeaderField::new(":path", "/"),
        HeaderField::new(":scheme", "https"),
        HeaderField::new(":authority", "example.com"),
    ];

    let result = normalize_http2_request(&h2_headers, Transport::Plaintext);
    assert!(
        result.is_err(),
        "must reject scheme/transport mismatch (https over plaintext)"
    );
}

#[test]
fn test_hpack_roundtrip_preserves_header_values() {
    // 验证 HPACK encode → decode 保真(不只是 header count,还有值)
    let original = vec![
        HeaderField::new(":method", "POST"),
        HeaderField::new(":path", "/api/v1/data?key=value&sort=desc"),
        HeaderField::new(":scheme", "https"),
        HeaderField::new(":authority", "api.example.com:8443"),
        HeaderField::new("content-type", "application/json; charset=utf-8"),
        HeaderField::new("authorization", "Bearer eyJhbGciOiJIUzI1NiJ9.payload.sig"),
        HeaderField::new("x-custom-header", "值 with 中文 unicode"),
    ];

    let mut encoder = HpackEncoder::new(0);
    let encoded = encoder.encode(&original).expect("encode");

    let mut decoder = HpackDecoder::new(0);
    let decoded = decoder.decode(&encoded).expect("decode");

    assert_eq!(decoded.len(), original.len());
    for (i, (orig, dec)) in original.iter().zip(decoded.iter()).enumerate() {
        assert_eq!(
            orig.name, dec.name,
            "header name mismatch at index {i}"
        );
        assert_eq!(
            orig.value, dec.value,
            "header value mismatch at index {i} (name={})",
            orig.name
        );
    }
}

#[test]
fn test_qpack_roundtrip_preserves_header_values() {
    // 验证 QPACK encode → decode 保真
    let original: Vec<(Vec<u8>, Vec<u8>)> = vec![
        (b":method".to_vec(), b"PUT".to_vec()),
        (b":path".to_vec(), "/api/v2/resource/更新".as_bytes().to_vec()),
        (b":scheme".to_vec(), b"https".to_vec()),
        (b":authority".to_vec(), b"example.com".to_vec()),
        (b"content-type".to_vec(), b"application/json".to_vec()),
        (b"x-trace-id".to_vec(), b"550e8400-e29b-41d4-a716-446655440000".to_vec()),
    ];

    let mut encoder = QpackEncoder::new(0).disable_auto_insert();
    let (encoded, _ric, _delta) = encoder
        .encode_field_section(&original)
        .expect("encode");

    let decoder = QpackDecoder::new(0);
    let decoded = decoder
        .decode_field_section(&encoded)
        .expect("decode");

    assert_eq!(decoded.len(), original.len());
    for (i, (orig, dec)) in original.iter().zip(decoded.iter()).enumerate() {
        assert_eq!(
            orig.0, dec.0,
            "QPACK header name mismatch at index {i}"
        );
        assert_eq!(
            orig.1, dec.1,
            "QPACK header value mismatch at index {i}"
        );
    }
}