grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/scrub/rules.rs
// Purpose:   The compiled rule set a Scrubber's policies share
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! [`ScrubRules`]: the regexes, keyword set and PII checks, compiled once.
//! A [`super::Scrubber`] is a policy over them, so a change of policy never
//! compiles a regex.

use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use super::config::{GITLEAKS, RuleConfig, RuleSpec};
use super::pii::{self, Pii};
use super::policy::PolicyBuilder;
use super::prefix::Prefixes;
use super::report::RuleMeta;
use super::rule::{self, Allow, Rule};
use super::{
    FIELD_RULE, Layer, Layers, PII_RULES, Report, RuleId, RuleList, ScrubError, ScrubScratch,
    SkipReason, SkipTarget, Skipped, Strictness, UnknownRule, known_rules,
};
use crate::strmatch::{Signature, SignatureSet};

/// Each rule set's id, so a scratch or report from another one is caught.
static NEXT_ID: AtomicU64 = AtomicU64::new(1);

/// What a build compiled. Shared by every policy over the rules.
#[derive(Debug)]
pub(super) struct Compiled {
    pub rules: Vec<Rule>,
    /// Report rows: the rules, then the field row, the text row and the PII
    /// checks.
    pub meta: Arc<[RuleMeta]>,
    /// Signature `i` is rule `keyed[i]`.
    pub keyed: Vec<usize>,
    pub keywords: SignatureSet,
    /// What every keyword starts with, to rule a text out before the set runs.
    pub keyword_starts: Prefixes,
    pub unkeyed: Vec<usize>,
    /// The config's own global allowlist.
    pub global: Vec<Allow>,
    pub skipped: Vec<Skipped>,
    pub pii: Vec<Pii>,
    /// Which of `pii` have a candidate in a text, found in one pass.
    pub pii_gate: pii::Gate,
    /// The layers compiled: a policy runs these or fewer.
    pub layers: Layers,
    /// Every rule id of the config, built or not.
    pub config_ids: Box<[Box<str>]>,
    /// Ties a scratch and a report to the rules that made them.
    pub id: u64,
}

/// A compiled rule set, shared across policies and threads.
///
/// Building one is the expensive step: it compiles every regex. It is cheap
/// to clone, as it holds an `Arc`, and the last clone frees it. A
/// [`ScrubRules::policy`] over it builds a [`super::Scrubber`] with no regex
/// compile, and its [`ScrubScratch`] and [`Report`] serve every policy over
/// the same rules. grippo keeps no cache of its own: the caller holds the
/// rules for as long as it wants them.
#[derive(Debug, Clone)]
pub struct ScrubRules(pub(super) Arc<Compiled>);

impl ScrubRules {
    /// A builder: every rule and layer, lenient.
    pub fn builder() -> ScrubRulesBuilder {
        ScrubRulesBuilder {
            strictness: Strictness::Lenient,
            keep: None,
            layers: Layers::ALL,
            only_rules: None,
            without: Vec::new(),
        }
    }

    /// Compile a rule config with the builder's defaults.
    ///
    /// # Errors
    ///
    /// As [`ScrubRulesBuilder::build`].
    pub fn new(config: &RuleConfig) -> Result<Self, ScrubError> {
        Self::builder().build(config)
    }

    /// The gitleaks v8.30.1 default rules with the builder's defaults.
    ///
    /// # Errors
    ///
    /// As [`ScrubRulesBuilder::build`].
    pub fn gitleaks() -> Result<Self, ScrubError> {
        Self::new(&RuleConfig::from_toml(GITLEAKS)?)
    }

    /// A policy over these rules: mask redaction, lenient, the layers
    /// compiled, the default credential terms, no exceptions and no scope.
    /// [`PolicyBuilder::build`] makes the [`super::Scrubber`] and compiles no
    /// regex.
    pub fn policy(&self) -> PolicyBuilder {
        PolicyBuilder::over(self.clone())
    }

