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
// =============================================================================
// Copyright (c) 2026 Haixing Hu.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Field scope for structured domain redaction.
use std::fmt::Debug;
use crate::Sensitivity;
use crate::domain::Redact;
use crate::domain::RedactLevelValue;
use crate::domain::RedactionWriter;
use crate::domain::internal::bounded_capture::bounded_debug;
use crate::domain::internal::resolve_keyed_field;
use crate::policy::ResolvedField;
/// Provides bounded redaction operations for named domain fields.
///
/// # Examples
///
/// ```
/// use qubit_redact::{Redact, RedactionWriter, Redactor, Sensitivity};
///
/// struct Credentials;
///
/// impl Redact for Credentials {
/// fn write_redacted(&self, writer: &mut RedactionWriter<'_>) {
/// writer.record("Credentials", |fields| {
/// fields.sensitive_at_least(Sensitivity::Secret, "token", || "raw-secret");
/// });
/// }
/// }
///
/// let output = Redactor::standard().redact_text(&Credentials);
/// assert!(!output.text().as_str().contains("raw-secret"));
/// ```
pub struct RedactionFields<'writer, 'session> {
/// Domain writer receiving field output.
pub(super) writer: &'writer mut RedactionWriter<'session>,
/// Whether field names are emitted before values.
pub(super) named: bool,
}
impl<'writer, 'session> RedactionFields<'writer, 'session> {
/// Writes a field that the implementer has explicitly classified as safe
/// to expose without redaction.
///
/// # Warning
///
/// This method is an explicit trust-boundary bypass: it does not consult
/// runtime field policy, even when that policy is strict, and it executes
/// `access`. Use it only for values independently reviewed as safe to
/// expose. Never pass credentials, user-controlled diagnostic data, or a
/// value whose classification depends on runtime policy. Every field
/// requiring redaction must use [`Self::sensitive_at_least`] or another
/// redaction-aware writer method instead.
pub fn unredacted<T, F>(&mut self, name: &str, access: F) -> &mut Self
where
T: Debug,
F: FnOnce() -> T,
{
if !self.admit_field(name) {
self.write_field_truncated();
return self;
}
self.write_admitted_unredacted(name, access)
}
/// Writes a field that has no explicit redaction mode.
///
/// # Warning
///
/// This is the derive-facing semantic alias for [`Self::unredacted`] and
/// carries the same trust-boundary requirements.
#[inline]
pub fn unmarked<T, F>(&mut self, name: &str, access: F) -> &mut Self
where
T: Debug,
F: FnOnce() -> T,
{
self.unredacted(name, access)
}
/// Writes a field with an explicit minimum sensitivity.
///
/// The effective sensitivity is the stronger of `level` and the active
/// policy's classification for `name`. A policy may therefore raise this
/// field's protection, but can never lower the implementer's explicit
/// minimum. When that effective level is [`Sensitivity::High`] or
/// [`Sensitivity::Secret`], `access` is not evaluated while redaction is
/// enabled.
///
/// This deliberate minimum-level composition lets an implementation mark
/// a field conservatively while still allowing a deployment policy to
/// raise protection for a shared name. The policy is consulted only for
/// that final effective level; it does not replace the explicit marker.
///
/// `access` must nevertheless be a valid lazy accessor for the actual
/// field value. In particular, callers must not replace it with a panic or
/// an unrelated sentinel merely because `level` is
/// [`Sensitivity::Secret`]: a disabled policy restores source values and
/// therefore evaluates the closure. Lower effective sensitivity levels
/// may also require the raw value to produce a partial mask.
///
/// # Parameters
///
/// * `level` - Minimum sensitivity enforced for the field.
/// * `name` - Diagnostic field name used for policy classification.
/// * `access` - Lazy accessor that returns the actual field value whenever
/// the selected policy needs it.
///
/// # Returns
///
/// This field writer for continued chained output.
///
/// # Panics
///
/// Propagates a panic from `access` when the selected policy evaluates the
/// closure, including when redaction is disabled.
pub fn sensitive_at_least<T, F>(&mut self, level: Sensitivity, name: &str, access: F) -> &mut Self
where
T: Debug,
F: FnOnce() -> T,
{
if !self.admit_field(name) {
self.write_field_truncated();
return self;
}
if self.writer.session.policy().is_disabled() {
return self.write_admitted_unredacted(name, access);
}
let effective_level = self
.writer
.session
.policy()
.sensitivity_for(name)
.map_or(level, |policy_level| policy_level.max(level));
if self.writer.session.is_inspection() {
self.writer.session.observe_sensitivity(effective_level);
return self;
}
self.write_prefix(name);
if !self.writer.can_write() {
return self;
}
if matches!(effective_level, Sensitivity::High | Sensitivity::Secret) {
let value = self
.writer
.session
.policy()
.masking()
.mask_opaque_bounded(effective_level, self.writer.remaining_output_bytes());
self.writer.write_debug(&value);
} else {
let raw_limit = self.writer.remaining_output_bytes();
let (raw, raw_truncated) = bounded_debug(&access(), raw_limit);
let (value, mask_truncated) = self.writer.session.policy().masking().mask_bounded_with_truncation(
effective_level,
&raw,
self.writer.remaining_output_bytes(),
);
self.writer.write_debug(value.as_ref());
if raw_truncated || mask_truncated {
self.writer.truncate_for_output_limit();
}
}
self.writer.write_fragment(", ");
self
}
/// Writes a sealed level-capable value while preserving its recursive
/// container shape and masking every scalar leaf independently.
///
/// The explicit `level` is final: field rules, floors, and strict unknown
/// handling do not raise or lower it. Disabled policy still restores
/// values. This is the sealed-value contract used by derive expansion:
/// callers choose the exact level for every scalar leaf, and policy rules
/// classify surrounding named fields without changing those leaf levels.
#[doc(hidden)]
pub fn sensitive_value_exact<T>(&mut self, level: Sensitivity, name: &str, value: &T) -> &mut Self
where
T: RedactLevelValue + ?Sized,
{
if !self.admit_field(name) {
self.write_field_truncated();
return self;
}
if self.writer.session.is_inspection() {
if !self.writer.session.policy().is_disabled() {
self.writer.session.observe_sensitivity(level);
}
return self;
}
self.write_prefix(name);
if self.writer.can_write() {
value.write_redacted_level(self.writer, level);
self.writer.write_fragment(", ");
}
self
}
/// Redacts JSON text for a named field through this shared transaction.
#[cfg(feature = "json")]
pub fn json(&mut self, name: &str, value: &str) -> &mut Self {
if !self.admit_field(name) {
self.write_field_truncated();
return self;
}
if self.writer.session.policy().is_disabled() {
return self.write_admitted_unredacted(name, || value);
}
self.write_prefix(name);
if !self.writer.can_write() {
return self;
}
self.writer.write_json_text(value);
self.writer.write_fragment(", ");
self
}
/// Writes a borrowed parsed JSON value without cloning or modifying it.
#[cfg(feature = "json")]
pub fn json_value(&mut self, name: &str, value: &serde_json::Value) -> &mut Self {
if !self.admit_field(name) {
self.write_field_truncated();
return self;
}
self.write_prefix(name);
if self.writer.can_write() {
self.writer.write_json_value(value);
self.writer.write_fragment(", ");
}
self
}
/// Writes a supported JSON string variant through its sealed capability.
#[cfg(feature = "json")]
#[doc(hidden)]
pub fn json_text_value<T>(&mut self, name: &str, value: &T) -> &mut Self
where
T: super::RedactJsonValue + ?Sized,
{
value.write_redacted_json(self, name);
self
}
/// Writes a nested domain value through the current session.
pub fn nested<T>(&mut self, name: &str, value: &T) -> &mut Self
where
T: Redact + ?Sized,
{
if !self.admit_field(name) {
self.write_field_truncated();
return self;
}
if self.writer.session.policy().is_disabled() {
self.write_prefix(name);
value.write_redacted(self.writer);
self.writer.write_fragment(", ");
return self;
}
self.write_prefix(name);
if !self.writer.can_write() {
return self;
}
value.write_redacted(self.writer);
self.writer.write_fragment(", ");
self
}
/// Writes admitted entries from a supported text-keyed map.
///
/// Each entry is admitted before the iterator advances. Sensitive keys use
/// the active runtime policy; keys not selected by that policy retain their
/// debug representation.
pub(crate) fn map_entries<I, K, V>(&mut self, name: &str, entries: I) -> &mut Self
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<str> + Debug,
V: RedactLevelValue + Debug,
{
if !self.admit_field(name) {
self.write_field_truncated();
return self;
}
if self.writer.session.policy().is_disabled() {
self.write_prefix(name);
if !self.writer.can_write() {
return self;
}
self.writer.write_fragment("{");
let mut entries = entries.into_iter();
while entries.size_hint().1 != Some(0) {
if !self.writer.can_write() || !self.writer.session.preflight_collection_item() {
self.write_field_truncated();
break;
}
let Some((key, value)) = entries.next() else {
break;
};
if !self.admit_item() {
self.write_field_truncated();
break;
}
if !self.writer.session.admit_domain_key(key.as_ref()) {
self.write_field_truncated();
break;
}
self.writer.write_debug(key.as_ref());
self.writer.write_fragment(": ");
if !self.writer.can_write() {
break;
}
self.writer.write_debug(&value);
if entries.size_hint().1 != Some(0) {
self.writer.write_fragment(", ");
}
}
self.writer.write_fragment("}");
return self;
}
self.write_prefix(name);
if !self.writer.can_write() {
return self;
}
self.writer.write_fragment("{");
let mut entries = entries.into_iter();
loop {
if entries.size_hint().1 == Some(0) {
break;
}
if !self.writer.can_write() || !self.writer.session.preflight_collection_item() {
self.write_field_truncated();
break;
}
let Some((key, value)) = entries.next() else {
break;
};
if !self.admit_item() {
self.write_field_truncated();
break;
}
let key = key.as_ref();
if !self.writer.session.admit_domain_key(key) {
self.write_field_truncated();
break;
}
if self.writer.session.is_inspection() {
if let ResolvedField::Sensitive { sensitivity } = self.writer.session.policy().resolve_field(key) {
self.writer.session.observe_sensitivity(sensitivity);
}
continue;
}
self.writer.write_debug(key);
self.writer.write_fragment(": ");
match self.writer.session.policy().resolve_field(key) {
ResolvedField::Sensitive { sensitivity } => {
value.write_redacted_level(self.writer, sensitivity);
}
ResolvedField::PassThrough => self.writer.write_debug(&value),
}
self.writer.write_fragment(", ");
if !self.writer.can_write() {
break;
}
}
if self.writer.can_write() {
self.writer.trim_trailing_separator();
self.writer.write_fragment("}");
self.writer.write_fragment(", ");
}
self
}
/// Writes map keys at a fixed level and leaves values unmarked.
pub(crate) fn map_key_level_entries<'value, I, K, V>(
&mut self,
name: &str,
entries: I,
key_level: Sensitivity,
value_level: Option<Sensitivity>,
) -> &mut Self
where
I: IntoIterator<Item = (&'value K, &'value V)>,
K: super::RedactLevelValue + 'value,
V: super::RedactLevelValue + Debug + 'value,
{
if !self.admit_field(name) {
self.write_field_truncated();
return self;
}
self.write_prefix(name);
self.writer.map(|output| {
output.for_each(entries, |output, (key, value)| {
output.key_level_entry(key, value, key_level, value_level);
});
});
self.writer.write_fragment(", ");
self
}
/// Writes a supported map with an explicit key sensitivity.
#[doc(hidden)]
pub fn map_level_values<T>(
&mut self,
name: &str,
value: &T,
key_level: Sensitivity,
value_level: Option<Sensitivity>,
) -> &mut Self
where
T: super::RedactMapKeyValue + ?Sized,
{
value.write_redacted_map_levels(self, name, key_level, value_level);
self
}
/// Writes a supported map field through its sealed capability.
pub fn map<T>(&mut self, name: &str, value: &T) -> &mut Self
where
T: super::RedactMapValue,
{
value.write_redacted_map(self, name);
self
}
/// Writes a supported map field through its sealed capability.
#[doc(hidden)]
pub fn map_value<T>(&mut self, name: &str, value: &T) -> &mut Self
where
T: super::RedactMapValue,
{
self.map(name, value)
}
/// Writes a value whose sensitivity is selected by a sibling policy key.
///
/// The output field name remains `name`, while `key` is the runtime text
/// used for policy lookup. This matches map-entry classification semantics:
/// pass-through keys preserve the value, and sensitive keys redact it at
/// the policy-selected level.
#[doc(hidden)]
pub fn keyed_value<K, T>(&mut self, name: &str, key: &K, value: &T) -> &mut Self
where
K: AsRef<str> + ?Sized,
T: RedactLevelValue + Debug + ?Sized,
{
if !self.admit_field(name) {
self.write_field_truncated();
return self;
}
let key = key.as_ref();
if !self.writer.session.admit_domain_key(key) {
self.write_field_truncated();
return self;
}
let policy = self.writer.session.policy();
let resolved = (!policy.is_disabled()).then(|| resolve_keyed_field(policy, key));
if self.writer.session.is_inspection() {
if let Some(ResolvedField::Sensitive { sensitivity }) = resolved {
self.writer.session.observe_sensitivity(sensitivity);
}
return self;
}
self.write_prefix(name);
if !self.writer.can_write() {
return self;
}
match resolved {
Some(ResolvedField::Sensitive { sensitivity }) => {
value.write_redacted_level(self.writer, sensitivity);
}
Some(ResolvedField::PassThrough) | None => self.writer.write_debug(&value),
}
self.writer.write_fragment(", ");
self
}
/// Writes a lazy debug value classified by a business key.
///
/// `name` is only the displayed field label; `key` selects the complete
/// runtime policy, including floors and unknown-field handling. High and
/// secret rules avoid evaluating `access`. Pass-through and disabled policy
/// preserve the value. Inspection never evaluates the accessor.
///
/// # Parameters
///
/// * `name` - Field label used in the diagnostic representation.
/// * `key` - Business key used for policy classification.
/// * `access` - Source accessor, invoked only after admission when needed.
///
/// # Returns
/// This scope for further field operations.
///
/// # Panics
/// Propagates accessor or formatter panics when rendering needs the value.
pub fn keyed<T, F>(&mut self, name: &str, key: &str, access: F) -> &mut Self
where
T: Debug,
F: FnOnce() -> T,
{
if !self.admit_field(name) {
self.write_field_truncated();
return self;
}
if !self.writer.session.admit_domain_key(key) {
self.write_field_truncated();
return self;
}
let policy = self.writer.session.policy();
let resolved = if policy.is_disabled() {
ResolvedField::PassThrough
} else {
resolve_keyed_field(policy, key)
};
match resolved {
ResolvedField::PassThrough => self.write_admitted_unredacted(name, access),
ResolvedField::Sensitive { sensitivity } => {
if self.writer.session.is_inspection() {
self.writer.session.observe_sensitivity(sensitivity);
return self;
}
self.write_prefix(name);
if !self.writer.can_write() {
return self;
}
if matches!(sensitivity, Sensitivity::High | Sensitivity::Secret) {
let masked = self
.writer
.session
.policy()
.masking()
.mask_opaque_bounded(sensitivity, self.writer.remaining_output_bytes());
self.writer.write_debug(&masked);
} else {
self.writer.write_masked_debug(sensitivity, &access());
}
self.writer.write_fragment(", ");
self
}
}
}
/// Writes a structured value classified by a sibling business key.
///
/// A pass-through outer key does not turn the child into an unclassified
/// `Debug` value: the child is written through [`Redact`] and can still
/// apply rules to its own fields. A sensitive outer key masks the whole
/// payload, which is the only safe treatment when the business key
/// classifies the payload itself.
pub fn keyed_nested<T>(&mut self, name: &str, key: &str, value: &T) -> &mut Self
where
T: Redact + Debug + ?Sized,
{
if !self.admit_field(name) || !self.writer.session.admit_domain_key(key) {
self.write_field_truncated();
return self;
}
let policy = self.writer.session.policy();
let resolved = (!policy.is_disabled()).then(|| resolve_keyed_field(policy, key));
if self.writer.session.is_inspection() {
match resolved {
Some(ResolvedField::Sensitive { sensitivity }) => {
self.writer.session.observe_sensitivity(sensitivity);
}
Some(ResolvedField::PassThrough) | None => value.write_redacted(self.writer),
}
return self;
}
self.write_prefix(name);
if !self.writer.can_write() {
return self;
}
match resolved {
Some(ResolvedField::Sensitive { sensitivity }) => {
self.writer.write_masked_debug(sensitivity, value);
}
Some(ResolvedField::PassThrough) | None => value.write_redacted(self.writer),
}
self.writer.write_fragment(", ");
self
}
/// Omits a field while redaction is enabled and restores it when disabled.
pub fn skipped<T, F>(&mut self, name: &str, access: F) -> &mut Self
where
T: Debug,
F: FnOnce() -> T,
{
if self.writer.session.policy().is_disabled() {
self.unredacted(name, access)
} else {
self
}
}
/// Writes an unredacted field after its structural node was admitted by
/// the calling field operation.
fn write_admitted_unredacted<T, F>(&mut self, name: &str, access: F) -> &mut Self
where
T: Debug,
F: FnOnce() -> T,
{
if self.writer.session.is_inspection() {
return self;
}
self.write_prefix(name);
if !self.writer.can_write() {
return self;
}
let value = access();
self.writer.write_debug(&value);
self.writer.write_fragment(", ");
self
}
/// Returns whether the next field may be inspected.
#[must_use]
fn admit_field(&mut self, name: &str) -> bool {
if self.writer.session.domain_frame_is_truncated() || !self.writer.can_write() {
return false;
}
self.writer.session.admit_domain_field() && self.writer.session.admit_domain_key(name)
}
/// Admits one tuple item against the active collection limit.
#[inline]
fn admit_item(&mut self) -> bool {
!self.writer.session.domain_frame_is_truncated() && self.writer.session.admit_domain_collection_item()
}
/// Writes the field-name prefix for named structures.
fn write_prefix(&mut self, name: &str) {
if self.named {
self.writer.write_fragment(name);
self.writer.write_fragment(": ");
}
}
/// Publishes the structural truncation marker once.
fn write_field_truncated(&mut self) {
if !self.writer.session.domain_frame_is_truncated() {
if self.named {
self.writer.write_fragment("...: <truncated>");
} else {
self.writer.write_fragment("<truncated>");
}
self.writer.truncate_without_output_limit();
}
}
}