use std::collections::HashMap;
use std::ops::Range;
use aho_corasick::AhoCorasick;
use regex_automata::meta::Regex;
use regex_automata::util::captures::Captures;
use regex_automata::util::syntax;
use regex_automata::{Anchored, Input, PatternID};
use super::config::AllowlistConfig;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Target {
Secret,
Match,
Line,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Condition {
Any,
All,
Never,
}
#[derive(Debug)]
pub(super) struct Allow {
regexes: Vec<Regex>,
stopwords: Option<AhoCorasick>,
target: Target,
condition: Condition,
}
#[derive(Debug)]
pub(super) struct Rule {
pub regex: Regex,
pub starts: Option<KeywordStarts>,
pub secret_group: Option<usize>,
pub entropy: Option<f64>,
pub allow: Vec<Allow>,
}
pub(super) enum Outcome {
Found {
matched: Range<usize>,
secret: Range<usize>,
},
LowEntropy,
Allowlisted,
}
fn is_repeat(rest: &[u8]) -> bool {
let digits = |s: &[u8]| s.iter().take_while(|b| b.is_ascii_digit()).count();
let n = digits(rest);
if n == 0 {
return false;
}
match rest.get(n) {
Some(b'}') => true,
Some(b',') => {
let m = digits(&rest[n + 1..]);
rest.get(n + 1 + m) == Some(&b'}')
}
_ => false,
}
}
pub(super) fn from_re2(re: &str) -> String {
let b = re.as_bytes();
let mut out = String::with_capacity(re.len() + 8);
let (mut i, mut class) = (0, false);
while i < b.len() {
match b[i] {
b'\\' => {
let end = (i + 2).min(b.len());
out.push_str(&re[i..end]);
i = end;
continue;
}
b'[' if !class => {
class = true;
out.push('[');
i += 1;
if b.get(i) == Some(&b'^') {
out.push('^');
i += 1;
}
if b.get(i) == Some(&b']') {
out.push(']');
i += 1;
}
continue;
}
b'[' if b.get(i + 1) == Some(&b':') => {
if let Some(len) = re[i..].find(":]") {
out.push_str(&re[i..i + len + 2]);
i += len + 2;
continue;
}
}
b']' if class => class = false,
b'{' if !class && !is_repeat(&b[i + 1..]) => {
out.push_str("\\{");
i += 1;
continue;
}
_ => {}
}
let len = re[i..].chars().next().map_or(1, char::len_utf8);
out.push_str(&re[i..i + len]);
i += len;
}
out
}
const DFA_CACHE: usize = 8 << 20;
pub(super) fn compile(re: &str) -> Result<Regex, Box<regex_automata::meta::BuildError>> {
Regex::builder()
.configure(Regex::config().hybrid_cache_capacity(DFA_CACHE))
.syntax(syntax::Config::new().unicode(false).utf8(false))
.build(&from_re2(re))
.map_err(Box::new)
}
pub(super) fn allow(cfg: &AllowlistConfig) -> Result<Allow, String> {
let and = cfg
.condition
.as_deref()
.is_some_and(|c| c.eq_ignore_ascii_case("AND"));
let regexes: Vec<Regex> = cfg
.regexes
.iter()
.map(|r| compile(r))
.collect::<Result<_, _>>()
.map_err(|e| e.to_string())?;
let stopwords = if cfg.stopwords.is_empty() {
None
} else {
let words: Vec<String> = cfg.stopwords.iter().map(|s| s.to_lowercase()).collect();
let ac = AhoCorasick::builder()
.ascii_case_insensitive(true)
.build(&words)
.map_err(|e| e.to_string())?;
Some(ac)
};
Ok(Allow {
regexes,
stopwords,
target: match cfg.regex_target.as_deref() {
Some("match") => Target::Match,
Some("line") => Target::Line,
_ => Target::Secret,
},
condition: match (and, cfg.paths.is_empty() && cfg.commits.is_empty()) {
(false, _) => Condition::Any,
(true, true) => Condition::All,
(true, false) => Condition::Never,
},
})
}
pub(super) fn entropy(secret: &[u8]) -> f64 {
if secret.is_empty() {
return 0.0;
}
#[allow(
clippy::cast_precision_loss,
reason = "a secret is far shorter than 2^52 bytes"
)]
let inv = 1.0 / secret.len() as f64;
let term = |n: u32| {
let f = f64::from(n) * inv;
-f * f.log2()
};
if secret.is_ascii() {
let mut counts = [0_u32; 128];
for &b in secret {
counts[usize::from(b)] += 1;
}
return counts.iter().filter(|&&n| n > 0).map(|&n| term(n)).sum();
}
let text = String::from_utf8_lossy(secret);
let mut counts: HashMap<char, u32> = HashMap::new();
for c in text.chars() {
*counts.entry(c).or_default() += 1;
}
counts.values().map(|&n| term(n)).sum()
}
pub(super) fn allowlisted(allows: &[Allow], text: &[u8], m: Range<usize>) -> bool {
if allows.is_empty() {
return false;
}
let start = memchr::memrchr(b'\n', &text[..m.start]).map_or(0, |p| p + 1);
let end = memchr::memchr(b'\n', &text[m.end..]).map_or(text.len(), |p| m.end + p);
let found = &text[m];
allows
.iter()
.any(|a| a.allows(found, found, &text[start..end], &mut None))
}
impl Allow {
pub(super) fn memory_usage(&self) -> usize {
self.regexes.iter().map(Regex::memory_usage).sum()
}
fn allows(
&self,
secret: &[u8],
matched: &[u8],
line: &[u8],
line_hit: &mut Option<bool>,
) -> bool {
if self.condition == Condition::Never {
return false;
}
let any = |target: &[u8]| self.regexes.iter().any(|r| r.is_match(target));
let regex = match self.target {
Target::Secret => any(secret),
Target::Match => any(matched),
Target::Line => *line_hit.get_or_insert_with(|| any(line)),
};
let stop = self.stopwords.as_ref().is_some_and(|ac| {
if secret.is_ascii() {
ac.is_match(secret)
} else {
ac.is_match(String::from_utf8_lossy(secret).to_lowercase().as_bytes())
}
});
match self.condition {
Condition::All => {
(self.regexes.is_empty() || regex) && (self.stopwords.is_none() || stop)
}
Condition::Any | Condition::Never => regex || stop,
}
}
}
#[derive(Debug)]
pub(super) struct KeywordStarts {
keywords: AhoCorasick,
class: [bool; 256],
reach: usize,
}
impl KeywordStarts {
pub(super) fn new(re: &str, keywords: &[String]) -> Option<Self> {
use regex_syntax::hir::literal::{ExtractKind, Extractor};
use regex_syntax::hir::{Class, Hir, HirKind};
if keywords.iter().any(String::is_empty) {
return None;
}
let hir = regex_syntax::ParserBuilder::new()
.unicode(false)
.utf8(false)
.build()
.parse(&from_re2(re))
.ok()?;
let HirKind::Concat(parts) = hir.kind() else {
return None;
};
let HirKind::Repetition(run) = parts.first()?.kind() else {
return None;
};
let HirKind::Class(Class::Bytes(bytes)) = run.sub.kind() else {
return None;
};
let reach = usize::try_from(run.max?).ok()?;
let mut class = [false; 256];
for r in bytes.ranges() {
for b in r.start()..=r.end() {
class[usize::from(b)] = true;
}
}
let mut extract = Extractor::new();
extract
.kind(ExtractKind::Prefix)
.limit_class(4)
.limit_repeat(4)
.limit_literal_len(64)
.limit_total(4096);
let rest = Hir::concat(parts.get(1..)?.to_vec());
let prefixes = extract.extract(&rest);
let words: Vec<Vec<u8>> = keywords
.iter()
.map(|k| k.as_bytes().to_ascii_lowercase())
.collect();
let covered = prefixes.literals().is_some_and(|literals| {
!literals.is_empty()
&& literals.iter().all(|l| {
let l = l.as_bytes().to_ascii_lowercase();
words.iter().any(|w| l.starts_with(w))
})
});
if run.min != 0 || !covered {
return None;
}
let keywords = AhoCorasick::builder()
.ascii_case_insensitive(true)
.build(keywords)
.ok()?;
Some(Self {
keywords,
class,
reach,
})
}
pub(super) fn matches(&self, regex: &Regex, text: &[u8], out: &mut Vec<Range<usize>>) {
let mut hits: Vec<usize> = self
.keywords
.find_overlapping_iter(text)
.map(|m| m.start())
.collect();
hits.sort_unstable();
hits.dedup();
let (mut end, mut tried) = (0, None);
for hit in hits {
if hit < end {
continue;
}
let mut start = hit;
while start > end
&& hit - start < self.reach
&& self.class[usize::from(text[start - 1])]
{
start -= 1;
}
if tried == Some(start) {
continue;
}
tried = Some(start);
let input = Input::new(text).range(start..).anchored(Anchored::Yes);
if let Some(m) = regex.search(&input) {
out.push(m.range());
end = m.end().max(m.start() + 1);
}
}
}
}
enum Found<'r, 'h> {
All(regex_automata::meta::FindMatches<'r, 'h>),
Listed(std::vec::IntoIter<Range<usize>>),
}
impl Iterator for Found<'_, '_> {
type Item = Range<usize>;
fn next(&mut self) -> Option<Range<usize>> {
match self {
Self::All(all) => all.next().map(|m| m.range()),
Self::Listed(listed) => listed.next(),
}
}
}
impl Rule {
pub(super) fn run(
&self,
text: &[u8],
global: &[Allow],
honour_marker: bool,
caps: &mut Captures,
mut on: impl FnMut(Outcome),
) {
let mut lines: Option<(Range<usize>, bool)> = None;
let mut line_hits: Vec<Option<bool>> = Vec::new();
let mut reusable = false;
let found = self.starts.as_ref().map_or_else(
|| Found::All(self.regex.find_iter(text)),
|starts| {
let mut listed = Vec::new();
starts.matches(&self.regex, text, &mut listed);
Found::Listed(listed.into_iter())
},
);
for matched in found {
let (span, marked) = match &lines {
Some((span, marked))
if reusable && span.start <= matched.start && matched.end <= span.end =>
{
(span.clone(), *marked)
}
_ => {
let floor = match &lines {
Some((s, _)) if s.start <= matched.start => s.start,
_ => 0,
};
let start = memchr::memrchr(b'\n', &text[floor..matched.start])
.map_or(floor, |p| floor + p + 1);
let end = memchr::memchr(b'\n', &text[matched.end..])
.map_or(text.len(), |p| matched.end + p);
let lines_text = &text[start..end];
let marked = honour_marker
&& memchr::memmem::find(lines_text, b"gitleaks:allow").is_some();
let one_line = memchr::memchr(b'\n', lines_text).is_none();
lines = Some((start..end, marked));
reusable = one_line;
line_hits.fill(None);
(start..end, marked)
}
};
if marked {
continue;
}
let line = &text[span];
let Some(local) = self.secret_in(&text[matched.clone()], caps) else {
continue;
};
let secret = matched.start + local.start..matched.start + local.end;
let bytes = &text[secret.clone()];
if self.entropy.is_some_and(|min| entropy(bytes) <= min) {
on(Outcome::LowEntropy);
continue;
}
let whole = &text[matched.clone()];
line_hits.resize(global.len() + self.allow.len(), None);
let allowed = global
.iter()
.chain(&self.allow)
.zip(line_hits.iter_mut())
.any(|(a, hit)| a.allows(bytes, whole, line, hit));
if allowed {
on(Outcome::Allowlisted);
continue;
}
on(Outcome::Found { matched, secret });
}
}
fn secret_in(&self, whole: &[u8], caps: &mut Captures) -> Option<Range<usize>> {
if caps.group_info().group_len(PatternID::ZERO) < 2 {
return Some(0..whole.len());
}
self.regex
.search_captures(&Input::new(whole).anchored(Anchored::Yes), caps);
if !caps.is_match() {
self.regex.search_captures(&Input::new(whole), caps);
}
let groups = caps.group_len();
if groups < 2 {
return Some(0..whole.len());
}
match self.secret_group {
Some(g) if g >= groups => None,
Some(g) => Some(caps.get_group(g).map_or(0..0, |s| s.range())),
None => Some(
(1..groups)
.find_map(|g| caps.get_group(g).filter(|s| !s.is_empty()))
.map_or(0..whole.len(), |s| s.range()),
),
}
}
}