clawspec-core 0.4.4

Core library for generating OpenAPI specifications from tests
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
//! Request body redaction support for OpenAPI documentation.
//!
//! This module provides functionality to redact sensitive values in JSON request bodies
//! before they are stored as examples in the OpenAPI specification. The key principle is:
//!
//! - **Original value for HTTP**: The actual serialized data is sent in the HTTP request
//! - **Redacted value for OpenAPI**: The redacted value is used for documentation examples
//!
//! This allows you to test with real data while keeping your OpenAPI examples clean,
//! stable, and free of sensitive information.
//!
//! # Path Syntax
//!
//! The path syntax is auto-detected based on the prefix:
//! - Paths starting with `$` use JSONPath (RFC 9535) - supports wildcards
//! - Paths starting with `/` use JSON Pointer (RFC 6901) - exact paths only
//!
//! # Example
//!
//! ```ignore
//! use clawspec_core::ApiClient;
//! use serde::Serialize;
//! use utoipa::ToSchema;
//!
//! #[derive(Clone, Serialize, ToSchema)]
//! struct CreateUser {
//!     username: String,
//!     password: String,
//!     api_key: String,
//! }
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let mut client = ApiClient::builder().build()?;
//!
//! let user = CreateUser {
//!     username: "alice".to_string(),
//!     password: "secret123".to_string(),
//!     api_key: "sk-live-abc123".to_string(),
//! };
//!
//! // The HTTP request will contain the real password and API key,
//! // but the OpenAPI example will show the redacted values.
//! client
//!     .post("/users")?
//!     .json_redacted(&user)?
//!     .redact("/password", "[REDACTED]")?
//!     .redact("/api_key", "[REDACTED]")?
//!     .await?;  // IntoFuture - no .finish() needed
//! # Ok(())
//! # }
//! ```

use std::future::{Future, IntoFuture};
use std::pin::Pin;

use utoipa::ToSchema;

use super::RedactOptions;
use super::apply::{apply_redaction, apply_remove};
use super::redactor::Redactor;
use crate::client::call::ApiCall;
use crate::client::error::ApiClientError;
use crate::client::{CallBody, CallResult};

/// Builder for redacting sensitive values in JSON request bodies.
///
/// This builder allows you to apply redactions to a JSON request body before
/// it's used in the OpenAPI documentation. The original (unredacted) value
/// is sent in the actual HTTP request.
///
/// # Key Principle
///
/// - **HTTP Request**: Uses the original value with real data for testing
/// - **OpenAPI Example**: Uses the redacted value with stable placeholders
///
/// This separation allows you to:
/// - Test with realistic data (passwords, tokens, API keys)
/// - Generate stable OpenAPI documentation (no dynamic values)
/// - Hide sensitive information from documentation
///
/// # Path Syntax
///
/// Paths are auto-detected based on their prefix:
/// - `/...` → JSON Pointer (RFC 6901) for exact paths
/// - `$...` → JSONPath (RFC 9535) for wildcards
///
/// # Example
///
/// ```ignore
/// use clawspec_core::ApiClient;
/// use serde::Serialize;
/// use utoipa::ToSchema;
///
/// #[derive(Clone, Serialize, ToSchema)]
/// struct LoginRequest {
///     email: String,
///     password: String,
/// }
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut client = ApiClient::builder().build()?;
///
/// let request = LoginRequest {
///     email: "user@example.com".to_string(),
///     password: "my-secret-password".to_string(),
/// };
///
/// client
///     .post("/auth/login")?
///     .json_redacted(&request)?
///     .redact("/password", "[REDACTED]")?
///     .await?;  // IntoFuture - no .finish() needed
/// # Ok(())
/// # }
/// ```
#[derive(derive_more::Debug)]
#[cfg_attr(docsrs, doc(cfg(feature = "redaction")))]
pub struct RequestBodyRedactionBuilder<T> {
    /// The original value (kept for reference, used in HTTP request via body.data)
    #[debug(skip)]
    value: T,
    /// The JSON representation for redaction operations
    redacted: serde_json::Value,
    /// The body being built (contains serialized data for HTTP)
    body: CallBody,
    /// The ApiCall to return when finished
    #[debug(skip)]
    api_call: ApiCall,
}

