grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
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
// Project:   grippo
// File:      src/scrub/policy.rs
// Purpose:   Build a Scrubber: a policy over compiled rules, or both in one step
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! [`PolicyBuilder`] makes a [`Scrubber`] over [`ScrubRules`] without
//! compiling a regex. [`ScrubberBuilder`] is the one-step form that compiles
//! the rules and builds one policy over them.

use super::config::{AllowlistConfig, RuleConfig, RuleSpec};
use super::field::{CredentialMatcher, is_plain};
use super::redact::Redactor;
use super::report::RuleMeta;
use super::rule::{self, Allow};
use super::rules::{ScrubRules, ScrubRulesBuilder};
use super::{
    AllowMarker, FIELD_RULE, FieldException, Layer, Layers, Redaction, RuleList, ScrubError,
    Scrubber, SkipReason, SkipTarget, Skipped, Strictness, UnknownRule, known_rules,
};

/// The settings of a policy, whichever builder holds them.
struct Spec {
    strictness: Strictness,
    layers: Option<Layers>,
    redaction: Redaction,
    credentials: CredentialMatcher,
    exceptions: Vec<String>,
    only: Vec<String>,
    allow_marker: AllowMarker,
    allow: Vec<AllowlistConfig>,
    scoped: Vec<(Vec<String>, AllowlistConfig)>,
    observe: Vec<String>,
}

impl Spec {
    fn new() -> Self {
        Self {
            strictness: Strictness::Lenient,
            layers: None,
            redaction: Redaction::Mask,
            credentials: CredentialMatcher::default_terms().clone(),
            exceptions: Vec::new(),
            only: Vec::new(),
            allow_marker: AllowMarker::Ignore,
            allow: Vec::new(),
            scoped: Vec::new(),
            observe: Vec::new(),
        }
    }

    /// Each id in `allow_rules` or `observe_rules` that `known` rejects.
    fn unknown(&self, known: &dyn Fn(&str) -> bool) -> Vec<UnknownRule> {
        let scoped = self.scoped.iter().flat_map(|(ids, _)| ids);
        let named = (scoped.map(|id| (RuleList::Allow, id)))
            .chain(self.observe.iter().map(|id| (RuleList::Observe, id)));
        let mut unknown: Vec<UnknownRule> = Vec::new();
        for (list, id) in named {
            let entry = UnknownRule {
                list,
                id: id.clone(),
            };
            if !known(id) && !unknown.contains(&entry) {
                unknown.push(entry);
            }
        }
        unknown
    }

    /// The scrubber for this policy over `rules`, its ids already checked. No
    /// regex compiles here, so the cost is the allowlists and the report rows.
    fn assemble(self, rules: &ScrubRules) -> Result<Scrubber, ScrubError> {
        let c = &*rules.0;
        if self
            .scoped
            .iter()
            .any(|(ids, _)| ids.iter().any(|i| i == FIELD_RULE))
        {
            return Err(ScrubError::FieldRuleAllowlist);
        }
        let layers = match self.layers {
            Some(asked) if !asked.within(c.layers) => {
                return Err(ScrubError::LayersNotCompiled {
                    asked,
                    compiled: c.layers,
                });
            }
            Some(asked) => asked,
            None => c.layers,
        };
        let own = |id: &str| -> Result<Vec<Allow>, ScrubError> {
            self.scoped
                .iter()
                .filter(|(ids, _)| ids.iter().any(|i| i == id))
                .map(|(_, cfg)| rule::allow(cfg))
                .collect::<Result<_, _>>()
                .map_err(|reason| ScrubError::GlobalAllowlist { reason })
        };
        let rule_allow = c.meta[..c.rules.len()]
            .iter()
            .map(|m| own(&m.id))
            .collect::<Result<_, _>>()?;
        let pii_allow = c.pii.iter().map(|p| own(p.id)).collect::<Result<_, _>>()?;
        let global: Vec<Allow> = self
            .allow
            .iter()
            .map(rule::allow)
            .collect::<Result<_, _>>()
            .map_err(|reason| ScrubError::GlobalAllowlist { reason })?;
        let mut skipped = c.skipped.clone();
        let mut exceptions = Vec::new();
        let mut scope = Vec::new();
        let paths =
            (self.exceptions.iter().map(|p| (p, false))).chain(self.only.iter().map(|p| (p, true)));
        for (path, scoped) in paths {
            match FieldException::new(path) {
                Some(e) if scoped => scope.push(e),
                Some(e) => exceptions.push(e),
                None if self.strictness == Strictness::Strict => {
                    return Err(ScrubError::Skipped {
                        target: SkipTarget::FieldPath(path.clone()),
                        reason: SkipReason::BadFieldPath,
                    });
                }
                None => skipped.push(Skipped {
                    target: SkipTarget::FieldPath(path.clone()),
                    reason: SkipReason::BadFieldPath,
                }),
            }
        }
        let observe = c
            .meta
            .iter()
            .map(|m| self.observe.iter().any(|o| **o == *m.id))
            .collect();
        let pair_token = format!(
            "[{}_REDACTED]",
            RuleMeta::new(FIELD_RULE, Layer::Text).token
        );
        let tokens_plain =
            is_plain(pair_token.as_bytes()) && c.meta.iter().all(|m| is_plain(m.token.as_bytes()));
        Ok(Scrubber {
            rules: rules.clone(),
            layers,
            redactor: Redactor::from(&self.redaction),
            credentials: self.credentials,
            exceptions,
            scope,
            global,
            rule_allow,
            pii_allow,
            observe,
            allow_marker: self.allow_marker,
            pair_token,
            tokens_plain,
            skipped,
        })
    }
}

