qubit-redact 0.9.0

Rule-driven redaction for fields, diagnostics, HTTP data, and Rust domain objects
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
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! HTTP adapter transaction contract tests.

#![cfg(feature = "http")]

use http::HeaderMap;
use http::HeaderValue;
use qubit_redact::RedactionCompletion;
use qubit_redact::RedactionPolicy;
use qubit_redact::RedactionReason;
use qubit_redact::Redactor;
use qubit_redact::formats::http::BodyCapture;

/// Verifies every HTTP aggregate operation appends to the parent transaction.
#[test]
fn test_http_aggregate_operations_share_the_parent_transaction_output() {
    let mut headers = HeaderMap::new();
    headers.insert("x-request-id", HeaderValue::from_static("request-42"));

    let output = Redactor::standard()
        .text_composer()
        .literal("http=")
        .http(|http| {
            let _ = http
                .url("https://example.test/path?token=raw")
                .headers(&headers)
                .body(BodyCapture::complete(br#"{"name":"Ada"}"#), None);
        })
        .finish();

    assert!(output.text().as_str().starts_with("http=https://example.test"));
    assert!(output.text().as_str().contains("x-request-id: [request-42]"));
    assert!(output.text().as_str().contains("{\"name\":\"Ada\"}"));
    assert_eq!(output.summary().usage().output_bytes(), output.text().as_str().len());
}

/// Verifies URL, header, and body handles are published only by `finish`.
#[test]
fn test_http_handle_operations_publish_from_the_parent_transaction() {
    let mut headers = HeaderMap::new();
    headers.insert("x-request-id", HeaderValue::from_static("request-42"));

    let mut batch = Redactor::standard().diagnostic_batch();
    let url = batch.redact_http_url("https://example.test/path?token=raw");
    let header = batch.redact_http_headers(&headers);
    let body = batch.redact_http_body(BodyCapture::complete(br#"{"name":"Ada"}"#), None);
    let output = batch.finish_with_marker("<redaction incomplete>");
    assert!(output.text(url).as_str().contains("example.test"));
    assert!(output.text(header).as_str().contains("x-request-id: [request-42]"));
    assert_eq!(output.text(body).as_str(), "{\"name\":\"Ada\"}");
}

/// Verifies direct HTTP handles and one-shot conveniences use the same
/// completed transaction path as the borrowed HTTP facade.
#[test]
fn test_http_direct_handle_and_redactor_convenience_operations() {
    let redactor = Redactor::strict();

    let url = redactor.redact_http_url("https://example.test/path?token=raw");
    assert!(url.text().as_str().contains("example.test"));
    assert!(!url.text().as_str().contains("token=raw"));

    let body = redactor.redact_http_body(BodyCapture::complete(br#"{"password":"raw"}"#), None);
    assert!(!body.text().as_str().contains("raw"));

    let mut batch = redactor.diagnostic_batch();
    let handle = batch.redact_http_url("https://example.test/path?token=raw");
    let output = batch.finish_with_marker("<redaction incomplete>");
    assert!(output.text(handle).as_str().contains("example.test"));

    let mut headers = HeaderMap::new();
    headers.insert("authorization", HeaderValue::from_static("Bearer raw-secret"));

    let headers_output = redactor.redact_http_headers(&headers);
    assert!(!headers_output.text().as_str().contains("raw-secret"));

    let mut batch = redactor.diagnostic_batch();
    let handle = batch.redact_http_headers(&headers);
    let output = batch.finish_with_marker("<redaction incomplete>");
    assert!(!output.text(handle).as_str().contains("raw-secret"));
    assert!(output.text(handle).as_str().contains("authorization"));
}

/// Empty input is not a valid absolute URL and must retain the parser's safe
/// invalid-URI provenance on the public one-shot path.
#[test]
fn test_http_empty_url_reports_safe_invalid_uri_result() {
    let output = Redactor::strict().redact_http_url("");

    assert!(output.summary().reasons().contains(RedactionReason::InvalidUri));
}

/// The composer path must retain invalid-URI provenance for an empty URL.
#[test]
fn test_http_composer_empty_url_reports_safe_invalid_uri_result() {
    let output = Redactor::strict()
        .text_composer()
        .http(|http| {
            http.url("");
        })
        .finish();

    assert!(output.summary().reasons().contains(RedactionReason::InvalidUri));
}

/// The batch path must retain invalid-URI provenance for an empty URL.
#[test]
fn test_http_batch_empty_url_reports_safe_invalid_uri_result() {
    let mut batch = Redactor::strict().diagnostic_batch();
    let handle = batch.redact_http_url("");
    let output = batch.finish_with_marker("<redaction incomplete>");

    assert!(output.summary().reasons().contains(RedactionReason::InvalidUri));
    assert_eq!(output.text(handle).as_str(), "<redacted: invalid URL>");
}

/// Verifies URL rendering receives only the output capacity still available
/// to its parent transaction rather than an independent unbounded ceiling.
#[test]
fn test_http_url_uses_the_session_remaining_output_budget() {
    let policy = RedactionPolicy::builder()
        .limits(|limits| {
            limits.max_output_bytes(32);
        })
        .expect("limit draft should build")
        .build()
        .expect("policy should build");
    let mut batch = Redactor::new(policy).diagnostic_batch();
    let handle =
        batch.redact_http_url("https://example.test/a-very-long-path?token=raw-secret-token&visible=long-value");
    let output = batch.finish_with_marker("<truncated>");

    assert!(output.text(handle).as_str().len() <= 32);
    assert_eq!(output.summary().completion(), RedactionCompletion::Truncated);
    assert!(output.summary().reasons().contains(RedactionReason::OutputLimitReached));
    assert!(output.summary().usage().output_bytes() <= 32);
}

/// Verifies URL, headers, and JSON body traversal all charge the enclosing
/// transaction's structural ledger.
#[test]
fn test_http_formats_share_the_transaction_structural_budget() {
    let policy = RedactionPolicy::builder()
        .limits(|limits| {
            limits.max_nodes(3).max_collection_items(1);
        })
        .expect("limit draft should build")
        .build()
        .expect("policy should build");
    let mut headers = HeaderMap::new();
    headers.insert("x-request-id", HeaderValue::from_static("request-42"));
    let output = Redactor::new(policy)
        .text_composer()
        .http(|http| {
            http.url("https://example.test/");
            http.headers(&headers);
            let _ = http.body(BodyCapture::complete(br#"{"password":"must-not-be-traversed"}"#), None);
        })
        .finish();

    assert!(output.text().as_str().contains("x-request-id"));
    assert!(!output.text().as_str().contains("must-not-be-traversed"));
    assert_eq!(output.summary().usage().visited_nodes(), 3);
    assert_eq!(output.summary().usage().visited_collection_items(), 1);
    assert_eq!(output.summary().completion(), RedactionCompletion::Truncated);
}

/// Verifies URL query-pair and embedded-URL traversal are admitted before the
/// HTTP renderer runs. A rejected nested URL must therefore publish only the
/// transaction fallback on both aggregate and handle paths.
#[test]
fn test_http_url_nested_traversal_uses_shared_structural_budget() {
    let policy = RedactionPolicy::builder()
        .limits(|limits| {
            limits.max_nodes(2);
        })
        .expect("limit draft should build")
        .build()
        .expect("policy should build");
    let nested = "https://outer.test/?next=https%3A%2F%2Finner.test%2F%3Ftoken%3Draw-secret";

    let aggregate = Redactor::new(policy.clone())
        .text_composer()
        .http(|http| {
            http.url(nested);
        })
        .finish();
    assert_eq!(aggregate.text().as_str(), "<truncated>");
    assert!(
        aggregate
            .summary()
            .reasons()
            .contains(RedactionReason::TraversalLimitReached)
    );
    assert!(!aggregate.text().as_str().contains("raw-secret"));

    let mut batch = Redactor::new(policy).diagnostic_batch();
    let handle = batch.redact_http_url(nested);
    let output = batch.finish_with_marker("<truncated>");
    assert_eq!(output.text(handle).as_str(), "<truncated>");
    assert_eq!(output.summary().completion(), RedactionCompletion::Truncated);
    assert!(!output.text(handle).as_str().contains("raw-secret"));
}

/// Verifies a URL query collection closes at the shared collection limit
/// before the renderer can inspect a later pair.
#[test]
fn test_http_url_query_collection_limit_stops_before_later_pair() {
    let policy = RedactionPolicy::builder()
        .limits(|limits| {
            limits.max_nodes(32).max_collection_items(1);
        })
        .expect("limit draft should build")
        .build()
        .expect("policy should build");
    let output = Redactor::new(policy)
        .text_composer()
        .http(|http| {
            http.url("https://example.test/?first=ok&later=raw-secret");
        })
        .finish();

    assert_eq!(output.text().as_str(), "<truncated>");
    assert_eq!(output.summary().usage().visited_collection_items(), 1);
    assert!(!output.text().as_str().contains("raw-secret"));
}

/// Verifies nested URL query traversal observes the transaction-wide depth
/// ceiling rather than only HTTP's fixed recursion ceiling.
#[test]
fn test_http_nested_url_uses_shared_depth_limit() {
    let policy = RedactionPolicy::builder()
        .limits(|limits| {
            limits.max_nodes(32).max_collection_items(32).max_depth(2);
        })
        .expect("limit draft should build")
        .build()
        .expect("policy should build");
    let output = Redactor::new(policy)
        .text_composer()
        .http(|http| {
            http.url("https://outer.test/?next=https%3A%2F%2Finner.test%2F%3Ftoken%3Draw-secret");
        })
        .finish();

    assert_eq!(output.text().as_str(), "<truncated>");
    assert!(output.summary().reasons().contains(RedactionReason::DepthLimitReached));
    assert!(!output.text().as_str().contains("raw-secret"));
}

/// Verifies text content types use the same session body transaction path as
/// native header values, including individually published body handles.
#[test]
fn test_http_text_content_type_body_operations_publish_safe_results() {
    let aggregate = Redactor::standard()
        .text_composer()
        .http(|http| {
            let _ = http.body_with_content_type_text(
                BodyCapture::complete(br#"{"password":"aggregate-secret"}"#),
                Some("application/json; charset=utf-8"),
            );
        })
        .finish();
    let mut batch = Redactor::standard().diagnostic_batch();
    let handle = batch.redact_http_body_with_content_type_text(
        BodyCapture::complete(br#"{"token":"handle-secret"}"#),
        Some("application/json"),
    );
    let output = batch.finish_with_marker("<redaction incomplete>");

    assert!(!aggregate.text().as_str().contains("aggregate-secret"));
    assert!(!output.text(handle).as_str().contains("handle-secret"));
    assert!(output.text(handle).as_str().contains("token"));
}

/// Invalid URL input must retain the HTTP parser provenance on a staged item
/// while replacing every untrusted source byte with the safe marker.
#[test]
fn test_http_invalid_url_handle_is_safe_and_keeps_reason() {
    let mut batch = Redactor::standard().diagnostic_batch();
    let handle = batch.redact_http_url("https://[not-an-ipv6");
    let output = batch.finish_with_marker("<redaction incomplete>");

    assert!(!output.text(handle).as_str().contains("not-an-ipv6"));
    assert!(output.summary().reasons().contains(RedactionReason::InvalidUri));
}

/// Headers are admitted as one structural collection. Once its shared
/// collection allowance rejects the list, the renderer must not see a later
/// confidential header and the handle reports structural truncation.
#[test]
fn test_http_header_handle_stops_before_later_header_at_collection_limit() {
    let policy = RedactionPolicy::builder()
        .limits(|limits| {
            limits.max_collection_items(1);
        })
        .expect("limit draft should build")
        .build()
        .expect("policy should build");
    let mut headers = HeaderMap::new();
    headers.insert("x-first", HeaderValue::from_static("visible"));
    headers.insert("authorization", HeaderValue::from_static("Bearer must-not-be-rendered"));
    let mut batch = Redactor::new(policy).diagnostic_batch();
    let handle = batch.redact_http_headers(&headers);
    let output = batch.finish_with_marker("");

    assert!(output.text(handle).as_str().is_empty());
    assert_eq!(output.summary().completion(), RedactionCompletion::Truncated);
    assert!(
        output
            .summary()
            .reasons()
            .contains(RedactionReason::TraversalLimitReached)
    );
    assert!(!output.text(handle).as_str().contains("must-not-be-rendered"));
}

/// JSON-looking bodies without an explicit content type still use the parent
/// structural ledger before HTTP body parsing can inspect a later field.
#[test]
fn test_http_inferred_json_body_uses_shared_structural_fallback() {
    let policy = RedactionPolicy::builder()
        .limits(|limits| {
            limits.max_nodes(1);
        })
        .expect("limit draft should build")
        .build()
        .expect("policy should build");
    let mut batch = Redactor::new(policy).diagnostic_batch();
    let handle = batch.redact_http_body(BodyCapture::complete(br#"{"password":"must-not-be-rendered"}"#), None);
    let output = batch.finish_with_marker("<truncated>");

    assert_eq!(output.text(handle).as_str(), "<truncated>");
    assert_eq!(output.summary().completion(), RedactionCompletion::Truncated);
    assert!(!output.text(handle).as_str().contains("must-not-be-rendered"));
}

/// URL-encoded form fields are one transaction-owned collection. A later
/// field must not reach the renderer after the shared collection limit closes.
#[test]
fn test_http_form_body_uses_shared_collection_budget() {
    let policy = RedactionPolicy::builder()
        .limits(|limits| {
            limits.max_nodes(32).max_collection_items(1);
        })
        .expect("limit draft should build")
        .build()
        .expect("policy should build");
    let content_type = HeaderValue::from_static("application/x-www-form-urlencoded");

    let output = Redactor::new(policy).redact_http_body(
        BodyCapture::complete(b"first=ok&password=must-not-be-rendered"),
        Some(&content_type),
    );

    assert_eq!(output.text().as_str(), "<truncated>");
    assert_eq!(output.summary().usage().visited_collection_items(), 1);
    assert!(
        output
            .summary()
            .reasons()
            .contains(RedactionReason::TraversalLimitReached)
    );
    assert!(!output.text().as_str().contains("must-not-be-rendered"));
}

/// Multipart parts and their nested JSON values remain in the enclosing
/// transaction's collection and depth ledgers.
#[test]
fn test_http_multipart_body_uses_shared_structural_budget() {
    let policy = RedactionPolicy::builder()
        .limits(|limits| {
            limits.max_nodes(32).max_collection_items(8).max_depth(2);
        })
        .expect("limit draft should build")
        .build()
        .expect("policy should build");
    let content_type = HeaderValue::from_static("multipart/form-data; boundary=boundary");
    let body = b"--boundary\r\nContent-Disposition: form-data; name=\"metadata\"\r\nContent-Type: application/json\r\n\r\n{\"password\":\"must-not-be-rendered\"}\r\n--boundary--\r\n";

    let output = Redactor::new(policy).redact_http_body(BodyCapture::complete(body), Some(&content_type));

    assert_eq!(output.text().as_str(), "<truncated>");
    assert_eq!(output.summary().usage().max_depth(), 2);
    assert!(output.summary().reasons().contains(RedactionReason::DepthLimitReached));
    assert!(!output.text().as_str().contains("must-not-be-rendered"));
}

/// Multipart part admission stops before a later part once the transaction's
/// shared collection allowance is consumed.
#[test]
fn test_http_multipart_parts_use_shared_collection_budget() {
    let policy = RedactionPolicy::builder()
        .limits(|limits| {
            limits.max_nodes(32).max_collection_items(1);
        })
        .expect("limit draft should build")
        .build()
        .expect("policy should build");
    let content_type = HeaderValue::from_static("multipart/form-data; boundary=boundary");
    let body = b"--boundary\r\nContent-Disposition: form-data; name=\"first\"\r\n\r\nok\r\n--boundary\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\nmust-not-be-rendered\r\n--boundary--\r\n";

    let output = Redactor::new(policy).redact_http_body(BodyCapture::complete(body), Some(&content_type));

    assert_eq!(output.text().as_str(), "<truncated>");
    assert_eq!(output.summary().usage().visited_collection_items(), 1);
    assert!(
        output
            .summary()
            .reasons()
            .contains(RedactionReason::TraversalLimitReached)
    );
    assert!(!output.text().as_str().contains("must-not-be-rendered"));
}

/// A source-truncated capture reports source provenance and known omitted
/// bytes without claiming that the transaction output limit was reached.
#[test]
fn test_http_known_source_truncation_has_truthful_summary_and_usage() {
    let capture = BodyCapture::truncated(b"visible", 12).expect("total length exceeds capture");
    let content_type = HeaderValue::from_static("text/plain");

    let output = Redactor::standard().redact_http_body(capture, Some(&content_type));

    assert_eq!(output.summary().completion(), RedactionCompletion::Truncated);
    assert!(output.summary().reasons().contains(RedactionReason::SourceTruncated));
    assert!(!output.summary().reasons().contains(RedactionReason::OutputLimitReached));
    assert_eq!(output.summary().usage().presented_input_bytes(), 22);
    assert_eq!(output.summary().usage().inspected_input_bytes(), 17);
    assert_eq!(output.summary().usage().omitted_input_bytes(), Some(5));
}

/// Unknown source length keeps omitted-byte accounting unknown while still
/// recording the captured prefix inspected by the HTTP adapter.
#[test]
fn test_http_unknown_source_truncation_keeps_omitted_usage_unknown() {
    let capture = BodyCapture::truncated_unknown(b"visible");

    let output = Redactor::standard().redact_http_body(capture, None);

    assert_eq!(output.summary().completion(), RedactionCompletion::Truncated);
    assert!(output.summary().reasons().contains(RedactionReason::SourceTruncated));
    assert!(!output.summary().reasons().contains(RedactionReason::OutputLimitReached));
    assert_eq!(output.summary().usage().presented_input_bytes(), 7);
    assert_eq!(output.summary().usage().inspected_input_bytes(), 7);
    assert_eq!(output.summary().usage().omitted_input_bytes(), None);
}

/// A URL handle created inside an aggregate HTTP namespace records the complete
/// input rejection before parser inspection.
#[test]
fn test_http_namespace_handle_tracks_its_own_input_rejection() {
    let policy = RedactionPolicy::builder()
        .limits(|limits| {
            limits.max_input_bytes(1);
        })
        .expect("limit draft should build")
        .build()
        .expect("policy should build");
    let mut batch = Redactor::new(policy).diagnostic_batch();
    let handle = batch.redact_http_url("https://example.test/");
    let output = batch.finish_with_marker("");

    assert_eq!(output.summary().completion(), RedactionCompletion::Truncated);
    assert!(output.summary().reasons().contains(RedactionReason::InputLimitReached));
    assert!(!output.summary().reasons().contains(RedactionReason::OutputLimitReached));
    assert_eq!(output.summary().usage().presented_input_bytes(), 21);
    assert_eq!(output.summary().usage().inspected_input_bytes(), 0);
    assert!(output.text(handle).as_str().is_empty());
}