    /// Number of rules compiled.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.rules.len()
    }

    /// `true` when no rule was compiled.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.rules.is_empty()
    }

    /// The layers compiled. A policy runs these or fewer.
    #[must_use]
    pub fn layers(&self) -> Layers {
        self.0.layers
    }

    /// Rules left out of the build, in config order.
    #[must_use]
    pub fn skipped(&self) -> &[Skipped] {
        &self.0.skipped
    }

    /// The rules compiled, by id and layer: each config rule built, each PII
    /// check, and [`FIELD_RULE`] under the field and text layers when they're
    /// compiled. A rule left out by id, by a skip or by the layers isn't
    /// listed.
    pub fn rules(&self) -> impl Iterator<Item = RuleId<'_>> {
        let layers = self.0.layers;
        self.0
            .meta
            .iter()
            .filter(move |m| layers.runs(m.layer))
            .map(|m| RuleId {
                id: &m.id,
                layer: m.layer,
            })
    }

    /// Heap bytes held by the compiled regexes. Lazy DFA caches live in the
    /// regexes' own pools and grow per thread as text arrives.
    #[must_use]
    pub fn memory_usage(&self) -> usize {
        let c = &*self.0;
        let rules: usize = c
            .rules
            .iter()
            .map(|r| {
                r.regex.memory_usage() + r.allow.iter().map(Allow::memory_usage).sum::<usize>()
            })
            .sum();
        rules
            + c.global.iter().map(Allow::memory_usage).sum::<usize>()
            + c.pii.iter().map(Pii::memory_usage).sum::<usize>()
            + c.pii_gate.memory_usage()
    }

    /// Buffers for one thread, good for every policy over these rules.
    #[must_use]
    pub fn scratch(&self) -> ScrubScratch {
        ScrubScratch::new(&self.0)
    }

    /// A report sized for these rules, to reuse across records and policies.
    #[must_use]
    pub fn report(&self) -> Report {
        Report::new(Arc::clone(&self.0.meta), self.0.id)
    }

    /// `true` when `id` is a config rule, a [`PII_RULES`] id or
    /// [`FIELD_RULE`], built or not.
    pub(super) fn knows(&self, id: &str) -> bool {
        self.0.config_ids.iter().any(|c| &**c == id) || PII_RULES.contains(&id) || id == FIELD_RULE
    }
}

/// Builds [`ScrubRules`]. Everything here changes what is compiled: the
/// rules, the keyword set and the layers. What a scrub does with a find is a
/// [`PolicyBuilder`] setting.
#[must_use]
pub struct ScrubRulesBuilder {
    strictness: Strictness,
    keep: Option<Box<dyn Fn(&RuleSpec) -> bool + Send + Sync>>,
    layers: Layers,
    only_rules: Option<Vec<String>>,
    without: Vec<String>,
}

impl ScrubRulesBuilder {
    /// The layers to compile. [`Layers::ALL`] when not set. A policy can run
    /// fewer, never more.
    pub const fn layers(mut self, layers: Layers) -> Self {
        self.layers = layers;
        self
    }

    /// What to do with a rule that can't run. [`Strictness::Lenient`] when
    /// not set.
    pub const fn strictness(mut self, strictness: Strictness) -> Self {
        self.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.keep = Some(Box::new(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.only_rules
            .get_or_insert_default()
            .extend(ids.into_iter().map(Into::into));
        self
    }

    /// Leave these rules out by id: a config rule, one of [`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.without.extend(ids.into_iter().map(Into::into));
        self
    }

    /// Each id in `only_rules` or `without_rules` that no rule has.
    /// `only_rules` takes config rules only, `without_rules` any id
    /// [`known_rules`] gives.
    pub(super) fn unknown_rules(&self, config: &RuleConfig) -> Vec<UnknownRule> {
        let named = (self.only_rules.iter().flatten())
            .map(|id| (RuleList::Only, id))
            .chain(self.without.iter().map(|id| (RuleList::Without, id)));
        let mut unknown: Vec<UnknownRule> = Vec::new();
        for (list, id) in named {
            let known = if list == RuleList::Only {
                config.rules.iter().any(|r| r.id == *id)
            } else {
                known_rules(config).any(|r| r.id == id.as_str())
            };
            let entry = UnknownRule {
                list,
                id: id.clone(),
            };
            if !known && !unknown.contains(&entry) {
                unknown.push(entry);
            }
        }
        unknown
    }

    /// Compile a rule config.
    ///
    /// # Errors
    ///
    /// [`ScrubError::UnknownRules`] naming each id in `only_rules` or
    /// `without_rules` that no rule has. A rule the layers or [`Self::keep`]
    /// leave out is still known. [`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<ScrubRules, ScrubError> {
        let unknown = self.unknown_rules(config);
        if !unknown.is_empty() {
            return Err(ScrubError::UnknownRules { unknown });
        }
        self.compile(config)
    }