/// Builds a [`Scrubber`] over [`ScrubRules`], from [`ScrubRules::policy`].
///
/// A policy is what a scrub does with a find and where it looks. Nothing
/// here compiles a regex, so a policy is cheap to build and the rules are
/// shared.
#[must_use]
pub struct PolicyBuilder {
    rules: ScrubRules,
    spec: Spec,
}

impl PolicyBuilder {
    pub(super) fn over(rules: ScrubRules) -> Self {
        Self {
            rules,
            spec: Spec::new(),
        }
    }

    /// What `gitleaks:allow` does. [`AllowMarker::Ignore`] when not set.
    pub const fn allow_marker(mut self, marker: AllowMarker) -> Self {
        self.spec.allow_marker = marker;
        self
    }

    /// The layers to run, a subset of those the rules compiled. The rules'
    /// layers when not set. A layer the rules didn't compile fails the build
    /// with [`ScrubError::LayersNotCompiled`].
    pub const fn layers(mut self, layers: Layers) -> Self {
        self.spec.layers = Some(layers);
        self
    }

    /// The terms that make a field name a credential.
    /// [`super::field::SENSITIVE_FIELDS`] when not set.
    pub fn credential_terms(mut self, credentials: CredentialMatcher) -> Self {
        self.spec.credentials = credentials;
        self
    }

