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
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Immutable field-classification, masking, and diagnostic policy.

use std::sync::Arc;
use std::sync::LazyLock;

use super::AllowRule;
use super::FieldClassification;
use super::FieldNameMatching;
use super::MaskingPolicy;
use super::RedactionFloor;
use super::RedactionPolicyBuilder;
use super::RedactionRules;
use super::SensitiveFieldRule;
use super::Sensitivity;
#[cfg(feature = "json")]
use super::UnkeyedJsonValuePolicy;
use super::UnknownFieldPolicy;
use super::internal::RedactionPolicyInner;
use super::redaction_limits::RedactionLimits;

/// Built-in sensitive fields not owned by a named preset.
pub(super) const STANDARD_EXTRA_FIELDS: &[(&str, Sensitivity)] = &[
    ("auth_app_token", Sensitivity::High),
    ("auth_user_token", Sensitivity::High),
    ("connection_string", Sensitivity::Secret),
    ("database_uri", Sensitivity::Secret),
    ("database_url", Sensitivity::Secret),
    ("license_key", Sensitivity::Medium),
    ("mysql_pwd", Sensitivity::Secret),
    ("rediscli_auth", Sensitivity::Secret),
    ("sig", Sensitivity::Secret),
    ("signature", Sensitivity::Secret),
];

/// Lazily initialized fixed standard policy.
static STANDARD_POLICY: LazyLock<RedactionPolicy> = LazyLock::new(|| {
    RedactionPolicy::from_rules(
        RedactionRules::new(
            RedactionPolicyInner {
                sensitive: Default::default(),
                allow_exact: Default::default(),
                allow_suffix: Default::default(),
                matching: FieldNameMatching::ExactOrTokenSuffix,
                unknown_field_policy: UnknownFieldPolicy::PassThrough,
            },
            Some(RedactionFloor::standard()),
        ),
        MaskingPolicy::default(),
        RedactionLimits::default(),
        #[cfg(feature = "http")]
        crate::formats::http::HttpPolicyBuilder::new()
            .build()
            .expect("the built-in HTTP policy must be valid"),
        #[cfg(feature = "uri")]
        crate::formats::uri::UriPolicyBuilder::new()
            .build()
            .expect("the built-in URI policy must be valid"),
        #[cfg(feature = "json")]
        UnkeyedJsonValuePolicy::PassThrough,
        false,
    )
});
/// Lazily initialized fixed strict policy.
static STRICT_POLICY: LazyLock<RedactionPolicy> = LazyLock::new(|| {
    RedactionPolicy::from_rules(
        RedactionRules::new(
            RedactionPolicyInner {
                sensitive: Default::default(),
                allow_exact: Default::default(),
                allow_suffix: Default::default(),
                matching: FieldNameMatching::ExactOrTokenSuffix,
                unknown_field_policy: UnknownFieldPolicy::Redact(Sensitivity::Secret),
            },
            Some(RedactionFloor::standard()),
        ),
        MaskingPolicy::default(),
        RedactionLimits::default(),
        #[cfg(feature = "http")]
        {
            let mut http = crate::formats::http::HttpPolicyBuilder::new();
            http.url_path_mut(crate::formats::http::UrlPathPolicy::Redact);
            http.text_body_mut(crate::formats::http::TextBodyPolicy::Redact);
            http.build().expect("the built-in HTTP policy must be valid")
        },
        #[cfg(feature = "uri")]
        {
            let mut uri = crate::formats::uri::UriPolicyBuilder::new();
            uri.path_policy_mut(crate::formats::uri::UriPathPolicy::Redact);
            uri.build().expect("the built-in URI policy must be valid")
        },
        #[cfg(feature = "json")]
        UnkeyedJsonValuePolicy::Redact,
        false,
    )
});
/// Immutable field classification, masking, format, and resource policy.
///
/// A disabled policy intentionally restores original values while retaining
/// resource limits. It is a deliberate debugging escape hatch whose
/// authorization belongs to downstream code.
///
/// # Warning
///
/// Disabling this policy opts out of confidentiality redaction. Every supported
/// format, derived field mode, and redaction-specific skip path may publish its
/// original value. Resource limits and diagnostic control-character escaping
/// still apply, but they do not make the output redacted. The framework
/// faithfully executes the chosen policy; it cannot and does not attempt to
/// prevent downstream code from deliberately or accidentally disabling
/// redaction. Callers own the authorization, environment, timing, and
/// consequences of that choice. They can observe it through
/// [`crate::RedactionSummary::is_redaction_disabled`] and
/// [`crate::RedactionInspection::is_redaction_disabled`].
///
/// # Examples
///
/// ```
/// use qubit_redact::RedactionPolicy;
///
/// let mut policy = RedactionPolicy::disabled();
/// assert!(policy.is_disabled());
/// policy.set_disabled(false);
/// assert!(!policy.is_disabled());
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RedactionPolicy {
    /// Explicit escape switch that restores source values while retaining
    /// limits.
    disabled: bool,
    /// Immutable field-classification layers.
    rules: RedactionRules,
    /// Shared masks selected after sensitivity resolution.
    masking: Arc<MaskingPolicy>,
    /// Resource ceilings applied to every transaction created from this
    /// policy.
    limits: RedactionLimits,
    /// HTTP-specific immutable policy snapshot.
    #[cfg(feature = "http")]
    http: Arc<crate::formats::http::HttpPolicy>,
    /// URI-specific immutable policy snapshot.
    #[cfg(feature = "uri")]
    uri: Arc<crate::formats::uri::UriPolicy>,
    /// Fallback behavior for JSON scalars without an object key.
    #[cfg(feature = "json")]
    unkeyed_json_value_policy: UnkeyedJsonValuePolicy,
}

