yang-base 0.6.0

个人使用构建后端服务器
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
//! Action 请求结构
//!
//! 提供 Action 系统的请求封装,包含请求体、请求头、查询参数和路径参数。

use std::any::Any;
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

fn parse_bearer_token(value: &str) -> Option<&str> {
    let mut parts = value.split_whitespace();
    let scheme = parts.next()?;
    let token = parts.next()?;

    if parts.next().is_some() || !scheme.eq_ignore_ascii_case("Bearer") {
        return None;
    }

    Some(token)
}

/// Action 请求
///
/// 封装 HTTP 请求信息,用于 Action 执行
///
/// # 字段
///
/// - `body`: 请求体(JSON 格式)
/// - `headers`: 请求头
/// - `query`: 查询参数
/// - `path_params`: 路径参数
///
/// # 示例
///
/// ```rust,ignore
/// use yang_base::action::Request;
/// use serde_json::json;
/// use std::collections::HashMap;
///
/// // 创建请求
/// let mut request = Request::new(json!({
///     "username": "alice",
///     "email": "alice@example.com"
/// }));
///
/// // 添加请求头
/// request = request.header("Content-Type", "application/json");
/// request = request.header("Authorization", "Bearer token123");
///
/// // 添加查询参数
/// request = request.query("page", "1");
/// request = request.query("limit", "10");
///
/// // 添加路径参数
/// request = request.path_param("id", "123");
///
/// // 提取 Token
/// if let Some(token) = request.token() {
///     println!("Token: {}", token);
/// }
/// ```
pub struct Request {
    /// 请求体(JSON)
    pub body: serde_json::Value,

    /// 请求头
    pub headers: HashMap<String, String>,

    /// 查询参数
    pub query: HashMap<String, String>,

    /// 路径参数
    pub path_params: HashMap<String, String>,

    /// 绑定请求生命周期的非业务资源;例如 multipart 临时目录。
    resource_guards: Vec<Arc<dyn Any + Send + Sync>>,
}

impl Clone for Request {
    fn clone(&self) -> Self {
        Self {
            body: self.body.clone(),
            headers: self.headers.clone(),
            query: self.query.clone(),
            path_params: self.path_params.clone(),
            // 请求作用域资源不得通过 Request::clone 逃逸 Handler 生命周期。
            resource_guards: Vec::new(),
        }
    }
}

impl Request {
    /// 创建新请求
    ///
    /// # 参数
    ///
    /// - `body`: 请求体(JSON 格式)
    ///
    /// # 返回
    ///
    /// - 新的 Request 实例
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({
    ///     "name": "Alice",
    ///     "age": 30
    /// }));
    /// ```
    pub fn new(body: serde_json::Value) -> Self {
        Self {
            body,
            headers: HashMap::new(),
            query: HashMap::new(),
            path_params: HashMap::new(),
            resource_guards: Vec::new(),
        }
    }

    /// 添加请求头
    ///
    /// # 参数
    ///
    /// - `name`: 请求头名称
    /// - `value`: 请求头值
    ///
    /// # 返回
    ///
    /// - 修改后的 Request 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({}))
    ///     .header("Content-Type", "application/json")
    ///     .header("Authorization", "Bearer token123");
    /// ```
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        let name = name.into();
        let name = name.trim();
        if name.is_empty() {
            return self;
        }

        self.headers.insert(name.to_ascii_lowercase(), value.into());
        self
    }

    /// 批量添加请求头
    ///
    /// # 参数
    ///
    /// - `headers`: 请求头映射
    ///
    /// # 返回
    ///
    /// - 修改后的 Request 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// let mut headers = HashMap::new();
    /// headers.insert("Content-Type".to_string(), "application/json".to_string());
    /// headers.insert("Authorization".to_string(), "Bearer token123".to_string());
    ///
    /// let request = Request::new(json!({}))
    ///     .headers(headers);
    /// ```
    pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
        for (name, value) in headers {
            self = self.header(name, value);
        }
        self
    }