    /// Field paths left alone, such as `event_data.TokenElevationType` or
    /// `event_data.*`. A key holding a dot is written quoted, as in
    /// `labels["app.kind"]`. An exception beats a credential field name. Each
    /// finding it hides is counted as [`super::Kind::ExceptedField`].
    pub fn except_fields<I, S>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.spec
            .exceptions
            .extend(paths.into_iter().map(|p| p.as_ref().to_owned()));
        self
    }

    /// Scrub only these field paths and everything below them, written as in
    /// [`Self::except_fields`]. A layer's mount, such as `cef` after
    /// `syslog > cef` or `doc` after `ndjson > field("doc"):xml`, scopes the
    /// scrub to that layer. Values outside are left alone and never counted,
    /// and an exception still beats the scope. Every field when not set.
    /// [`Scrubber::scrub_text`] reads no path, so a scope doesn't reach it.
    /// Where a key or the scoped key is past ASCII, they match when they read
    /// the same as credential names do, so a key in one Unicode normal form is
    /// in a scope written in another. An exception's key matches only as
    /// written.
    pub fn only_fields<I, S>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.spec
            .only
            .extend(paths.into_iter().map(|p| p.as_ref().to_owned()));
        self
    }

    /// What a found secret becomes. [`Redaction::Mask`] when not set.
    pub fn redaction(mut self, redaction: Redaction) -> Self {
        self.spec.redaction = redaction;
        self
    }

    /// Count every find and leave the bytes alone: [`Redaction::Observe`].
    pub fn observe_all(self) -> Self {
        self.redaction(Redaction::Observe)
    }

    /// What to do with a field path that can't be read.
    /// [`Strictness::Lenient`] when not set.
    pub const fn strictness(mut self, strictness: Strictness) -> Self {
        self.spec.strictness = strictness;
        self
    }

    /// Count these rules' finds as [`super::Kind::Observed`] and leave their
    /// bytes alone, by id: a config rule, one of [`super::PII_RULES`], or
    /// [`FIELD_RULE`], while the other rules redact. A rule the rules didn't
    /// compile is a known id that counts nothing.
    pub fn observe_rules<I, S>(mut self, ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.spec.observe.extend(ids.into_iter().map(Into::into));
        self
    }

    /// A global allowlist of the caller's, beside the config's.
    pub fn allow(mut self, allowlist: AllowlistConfig) -> Self {
        self.spec.allow.push(allowlist);
        self
    }

    /// An allowlist of the caller's for these rules only, by id: a config
    /// rule or one of [`super::PII_RULES`]. [`FIELD_RULE`] takes none, so
    /// naming it fails the build with [`ScrubError::FieldRuleAllowlist`].
    pub fn allow_rules<I, S>(mut self, ids: I, allowlist: AllowlistConfig) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let ids = ids.into_iter().map(Into::into).collect();
        self.spec.scoped.push((ids, allowlist));
        self
    }

    /// Build the scrubber.
    ///
    /// # Errors
    ///
    /// [`ScrubError::UnknownRules`] naming each id in `observe_rules` or
    /// `allow_rules` that no rule of the config has, and the list it was in.
    /// [`ScrubError::FieldRuleAllowlist`] when `allow_rules` names
    /// [`FIELD_RULE`]. [`ScrubError::LayersNotCompiled`] for a layer the
    /// rules lack. [`ScrubError::GlobalAllowlist`] for an allowlist that
    /// doesn't compile, and under [`Strictness::Strict`]
    /// [`ScrubError::Skipped`] for a field path that can't be read.
    pub fn build(self) -> Result<Scrubber, ScrubError> {
        let unknown = self.spec.unknown(&|id| self.rules.knows(id));
        if !unknown.is_empty() {
            return Err(ScrubError::UnknownRules { unknown });
        }
        self.spec.assemble(&self.rules)
    }
}

/// Builds a [`Scrubber`] in one step: the rules and one policy over them. A
/// caller with several policies builds [`ScrubRules`] once and a
/// [`PolicyBuilder`] for each.
#[must_use]
pub struct ScrubberBuilder {
    rules: ScrubRulesBuilder,
    spec: Spec,
}

impl ScrubberBuilder {
    pub(super) fn new() -> Self {
        Self {
            rules: ScrubRules::builder(),
            spec: Spec::new(),
        }
    }

    /// What `gitleaks:allow` does. [`AllowMarker::Ignore`] when not set.
    pub const fn allow_marker(mut self, marker: AllowMarker) -> Self {
        self.spec.allow_marker = marker;
        self
    }

    /// The layers to run. [`Layers::ALL`] when not set.
    pub fn layers(mut self, layers: Layers) -> Self {
        self.rules = self.rules.layers(layers);
        self
    }

    /// The terms that make a field name a credential.
    /// [`super::field::SENSITIVE_FIELDS`] when not set.
    pub fn credential_terms(mut self, credentials: CredentialMatcher) -> Self {
        self.spec.credentials = credentials;
        self
    }