impl<T> RequestBodyRedactionBuilder<T> {
    /// Creates a new request body redaction builder.
    pub(crate) fn new(
        value: T,
        redacted: serde_json::Value,
        body: CallBody,
        api_call: ApiCall,
    ) -> Self {
        Self {
            value,
            redacted,
            body,
            api_call,
        }
    }

    /// Redacts values at the specified path using a redactor.
    ///
    /// The path can be either JSON Pointer (RFC 6901) or JSONPath (RFC 9535).
    /// The syntax is auto-detected based on the prefix:
    /// - `$...` → JSONPath (supports wildcards)
    /// - `/...` → JSON Pointer (exact path)
    ///
    /// The redactor can be:
    /// - A static value: `"replacement"` or `serde_json::json!(...)`
    /// - A closure: `|path, val| transform(path, val)`
    ///
    /// # Arguments
    ///
    /// * `path` - Path expression (e.g., `/password`, `$.users[*].token`)
    /// * `redactor` - The redactor to apply (static value or closure)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The path is invalid
    /// - The path matches no values
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use clawspec_core::ApiClient;
    /// # use serde::Serialize;
    /// # use utoipa::ToSchema;
    /// # #[derive(Clone, Serialize, ToSchema)]
    /// # struct Request { token: String }
    /// # async fn example(client: &mut ApiClient) -> Result<(), Box<dyn std::error::Error>> {
    /// // Static value
    /// client.post("/api")?
    ///     .json_redacted(&Request { token: "secret".into() })?
    ///     .redact("/token", "[REDACTED]")?
    ///     .await?;  // IntoFuture - no .finish() needed
    /// # Ok(())
    /// # }
    /// ```
    pub fn redact<R: Redactor>(self, path: &str, redactor: R) -> Result<Self, ApiClientError> {
        self.redact_with_options(path, redactor, RedactOptions::default())
    }

    /// Redacts values at the specified path with configurable options.
    ///
    /// This is like [`redact`](Self::redact) but allows customizing
    /// behavior through [`RedactOptions`].
    ///
    /// # Arguments
    ///
    /// * `path` - Path expression (e.g., `/password`, `$.users[*].token`)
    /// * `redactor` - The redactor to apply
    /// * `options` - Configuration options
    ///
    /// # Example
    ///
    /// ```ignore
    /// use clawspec_core::RedactOptions;
    ///
    /// // Allow empty matches for optional fields
    /// let options = RedactOptions { allow_empty_match: true };
    ///
    /// builder
    ///     .redact_with_options("$.optional_field", "value", options)?
    ///     .await?;  // IntoFuture - no .finish() needed
    /// ```
    pub fn redact_with_options<R: Redactor>(
        mut self,
        path: &str,
        redactor: R,
        options: RedactOptions,
    ) -> Result<Self, ApiClientError> {
        apply_redaction(&mut self.redacted, path, redactor, options)?;
        Ok(self)
    }

    /// Removes values at the specified path from the OpenAPI example.
    ///
    /// This completely removes the field from the OpenAPI documentation example,
    /// unlike setting it to `null`. The original value is still sent in the HTTP request.
    ///
    /// The path can be either JSON Pointer (RFC 6901) or JSONPath (RFC 9535).
    ///
    /// # Arguments
    ///
    /// * `path` - Path expression to remove
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The path is invalid
    /// - The path matches no values
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use clawspec_core::ApiClient;
    /// # use serde::Serialize;
    /// # use utoipa::ToSchema;
    /// # #[derive(Clone, Serialize, ToSchema)]
    /// # struct Request { password: String, internal_id: String }
    /// # async fn example(client: &mut ApiClient) -> Result<(), Box<dyn std::error::Error>> {
    /// client.post("/api")?
    ///     .json_redacted(&Request {
    ///         password: "secret".into(),
    ///         internal_id: "internal-123".into(),
    ///     })?
    ///     .redact("/password", "[REDACTED]")?
    ///     .redact_remove("/internal_id")?  // Remove entirely from docs
    ///     .await?;  // IntoFuture - no .finish() needed
    /// # Ok(())
    /// # }
    /// ```
    pub fn redact_remove(self, path: &str) -> Result<Self, ApiClientError> {
        self.redact_remove_with(path, RedactOptions::default())
    }