impl RedactionPolicy {
    /// Returns the fixed built-in standard policy.
    ///
    /// Its application rules are empty and its explicit floor is
    /// [`RedactionFloor::standard`], so it never observes later process-wide
    /// default installations.
    #[must_use]
    #[inline(always)]
    pub fn standard() -> Self {
        STANDARD_POLICY.clone()
    }

    /// Returns a strict boundary policy whose unknown fields are masked at
    /// [`Sensitivity::Secret`] in addition to the standard floor.
    ///
    /// This preset is intended for untrusted external boundaries. It is more
    /// protective than [`Self::standard`] but may reduce diagnostic detail.
    /// Non-root HTTP and URI paths are hidden when their features are enabled.
    #[must_use]
    #[inline(always)]
    pub fn strict() -> Self {
        STRICT_POLICY.clone()
    }

    /// Returns the standard policy with confidentiality redaction globally
    /// disabled.
    ///
    /// # Warning
    ///
    /// Outputs produced with this policy may contain every original value.
    /// Limits and control-character escaping remain active, but masking and
    /// redaction-specific field decisions do not. This deliberate debugging
    /// capability transfers confidentiality responsibility to the caller.
    #[must_use]
    pub fn disabled() -> Self {
        let mut policy = Self::standard();
        policy.disabled = true;
        policy
    }

    /// Creates a deterministic builder with no application rules and the
    /// standard minimum-protection floor.
    #[must_use]
    #[inline(always)]
    pub fn builder() -> RedactionPolicyBuilder {
        RedactionPolicyBuilder::new()
    }

