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};
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
#[derive(Debug)]
pub(super) struct Compiled {
pub rules: Vec<Rule>,
pub meta: Arc<[RuleMeta]>,
pub keyed: Vec<usize>,
pub keywords: SignatureSet,
pub keyword_starts: Prefixes,
pub unkeyed: Vec<usize>,
pub global: Vec<Allow>,
pub skipped: Vec<Skipped>,
pub pii: Vec<Pii>,
pub pii_gate: pii::Gate,
pub layers: Layers,
pub config_ids: Box<[Box<str>]>,
pub id: u64,
}
#[derive(Debug, Clone)]
pub struct ScrubRules(pub(super) Arc<Compiled>);
impl ScrubRules {
pub fn builder() -> ScrubRulesBuilder {
ScrubRulesBuilder {
strictness: Strictness::Lenient,
keep: None,
layers: Layers::ALL,
only_rules: None,
without: Vec::new(),
}
}
pub fn new(config: &RuleConfig) -> Result<Self, ScrubError> {
Self::builder().build(config)
}
pub fn gitleaks() -> Result<Self, ScrubError> {
Self::new(&RuleConfig::from_toml(GITLEAKS)?)
}
pub fn policy(&self) -> PolicyBuilder {
PolicyBuilder::over(self.clone())
}
#[must_use]
pub fn len(&self) -> usize {
self.0.rules.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.rules.is_empty()
}
#[must_use]
pub fn layers(&self) -> Layers {
self.0.layers
}
#[must_use]
pub fn skipped(&self) -> &[Skipped] {
&self.0.skipped
}
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,
})
}
#[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()
}
#[must_use]
pub fn scratch(&self) -> ScrubScratch {
ScrubScratch::new(&self.0)
}
#[must_use]
pub fn report(&self) -> Report {
Report::new(Arc::clone(&self.0.meta), self.0.id)
}
pub(super) fn knows(&self, id: &str) -> bool {
self.0.config_ids.iter().any(|c| &**c == id) || PII_RULES.contains(&id) || id == FIELD_RULE
}
}
#[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 {
pub const fn layers(mut self, layers: Layers) -> Self {
self.layers = layers;
self
}
pub const fn strictness(mut self, strictness: Strictness) -> Self {
self.strictness = strictness;
self
}
pub fn keep(mut self, keep: impl Fn(&RuleSpec) -> bool + Send + Sync + 'static) -> Self {
self.keep = Some(Box::new(keep));
self
}
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
}
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
}
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
}
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)
}
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)?,
})
}