qubit-redact 0.3.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
477
478
479
480
481
482
483
484
485
486
487
488
489
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Immutable field-classification and masking policy.

use std::{
    collections::{
        BTreeMap,
        BTreeSet,
    },
    ops::ControlFlow,
    sync::{
        Arc,
        LazyLock,
        OnceLock,
    },
};

use super::{
    AllowRule,
    DiagnosticBudget,
    FieldClassification,
    FieldMatchKind,
    FieldNameMatching,
    GlobalDefaultAlreadySet,
    MaskingPolicy,
    RedactionPolicyBuilder,
    SensitiveFieldPreset,
    SensitiveFieldRule,
    Sensitivity,
    UnknownFieldPolicy,
    internal::{
        RedactionPolicyInner,
        visit_canonical_field_candidates,
    },
};

/// Built-in sensitive fields not owned by a named preset.
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 built-in conservative policy.
static STANDARD_POLICY: LazyLock<RedactionPolicy> =
    LazyLock::new(RedactionPolicy::build_standard);

/// Process-wide default policy installed at most once.
static GLOBAL_DEFAULT: OnceLock<RedactionPolicy> = OnceLock::new();

/// Immutable field-classification and value-masking policy.
///
/// Cloning a policy shares its complete configuration and has constant cost.
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RedactionPolicy {
    /// Shared immutable policy state.
    inner: Arc<RedactionPolicyInner>,
    /// Limits applied whenever this policy renders a diagnostic.
    diagnostic_budget: DiagnosticBudget,
}

impl RedactionPolicy {
    /// Returns the built-in conservative policy.
    ///
    /// # Returns
    ///
    /// A policy containing every built-in preset and extra sensitive field.
    #[inline(always)]
    pub fn standard() -> Self {
        STANDARD_POLICY.clone()
    }

    /// Returns a snapshot of the process-wide default policy.
    ///
    /// Before a custom default is installed, this returns a new shared handle
    /// to the built-in [`Self::standard`] policy. The returned snapshot never
    /// changes after a later installation.
    ///
    /// # Returns
    ///
    /// A shared immutable snapshot of the current process-wide default.
    #[inline]
    pub fn global_default() -> Self {
        GLOBAL_DEFAULT.get().cloned().unwrap_or_else(Self::standard)
    }

    /// Creates a builder without sensitive or allow rules.
    ///
    /// # Returns
    ///
    /// A mutable builder with default matching, masking, and diagnostic limits.
    #[inline]
    pub fn builder() -> RedactionPolicyBuilder {
        RedactionPolicyBuilder::new()
    }

    /// Creates a builder initialized from the current default policy.
    ///
    /// # Returns
    ///
    /// A mutable builder containing a snapshot of the current default policy.
    #[inline]
    pub fn builder_from_default() -> RedactionPolicyBuilder {
        RedactionPolicyBuilder::from_policy(&Self::default())
    }

    /// Creates a builder by copying one immutable policy snapshot.
    ///
    /// # Parameters
    ///
    /// * `base` - Policy whose complete configuration is copied.
    ///
    /// # Returns
    ///
    /// A mutable builder initialized from `base`.
    #[inline]
    pub fn builder_from(base: &Self) -> RedactionPolicyBuilder {
        RedactionPolicyBuilder::from_policy(base)
    }

    /// Constructs the built-in policy without consulting `Default`.
    ///
    /// # Returns
    ///
    /// The complete built-in conservative policy.
    pub(super) fn build_standard() -> Self {
        let mut builder = RedactionPolicyBuilder::empty();
        for preset in [
            SensitiveFieldPreset::Credentials,
            SensitiveFieldPreset::CredentialContainers,
            SensitiveFieldPreset::AuthTokens,
            SensitiveFieldPreset::Http,
            SensitiveFieldPreset::Session,
        ] {
            builder = builder.include_preset(preset);
        }
        for &(field, level) in STANDARD_EXTRA_FIELDS {
            builder = builder.raise(field, level);
        }
        builder.into_policy()
    }

    /// Creates an immutable policy from validated builder components.
    ///
    /// # Parameters
    ///
    /// * `sensitive` - Canonical sensitive fields and levels.
    /// * `allow_exact` - Canonical exact-only allow rules.
    /// * `allow_suffix` - Canonical suffix allow rules.
    /// * `matching` - Sensitive-field matching breadth.
    /// * `unknown_field_policy` - Fallback for fields with no matching rule.
    /// * `masking` - Four-level value-masking policy.
    /// * `diagnostic_budget` - Input and output limits for diagnostics.
    ///
    /// # Returns
    ///
    /// A cheap-clone immutable policy.
    #[inline(always)]
    pub(super) fn from_parts(
        sensitive: BTreeMap<String, Sensitivity>,
        allow_exact: BTreeSet<String>,
        allow_suffix: BTreeSet<String>,
        matching: FieldNameMatching,
        unknown_field_policy: UnknownFieldPolicy,
        masking: MaskingPolicy,
        diagnostic_budget: DiagnosticBudget,
    ) -> Self {
        Self {
            inner: Arc::new(RedactionPolicyInner {
                sensitive,
                allow_exact,
                allow_suffix,
                matching,
                unknown_field_policy,
                masking,
            }),
            diagnostic_budget,
        }
    }