    /// 添加查询参数
    ///
    /// # 参数
    ///
    /// - `key`: 参数名
    /// - `value`: 参数值
    ///
    /// # 返回
    ///
    /// - 修改后的 Request 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({}))
    ///     .query("page", "1")
    ///     .query("limit", "10");
    /// ```
    pub fn query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        let key = key.into();
        let key = key.trim();
        if key.is_empty() {
            return self;
        }

        self.query.insert(key.to_string(), value.into());
        self
    }

    /// 批量添加查询参数
    ///
    /// # 参数
    ///
    /// - `query`: 查询参数映射
    ///
    /// # 返回
    ///
    /// - 修改后的 Request 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// let mut query = HashMap::new();
    /// query.insert("page".to_string(), "1".to_string());
    /// query.insert("limit".to_string(), "10".to_string());
    ///
    /// let request = Request::new(json!({}))
    ///     .queries(query);
    /// ```
    pub fn queries(mut self, query: HashMap<String, String>) -> Self {
        for (key, value) in query {
            self = self.query(key, value);
        }
        self
    }

    /// 添加路径参数
    ///
    /// # 参数
    ///
    /// - `key`: 参数名
    /// - `value`: 参数值
    ///
    /// # 返回
    ///
    /// - 修改后的 Request 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({}))
    ///     .path_param("id", "123")
    ///     .path_param("action", "update");
    /// ```
    pub fn path_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        let key = key.into();
        let key = key.trim();
        if key.is_empty() {
            return self;
        }

        self.path_params.insert(key.to_string(), value.into());
        self
    }

    /// 批量添加路径参数
    ///
    /// # 参数
    ///
    /// - `path_params`: 路径参数映射
    ///
    /// # 返回
    ///
    /// - 修改后的 Request 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// let mut path_params = HashMap::new();
    /// path_params.insert("id".to_string(), "123".to_string());
    /// path_params.insert("action".to_string(), "update".to_string());
    ///
    /// let request = Request::new(json!({}))
    ///     .path_params(path_params);
    /// ```
    pub fn path_params(mut self, path_params: HashMap<String, String>) -> Self {
        for (key, value) in path_params {
            self = self.path_param(key, value);
        }
        self
    }

    #[cfg(feature = "transport-axum")]
    pub(crate) fn retain_resource<T>(mut self, resource: Arc<T>) -> Self
    where
        T: Any + Send + Sync,
    {
        self.resource_guards.push(resource);
        self
    }

    /// 从 Authorization 头提取 Token
    ///
    /// 支持 Bearer Token 格式:`Authorization: Bearer <token>`
    ///
    /// # 返回
    ///
    /// - `Some(&str)`: Token 字符串
    /// - `None`: 未找到 Token 或格式不正确
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({}))
    ///     .header("Authorization", "Bearer my_secret_token");
    ///
    /// assert_eq!(request.token(), Some("my_secret_token"));
    /// ```
    pub fn token(&self) -> Option<&str> {
        self.get_header("authorization")
            .and_then(parse_bearer_token)
    }

    /// 获取规范化 headers 中的 `User-Agent`。
    pub fn user_agent(&self) -> Option<&str> {
        self.get_header("user-agent")
    }

    /// 获取规范化 headers 中的 `Cookie`。
    pub fn cookie(&self) -> Option<&str> {
        self.get_header("cookie")
    }

    /// 获取请求头值
    ///
    /// # 参数
    ///
    /// - `name`: 请求头名称
    ///
    /// # 返回
    ///
    /// - `Some(&str)`: 请求头值
    /// - `None`: 请求头不存在
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({}))
    ///     .header("Content-Type", "application/json");
    ///
    /// assert_eq!(request.get_header("Content-Type"), Some("application/json"));
    /// ```
    pub fn get_header(&self, name: &str) -> Option<&str> {
        let name = name.trim();
        if name.is_empty() {
            return None;
        }

        self.headers
            .get(name)
            .or_else(|| {
                self.headers
                    .iter()
                    .find_map(|(key, value)| key.eq_ignore_ascii_case(name).then_some(value))
            })
            .map(|s| s.as_str())
    }

    /// 获取查询参数值
    ///
    /// # 参数
    ///
    /// - `key`: 参数名
    ///
    /// # 返回
    ///
    /// - `Some(&str)`: 参数值
    /// - `None`: 参数不存在
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({}))
    ///     .query("page", "1");
    ///
    /// assert_eq!(request.get_query("page"), Some("1"));
    /// ```
    pub fn get_query(&self, key: &str) -> Option<&str> {
        let key = key.trim();
        if key.is_empty() {
            return None;
        }

        self.query.get(key).map(|s| s.as_str())
    }

    /// 获取路径参数值
    ///
    /// # 参数
    ///
    /// - `key`: 参数名
    ///
    /// # 返回
    ///
    /// - `Some(&str)`: 参数值
    /// - `None`: 参数不存在
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::Request;
    /// use serde_json::json;
    ///
    /// let request = Request::new(json!({}))
    ///     .path_param("id", "123");
    ///
    /// assert_eq!(request.get_path_param("id"), Some("123"));
    /// ```
    pub fn get_path_param(&self, key: &str) -> Option<&str> {
        let key = key.trim();
        if key.is_empty() {
            return None;
        }

        self.path_params.get(key).map(|s| s.as_str())
    }
}