    /// Removes values at the specified path with configurable options.
    ///
    /// This is like [`redact_remove`](Self::redact_remove) but allows customizing
    /// behavior through [`RedactOptions`].
    ///
    /// # Arguments
    ///
    /// * `path` - Path expression to remove
    /// * `options` - Configuration options
    ///
    /// # Example
    ///
    /// ```ignore
    /// use clawspec_core::RedactOptions;
    ///
    /// // Allow empty matches for optional fields
    /// let options = RedactOptions { allow_empty_match: true };
    ///
    /// builder
    ///     .redact_remove_with("$.optional_field", options)?
    ///     .await?;  // IntoFuture - no .finish() needed
    /// ```
    pub fn redact_remove_with(
        mut self,
        path: &str,
        options: RedactOptions,
    ) -> Result<Self, ApiClientError> {
        apply_remove(&mut self.redacted, path, options)?;
        Ok(self)
    }

    /// Finalizes the redaction and returns the configured ApiCall.
    ///
    /// This consumes the builder and returns the `ApiCall` with the request body
    /// configured. The body will contain:
    /// - **HTTP data**: The original (unredacted) serialized value
    /// - **OpenAPI example**: The redacted value for documentation
    ///
    /// After calling `finish()`, you can `.await` the `ApiCall` to execute
    /// the HTTP request.
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use clawspec_core::ApiClient;
    /// # use serde::Serialize;
    /// # use utoipa::ToSchema;
    /// # #[derive(Clone, Serialize, ToSchema)]
    /// # struct Request { password: String }
    /// # async fn example(client: &mut ApiClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let response = client
    ///     .post("/api")?
    ///     .json_redacted(&Request { password: "secret".into() })?
    ///     .redact("/password", "[REDACTED]")?
    ///     .finish()?  // Returns ApiCall
    ///     .await?;    // Executes the HTTP request
    /// # Ok(())
    /// # }
    /// ```
    pub fn finish(mut self) -> Result<ApiCall, ApiClientError>
    where
        T: ToSchema + 'static,
    {
        // Set the redacted example on the body
        self.body.set_example(self.redacted);

        // Set the body on the ApiCall
        self.api_call.body = Some(self.body);

        Ok(self.api_call)
    }

    /// Returns a reference to the original (unredacted) value.
    ///
    /// This can be useful if you need to inspect the original value
    /// while building the redactions.
    pub fn original_value(&self) -> &T {
        &self.value
    }

    /// Returns a reference to the current redacted JSON value.
    ///
    /// This can be useful if you need to inspect the redacted state
    /// while building the redactions.
    pub fn redacted_value(&self) -> &serde_json::Value {
        &self.redacted
    }
}

/// Implements `IntoFuture` to allow direct `.await` on the builder.
///
/// This enables a more ergonomic API where you can write:
///
/// ```ignore
/// client
///     .post("/users")?
///     .json_redacted(&user)?
///     .redact("/password", "[REDACTED]")?
///     .await?;  // No need for .finish()?
/// ```
///
/// Instead of:
///
/// ```ignore
/// client
///     .post("/users")?
///     .json_redacted(&user)?
///     .redact("/password", "[REDACTED]")?
///     .finish()?
///     .await?;
/// ```
impl<T> IntoFuture for RequestBodyRedactionBuilder<T>
where
    T: ToSchema + 'static,
{
    type Output = Result<CallResult, ApiClientError>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        // Call finish() synchronously to avoid capturing self in the async block
        match self.finish() {
            Ok(api_call) => api_call.into_future(),
            Err(e) => Box::pin(async move { Err(e) }),
        }
    }
}

#[cfg(test)]
mod tests {
    use serde::{Deserialize, Serialize};
    use serde_json::json;
    use utoipa::ToSchema;

    use super::*;

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
    struct TestRequest {
        username: String,
        password: String,
        api_key: String,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
    struct NestedRequest {
        user: UserInfo,
        items: Vec<Item>,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
    struct UserInfo {
        id: String,
        token: String,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
    struct Item {
        id: String,
        secret: String,
    }

