#![allow(
clippy::option_if_let_else,
reason = "a match over multi-field struct literals reads clearer than map_or_else"
)]
use std::borrow::Cow;
use std::fmt::Write as _;
use std::sync::LazyLock;
use super::ScrubError;
use super::prefix::{Fold, Prefixes};
use skeleton::{escape_before, may_escape, sgr_before, sgr_len, skeleton};
pub(super) use skeleton::{is_mark, skeleton as key_skeleton};
mod skeleton;
pub const SENSITIVE_FIELDS: &[&str] = &[
"password",
"passwd",
"pwd",
"pass",
"passphrase",
"pgpass",
"token",
"access_token",
"refresh_token",
"id_token",
"session_token",
"api_token",
"bearer",
"bearer_token",
"api_key",
"apikey",
"api-key",
"api_secret",
"secret",
"client_secret",
"secret_key",
"private_key",
"privatekey",
"secret_access_key",
"aws_secret_access_key",
"aws_secret",
"access_key",
"access_key_id",
"account_key",
"azure_key",
"client_key",
"encryption_key",
"gcp_key",
"hmac_key",
"integration_key",
"jwt_key",
"licence_key",
"license_key",
"master_key",
"sasl_key",
"shared_key",
"signing_key",
"ssh_key",
"ssl_key",
"tls_key",
"authorization",
"auth",
"jaas_config",
"header_value",
"headers_value",
"session_id",
"session_key",
"sessionid",
"cookie",
"csrf",
"certificate",
"cert",
"ssl_cert",
"credential",
"credentials",
"creds",
"db_password",
"database_password",
"connection_string",
"ssn",
"tfn",
"medicare",
"credit_card",
"creditcard",
"card_number",
"cvv",
"pin",
"email",
"phone",
];
const BARE_NAMES: [&str; 4] = ["key", "keys", "value", "values"];
const MAX_WRAPPER_LEN: usize = 4096;
const AUTHORIZATION: &[u8] = b"authorization";
const AUTH_SCHEMES: [&str; 23] = [
"basic",
"bearer",
"concealed",
"digest",
"dpop",
"gnap",
"hoba",
"mutual",
"negotiate",
"oauth",
"privatetoken",
"scram-sha-1",
"scram-sha-256",
"vapid",
"apikey",
"aws4-hmac-sha256",
"ntlm",
"sharedaccesssignature",
"sharedkey",
"sharedkeylite",
"splunk",
"ssws",
"token",
];
static DEFAULT_MATCHER: LazyLock<CredentialMatcher> = LazyLock::new(|| {
let mut buf = String::new();
CredentialMatcher::from_spelled(SENSITIVE_FIELDS.iter().map(|term| spelled(term, &mut buf)))
});
const QUALIFIERS: [&str; 12] = [
"value",
"values",
"pem",
"hash",
"b64",
"base64",
"enc",
"encrypted",
"raw",
"data",
"primary",
"secondary",
];
const SUFFIX_MIN: usize = 6;
#[derive(Debug, Clone)]
pub struct CredentialMatcher {
terms: Vec<String>,
by_last: Vec<Vec<usize>>,
starts: Prefixes,
}
impl CredentialMatcher {
pub fn new<I, S>(terms: I) -> Result<Self, ScrubError>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut buf = String::new();
let mut spelt = Vec::new();
for term in terms {
let words = spelled(term.as_ref(), &mut buf);
if words.is_empty() {
return Err(ScrubError::CredentialTerm {
term: term.as_ref().to_owned(),
});
}
spelt.push(words);
}
Ok(Self::from_spelled(spelt))
}
fn from_spelled(terms: impl IntoIterator<Item = String>) -> Self {
let mut terms: Vec<String> = terms.into_iter().collect();
terms.sort_unstable();
terms.dedup();
let mut by_last = vec![Vec::new(); 256];
for (i, term) in terms.iter().enumerate() {
if let Some(&last) = term.as_bytes().last() {
by_last[usize::from(last)].push(i);
}
}
let starts = Prefixes::new(terms.iter().map(String::as_bytes));
Self {
terms,
by_last,
starts,
}
}
fn may_name_in(&self, text: &str, plain: bool) -> bool {
let bytes = text.as_bytes();
if plain || is_plain(bytes) {
return self.starts.may_hold_folded(bytes, Fold::Alnum);
}
self.may_name_in_unplain(text)
}
fn may_name_in_unplain(&self, text: &str) -> bool {
if may_escape(text) {
return true;
}
let spelt: String = skeleton(text)
.chars()
.filter(|c| c.is_alphanumeric())
.flat_map(char::to_lowercase)
.collect();
self.starts.may_hold(spelt.bytes())
}
fn ending_like(&self, name: &[u8]) -> impl Iterator<Item = &[u8]> {
let last = name.iter().rev().find(|&&b| b != b'_');
last.map_or(&[][..], |&b| &self.by_last[usize::from(b)])
.iter()
.map(|&i| self.terms[i].as_bytes())
}
pub fn default_terms() -> &'static Self {
&DEFAULT_MATCHER
}
pub const fn is_empty(&self) -> bool {
self.terms.is_empty()
}
pub fn matches(&self, name: &str, parent: &str) -> bool {
self.matches_in(name, parent, &mut Spellings::default())
}
pub fn matches_in(&self, name: &str, parent: &str, buf: &mut Spellings) -> bool {
self.name_match(name, parent, buf) != NameMatch::None
}
pub fn matches_value(
&self,
name: &str,
parent: &str,
value: &[u8],
buf: &mut Spellings,
) -> bool {
match self.name_match(name, parent, buf) {
NameMatch::None => false,
NameMatch::Term => true,
NameMatch::Plural => !is_number(value),
}
}
pub(crate) fn name_match(&self, name: &str, parent: &str, buf: &mut Spellings) -> NameMatch {
if parent.is_empty() && !self.may_name_in(name, buf.plain()) {
return NameMatch::None;
}
buf.spell(name);
if !parent.is_empty() && BARE_NAMES.contains(&buf.joined.as_str()) {
if self.name_match(parent, "", buf) == NameMatch::Term {
return NameMatch::Term;
}
let mut qualified = std::mem::take(&mut buf.qualified);
qualified.clear();
qualified.push_str(parent);
qualified.push('_');
qualified.push_str(name);
buf.spell(&qualified);
buf.qualified = qualified;
}
let mut found = NameMatch::None;
let mut stem = buf.joined.as_str();
for _ in 0..MAX_STRIPPED {
let bytes = stem.as_bytes();
if self
.ending_like(bytes)
.any(|term| ends_with_term(bytes, term, term.len() >= SUFFIX_MIN))
{
return NameMatch::Term;
}
if let Some(singular) = bytes.strip_suffix(b"s") {
for term in self.ending_like(singular) {
let long = term.len() >= SUFFIX_MIN;
if ends_with_term(singular, term, long) {
if long {
return NameMatch::Term;
}
found = NameMatch::Plural;
}
}
}
match strip_last_word(stem) {
Some(shorter) => stem = shorter,
None => break,
}
}
found
}
}
const MAX_STRIPPED: usize = 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NameMatch {
None,
Term,
Plural,
}
fn strip_last_word(name: &str) -> Option<&str> {
let (rest, last) = name.rsplit_once('_')?;
if QUALIFIERS.contains(&last) {
return Some(rest);
}
if !last.chars().all(char::is_numeric) {
return None;
}
Some(rest.strip_suffix("_v").unwrap_or(rest)).filter(|s| *s != "v")
}
fn is_number(value: &[u8]) -> bool {
let v = value.trim_ascii();
let v = v
.strip_prefix(b"\"")
.and_then(|v| v.strip_suffix(b"\""))
.unwrap_or(v);
let v = v.strip_prefix(b"-").unwrap_or(v);
let (whole, fraction) = v.split_at(v.iter().position(|&b| b == b'.').unwrap_or(v.len()));
let digits = |d: &[u8]| {
!d.is_empty()
&& (d.iter().all(u8::is_ascii_digit)
|| std::str::from_utf8(d)
.is_ok_and(|s| s.chars().all(|c| super::pii::decimal(c).is_some())))
};
digits(whole) && (fraction.is_empty() || (fraction.len() > 1 && digits(&fraction[1..])))
}
const fn ends_with_term(name: &[u8], term: &[u8], in_last_word: bool) -> bool {
let mut i = name.len();
let mut j = term.len();
let mut crossed = false;
while j > 0 {
let Some(at) = i.checked_sub(1) else {
return false;
};
i = at;
if name[i] == b'_' {
crossed = true;
continue;
}
j -= 1;
if name[i] != term[j] {
return false;
}
}
i == 0 || name[i - 1] == b'_' || (in_last_word && !crossed)
}
#[derive(Debug, Default, Clone)]
pub struct Spellings {
joined: String,
qualified: String,
plain: bool,
}
impl Spellings {
pub(crate) const fn plain(&self) -> bool {
self.plain
}
pub(crate) const fn set_plain(&mut self, plain: bool) {
self.plain = plain;
}
fn spell(&mut self, name: &str) {
joined_words_into(name, &mut self.joined);
}
}
#[cfg(test)]
fn joined_words(name: &str) -> String {
let mut out = String::new();
joined_words_into(name, &mut out);
out
}
fn joined_words_into(name: &str, out: &mut String) {
spell_words(&skeleton(name), out);
}
fn spelled(term: &str, buf: &mut String) -> String {
joined_words_into(term, buf);
buf.replace('_', "")
}
fn spell_words(name: &str, out: &mut String) {
out.clear();
let mut start = 0;
while start < name.len() {
let end = word_end(name, start);
if end == start {
start += name[start..].chars().next().map_or(1, char::len_utf8);
continue;
}
if !out.is_empty() {
out.push('_');
}
out.extend(name[start..end].chars().flat_map(char::to_lowercase));
start = end;
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Glyph {
Upper,
Lower,
Digit,
Other,
}
fn glyph(c: char) -> Glyph {
if c.is_uppercase() {
Glyph::Upper
} else if c.is_lowercase() || c.is_alphabetic() {
Glyph::Lower
} else if c.is_numeric() {
Glyph::Digit
} else {
Glyph::Other
}
}
fn word_end(text: &str, start: usize) -> usize {
let run = |from: usize, class: Glyph| {
from + text[from..]
.chars()
.take_while(|&c| glyph(c) == class)
.map(char::len_utf8)
.sum::<usize>()
};
let Some(first) = text[start..].chars().next() else {
return start;
};
match glyph(first) {
Glyph::Upper => {
let upper_end = run(start, Glyph::Upper);
let lower_follows = text[upper_end..]
.chars()
.next()
.is_some_and(|c| glyph(c) == Glyph::Lower);
if !lower_follows {
return upper_end;
}
let last = text[start..upper_end]
.chars()
.next_back()
.map_or(0, char::len_utf8);
if upper_end - start > last {
return upper_end - last;
}
run(upper_end, Glyph::Lower)
}
class @ (Glyph::Lower | Glyph::Digit) => run(start, class),
Glyph::Other => start,
}
}
#[must_use]
pub fn is_credential_name(name: &str, parent: &str) -> bool {
CredentialMatcher::default_terms().matches(name, parent)
}
fn is_space(c: char) -> bool {
c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)
}
fn is_blank(c: char) -> bool {
is_space(c) && !matches!(c, '\n' | '\r')
}
pub(super) const fn is_ignorable(c: char) -> bool {
matches!(
c,
'\u{ad}'
| '\u{34f}'
| '\u{61c}'
| '\u{115f}'
| '\u{1160}'
| '\u{17b4}'
| '\u{17b5}'
| '\u{180b}'..='\u{180f}'
| '\u{200b}'..='\u{200f}'
| '\u{202a}'..='\u{202e}'
| '\u{2060}'..='\u{206f}'
| '\u{3164}'
| '\u{fe00}'..='\u{fe0f}'
| '\u{feff}'
| '\u{ffa0}'
| '\u{fff0}'..='\u{fff8}'
| '\u{e0000}'..='\u{e0fff}'
)
}
fn is_gap(c: char) -> bool {
is_blank(c) || is_ignorable(c)
}
fn is_colon_gap(c: char) -> bool {
is_space(c) || is_ignorable(c)
}
fn is_mask(value: &str, mask: &str) -> bool {
!mask.is_empty() && value == mask
}
fn mask_end(text: &str, at: usize, mask: &str) -> Option<usize> {
if mask.is_empty() {
return None;
}
let rest = text.get(at..)?;
let (quote, inner) = match rest.chars().next()? {
q @ ('"' | '\'') => (Some(q), &rest[1..]),
_ => (None, rest),
};
let after = inner.strip_prefix(mask)?;
let end = text.len() - after.len();
match quote {
Some(q) => after.starts_with(q).then_some(end + 1),
None => after
.chars()
.next()
.is_none_or(|c| !(c.is_alphanumeric() || c == '_'))
.then_some(end),
}
}
fn scan_until(text: &str, from: usize, stop: impl Fn(char) -> bool) -> usize {
text[from..]
.char_indices()
.find(|&(_, c)| stop(c))
.map_or(text.len(), |(i, _)| from + i)
}
#[must_use]
pub fn mask_url_userinfo<'a>(text: &'a str, mask: &str, keep_user: bool) -> Cow<'a, str> {
url_masked(text, mask, keep_user, &mut 0)
}
fn url_masked<'a>(text: &'a str, mask: &str, keep_user: bool, n: &mut usize) -> Cow<'a, str> {
let mut out: Option<String> = None;
let mut copied = 0;
for (head, colon, at) in url_userinfo(text) {
if is_mask(&text[colon + 1..at], mask) {
continue;
}
if keep_user && at > colon + 1 {
let buf = out.get_or_insert_with(|| String::with_capacity(text.len()));
buf.push_str(&text[copied..=colon]);
buf.push_str(mask);
*n += 1;
copied = at;
} else if !keep_user {
let buf = out.get_or_insert_with(|| String::with_capacity(text.len()));
buf.push_str(&text[copied..head]);
buf.push_str("://");
buf.push_str(mask);
*n += 1;
copied = at;
}
}
finish(text, out, copied)
}
#[must_use]
pub fn url_passwords(text: &str) -> Vec<&str> {
url_userinfo(text)
.filter(|&(_, colon, at)| at > colon + 1)
.map(|(_, colon, at)| &text[colon + 1..at])
.collect()
}
fn url_userinfo(text: &str) -> impl Iterator<Item = (usize, usize, usize)> + '_ {
let bytes = text.as_bytes();
let mut from = 0;
std::iter::from_fn(move || {
while let Some(head) = next_scheme_end(bytes, from) {
let colon = scan_until(text, head + 3, |c| {
is_space(c) || matches!(c, ':' | '/' | '@')
});
if bytes.get(colon) != Some(&b':') {
from = head + 1;
continue;
}
let run_end = password_run_end(text, colon + 1);
let Some(at) = last_host_at(text, colon + 1, run_end) else {
from = head + 1;
continue;
};
from = at;
return Some((head, colon, at));
}
None
})
}
fn next_scheme_end(bytes: &[u8], from: usize) -> Option<usize> {
memchr::memchr_iter(b':', bytes.get(from..)?)
.map(|found| from + found)
.find(|&at| bytes[at..].starts_with(b"://"))
}
fn password_run_end(text: &str, from: usize) -> usize {
text[from..]
.char_indices()
.find(|&(i, c)| is_space(c) || text[from + i..].starts_with("://"))
.map_or(text.len(), |(i, _)| from + i)
}
fn last_host_at(text: &str, from: usize, to: usize) -> Option<usize> {
text[from..to]
.rmatch_indices('@')
.map(|(i, _)| from + i)
.find(|&at| host_follows(text, at))
}
fn host_follows(text: &str, at: usize) -> bool {
let end = scan_until(text, at + 1, |c| {
is_space(c) || matches!(c, '@' | '/' | '?' | '#')
});
text[end..]
.chars()
.next()
.is_none_or(|c| is_space(c) || matches!(c, '/' | '?' | '#'))
}
const SIGNATURE_PARAMS: [&str; 4] = [
"sig",
"x-amz-signature",
"x-amz-security-token",
"x-goog-signature",
];
fn mask_query_signatures<'a>(text: &'a str, mask: &str, n: &mut usize) -> Cow<'a, str> {
let mut out: Option<String> = None;
let mut copied = 0;
let mut from = 0;
while let Some(found) = memchr::memchr2(b'?', b'&', &text.as_bytes()[from..]) {
let name_start = from + found + 1;
from = name_start;
let value_start = SIGNATURE_PARAMS.iter().find_map(|name| {
let name_end = name_start + name.len();
let named = text
.get(name_start..name_end)
.is_some_and(|written| written.eq_ignore_ascii_case(name));
(named && text.as_bytes().get(name_end) == Some(&b'=')).then_some(name_end + 1)
});
let Some(value_start) = value_start else {
continue;
};
let value_end = scan_until(text, value_start, |c| {
is_space(c) || matches!(c, '&' | '"' | '\'')
});
from = value_end;
if is_mask(&text[value_start..value_end], mask) {
continue;
}
let buf = out.get_or_insert_with(|| String::with_capacity(text.len()));
buf.push_str(&text[copied..value_start]);
buf.push_str(mask);
*n += 1;
copied = value_end;
}
finish(text, out, copied)
}
const REFUSED_HEADER: &str = "illegal header value ";
fn mask_refused_headers<'a>(text: &'a str, mask: &str, n: &mut usize) -> Cow<'a, str> {
let bytes = text.as_bytes();
let mut out: Option<String> = None;
let mut copied = 0;
let mut from = 0;
while let Some(head) = find_refused_header(text, from) {
from = head + 1;
let mut open = head + REFUSED_HEADER.len();
if matches!(bytes.get(open), Some(b'b' | b'B')) {
open += 1;
}
let Some("e @ (b'\'' | b'"')) = bytes.get(open) else {
continue;
};
let mut end = open + 1;
let close = loop {
match bytes.get(end) {
None | Some(b'\n') => break end,
Some(&b) if b == quote => break end + 1,
Some(b'\\') if !matches!(bytes.get(end + 1), None | Some(b'\n')) => end += 2,
Some(b'\\') => break end,
Some(_) => end += 1,
}
};
from = close;
if close == end + 1 && is_mask(&text[open + 1..end], mask) {
continue;
}
let buf = out.get_or_insert_with(|| String::with_capacity(text.len()));
buf.push_str(&text[copied..=open]);
buf.push_str(mask);
buf.push(char::from(quote));
*n += 1;
copied = close;
}
finish(text, out, copied)
}
const REFUSED_HEADER_V: usize = 15;
fn find_refused_header(text: &str, from: usize) -> Option<usize> {
let bytes = text.as_bytes();
memchr::memchr2_iter(b'v', b'V', bytes.get(from + REFUSED_HEADER_V..)?)
.map(|found| from + found)
.find(|&head| {
bytes
.get(head..head + REFUSED_HEADER.len())
.is_some_and(|w| w.eq_ignore_ascii_case(REFUSED_HEADER.as_bytes()))
&& text[..head]
.chars()
.next_back()
.is_none_or(|c| !(c.is_alphanumeric() || c == '_'))
})
}
fn mask_bearer<'a>(text: &'a str, mask: &str, n: &mut usize) -> Cow<'a, str> {
let mut out: Option<String> = None;
let mut copied = 0;
let mut from = 0;
while let Some(found) = find_bearer(text, from) {
let gap_end = scan_until(text, found + 6, |c| !is_space(c));
let token_end = scan_until(text, gap_end, is_space);
if gap_end == found + 6 || token_end == gap_end {
from = found + 1;
continue;
}
from = token_end;
if is_mask(&text[gap_end..token_end], mask) {
continue;
}
let buf = out.get_or_insert_with(|| String::with_capacity(text.len()));
buf.push_str(&text[copied..found]);
buf.push_str("bearer ");
buf.push_str(mask);
*n += 1;
copied = token_end;
}
finish(text, out, copied)
}
fn find_bearer(text: &str, from: usize) -> Option<usize> {
let bytes = text.as_bytes();
memchr::memchr2_iter(b'b', b'B', bytes.get(from..)?)
.map(|found| from + found)
.find(|&i| {
text.get(i..i + 6)
.is_some_and(|w| w.eq_ignore_ascii_case("bearer"))
&& text[..i]
.chars()
.next_back()
.is_none_or(|c| !(c.is_alphanumeric() || c == '_'))
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Separator {
Colon,
Equals,
}
#[derive(Debug, Clone, Copy)]
struct Head {
start: usize,
key_end: usize,
end: usize,
}
fn is_sudo_cwd(text: &str, head: &Head) -> bool {
if &text[head.start..head.key_end] != "PWD" {
return false;
}
let Some(before) = text[..head.start].strip_suffix(" ; ") else {
return false;
};
let field = before.rsplit(' ').next().unwrap_or_default();
if !(field.starts_with("TTY=") || field.starts_with("CHROOT=")) {
return false;
}
let line = text[head.end..].split('\n').next().unwrap_or_default();
line.split_once(" ; ")
.is_some_and(|(_, next)| next.starts_with("USER="))
}
fn is_key_char(c: char) -> bool {
c.is_alphanumeric() || matches!(c, '_' | '.' | '-') || is_ignorable(c) || is_mark(c)
}
const fn is_closing_quote(c: char) -> bool {
matches!(
c,
'"' | '\''
| '\u{201d}'
| '\u{2019}'
| '\u{201c}'
| '\u{bb}'
| '\u{ab}'
| '\u{203a}'
| '\u{2039}'
| '\u{300d}'
| '\u{300f}'
)
}
const fn typographic_closers(open: char) -> &'static [char] {
match open {
'\u{201c}' => &['\u{201d}'],
'\u{2018}' => &['\u{2019}'],
'\u{201e}' => &['\u{201c}', '\u{201d}'],
'\u{201a}' => &['\u{2018}', '\u{2019}'],
'\u{ab}' => &['\u{bb}'],
'\u{bb}' => &['\u{ab}'],
'\u{2039}' => &['\u{203a}'],
'\u{203a}' => &['\u{2039}'],
'\u{300c}' => &['\u{300d}'],
'\u{300e}' => &['\u{300f}'],
_ => &[],
}
}
fn opens_typographic_quote(text: &str, from: usize) -> bool {
text[from..]
.chars()
.next()
.is_some_and(|c| !typographic_closers(c).is_empty())
}
fn typographic_end(text: &str, from: usize) -> Option<usize> {
let open = text[from..].chars().next()?;
let closers = typographic_closers(open);
if closers.is_empty() {
return None;
}
let body = from + open.len_utf8();
text[body..]
.char_indices()
.take_while(|&(_, c)| c != '\n')
.find(|&(_, c)| closers.contains(&c))
.map(|(i, c)| body + i + c.len_utf8())
}
fn names_authorization(key: &str) -> bool {
key.as_bytes()
.windows(AUTHORIZATION.len())
.any(|window| window.eq_ignore_ascii_case(AUTHORIZATION))
}
fn is_auth_scheme(word: &str) -> bool {
AUTH_SCHEMES
.iter()
.any(|scheme| word.eq_ignore_ascii_case(scheme))
}
fn next_head(text: &str, from: usize, separator: Separator) -> Option<Head> {
let bytes = text.as_bytes();
let byte = match separator {
Separator::Colon => b':',
Separator::Equals => b'=',
};
let mut search = from;
while let Some(found) = memchr::memchr3(byte, 0xEF, b'%', &bytes[search..]) {
let at = search + found;
search = at + 1;
if separator_len(bytes, at, separator).is_none() {
continue;
}
let before = &text[from..at];
let spaced = match separator {
Separator::Colon => trim_gap_end(before, is_colon_gap),
Separator::Equals => trim_gap_end(before, is_gap),
};
let quote = spaced.chars().next_back().filter(|&c| is_closing_quote(c));
let key_end = from + spaced.len() - quote.map_or(0, char::len_utf8);
let key = key_len(&text[from..key_end]);
let start = key_end - key;
if key == 0 || text[..start].chars().next_back().is_some_and(is_key_char) {
continue;
}
if let Some(end) = separator_end(text, start, key_end, separator) {
return Some(Head {
start,
key_end,
end,
});
}
}
None
}
fn separator_end(text: &str, start: usize, key_end: usize, separator: Separator) -> Option<usize> {
let bytes = text.as_bytes();
let mut at = key_end;
if let Some(quote) = text[at..].chars().next().filter(|&c| is_closing_quote(c)) {
at += quote.len_utf8();
}
match separator {
Separator::Colon => {
at = skip_gap(text, at, is_colon_gap);
let len = separator_len(bytes, at, separator)?;
if start >= 2 && &bytes[start - 2..start] == b"::" {
return None;
}
let mut after = at + len;
if len == 1 && matches!(bytes.get(after), Some(b':' | b'=')) {
after += 1;
}
Some(skip_gap(text, after, is_colon_gap))
}
Separator::Equals => {
at = skip_gap(text, at, is_gap);
let len = separator_len(bytes, at, separator)?;
let mut after = at + len;
if len == 1 {
match bytes.get(after) {
Some(b'=') => return None,
Some(b'>') if follows_rocket(&text[..start]) => return None,
Some(b'>') => after += 1,
_ => {}
}
}
Some(skip_gap(text, after, is_gap))
}
}
}
fn follows_rocket(before: &str) -> bool {
before
.trim_end_matches(|c| is_gap(c) || is_closing_quote(c))
.ends_with("=>")
}
fn separator_len(bytes: &[u8], at: usize, separator: Separator) -> Option<usize> {
let rest = bytes.get(at..)?;
match separator {
Separator::Colon => match rest {
[b':', ..] => Some(1),
[0xEF, 0xBC, 0x9A, ..]
| [0xEF, 0xB9, 0x95, ..]
| [0xEF, 0xB8, 0x93, ..]
| [b'%', b'3', b'A' | b'a', ..] => Some(3),
_ => None,
},
Separator::Equals => match rest {
[b'=', ..] => Some(1),
[0xEF, 0xBC, 0x9D, ..] | [0xEF, 0xB9, 0xA6, ..] | [b'%', b'3', b'D' | b'd', ..] => {
Some(3)
}
_ => None,
},
}
}
fn trim_gap_end(text: &str, gap: fn(char) -> bool) -> &str {
let mut rest = text;
loop {
let trimmed = rest.trim_end_matches(gap);
let sgr = sgr_before(trimmed);
if sgr == 0 {
return trimmed;
}
rest = &trimmed[..trimmed.len() - sgr];
}
}
fn skip_gap(text: &str, from: usize, gap: fn(char) -> bool) -> usize {
let mut at = from;
loop {
at = scan_until(text, at, |c| !gap(c));
let sgr = sgr_len(&text[at..]);
if sgr == 0 {
return at;
}
at += sgr;
}
}
fn key_len(before: &str) -> usize {
let mut rest = before;
loop {
let escape = escape_before(rest).max(sgr_before(rest));
if escape > 0 {
rest = &rest[..rest.len() - escape];
} else if let Some(c) = rest.chars().next_back().filter(|&c| is_key_char(c)) {
rest = &rest[..rest.len() - c.len_utf8()];
} else {
return before.len() - rest.len();
}
}
}
fn quoted_end(text: &str, from: usize, multiline: bool) -> Option<usize> {
let quote = char::from(text.as_bytes()[from]);
let mut chars = text[from + 1..].char_indices();
while let Some((i, c)) = chars.next() {
match c {
'\\' => match chars.next() {
Some((_, '\n')) if !multiline => return None,
Some(_) => {}
None => return None,
},
'\n' if !multiline => return None,
c if c == quote => return Some(from + 1 + i + 1),
_ => {}
}
}
None
}
fn plain_quoted_end(text: &str, from: usize, multiline: bool) -> Option<usize> {
let quote = char::from(text.as_bytes()[from]);
let rest = &text[from + 1..];
let close = if multiline {
rest.find(quote)
} else {
rest.find([quote, '\n'])
}?;
(rest.as_bytes()[close] != b'\n').then_some(from + 1 + close + 1)
}
fn quoted_value_end(text: &str, from: usize, multiline: bool) -> Option<usize> {
quoted_end(text, from, multiline).or_else(|| plain_quoted_end(text, from, multiline))
}
fn last_closable(text: &str, quote: u8) -> Option<usize> {
let bytes = text.as_bytes();
let mut end = bytes.len();
while let Some(at) = bytes[..end].iter().rposition(|&b| b == quote) {
let escapes = bytes[..at]
.iter()
.rev()
.take_while(|&&b| b == b'\\')
.count();
if escapes.is_multiple_of(2) {
return Some(at);
}
end = at;
}
None
}
fn digit_group_ends(text: &str, from: usize, stop: fn(char) -> bool) -> Vec<usize> {
let bytes = text.as_bytes();
let mut ends = vec![from];
let mut at = from;
while let Some(blank) = text[at..].chars().next().filter(|&c| is_blank(c)) {
let mut next = at + blank.len_utf8();
if matches!(bytes.get(next), Some(b'(' | b'+')) {
next += 1;
}
let Some(digit) = text[next..].chars().next().filter(|c| c.is_numeric()) else {
break;
};
at = scan_until(text, next + digit.len_utf8(), stop);
ends.push(at);
}
ends
}
fn ends_colon_value(c: char) -> bool {
is_space(c) || matches!(c, ',' | '"' | '}')
}
fn ends_equals_value(c: char) -> bool {
is_space(c) || c == '&'
}
fn unquoted_colon_end(text: &str, from: usize) -> Option<usize> {
let run_end = scan_until(text, from, ends_colon_value);
let clean_end = |at: usize| {
text[at..]
.chars()
.next()
.is_none_or(|c| is_space(c) || matches!(c, ',' | '}'))
};
(run_end > from)
.then(|| {
digit_group_ends(text, run_end, ends_colon_value)
.into_iter()
.rev()
.find(|&end| clean_end(end))
})
.flatten()
}
fn unquoted_equals_end(text: &str, from: usize) -> usize {
let run_end = scan_until(text, from, ends_equals_value);
digit_group_ends(text, run_end, ends_equals_value)
.last()
.copied()
.unwrap_or(run_end)
}
fn json_escaped(mask: &str) -> Cow<'_, str> {
if !mask.chars().any(|c| matches!(c, '"' | '\\') || c < ' ') {
return Cow::Borrowed(mask);
}
let mut out = String::with_capacity(mask.len() + 8);
for c in mask.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c < ' ' => {
let _ = write!(out, "\\u{:04x}", u32::from(c));
}
c => out.push(c),
}
}
Cow::Owned(out)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Cover {
Mask,
QuotedMask,
Cut,
}
impl Cover {
fn len(self, mask: &str) -> usize {
match self {
Self::Mask => mask.len(),
Self::QuotedMask => json_escaped(mask).len() + 2,
Self::Cut => 0,
}
}
}
#[derive(Debug, Clone, Copy)]
struct Span {
start: usize,
end: usize,
cover: Cover,
}
#[derive(Debug, Clone, Copy)]
struct Read {
end: Option<usize>,
cover: Cover,
reach: usize,
}
impl Read {
const fn whole(end: usize, cover: Cover) -> Self {
Self {
end: Some(end),
cover,
reach: end,
}
}
}
struct Values<'a> {
text: &'a str,
line_end: Option<usize>,
closable: Option<[Option<usize>; 2]>,
}
impl<'a> Values<'a> {
const fn new(text: &'a str) -> Self {
Self {
text,
line_end: None,
closable: None,
}
}
fn colon(&mut self, from: usize, header: bool) -> Read {
let text = self.text;
match text.as_bytes().get(from) {
Some(b'"') => match quoted_value_end(text, from, true) {
Some(end) => Read::whole(end, Cover::QuotedMask),
None => Read {
end: None,
cover: Cover::QuotedMask,
reach: self.text_end(),
},
},
Some(b'\'') => match quoted_value_end(text, from, false) {
Some(end) => Read::whole(end, Cover::Mask),
None => Read {
end: unquoted_colon_end(text, from),
cover: Cover::Mask,
reach: self.line(from),
},
},
_ if opens_typographic_quote(text, from) => match typographic_end(text, from) {
Some(end) => Read::whole(end, Cover::Mask),
None => Read {
end: unquoted_colon_end(text, from),
cover: Cover::Mask,
reach: self.line(from),
},
},
_ => self.unquoted(
from,
unquoted_colon_end(text, from),
header,
Separator::Colon,
),
}
}
fn equals(&mut self, from: usize, header: bool) -> Read {
let text = self.text;
let opens_typographic = opens_typographic_quote(text, from);
if matches!(text.as_bytes().get(from), Some(b'"' | b'\'')) || opens_typographic {
let closed = if opens_typographic {
typographic_end(text, from)
} else {
quoted_value_end(text, from, false)
};
return match closed {
Some(end) => Read::whole(end, Cover::Mask),
None => Read {
end: Some(unquoted_equals_end(text, from)),
cover: Cover::Mask,
reach: self.line(from),
},
};
}
self.unquoted(
from,
Some(unquoted_equals_end(text, from)),
header,
Separator::Equals,
)
}
fn unquoted(
&mut self,
from: usize,
end: Option<usize>,
header: bool,
separator: Separator,
) -> Read {
let (wrapped, reach) = self.wrapper(from);
let mut end = end.max(wrapped);
if reach.is_none()
&& let Some(scheme_end) = end.filter(|&scheme_end| scheme_end > from)
&& (header || is_auth_scheme(&self.text[from..scheme_end]))
{
end = Some(self.credentials(scheme_end, separator));
}
let low = end.unwrap_or(from);
Read {
end,
cover: Cover::Mask,
reach: reach.map_or(low, |reach| reach.max(low)),
}
}
fn wrapper(&mut self, from: usize) -> (Option<usize>, Option<usize>) {
let text = self.text;
let bytes = text.as_bytes();
let name_end = from
+ text[from..]
.chars()
.take_while(|&c| c.is_alphanumeric() || c == '_')
.map(char::len_utf8)
.sum::<usize>();
if name_end == from || bytes.get(name_end) != Some(&b'(') {
return (None, None);
}
let never = (None, Some(self.text_end()));
let mut limit = text.len().min(from + MAX_WRAPPER_LEN);
while !text.is_char_boundary(limit) {
limit -= 1;
}
let window = &text[..limit];
let mut escaped = false;
let mut depth = 0usize;
let mut at = name_end;
while at < limit {
match bytes[at] {
b'(' => depth += 1,
b')' => {
depth -= 1;
if depth == 0 {
let end = at + 1;
let digit = text[from..].chars().next().is_some_and(char::is_numeric);
let replaced = !(escaped || digit);
return (replaced.then_some(end), Some(end));
}
}
quote @ (b'"' | b'\'') => {
let close = if self.closes_after(at) {
quoted_end(window, at, true)
} else {
escaped = true;
window[at + 1..]
.find(char::from(quote))
.map(|i| at + 1 + i + 1)
};
let Some(close) = close else {
return never;
};
at = close - 1;
}
_ => {}
}
at += 1;
}
never
}
fn credentials(&mut self, scheme_end: usize, separator: Separator) -> usize {
let text = self.text;
let blanks_end = |from: usize| scan_until(text, from, |c| !is_blank(c));
let mut at = blanks_end(scheme_end);
if at == scheme_end {
return scheme_end;
}
let mut end = scheme_end;
loop {
let item_end = self.credential_item(at, separator);
if item_end == at {
return end;
}
end = item_end;
let comma = blanks_end(end);
if text.as_bytes().get(comma) != Some(&b',') {
return end;
}
at = blanks_end(comma + 1);
}
}
fn credential_item(&mut self, from: usize, separator: Separator) -> usize {
let text = self.text;
let bytes = text.as_bytes();
let ends_at_ampersand = separator == Separator::Equals;
let mut at = from;
while let Some(c) = text[at..].chars().next() {
if c == '"' && (at == from || bytes[at - 1] == b'=') {
match quoted_value_end(text, at, false) {
Some(close) => at = close,
None => return self.line(at),
}
} else if is_space(c) || matches!(c, ',' | '}' | '"') || (c == '&' && ends_at_ampersand)
{
break;
} else {
at += c.len_utf8();
}
}
at
}
fn closes_after(&mut self, at: usize) -> bool {
let text = self.text;
let closable = *self
.closable
.get_or_insert_with(|| [last_closable(text, b'"'), last_closable(text, b'\'')]);
let kind = usize::from(text.as_bytes()[at] == b'\'');
closable[kind].is_some_and(|last| last > at)
}
fn text_end(&self) -> usize {
self.text
.strip_suffix('\n')
.map_or(self.text.len(), str::len)
}
fn line(&mut self, from: usize) -> usize {
if let Some(end) = self.line_end
&& from <= end
{
return end;
}
let end = self.text[from..]
.find('\n')
.map_or(self.text.len(), |i| from + i);
self.line_end = Some(end);
end
}
}
fn pair_spans(
text: &str,
separator: Separator,
matcher: &CredentialMatcher,
mask: &str,
spellings: &mut Spellings,
) -> (Vec<Span>, Vec<Span>) {
let mut values = Values::new(text);
let mut spans = Vec::new();
let mut runs = Vec::new();
let mut copied = 0;
let mut from = 0;
while let Some(head) = next_head(text, from, separator) {
from = head.end;
let key = &text[head.start..head.key_end];
let found = matcher.name_match(key, "", spellings);
if head.start < copied || found == NameMatch::None {
continue;
}
if let Some(end) = mask_end(text, head.end, mask) {
from = end;
continue;
}
if separator == Separator::Equals && is_sudo_cwd(text, &head) {
continue;
}
let header = names_authorization(key);
let read = match separator {
Separator::Colon => values.colon(head.end, header),
Separator::Equals => values.equals(head.end, header),
};
if found == NameMatch::Plural
&& read
.end
.is_some_and(|end| is_number(&text.as_bytes()[head.end..end]))
{
continue;
}
let low = read.end.unwrap_or(head.end);
if let Some(end) = read.end {
spans.push(Span {
start: head.end,
end,
cover: read.cover,
});
copied = end;
}
if read.reach > low {
let cover = if read.end.is_some() {
Cover::Cut
} else {
read.cover
};
runs.push(Span {
start: low,
end: read.reach,
cover,
});
}
}
(spans, runs)
}
fn placed_after(runs: Vec<Span>, spans: &[Span], mask: &str) -> Vec<Span> {
let mut cover_ends = Vec::with_capacity(spans.len());
let mut written = 0;
let mut copied = 0;
for span in spans {
written += span.start - copied + span.cover.len(mask);
cover_ends.push(written);
copied = span.end;
}
let place = |at: usize| {
let Some(index) = spans
.partition_point(|span| span.start <= at)
.checked_sub(1)
else {
return at;
};
let span = spans[index];
if at >= span.end {
cover_ends[index] + (at - span.end)
} else if at > span.start {
cover_ends[index]
} else {
cover_ends[index] - span.cover.len(mask)
}
};
runs.into_iter()
.map(|run| Span {
start: place(run.start),
end: place(run.end),
cover: run.cover,
})
.collect()
}
fn apply<'a>(text: &'a str, mut spans: Vec<Span>, mask: &str, n: &mut usize) -> Cow<'a, str> {
if spans.is_empty() {
return Cow::Borrowed(text);
}
spans.sort_by_key(|span| (span.start, span.cover == Cover::Cut));
let mut out = String::with_capacity(text.len());
let mut copied = 0;
let mut spans = spans.into_iter().peekable();
while let Some(first) = spans.next() {
let mut end = first.end;
while let Some(next) = spans.next_if(|next| next.start <= end) {
end = end.max(next.end);
}
out.push_str(&text[copied..first.start]);
match first.cover {
Cover::Mask => out.push_str(mask),
Cover::QuotedMask => {
out.push('"');
out.push_str(&json_escaped(mask));
out.push('"');
}
Cover::Cut => {}
}
if first.cover != Cover::Cut {
*n += 1;
}
copied = end;
}
out.push_str(&text[copied..]);
Cow::Owned(out)
}
fn mask_pairs<'a>(
text: &'a str,
matcher: &CredentialMatcher,
mask: &str,
spellings: &mut Spellings,
n: &mut usize,
) -> Cow<'a, str> {
let bytes = text.as_bytes();
let separated = memchr::memchr3(b':', b'=', b'%', bytes).is_some()
|| (!spellings.plain() && memchr::memchr(0xEF, bytes).is_some());
if !separated || !matcher.may_name_in(text, spellings.plain()) {
return Cow::Borrowed(text);
}
let (spans, runs) = pair_spans(text, Separator::Colon, matcher, mask, spellings);
let runs = placed_after(runs, &spans, mask);
let colon_masked = apply(text, spans, mask, n);
let (mut spans, more) = pair_spans(&colon_masked, Separator::Equals, matcher, mask, spellings);
spans.extend(more);
spans.extend(runs);
then(colon_masked, |t| apply(t, spans, mask, n))
}
pub fn mask_text<'a>(text: &'a str, matcher: &CredentialMatcher, mask: &str) -> Cow<'a, str> {
mask_text_in(text, matcher, mask, &mut Spellings::default()).0
}
pub fn mask_text_in<'a>(
text: &'a str,
matcher: &CredentialMatcher,
mask: &str,
spellings: &mut Spellings,
) -> (Cow<'a, str>, usize) {
let mut n = 0;
let text = url_masked(text, mask, true, &mut n);
let text = then(text, |t| mask_query_signatures(t, mask, &mut n));
let text = then(text, |t| mask_refused_headers(t, mask, &mut n));
let text = then(text, |t| mask_bearer(t, mask, &mut n));
let text = then(text, |t| mask_pairs(t, matcher, mask, spellings, &mut n));
(text, n)
}
pub(crate) fn may_mask(text: &[u8], plain: bool) -> bool {
let bearer = "bearer ".len() < text.len() && memchr::memchr2(b'b', b'B', text).is_some();
let refused = REFUSED_HEADER.len() < text.len() && memchr::memchr2(b'v', b'V', text).is_some();
bearer
|| refused
|| memchr::memchr3(b':', b'=', b'?', text).is_some()
|| if plain {
memchr::memchr2(b'&', b'%', text).is_some()
} else {
memchr::memchr3(b'&', b'%', 0xEF, text).is_some()
}
}
#[cfg(test)]
thread_local! {
static PLAIN_OFF: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
#[cfg(test)]
pub(crate) fn plain_forced_off() -> bool {
PLAIN_OFF.get()
}
#[cfg(all(test, feature = "record"))]
pub(crate) fn with_plain_off<T>(run: impl FnOnce() -> T) -> T {
struct Restore;
impl Drop for Restore {
fn drop(&mut self) {
PLAIN_OFF.set(false);
}
}
let _restore = Restore;
PLAIN_OFF.set(true);
run()
}
const SHORT: usize = 64;
pub(crate) fn is_plain(text: &[u8]) -> bool {
#[cfg(test)]
if plain_forced_off() {
return false;
}
if text.len() >= SHORT {
return text.is_ascii() && memchr::memchr2(b'\\', 0x1b, text).is_none();
}
let (chunks, rest) = text.as_chunks::<8>();
let whole = chunks
.iter()
.all(|&chunk| plain_word(u64::from_le_bytes(chunk)));
let mut tail = [b' '; 8];
tail[..rest.len()].copy_from_slice(rest);
whole && plain_word(u64::from_le_bytes(tail))
}
const fn plain_word(word: u64) -> bool {
const ONES: u64 = 0x0101_0101_0101_0101;
const HIGH: u64 = 0x8080_8080_8080_8080;
const fn none_equal(word: u64, byte: u8) -> bool {
let x = word ^ (ONES * byte as u64);
x.wrapping_sub(ONES) & !x & HIGH == 0
}
word & HIGH == 0 && none_equal(word, b'\\') && none_equal(word, 0x1b)
}
fn then(text: Cow<'_, str>, step: impl FnOnce(&str) -> Cow<'_, str>) -> Cow<'_, str> {
let changed = match step(&text) {
Cow::Borrowed(_) => None,
Cow::Owned(masked) => Some(masked),
};
changed.map_or(text, Cow::Owned)
}
fn finish(text: &str, out: Option<String>, copied: usize) -> Cow<'_, str> {
match out {
None => Cow::Borrowed(text),
Some(mut buf) => {
buf.push_str(&text[copied..]);
Cow::Owned(buf)
}
}
}
#[cfg(test)]
mod tests;