struct RedactedMap<'a>(&'a HashMap<String, String>);

impl fmt::Debug for RedactedMap<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut map = formatter.debug_map();
        for key in self.0.keys() {
            map.entry(key, &"[REDACTED]");
        }
        map.finish()
    }
}

/// `body` 的 Debug 安全摘要:只输出顶层类型 / 键名集合 / 长度,不输出任何值。
///
/// 纵深防御:登录密码、Refresh Token、验证码等凭据常以 JSON body 承载,
/// `tracing::debug!(?ctx)` 等日志不应把它们写进日志。该摘要只保护 `Debug`
/// 输出;显式读取 [`Request::body`] 的调用方(如审计快照)仍需自行脱敏。
struct RedactedBody<'a>(&'a serde_json::Value);

/// 不暴露值内容的类型/尺寸描述。
fn body_shape_summary(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::Null => "null".to_string(),
        serde_json::Value::Bool(_) => "bool".to_string(),
        serde_json::Value::Number(_) => "number".to_string(),
        serde_json::Value::String(value) => format!("string(len={})", value.len()),
        serde_json::Value::Array(values) => format!("array(len={})", values.len()),
        serde_json::Value::Object(map) => format!("object(keys={})", map.len()),
    }
}

impl fmt::Debug for RedactedBody<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            serde_json::Value::Object(map) => {
                let mut summary = formatter.debug_map();
                for (key, value) in map {
                    let shape = body_shape_summary(value);
                    summary.entry(key, &format!("[REDACTED:{shape}]"));
                }
                summary.finish()
            }
            value => write!(formatter, "[REDACTED:{}]", body_shape_summary(value)),
        }
    }
}

impl fmt::Debug for Request {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Request")
            .field("body", &RedactedBody(&self.body))
            .field("headers", &RedactedMap(&self.headers))
            .field("query", &RedactedMap(&self.query))
            .field("path_params", &RedactedMap(&self.path_params))
            .field("resource_guard_count", &self.resource_guards.len())
            .finish()
    }
}