    /// Creates a policy from fully resolved field rules and resource limits.
    ///
    /// # Parameters
    ///
    /// - `rules`: Validated application classification and minimum floors.
    /// - `masking`: One mask table shared by all sensitivity decisions.
    /// - `limits`: Validated ceilings copied into each new transaction.
    /// - `http`: HTTP context policy, when the `http` feature is enabled.
    /// - `uri`: URI component policy, when the `uri` feature is enabled.
    /// - `unkeyed_json_value_policy`: Root/array scalar handling with `json`.
    /// - `disabled`: Whether to restore source values while retaining limits.
    ///
    /// # Returns
    ///
    /// An owned policy sharing the immutable masking and format configuration.
    /// This internal constructor assumes its inputs were already validated.
    #[must_use]
    pub(crate) fn from_rules(
        rules: RedactionRules,
        masking: MaskingPolicy,
        limits: RedactionLimits,
        #[cfg(feature = "http")] http: crate::formats::http::HttpPolicy,
        #[cfg(feature = "uri")] uri: crate::formats::uri::UriPolicy,
        #[cfg(feature = "json")] unkeyed_json_value_policy: UnkeyedJsonValuePolicy,
        disabled: bool,
    ) -> Self {
        Self {
            disabled,
            rules,
            masking: Arc::new(masking),
            limits,
            #[cfg(feature = "http")]
            http: Arc::new(http),
            #[cfg(feature = "uri")]
            uri: Arc::new(uri),
            #[cfg(feature = "json")]
            unkeyed_json_value_policy,
        }
    }

    /// Returns whether this policy publishes original values while retaining
    /// limits and control-character escaping.
    ///
    /// A `true` result means confidentiality redaction is disabled.
    #[must_use]
    #[inline(always)]
    pub const fn is_disabled(&self) -> bool {
        self.disabled
    }

    /// Returns all static limits used by this policy.
    #[must_use]
    #[inline(always)]
    pub const fn limits(&self) -> &RedactionLimits {
        &self.limits
    }

    /// Returns the unified HTTP context policy.
    #[must_use]
    #[cfg(feature = "http")]
    #[inline(always)]
    pub fn http(&self) -> &crate::formats::http::HttpPolicy {
        self.http.as_ref()
    }

    /// Returns the unified URI context policy.
    #[must_use]
    #[cfg(feature = "uri")]
    #[inline(always)]
    pub fn uri(&self) -> &crate::formats::uri::UriPolicy {
        self.uri.as_ref()
    }

    /// Returns the behavior for root and array JSON scalar values.
    #[must_use]
    #[cfg(feature = "json")]
    #[inline(always)]
    pub const fn unkeyed_json_value_policy(&self) -> UnkeyedJsonValuePolicy {
        self.unkeyed_json_value_policy
    }

    /// Returns the immutable field rules without diagnostic resource limits.
    #[must_use]
    #[inline(always)]
    pub const fn rules(&self) -> &RedactionRules {
        &self.rules
    }

    /// Returns the attached minimum floor, or `None` when it was explicitly
    /// disabled.
    #[must_use]
    #[inline(always)]
    pub fn floor(&self) -> Option<&RedactionFloor> {
        self.rules.floor()
    }

    /// Returns the final sensitivity for `field` after applying application
    /// rules and the enabled floor.
    ///
    /// Returns `None` only when neither layer classifies the field as
    /// sensitive.
    #[must_use]
    #[inline(always)]
    pub fn sensitivity_for(&self, field: &str) -> Option<Sensitivity> {
        self.rules.sensitivity_for(field)
    }

    /// Returns the application layer's field-name matching mode.
    ///
    /// An attached floor may use a different matching mode for its independent
    /// classification.
    #[must_use]
    #[inline(always)]
    pub fn matching(&self) -> FieldNameMatching {
        self.rules.matching()
    }

    /// Returns the application layer's fallback for unclassified fields.
    ///
    /// An attached floor applies its own fallback independently.
    #[must_use]
    #[inline(always)]
    pub fn unknown_field_policy(&self) -> UnknownFieldPolicy {
        self.rules.unknown_field_policy()
    }

    /// Returns the single mask table used by every sensitivity decision.
    ///
    /// Field classification determines the effective sensitivity; this table
    /// determines how that sensitivity is rendered. Floors never own a second
    /// mask table.
    #[must_use]
    #[inline(always)]
    pub fn masking(&self) -> &MaskingPolicy {
        self.masking.as_ref()
    }