    /// Compile `config`, its ids already checked.
    pub(super) fn compile(self, config: &RuleConfig) -> Result<ScrubRules, ScrubError> {
        let mut rules = Vec::new();
        let mut meta = Vec::new();
        let mut sigs = Vec::new();
        let mut words_all: Vec<String> = Vec::new();
        let mut keyed = Vec::new();
        let mut unkeyed = Vec::new();
        let mut skipped = Vec::new();
        let out = |id: &str| self.without.iter().any(|w| w == id);
        let layers = if out(FIELD_RULE) {
            self.layers.without(Layers::FIELD.with(Layers::TEXT))
        } else {
            self.layers
        };
        let secret = layers.runs(Layer::Secret);
        let kept = config.rules.iter().filter(|r| {
            secret
                && !out(&r.id)
                && self
                    .only_rules
                    .as_ref()
                    .is_none_or(|ids| ids.contains(&r.id))
                && self.keep.as_ref().is_none_or(|k| k(r))
        });
        for spec in kept {
            let rule = match compile_rule(spec) {
                Ok(rule) => rule,
                Err(reason) if self.strictness == Strictness::Strict => {
                    return Err(ScrubError::Skipped {
                        target: SkipTarget::Rule(spec.id.clone()),
                        reason,
                    });
                }
                Err(reason) => {
                    skipped.push(Skipped {
                        target: SkipTarget::Rule(spec.id.clone()),
                        reason,
                    });
                    continue;
                }
            };
            let i = rules.len();
            rules.push(rule);
            meta.push(RuleMeta::new(&spec.id, Layer::Secret));
            let words: Vec<String> = spec
                .keywords
                .iter()
                .map(|k| rule::fold_keyword(k))
                .filter(|k| !k.is_empty())
                .collect();
            if words.is_empty() {
                unkeyed.push(i);
            } else {
                sigs.push(Signature::builder().any_of(&words).build()?);
                keyed.push(i);
                words_all.extend(words);
            }
        }
        let global: Vec<Allow> = config
            .allowlist
            .iter()
            .map(rule::allow)
            .collect::<Result<_, _>>()
            .map_err(|reason| ScrubError::GlobalAllowlist { reason })?;
        meta.push(RuleMeta::new(FIELD_RULE, Layer::Field));
        meta.push(RuleMeta::new(FIELD_RULE, Layer::Text));
        let mut pii = if layers.runs(Layer::Pii) {
            pii::defaults().map_err(|source| ScrubError::Builtin { source })?
        } else {
            Vec::new()
        };
        pii.retain(|p| !out(p.id));
        let pii_gate = pii::Gate::new(&pii).map_err(|source| ScrubError::Builtin { source })?;
        meta.extend(pii.iter().map(|p| RuleMeta::new(p.id, Layer::Pii)));
        Ok(ScrubRules(Arc::new(Compiled {
            keywords: SignatureSet::new(&sigs)?,
            keyword_starts: Prefixes::new(words_all.iter().map(String::as_bytes)),
            rules,
            meta: meta.into(),
            keyed,
            unkeyed,
            global,
            skipped,
            pii,
            pii_gate,
            layers,
            config_ids: config.rules.iter().map(|r| r.id.as_str().into()).collect(),
            id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
        })))
    }
}

fn compile_rule(spec: &RuleSpec) -> Result<Rule, SkipReason> {
    if spec.path.is_some() {
        return Err(SkipReason::PathGated);
    }
    let re = spec.regex.as_deref().ok_or(SkipReason::NoRegex)?;
    let bad = |e: Box<regex_automata::meta::BuildError>| SkipReason::BadRegex(e.to_string());
    Ok(Rule {
        regex: rule::compile(re).map_err(bad)?,
        starts: rule::KeywordStarts::new(re, &spec.keywords),
        secret_group: spec.secret_group.filter(|&g| g > 0),
        entropy: spec.entropy.filter(|&e| e != 0.0),
        allow: spec
            .allowlists
            .iter()
            .map(rule::allow)
            .collect::<Result<_, _>>()
            .map_err(SkipReason::BadRegex)?,
    })
}