impl Default for Request {
    fn default() -> Self {
        Self::new(serde_json::Value::Null)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    #[cfg(feature = "transport-axum")]
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[cfg(feature = "transport-axum")]
    struct DropResource(Arc<AtomicUsize>);

    #[cfg(feature = "transport-axum")]
    impl Drop for DropResource {
        fn drop(&mut self) {
            self.0.fetch_add(1, Ordering::SeqCst);
        }
    }

    #[test]
    fn test_header_lookup_is_case_insensitive() {
        let request = Request::new(json!({}))
            .header("Content-Type", "application/json")
            .header("aUtHoRiZaTiOn", "Bearer token123");

        assert_eq!(request.get_header("content-type"), Some("application/json"));
        assert_eq!(request.get_header("AUTHORIZATION"), Some("Bearer token123"));
        assert_eq!(request.token(), Some("token123"));
    }

    #[test]
    #[cfg(feature = "transport-axum")]
    fn clone_does_not_extend_request_scoped_resource_lifetime() {
        let drops = Arc::new(AtomicUsize::new(0));
        let resource = Arc::new(DropResource(Arc::clone(&drops)));
        let request = Request::new(json!({})).retain_resource(Arc::clone(&resource));
        drop(resource);
        let cloned = request.clone();

        drop(request);
        assert_eq!(drops.load(Ordering::SeqCst), 1);
        drop(cloned);
        assert_eq!(drops.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_header_insert_normalizes_name_and_overwrites_case_variants() {
        let request = Request::new(json!({}))
            .header("Authorization", "Bearer old")
            .header("authorization", "Bearer new");

        assert_eq!(request.headers.len(), 1);
        assert_eq!(
            request.headers.get("authorization").map(String::as_str),
            Some("Bearer new")
        );
        assert_eq!(request.get_header("Authorization"), Some("Bearer new"));
        assert_eq!(request.token(), Some("new"));
    }

    #[test]
    fn test_header_trims_name_before_normalizing() {
        let request = Request::new(json!({})).header(" Authorization ", "Bearer token123");

        assert_eq!(request.headers.len(), 1);
        assert_eq!(request.get_header("authorization"), Some("Bearer token123"));
        assert_eq!(
            request.get_header(" Authorization "),
            Some("Bearer token123")
        );
        assert_eq!(request.token(), Some("token123"));
    }

    #[test]
    fn test_header_rejects_blank_names() {
        let request = Request::new(json!({}))
            .header("", "empty")
            .header("   ", "blank")
            .header("X-Request-Id", "abc");

        assert_eq!(request.get_header("x-request-id"), Some("abc"));
        assert_eq!(request.get_header(""), None);
        assert_eq!(request.get_header("   "), None);
    }

    #[test]
    fn test_get_header_rejects_blank_names() {
        let mut request = Request::new(json!({}));
        request.headers.insert("".to_string(), "empty".to_string());
        request
            .headers
            .insert("   ".to_string(), "blank".to_string());
        request
            .headers
            .insert("x-request-id".to_string(), "abc".to_string());

        assert_eq!(request.get_header("x-request-id"), Some("abc"));
        assert_eq!(request.get_header(""), None);
        assert_eq!(request.get_header("   "), None);
    }

    #[test]
    fn test_token_accepts_case_insensitive_bearer_scheme() {
        let lower = Request::new(json!({})).header("authorization", "bearer lower-token");
        let upper = Request::new(json!({})).header("authorization", "BEARER upper-token");

        assert_eq!(lower.token(), Some("lower-token"));
        assert_eq!(upper.token(), Some("upper-token"));
    }

    #[test]
    fn test_token_trims_scheme_spacing_and_rejects_empty_or_split_token() {
        let padded = Request::new(json!({})).header("authorization", "Bearer    padded-token");
        let empty = Request::new(json!({})).header("authorization", "Bearer ");
        let split = Request::new(json!({})).header("authorization", "Bearer token extra");

        assert_eq!(padded.token(), Some("padded-token"));
        assert_eq!(empty.token(), None);
        assert_eq!(split.token(), None);
    }

    #[test]
    fn test_query_rejects_blank_keys() {
        let request = Request::new(json!({}))
            .query("", "empty")
            .query("   ", "blank")
            .query("page", "1");

        let mut query = std::collections::HashMap::new();
        query.insert("".to_string(), "empty-bulk".to_string());
        query.insert("   ".to_string(), "blank-bulk".to_string());
        query.insert("limit".to_string(), "10".to_string());

        let request = request.queries(query);

        assert_eq!(request.get_query("page"), Some("1"));
        assert_eq!(request.get_query("limit"), Some("10"));
        assert_eq!(request.get_query(""), None);
        assert_eq!(request.get_query("   "), None);
    }

    #[test]
    fn test_query_trims_keys_before_storing() {
        let request = Request::new(json!({})).query(" page ", "1");

        assert_eq!(request.query.len(), 1);
        assert_eq!(request.get_query("page"), Some("1"));
        assert_eq!(request.get_query(" page "), Some("1"));
    }

    #[test]
    fn test_get_query_rejects_blank_keys() {
        let mut request = Request::new(json!({}));
        request.query.insert("".to_string(), "empty".to_string());
        request.query.insert("   ".to_string(), "blank".to_string());
        request.query.insert("page".to_string(), "1".to_string());

        assert_eq!(request.get_query("page"), Some("1"));
        assert_eq!(request.get_query(""), None);
        assert_eq!(request.get_query("   "), None);
    }

    #[test]
    fn test_path_param_rejects_blank_keys() {
        let request = Request::new(json!({}))
            .path_param("", "empty")
            .path_param("   ", "blank")
            .path_param("id", "42");

        let mut path_params = std::collections::HashMap::new();
        path_params.insert("".to_string(), "empty-bulk".to_string());
        path_params.insert("   ".to_string(), "blank-bulk".to_string());
        path_params.insert("slug".to_string(), "demo".to_string());

        let request = request.path_params(path_params);

        assert_eq!(request.get_path_param("id"), Some("42"));
        assert_eq!(request.get_path_param("slug"), Some("demo"));
        assert_eq!(request.get_path_param(""), None);
        assert_eq!(request.get_path_param("   "), None);
    }

    #[test]
    fn test_path_param_trims_keys_before_storing() {
        let request = Request::new(json!({})).path_param(" id ", "42");

        assert_eq!(request.path_params.len(), 1);
        assert_eq!(request.get_path_param("id"), Some("42"));
        assert_eq!(request.get_path_param(" id "), Some("42"));
    }

    #[test]
    fn test_get_path_param_rejects_blank_keys() {
        let mut request = Request::new(json!({}));
        request
            .path_params
            .insert("".to_string(), "empty".to_string());
        request
            .path_params
            .insert("   ".to_string(), "blank".to_string());
        request
            .path_params
            .insert("id".to_string(), "42".to_string());

        assert_eq!(request.get_path_param("id"), Some("42"));
        assert_eq!(request.get_path_param(""), None);
        assert_eq!(request.get_path_param("   "), None);
    }

    #[test]
    fn debug_redacts_request_body_values() {
        // F030 RED 场景:旧 Debug 直接输出 `body`,登录密码、Refresh Token 等
        // 凭据会经 `format!("{request:?}")` / `tracing::debug!(?ctx)` 进入日志。
        let request = Request::new(json!({
            "username": "alice",
            "password": "body-password-secret",
            "refresh_token": "body-refresh-secret",
            "nested": { "code": "body-code-secret" },
            "items": ["body-list-secret"],
        }))
        .header("Authorization", "Bearer header-secret")
        .query("access_token", "query-secret")
        .path_param("session", "path-secret");

        let debug = format!("{request:?}");
        for secret in [
            "alice",
            "body-password-secret",
            "body-refresh-secret",
            "body-code-secret",
            "body-list-secret",
            "header-secret",
            "query-secret",
            "path-secret",
        ] {
            assert!(
                !debug.contains(secret),
                "Request Debug 泄露 {secret}: {debug}"
            );
        }
        // 键名与类型/长度摘要保留,维持排障可用性。
        assert!(debug.contains("password"), "应保留 body 键名: {debug}");
        assert!(debug.contains("string(len="), "应保留长度摘要: {debug}");
        assert!(debug.contains("object(keys=1)"), "应保留类型摘要: {debug}");
        assert!(debug.contains("[REDACTED]"), "{debug}");
    }
}