    /// Creates a minimal ApiCall for testing purposes.
    fn create_test_api_call() -> ApiCall {
        let client = reqwest::Client::new();
        let base_uri = "http://localhost:8080".parse().expect("valid URI");
        let collector_sender = crate::client::openapi::channel::CollectorSender::dummy();
        let path = crate::client::CallPath::from("/test");
        let query = crate::client::CallQuery::new();
        let expected_status_codes = crate::client::response::ExpectedStatusCodes::default();
        let metadata = crate::client::call_parameters::OperationMetadata::default();

        ApiCall {
            client,
            base_uri,
            collector_sender,
            method: http::Method::POST,
            path,
            query,
            headers: None,
            body: None,
            authentication: None,
            cookies: None,
            expected_status_codes,
            metadata,
            response_description: None,
            skip_collection: false,
            security: None,
        }
    }

    fn create_test_builder() -> RequestBodyRedactionBuilder<TestRequest> {
        let value = TestRequest {
            username: "alice".to_string(),
            password: "secret123".to_string(),
            api_key: "sk-live-abc123".to_string(),
        };

        let redacted = json!({
            "username": "alice",
            "password": "secret123",
            "api_key": "sk-live-abc123"
        });

        let body = CallBody::json_without_example(&value).expect("should create body");
        let api_call = create_test_api_call();

        RequestBodyRedactionBuilder::new(value, redacted, body, api_call)
    }

    fn create_nested_builder() -> RequestBodyRedactionBuilder<NestedRequest> {
        let value = NestedRequest {
            user: UserInfo {
                id: "user-123".to_string(),
                token: "token-abc".to_string(),
            },
            items: vec![
                Item {
                    id: "item-1".to_string(),
                    secret: "secret-1".to_string(),
                },
                Item {
                    id: "item-2".to_string(),
                    secret: "secret-2".to_string(),
                },
            ],
        };

        let redacted = serde_json::to_value(&value).expect("should serialize");
        let body = CallBody::json_without_example(&value).expect("should create body");
        let api_call = create_test_api_call();

        RequestBodyRedactionBuilder::new(value, redacted, body, api_call)
    }

    #[test]
    fn should_redact_single_field() {
        let builder = create_test_builder()
            .redact("/password", "[REDACTED]")
            .expect("redaction should succeed");

        assert_eq!(
            builder.redacted.get("password").and_then(|v| v.as_str()),
            Some("[REDACTED]")
        );
        assert_eq!(
            builder.redacted.get("username").and_then(|v| v.as_str()),
            Some("alice")
        );
        assert_eq!(
            builder.redacted.get("api_key").and_then(|v| v.as_str()),
            Some("sk-live-abc123")
        );
    }

    #[test]
    fn should_redact_multiple_fields() {
        let builder = create_test_builder()
            .redact("/password", "[REDACTED]")
            .and_then(|b| b.redact("/api_key", "[REDACTED]"))
            .expect("redaction should succeed");

        assert_eq!(
            builder.redacted.get("password").and_then(|v| v.as_str()),
            Some("[REDACTED]")
        );
        assert_eq!(
            builder.redacted.get("api_key").and_then(|v| v.as_str()),
            Some("[REDACTED]")
        );
        assert_eq!(
            builder.redacted.get("username").and_then(|v| v.as_str()),
            Some("alice")
        );
    }

    #[test]
    fn should_redact_with_jsonpath_wildcards() {
        let builder = create_nested_builder()
            .redact("$.items[*].secret", "[REDACTED]")
            .expect("redaction should succeed");

        let items = builder
            .redacted
            .get("items")
            .and_then(|v| v.as_array())
            .expect("should have items");

        for item in items {
            assert_eq!(
                item.get("secret").and_then(|v| v.as_str()),
                Some("[REDACTED]")
            );
        }
    }

    #[test]
    fn should_redact_with_closure() {
        let builder = create_test_builder()
            .redact("/password", |_path: &str, _val: &serde_json::Value| {
                json!("redacted-by-closure")
            })
            .expect("redaction should succeed");

        assert_eq!(
            builder.redacted.get("password").and_then(|v| v.as_str()),
            Some("redacted-by-closure")
        );
    }

    #[test]
    fn should_remove_fields() {
        let builder = create_test_builder()
            .redact_remove("/password")
            .expect("removal should succeed");

        assert!(builder.redacted.get("password").is_none());
        assert!(builder.redacted.get("username").is_some());
        assert!(builder.redacted.get("api_key").is_some());
    }

