pub mod config;
pub mod field;
#[cfg(feature = "scrub-json")]
mod json;
mod pii;
mod redact;
mod report;
mod rule;
use std::borrow::Cow;
use std::ops::Range;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use regex_automata::util::captures::Captures;
use thiserror::Error;
pub use config::{AllowlistConfig, GITLEAKS, RuleConfig, RuleSpec};
pub use redact::{HASH_ALGORITHM, HashKey, Redaction};
pub use report::{Entry, Kind, Layer, Report};
use crate::strmatch::{Signature, SignatureError, SignatureScratch, SignatureSet};
use field::CredentialMatcher;
use pii::Pii;
use redact::Redactor;
use report::RuleMeta;
use rule::{Allow, Outcome, Rule};
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ScrubError {
#[error("scrub: the rule config doesn't parse: {0}")]
Config(#[from] toml::de::Error),
#[error("scrub: an allowlist doesn't build: {reason}")]
GlobalAllowlist {
reason: String,
},
#[error("scrub: rule {rule:?} can't run: {reason}")]
Skipped {
rule: String,
reason: SkipReason,
},
#[error("scrub: a built-in PII pattern doesn't compile: {source}")]
Builtin {
#[source]
source: Box<regex_automata::meta::BuildError>,
},
#[error(transparent)]
Keywords(#[from] SignatureError),
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum SkipReason {
#[error("it matches on a file path")]
PathGated,
#[error("it has no regex")]
NoRegex,
#[error("a regex doesn't compile: {0}")]
BadRegex(String),
#[error("the field path is malformed")]
BadFieldPath,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Skipped {
pub rule: String,
pub reason: SkipReason,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum AllowMarker {
#[default]
Ignore,
Honour,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Strictness {
#[default]
Lenient,
Strict,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding<'s> {
pub rule: &'s str,
pub matched: Range<usize>,
pub secret: Range<usize>,
}
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
pub const FIELD_RULE: &str = "credential-field";
#[must_use]
pub fn rule_token(id: &str) -> String {
RuleMeta::new(id, Layer::Secret).token.into()
}
pub const PII_RULES: &[&str] = &[
"credit-card",
"iban",
"email",
#[cfg(feature = "scrub-phone")]
"phone",
"au-abn",
"au-acn",
"au-medicare",
"au-tfn",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Layers(u8);
impl Layers {
pub const SECRET: Self = Self(1);
pub const FIELD: Self = Self(2);
pub const PII: Self = Self(4);
pub const TEXT: Self = Self(8);
pub const ALL: Self = Self(15);
#[must_use]
pub const fn with(self, other: Self) -> Self {
Self(self.0 | other.0)
}
#[must_use]
pub const fn without(self, other: Self) -> Self {
Self(self.0 & !other.0)
}
#[must_use]
pub const fn runs(self, layer: Layer) -> bool {
let bit = match layer {
Layer::Secret => Self::SECRET.0,
Layer::Field => Self::FIELD.0,
Layer::Pii => Self::PII.0,
Layer::Text => Self::TEXT.0,
};
self.0 & bit != 0
}
}
#[derive(Debug, Clone)]
struct FieldException {
segments: Vec<String>,
below: bool,
}
impl FieldException {
fn new(path: &str) -> Option<Self> {
let (path, below) = path.strip_suffix(".*").map_or((path, false), |p| (p, true));
let segments: Vec<String> = path.split('.').map(str::to_owned).collect();
let bad = segments.iter().any(|s| s.is_empty() || s.contains('*'));
(!bad).then_some(Self { segments, below })
}
fn covers(&self, path: &[&str]) -> bool {
let n = self.segments.len();
let len_fits = if self.below {
path.len() > n
} else {
path.len() == n
};
len_fits && self.segments.iter().zip(path).all(|(a, b)| a == b)
}
}
#[must_use]
pub struct ScrubberBuilder {
redaction: Redaction,
strictness: Strictness,
keep: Option<Box<dyn Fn(&RuleSpec) -> bool + Send + Sync>>,
layers: Layers,
credentials: CredentialMatcher,
exceptions: Vec<String>,
allow_marker: AllowMarker,
without: Vec<String>,
allow: Vec<AllowlistConfig>,
scoped: Vec<(Vec<String>, AllowlistConfig)>,
observe: Vec<String>,
}
impl ScrubberBuilder {
pub const fn allow_marker(mut self, marker: AllowMarker) -> Self {
self.allow_marker = marker;
self
}
pub const fn layers(mut self, layers: Layers) -> Self {
self.layers = layers;
self
}
pub fn credential_terms(mut self, credentials: CredentialMatcher) -> Self {
self.credentials = credentials;
self
}
pub fn except_fields<I, S>(mut self, paths: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
self.exceptions
.extend(paths.into_iter().map(|p| p.as_ref().to_owned()));
self
}
pub fn redaction(mut self, redaction: Redaction) -> Self {
self.redaction = redaction;
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 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 fn observe_rules<I, S>(mut self, ids: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.observe.extend(ids.into_iter().map(Into::into));
self
}
pub fn allow(mut self, allowlist: AllowlistConfig) -> Self {
self.allow.push(allowlist);
self
}
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.scoped.push((ids, allowlist));
self
}
pub fn build(self, config: &RuleConfig) -> Result<Scrubber, ScrubError> {
let mut rules = Vec::new();
let mut meta = Vec::new();
let mut sigs = 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.keep.as_ref().is_none_or(|k| k(r)));
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 })
};
for spec in kept {
let mut rule = match compile_rule(spec) {
Ok(rule) => rule,
Err(reason) if self.strictness == Strictness::Strict => {
return Err(ScrubError::Skipped {
rule: spec.id.clone(),
reason,
});
}
Err(reason) => {
skipped.push(Skipped {
rule: spec.id.clone(),
reason,
});
continue;
}
};
rule.allow.extend(own(&spec.id)?);
let i = rules.len();
rules.push(rule);
meta.push(RuleMeta::new(&spec.id, Layer::Secret));
let words: Vec<String> = spec
.keywords
.iter()
.map(|k| k.to_lowercase())
.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);
}
}
let global: Vec<Allow> = config
.allowlist
.iter()
.chain(&self.allow)
.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 exceptions = Vec::new();
for path in &self.exceptions {
match FieldException::new(path) {
Some(e) => exceptions.push(e),
None if self.strictness == Strictness::Strict => {
return Err(ScrubError::Skipped {
rule: path.clone(),
reason: SkipReason::BadFieldPath,
});
}
None => skipped.push(Skipped {
rule: path.clone(),
reason: SkipReason::BadFieldPath,
}),
}
}
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 })?;
let pii_allow = pii.iter().map(|p| own(p.id)).collect::<Result<_, _>>()?;
meta.extend(pii.iter().map(|p| RuleMeta::new(p.id, Layer::Pii)));
let observe = meta
.iter()
.map(|m| self.observe.iter().any(|o| **o == *m.id))
.collect();
Ok(Scrubber {
keywords: SignatureSet::new(&sigs)?,
rules,
meta: meta.into(),
keyed,
unkeyed,
global,
skipped,
redactor: Redactor::from(&self.redaction),
pii_gate,
pii_allow,
observe,
layers,
credentials: self.credentials,
exceptions,
id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
allow_marker: self.allow_marker,
pii,
pair_token: format!(
"[{}_REDACTED]",
RuleMeta::new(FIELD_RULE, Layer::Text).token
),
})
}
}
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)?,
})
}
#[derive(Debug)]
pub struct Scrubber {
rules: Vec<Rule>,
meta: Arc<[RuleMeta]>,
keyed: Vec<usize>,
keywords: SignatureSet,
unkeyed: Vec<usize>,
global: Vec<Allow>,
skipped: Vec<Skipped>,
redactor: Redactor,
pii_allow: Vec<Vec<Allow>>,
observe: Box<[bool]>,
layers: Layers,
credentials: CredentialMatcher,
exceptions: Vec<FieldException>,
pii: Vec<Pii>,
pii_gate: pii::Gate,
id: u64,
allow_marker: AllowMarker,
pair_token: String,
}
#[derive(Debug, Clone)]
struct Hit {
rule: usize,
secret: Range<usize>,
}
pub struct ScrubScratch {
owner: u64,
lower: Vec<u8>,
hits: SignatureScratch,
run: Vec<bool>,
caps: Vec<Captures>,
found: Vec<Hit>,
#[cfg_attr(not(feature = "scrub-json"), allow(dead_code))]
number: String,
spellings: field::Spellings,
pii_seen: regex_automata::PatternSet,
}
impl std::fmt::Debug for ScrubScratch {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ScrubScratch")
.field("lower_capacity", &self.lower.capacity())
.field("rules", &self.caps.len())
.finish_non_exhaustive()
}
}
enum FieldLayer {
NotCredential,
Kept,
Replaced(Vec<u8>),
}
impl Scrubber {
fn own(&self, report: &mut Report) {
if report.owner() != self.id {
*report = self.report();
}
}
pub fn builder() -> ScrubberBuilder {
ScrubberBuilder {
redaction: Redaction::Mask,
strictness: Strictness::Lenient,
keep: None,
layers: Layers::ALL,
credentials: CredentialMatcher::default_terms().clone(),
exceptions: Vec::new(),
allow_marker: AllowMarker::Ignore,
without: Vec::new(),
allow: Vec::new(),
scoped: Vec::new(),
observe: Vec::new(),
}
}
fn field_layer(
&self,
path: &[&str],
value: &[u8],
excepted: bool,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> FieldLayer {
let name = path.last().copied().unwrap_or_default();
let parent = path.len().checked_sub(2).map_or("", |i| path[i]);
if !self.layers.runs(Layer::Field)
|| value.is_empty()
|| name.is_empty()
|| !self
.credentials
.matches_value(name, parent, value, &mut scratch.spellings)
{
return FieldLayer::NotCredential;
}
let field = self.rules.len();
if excepted {
report.add(field, Kind::ExceptedField);
return FieldLayer::Kept;
}
if self.observes(field) {
report.add(field, Kind::Observed);
return FieldLayer::Kept;
}
report.add(field, Kind::Redacted);
report.set_changed();
let mut out = Vec::with_capacity(FIELD_RULE.len() + 20);
self.redactor
.write(&mut out, &self.meta[field].token, value);
FieldLayer::Replaced(out)
}
#[cfg(feature = "scrub-json")]
fn scrub_number(
&self,
path: &[&str],
value: &[u8],
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Option<Vec<u8>> {
self.own(report);
let excepted = self.exceptions.iter().any(|e| e.covers(path));
match self.field_layer(path, value, excepted, scratch, report) {
FieldLayer::Replaced(out) => Some(out),
FieldLayer::NotCredential | FieldLayer::Kept => None,
}
}
pub fn scrub_field(
&self,
path: &[&str],
value: &[u8],
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Option<Vec<u8>> {
self.own(report);
let excepted = self.exceptions.iter().any(|e| e.covers(path));
match self.field_layer(path, value, excepted, scratch, report) {
FieldLayer::NotCredential => {}
FieldLayer::Kept => return None,
FieldLayer::Replaced(out) => return Some(out),
}
if excepted {
self.scan(value, scratch, |rule, outcome| {
if let Outcome::Found { .. } = outcome {
report.add(rule, Kind::ExceptedField);
}
});
for chunk in value.utf8_chunks() {
if self.layers.runs(Layer::Text) {
self.scrub_pairs_str(
chunk.valid(),
&mut scratch.spellings,
Kind::ExceptedField,
report,
);
}
let candidates = self
.pii_gate
.candidates(chunk.valid(), &mut scratch.pii_seen);
for (k, validator) in self.pii.iter().enumerate() {
if candidates & (1 << k) == 0 {
continue;
}
let rule = self.pii_base() + k;
validator.confirmed(chunk.valid(), |_| report.add(rule, Kind::ExceptedField));
}
}
return None;
}
self.scrub_text(value, scratch, report)
}
pub fn new(config: &RuleConfig) -> Result<Self, ScrubError> {
Self::builder().build(config)
}
pub fn gitleaks() -> Result<Self, ScrubError> {
Self::new(&RuleConfig::from_toml(GITLEAKS)?)
}
#[must_use]
pub const fn len(&self) -> usize {
self.rules.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.rules.is_empty()
}
#[must_use]
pub fn skipped(&self) -> &[Skipped] {
&self.skipped
}
#[must_use]
pub fn memory_usage(&self) -> usize {
let rules: usize = self
.rules
.iter()
.map(|r| {
r.regex.memory_usage() + r.allow.iter().map(Allow::memory_usage).sum::<usize>()
})
.sum();
rules
+ self.global.iter().map(Allow::memory_usage).sum::<usize>()
+ self.pii.iter().map(Pii::memory_usage).sum::<usize>()
+ self.pii_gate.memory_usage()
}
#[must_use]
pub fn scratch(&self) -> ScrubScratch {
ScrubScratch {
owner: self.id,
lower: Vec::new(),
hits: self.keywords.scratch(),
run: vec![false; self.rules.len()],
caps: self
.rules
.iter()
.map(|r| r.regex.create_captures())
.collect(),
found: Vec::new(),
number: String::new(),
spellings: field::Spellings::default(),
pii_seen: self.pii_gate.scratch(),
}
}
#[must_use]
pub fn report(&self) -> Report {
Report::new(Arc::clone(&self.meta), self.id)
}
pub fn find(&self, text: &[u8], scratch: &mut ScrubScratch) -> Vec<Finding<'_>> {
let mut found = Vec::new();
self.scan(text, scratch, |i, outcome| {
if let Outcome::Found { matched, secret } = outcome {
found.push(Finding {
rule: &self.meta[i].id,
matched,
secret,
});
}
});
found
}
pub fn scrub_text(
&self,
text: &[u8],
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Option<Vec<u8>> {
self.own(report);
let secret = self.scrub_secrets(text, scratch, report);
let pairs = if self.layers.runs(Layer::Text) {
let kind = self.found_kind(self.rules.len() + 1);
let read = String::from_utf8_lossy(secret.as_deref().unwrap_or(text));
self.scrub_pairs_str(&read, &mut scratch.spellings, kind, report)
.map(String::into_bytes)
} else {
None
};
let pairs = pairs.or(secret);
let pii = if self.pii.is_empty() {
None
} else {
let seen = &mut scratch.pii_seen;
per_chunk(pairs.as_deref().unwrap_or(text), |s| {
self.scrub_pii_str(s, seen, report)
})
};
let out = pii.or(pairs);
if out.is_some() {
report.set_changed();
}
out
}
fn scrub_pairs_str(
&self,
text: &str,
spellings: &mut field::Spellings,
kind: Kind,
report: &mut Report,
) -> Option<String> {
let token = self.pair_token.as_str();
let (masked, _) = field::mask_text_in(text, &self.credentials, token, spellings);
let Cow::Owned(masked) = masked else {
return None;
};
let found = masked
.matches(token)
.count()
.saturating_sub(text.matches(token).count())
.max(1);
report.add_n(self.rules.len() + 1, kind, found);
(kind == Kind::Redacted).then_some(masked)
}
fn observes(&self, row: usize) -> bool {
self.redactor.observes() || self.observe[row]
}
fn found_kind(&self, row: usize) -> Kind {
if self.observes(row) {
Kind::Observed
} else {
Kind::Redacted
}
}
fn scrub_pii_str(
&self,
text: &str,
seen: &mut regex_automata::PatternSet,
report: &mut Report,
) -> Option<String> {
let mut current: Cow<'_, str> = Cow::Borrowed(text);
let mut candidates = self.pii_gate.candidates(text, seen);
for (k, validator) in self.pii.iter().enumerate() {
if candidates & (1 << k) == 0 {
continue;
}
let rule = self.pii_base() + k;
let observe = self.observes(rule);
let mut out: Option<String> = None;
let mut copied = 0;
validator.confirmed(¤t, |m| {
let bytes = current.as_bytes();
if rule::allowlisted(&self.global, bytes, m.clone())
|| rule::allowlisted(&self.pii_allow[k], bytes, m.clone())
{
report.add(rule, Kind::AllowlistedValue);
return;
}
if observe {
report.add(rule, Kind::Observed);
return;
}
report.add(rule, Kind::Redacted);
let o = out.get_or_insert_with(|| String::with_capacity(current.len() + 32));
o.push_str(¤t[copied..m.start]);
self.redactor
.write_str(o, &self.meta[rule].token, current[m.clone()].as_bytes());
copied = m.end;
});
if let Some(mut o) = out {
o.push_str(¤t[copied..]);
current = Cow::Owned(o);
candidates = self.pii_gate.candidates(¤t, seen);
}
}
match current {
Cow::Owned(s) => Some(s),
Cow::Borrowed(_) => None,
}
}
const fn pii_base(&self) -> usize {
self.rules.len() + 2
}
fn scrub_secrets(
&self,
text: &[u8],
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Option<Vec<u8>> {
let mut found = std::mem::take(&mut scratch.found);
found.clear();
self.scan(text, scratch, |rule, outcome| match outcome {
Outcome::Found { secret, .. } => {
let observe = self.observes(rule);
report.add(
rule,
if observe {
Kind::Observed
} else {
Kind::Redacted
},
);
if !observe && !secret.is_empty() {
found.push(Hit {
rule,
secret: char_bounds(text, secret),
});
}
}
Outcome::LowEntropy => report.add(rule, Kind::LowEntropy),
Outcome::Allowlisted => report.add(rule, Kind::AllowlistedValue),
});
let out = (!found.is_empty()).then(|| self.redact(text, &mut found));
scratch.found = found;
out
}
fn redact(&self, text: &[u8], found: &mut [Hit]) -> Vec<u8> {
found.sort_unstable_by(|a, b| {
(a.secret.start, b.secret.end, a.rule).cmp(&(b.secret.start, a.secret.end, b.rule))
});
let mut out = Vec::with_capacity(text.len() + 32 * found.len());
let mut at = 0;
let mut i = 0;
while i < found.len() {
let first = &found[i];
let mut end = first.secret.end;
let mut j = i + 1;
while j < found.len() && found[j].secret.start < end {
end = end.max(found[j].secret.end);
j += 1;
}
out.extend_from_slice(&text[at..first.secret.start]);
self.redactor.write(
&mut out,
&self.meta[first.rule].token,
&text[first.secret.start..end],
);
at = end;
i = j;
}
out.extend_from_slice(&text[at..]);
out
}
fn scan(&self, text: &[u8], scratch: &mut ScrubScratch, mut on: impl FnMut(usize, Outcome)) {
if scratch.owner != self.id {
*scratch = self.scratch();
}
scratch.lower.clear();
scratch
.lower
.extend(text.iter().map(u8::to_ascii_lowercase));
scratch.run.clear();
scratch.run.resize(self.rules.len(), false);
for &i in &self.unkeyed {
scratch.run[i] = true;
}
let (keyed, run) = (&self.keyed, &mut scratch.run);
self.keywords
.for_each_match(&scratch.lower, &mut scratch.hits, |m| {
run[keyed[m.index]] = true;
});
for (i, rule) in self.rules.iter().enumerate() {
if scratch.run[i] {
rule.run(
text,
&self.global,
self.allow_marker == AllowMarker::Honour,
&mut scratch.caps[i],
|o| on(i, o),
);
}
}
}
}
fn char_bounds(text: &[u8], r: Range<usize>) -> Range<usize> {
let inside = |i: usize| text.get(i).is_some_and(|b| b & 0xC0 == 0x80);
let mut start = r.start;
while start > 0 && inside(start) {
start -= 1;
}
let mut end = r.end;
while inside(end) {
end += 1;
}
start..end
}
fn per_chunk(text: &[u8], mut f: impl FnMut(&str) -> Option<String>) -> Option<Vec<u8>> {
let mut out: Option<Vec<u8>> = None;
let (mut at, mut copied) = (0, 0);
for chunk in text.utf8_chunks() {
let valid = chunk.valid();
if let Some(s) = f(valid) {
let o = out.get_or_insert_with(|| Vec::with_capacity(text.len()));
o.extend_from_slice(&text[copied..at]);
o.extend_from_slice(s.as_bytes());
copied = at + valid.len();
}
at += valid.len() + chunk.invalid().len();
}
out.map(|mut o| {
o.extend_from_slice(&text[copied..]);
o
})
}
#[cfg(test)]
mod tests;