    /// Returns the hard limits for diagnostics rendered with this policy.
    ///
    /// # Returns
    ///
    /// The immutable diagnostic input and output budget.
    #[must_use = "use the diagnostic budget to bound rendered diagnostics"]
    #[inline(always)]
    pub const fn diagnostic_budget(&self) -> DiagnosticBudget {
        self.diagnostic_budget
    }

    /// Installs the process-wide default policy exactly once.
    ///
    /// The installed immutable policy affects later calls to [`Self::default`]
    /// and [`RedactionPolicyBuilder::load_default`]. Previously created
    /// snapshots remain unchanged.
    ///
    /// # Parameters
    ///
    /// * `policy` - Immutable policy to install as the process-wide default.
    ///
    /// # Returns
    ///
    /// `Ok(())` when this call installs the process-wide default.
    ///
    /// # Errors
    ///
    /// Returns [`GlobalDefaultAlreadySet`] when a policy was installed by an
    /// earlier successful call. The existing policy is never replaced.
    #[inline]
    pub fn set_global_default(
        policy: Self,
    ) -> Result<(), GlobalDefaultAlreadySet> {
        GLOBAL_DEFAULT
            .set(policy)
            .map_err(|_| GlobalDefaultAlreadySet)
    }

    /// Classifies `field` and returns the configured rule that decided it.
    ///
    /// Candidates are examined from the complete canonical name to shorter
    /// semantic token suffixes. An allow rule wins over a sensitive rule at
    /// the same candidate, but exact allow rules apply only to the complete
    /// input candidate.
    ///
    /// # Type Parameters
    ///
    /// * `'a` - Lifetime of rules borrowed from this policy in the result.
    ///
    /// # Parameters
    ///
    /// * `field` - Raw field name to classify.
    ///
    /// # Returns
    ///
    /// A borrowed sensitive or allow rule for the first matching candidate, or
    /// [`FieldClassification::Unknown`] when no rule matches.
    pub fn classify_field<'a>(
        &'a self,
        field: &str,
    ) -> FieldClassification<'a> {
        self.classify_field_with_matching(field, self.inner.matching)
    }

    /// Resolves the sensitivity configured for `field`.
    ///
    /// # Parameters
    ///
    /// * `field` - Raw field name to classify.
    ///
    /// # Returns
    ///
    /// `Some(level)` for a sensitive classification or configured unknown-field
    /// fallback, or `None` when an allow rule wins or the fallback passes
    /// unknown fields through.
    #[must_use]
    #[inline]
    pub fn sensitivity_for(&self, field: &str) -> Option<Sensitivity> {
        self.effective_sensitivity(self.classify_field(field))
    }

    /// Classifies a field using an explicit candidate-generation breadth.
    ///
    /// # Type Parameters
    ///
    /// * `'a` - Lifetime of rules borrowed from this policy in the result.
    ///
    /// # Parameters
    ///
    /// * `field` - Raw field name to classify.
    /// * `matching` - Exact or semantic-suffix candidate generation.
    ///
    /// # Returns
    ///
    /// The first sensitive or allow rule in candidate order, otherwise
    /// [`FieldClassification::Unknown`].
    fn classify_field_with_matching<'a>(
        &'a self,
        field: &str,
        matching: FieldNameMatching,
    ) -> FieldClassification<'a> {
        match visit_canonical_field_candidates(
            field,
            matching,
            |is_exact, candidate| {
                let match_kind = if is_exact {
                    FieldMatchKind::Exact
                } else {
                    FieldMatchKind::TokenSuffix
                };
                if is_exact
                    && let Some(field) = self.inner.allow_exact.get(candidate)
                {
                    return ControlFlow::Break(FieldClassification::Allowed {
                        rule: AllowRule::new(field, FieldNameMatching::Exact),
                        match_kind,
                    });
                }
                if let Some(field) = self.inner.allow_suffix.get(candidate) {
                    return ControlFlow::Break(FieldClassification::Allowed {
                        rule: AllowRule::new(
                            field,
                            FieldNameMatching::ExactOrTokenSuffix,
                        ),
                        match_kind,
                    });
                }
                if let Some((field, sensitivity)) =
                    self.inner.sensitive.get_key_value(candidate)
                {
                    return ControlFlow::Break(
                        FieldClassification::Sensitive {
                            rule: SensitiveFieldRule::new(field, *sensitivity),
                            match_kind,
                        },
                    );
                }
                ControlFlow::Continue(())
            },
        ) {
            ControlFlow::Break(classification) => classification,
            ControlFlow::Continue(()) => FieldClassification::Unknown,
        }
    }

    /// Resolves sensitivity only for the complete canonical field name.
    ///
    /// This restricted lookup supports syntax adapters that must not interpret
    /// compact values as semantic field-name suffixes.
    ///
    /// # Parameters
    ///
    /// * `field` - Raw field name to classify exactly.
    ///
    /// # Returns
    ///
    /// `Some(level)` for an exact sensitive rule or configured unknown-field
    /// fallback, or `None` when an allow rule wins or the fallback passes
    /// unknown fields through.
    pub(crate) fn sensitivity_for_exact(
        &self,
        field: &str,
    ) -> Option<Sensitivity> {
        self.effective_sensitivity(
            self.classify_field_with_matching(field, FieldNameMatching::Exact),
        )
    }

    /// Returns the configured sensitive-field matching breadth.
    ///
    /// # Returns
    ///
    /// The matching mode used to generate lookup candidates.
    #[inline(always)]
    pub fn matching(&self) -> FieldNameMatching {
        self.inner.matching
    }

    /// Returns fallback behavior for fields with no matching rule.
    ///
    /// # Returns
    ///
    /// The immutable unknown-field policy configured for this snapshot.
    #[inline(always)]
    pub fn unknown_field_policy(&self) -> UnknownFieldPolicy {
        self.inner.unknown_field_policy
    }

    /// Returns the configured value-masking policy.
    ///
    /// # Returns
    ///
    /// The four-level immutable masking configuration.
    #[inline(always)]
    pub fn masking(&self) -> &MaskingPolicy {
        &self.inner.masking
    }

    /// Iterates configured sensitive-field rules in canonical name order.
    ///
    /// # Returns
    ///
    /// Borrowed read-only views of all sensitive-field rules.
    pub fn sensitive_rules(
        &self,
    ) -> impl Iterator<Item = SensitiveFieldRule<'_>> {
        self.inner.sensitive.iter().map(|(field, sensitivity)| {
            SensitiveFieldRule::new(field, *sensitivity)
        })
    }

    /// Iterates exact allow rules followed by suffix allow rules.
    ///
    /// Each group is ordered by canonical field name.
    ///
    /// # Returns
    ///
    /// Borrowed read-only views of all allow rules.
    pub fn allow_rules(&self) -> impl Iterator<Item = AllowRule<'_>> {
        let exact = self
            .inner
            .allow_exact
            .iter()
            .map(|field| AllowRule::new(field, FieldNameMatching::Exact));
        let suffix = self.inner.allow_suffix.iter().map(|field| {
            AllowRule::new(field, FieldNameMatching::ExactOrTokenSuffix)
        });
        exact.chain(suffix)
    }

    /// Clones the canonical sensitive-field map for a new builder.
    ///
    /// # Returns
    ///
    /// An owned copy of all sensitive-field rules.
    pub(super) fn clone_sensitive(&self) -> BTreeMap<String, Sensitivity> {
        self.inner.sensitive.clone()
    }

    /// Clones the exact allow-rule set for a new builder.
    ///
    /// # Returns
    ///
    /// An owned copy of all exact allow rules.
    pub(super) fn clone_allow_exact(&self) -> BTreeSet<String> {
        self.inner.allow_exact.clone()
    }

    /// Clones the suffix allow-rule set for a new builder.
    ///
    /// # Returns
    ///
    /// An owned copy of all suffix allow rules.
    pub(super) fn clone_allow_suffix(&self) -> BTreeSet<String> {
        self.inner.allow_suffix.clone()
    }

    /// Applies fallback behavior after complete explicit-rule classification.
    ///
    /// # Parameters
    ///
    /// * classification - Result of the current candidate traversal.
    ///
    /// # Returns
    ///
    /// The matched sensitivity, no sensitivity for an explicit allow rule, or
    /// the configured fallback for an unknown field.
    #[inline(always)]
    fn effective_sensitivity(
        &self,
        classification: FieldClassification<'_>,
    ) -> Option<Sensitivity> {
        match classification {
            FieldClassification::Sensitive { rule, .. } => {
                Some(rule.sensitivity())
            }
            FieldClassification::Allowed { .. } => None,
            FieldClassification::Unknown => {
                self.unknown_field_policy().sensitivity()
            }
        }
    }
}

impl Default for RedactionPolicy {
    /// Returns a snapshot of the current process-wide default policy.
    ///
    /// # Returns
    ///
    /// The installed global configuration, or [`RedactionPolicy::standard`]
    /// before a custom default is installed.
    #[inline(always)]
    fn default() -> Self {
        Self::global_default()
    }
}