    /// Field paths left alone, such as `event_data.TokenElevationType` or
    /// `event_data.*`. A key holding a dot is written quoted, as in
    /// `labels["app.kind"]`. An exception beats a credential field name. Each
    /// finding it hides is counted as [`super::Kind::ExceptedField`].
    pub fn except_fields<I, S>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.spec
            .exceptions
            .extend(paths.into_iter().map(|p| p.as_ref().to_owned()));
        self
    }

    /// Scrub only these field paths and everything below them, written as in
    /// [`Self::except_fields`]. A layer's mount, such as `cef` after
    /// `syslog > cef` or `doc` after `ndjson > field("doc"):xml`, scopes the
    /// scrub to that layer. Values outside are left alone and never counted,
    /// and an exception still beats the scope. Every field when not set.
    /// [`Scrubber::scrub_text`] reads no path, so a scope doesn't reach it.
    /// Where a key or the scoped key is past ASCII, they match when they read
    /// the same as credential names do, so a key in one Unicode normal form is
    /// in a scope written in another. An exception's key matches only as
    /// written.
    pub fn only_fields<I, S>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.spec
            .only
            .extend(paths.into_iter().map(|p| p.as_ref().to_owned()));
        self
    }

    /// What a found secret becomes. [`Redaction::Mask`] when not set.
    pub fn redaction(mut self, redaction: Redaction) -> Self {
        self.spec.redaction = redaction;
        self
    }

    /// What to do with a rule that can't run. [`Strictness::Lenient`] when
    /// not set.
    pub fn strictness(mut self, strictness: Strictness) -> Self {
        self.rules = self.rules.strictness(strictness);
        self.spec.strictness = strictness;
        self
    }

    /// Build only the rules `keep` accepts. The rest are never evaluated and
    /// never counted.
    pub fn keep(mut self, keep: impl Fn(&RuleSpec) -> bool + Send + Sync + 'static) -> Self {
        self.rules = self.rules.keep(keep);
        self
    }

    /// Build only these config rules, by id. The PII and field layers are
    /// untouched, so an id of theirs is unknown here. An empty list builds no
    /// config rule. Every config rule when not set.
    pub fn only_rules<I, S>(mut self, ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.rules = self.rules.only_rules(ids);
        self
    }

    /// Leave these rules out by id: a config rule, one of [`super::PII_RULES`],
    /// or [`FIELD_RULE`], which drops the field and text layers. A rule left
    /// out is never evaluated and never counted.
    pub fn without_rules<I, S>(mut self, ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.rules = self.rules.without_rules(ids);
        self
    }

    /// Count these rules' finds as [`super::Kind::Observed`] and leave their
    /// bytes alone, by id as in [`Self::without_rules`], while the other
    /// rules redact.
    pub fn observe_rules<I, S>(mut self, ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.spec.observe.extend(ids.into_iter().map(Into::into));
        self
    }

    /// A global allowlist of the caller's, beside the config's.
    pub fn allow(mut self, allowlist: AllowlistConfig) -> Self {
        self.spec.allow.push(allowlist);
        self
    }

    /// An allowlist of the caller's for these rules only, by id: a config
    /// rule or one of [`super::PII_RULES`]. [`FIELD_RULE`] takes none, so
    /// naming it fails the build with [`ScrubError::FieldRuleAllowlist`].
    pub fn allow_rules<I, S>(mut self, ids: I, allowlist: AllowlistConfig) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let ids = ids.into_iter().map(Into::into).collect();
        self.spec.scoped.push((ids, allowlist));
        self
    }

    /// Build from a rule config.
    ///
    /// # Errors
    ///
    /// [`ScrubError::UnknownRules`] naming each rule id that no rule has, and
    /// the list it was in. A rule the layers or [`Self::keep`] leave out is
    /// still known. [`ScrubError::FieldRuleAllowlist`] when `allow_rules`
    /// names [`FIELD_RULE`]. [`ScrubError`] too when the global allowlist or
    /// the keyword set doesn't build, or under [`Strictness::Strict`] when a
    /// rule can't run.
    pub fn build(self, config: &RuleConfig) -> Result<Scrubber, ScrubError> {
        let mut unknown = self.rules.unknown_rules(config);
        unknown.extend(
            self.spec
                .unknown(&|id| known_rules(config).any(|r| r.id == id)),
        );
        if !unknown.is_empty() {
            return Err(ScrubError::UnknownRules { unknown });
        }
        let rules = self.rules.compile(config)?;
        self.spec.assemble(&rules)
    }
}