    /// Iterates sensitive rules configured in the application layer only.
    ///
    /// Use [`Self::floor`] to inspect the independent minimum-protection
    /// rules.
    #[inline(always)]
    pub fn application_sensitive_rules(&self) -> impl Iterator<Item = SensitiveFieldRule<'_>> {
        self.rules.application_sensitive_rules()
    }

    /// Iterates allow rules configured in the application layer only.
    ///
    /// These rules never bypass an enabled floor.
    #[inline(always)]
    pub fn application_allow_rules(&self) -> impl Iterator<Item = AllowRule<'_>> {
        self.rules.application_allow_rules()
    }

    /// Changes this policy’s redaction switch and returns this policy for
    /// chaining.
    ///
    /// # Warning
    ///
    /// Passing `true` allows every supported redaction entry to publish its
    /// original value. The caller owns authorization and operational controls;
    /// the framework does not distinguish debugging use from misuse.
    #[must_use]
    #[inline(always)]
    pub fn set_disabled(&mut self, disabled: bool) -> &mut Self {
        self.disabled = disabled;
        self
    }

    /// Creates a builder that exactly copies `self`.
    ///
    /// The copy includes application rules, limits, and the attached floor.
    #[must_use]
    #[inline(always)]
    pub fn to_builder(&self) -> RedactionPolicyBuilder {
        RedactionPolicyBuilder::from_policy(self)
    }

    /// Replaces the floor for this immutable policy.
    #[must_use]
    #[inline(always)]
    pub fn with_floor(mut self, floor: RedactionFloor) -> Self {
        self.rules = self.rules.with_floor(floor);
        self
    }

    /// Adds mandatory minimum protection while retaining existing floor rules.
    #[must_use]
    #[inline(always)]
    pub fn add_floor(mut self, floor: RedactionFloor) -> Self {
        self.rules = self.rules.add_floor(floor);
        self
    }

    /// Disables every floor for this immutable policy.
    ///
    /// # Security
    ///
    /// This explicitly removes minimum protection inherited from any source.
    #[must_use]
    #[inline(always)]
    pub fn disable_floor(mut self) -> Self {
        self.rules = self.rules.disable_floor();
        self
    }

    /// Explains application-rule matching for `field` without applying the
    /// floor.
    ///
    /// This is useful for diagnostics about configured application rules. Use
    /// [`Self::sensitivity_for`] for the final security decision.
    #[inline(always)]
    #[must_use]
    pub fn classify_field<'a>(&'a self, field: &str) -> FieldClassification<'a> {
        self.rules.classify_field(field)
    }

    /// Resolves final sensitivity with exact-only field matching.
    #[must_use]
    #[inline(always)]
    pub(crate) fn sensitivity_for_exact(&self, field: &str) -> Option<Sensitivity> {
        self.rules.sensitivity_for_exact(field)
    }

    /// Resolves final sensitivity with exact-only field matching.
    #[inline(always)]
    pub(crate) fn resolve_field_exact(&self, field: &str) -> super::ResolvedField {
        self.rules.resolve_field_exact(field)
    }

    /// Replaces the mask table while preserving all classification and limit
    /// settings. This is used by format boundaries that own the mask policy.
    #[doc(hidden)]
    #[cfg(feature = "uri")]
    #[inline(always)]
    pub(crate) fn with_masking(mut self, masking: MaskingPolicy) -> Self {
        self.masking = Arc::new(masking);
        self
    }

    /// Resolves final sensitivity for `field`.
    #[inline(always)]
    #[must_use]
    pub(crate) fn resolve_field(&self, field: &str) -> super::ResolvedField {
        self.rules.resolve_field(field)
    }
}

impl Default for RedactionPolicy {
    /// Clones the fixed standard policy.
    #[inline(always)]
    fn default() -> Self {
        STANDARD_POLICY.clone()
    }
}