    #[test]
    fn should_preserve_original_value() {
        let builder = create_test_builder()
            .redact("/password", "[REDACTED]")
            .expect("redaction should succeed");

        assert_eq!(builder.original_value().password, "secret123");
        assert_eq!(
            builder.redacted.get("password").and_then(|v| v.as_str()),
            Some("[REDACTED]")
        );
    }

    #[test]
    fn should_fail_on_invalid_path() {
        let result = create_test_builder().redact("$.nonexistent", "[REDACTED]");

        assert!(result.is_err());
    }

    #[test]
    fn should_allow_empty_match_with_option() {
        let options = RedactOptions {
            allow_empty_match: true,
        };
        let result =
            create_test_builder().redact_with_options("$.nonexistent", "[REDACTED]", options);

        assert!(result.is_ok());
    }

    #[test]
    fn should_access_redacted_value() {
        let builder = create_test_builder();

        assert_eq!(
            builder
                .redacted_value()
                .get("password")
                .and_then(|v| v.as_str()),
            Some("secret123")
        );

        let builder = builder
            .redact("/password", "[REDACTED]")
            .expect("should redact");

        assert_eq!(
            builder
                .redacted_value()
                .get("password")
                .and_then(|v| v.as_str()),
            Some("[REDACTED]")
        );
    }

    #[test]
    fn should_finish_and_return_api_call() {
        let api_call = create_test_builder()
            .redact("/password", "[REDACTED]")
            .and_then(|b| b.finish())
            .expect("should finish");

        assert!(api_call.body.is_some());
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
    struct LoginRequest {
        username: String,
        password: String,
    }

    fn get_request_body_example(
        openapi: &utoipa::openapi::OpenApi,
        path: &str,
        method: &str,
    ) -> Option<serde_json::Value> {
        let path_item = openapi.paths.paths.get(path)?;
        let operation = match method.to_uppercase().as_str() {
            "POST" => path_item.post.as_ref(),
            "PUT" => path_item.put.as_ref(),
            "PATCH" => path_item.patch.as_ref(),
            "DELETE" => path_item.delete.as_ref(),
            "GET" => path_item.get.as_ref(),
            _ => None,
        }?;
        let request_body = operation.request_body.as_ref()?;
        let content = request_body.content.get("application/json")?;
        content.example.clone()
    }

    #[tokio::test]
    async fn should_send_original_value_to_server_and_use_redacted_in_openapi() {
        use wiremock::matchers::{body_json, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        use crate::client::ApiClient;

        // 1. Start mock server
        let mock_server = MockServer::start().await;

        // 2. Set up mock to capture and verify request body
        // The mock expects the ORIGINAL (unredacted) value
        Mock::given(method("POST"))
            .and(path("/api/login"))
            .and(body_json(json!({
                "username": "alice",
                "password": "secret123"
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"status": "ok"})))
            .expect(1)
            .mount(&mock_server)
            .await;

        // 3. Create ApiClient pointing to mock server
        let uri: http::Uri = mock_server.uri().parse().expect("valid URI");
        let mut client = ApiClient::builder()
            .with_host(uri.host().expect("should have host"))
            .with_port(uri.port_u16().expect("should have port"))
            .build()
            .expect("should build client");

        // 4. Make request with redaction
        let request = LoginRequest {
            username: "alice".to_string(),
            password: "secret123".to_string(),
        };

        client
            .post("/api/login")
            .expect("should create call")
            .json_redacted(&request)
            .expect("should set body")
            .redact("/password", "[REDACTED]")
            .expect("should redact")
            .await
            .expect("request should succeed")
            .as_empty()
            .await
            .expect("should complete");

        // 5. Verify mock received the original value (implicit via matcher)
        // wiremock will fail if body doesn't match

        // 6. Verify OpenAPI example contains redacted value
        let openapi = client.collected_openapi().await;
        let example = get_request_body_example(&openapi, "/api/login", "POST")
            .expect("should have request body example");

        assert_eq!(
            example.get("password").and_then(|v| v.as_str()),
            Some("[REDACTED]"),
            "OpenAPI example should have redacted password"
        );
        assert_eq!(
            example.get("username").and_then(|v| v.as_str()),
            Some("alice"),
            "OpenAPI example should have original username"
        );
    }
}