#![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::sync::LazyLock;
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(|| CredentialMatcher::new(SENSITIVE_FIELDS));
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>>,
}
impl CredentialMatcher {
pub fn new<I, S>(terms: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut buf = String::new();
let mut terms: Vec<String> = terms
.into_iter()
.map(|term| {
joined_words_into(term.as_ref(), &mut buf);
buf.replace('_', "")
})
.filter(|term| !term.is_empty())
.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);
}
}
Self { terms, by_last }
}
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 {
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.bytes().all(|b| b.is_ascii_digit()) {
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()));
!whole.is_empty()
&& whole.iter().all(u8::is_ascii_digit)
&& (fraction.is_empty()
|| (fraction.len() > 1 && fraction[1..].iter().all(u8::is_ascii_digit)))
}
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,
}
impl Spellings {
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) {
out.clear();
let bytes = name.as_bytes();
let mut start = 0;
while start < bytes.len() {
let end = word_end(bytes, start);
if end == start {
start += 1;
continue;
}
if !out.is_empty() {
out.push('_');
}
out.extend(
bytes[start..end]
.iter()
.map(|b| char::from(b.to_ascii_lowercase())),
);
start = end;
}
}
fn word_end(bytes: &[u8], start: usize) -> usize {
let run = |from: usize, class: fn(&u8) -> bool| {
from + bytes[from..].iter().take_while(|&b| class(b)).count()
};
let first = bytes[start];
if first.is_ascii_uppercase() {
let upper_end = run(start, u8::is_ascii_uppercase);
if bytes.get(upper_end).is_some_and(u8::is_ascii_lowercase) {
if upper_end - start >= 2 {
return upper_end - 1;
}
return run(upper_end, u8::is_ascii_lowercase);
}
return upper_end;
}
if first.is_ascii_lowercase() {
return run(start, u8::is_ascii_lowercase);
}
if first.is_ascii_digit() {
return run(start, u8::is_ascii_digit);
}
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 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 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(found) = text[from..].find("://") {
let head = from + found;
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 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, '&' | '"' | '\'')
});
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;
from = 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,
}
};
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;
from = 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;
}
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;
from = 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,
}
const fn is_key_byte(b: u8) -> bool {
b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-')
}
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::memchr(byte, &bytes[search..]) {
let at = search + found;
search = at + 1;
let before = &text[from..at];
let spaced = match separator {
Separator::Colon => before.trim_end_matches(is_space),
Separator::Equals => before.trim_end_matches([' ', '\t']),
};
let quoted = matches!(spaced.as_bytes().last(), Some(b'"' | b'\''));
let key_end = from + spaced.len() - usize::from(quoted);
let key = bytes[from..key_end]
.iter()
.rev()
.take_while(|&&b| is_key_byte(b))
.count();
let start = key_end - key;
if key == 0 || (start > 0 && is_key_byte(bytes[start - 1])) {
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 matches!(bytes.get(at), Some(b'"' | b'\'')) {
at += 1;
}
match separator {
Separator::Colon => {
at = scan_until(text, at, |c| !is_space(c));
if bytes.get(at) != Some(&b':') {
return None;
}
if start >= 2 && &bytes[start - 2..start] == b"::" {
return None;
}
if bytes.get(at + 1) == Some(&b':') {
at += 1;
}
Some(scan_until(text, at + 1, |c| !is_space(c)))
}
Separator::Equals => {
at = scan_until(text, at, |c| !matches!(c, ' ' | '\t'));
if bytes.get(at) != Some(&b'=') || matches!(bytes.get(at + 1), Some(b'=' | b'>')) {
return None;
}
Some(scan_until(text, at + 1, |c| !matches!(c, ' ' | '\t')))
}
}
}
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;
loop {
if bytes.get(at) != Some(&b' ') {
break;
}
let mut next = at + 1;
if matches!(bytes.get(next), Some(b'(' | b'+')) {
next += 1;
}
if !bytes.get(next).is_some_and(u8::is_ascii_digit) {
break;
}
at = scan_until(text, next + 1, 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)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Cover {
Mask,
QuotedMask,
Cut,
}
impl Cover {
const fn len(self, mask: &str) -> usize {
match self {
Self::Mask => mask.len(),
Self::QuotedMask => 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),
},
},
_ => self.unquoted(
from,
unquoted_colon_end(text, from),
header,
Separator::Colon,
),
}
}
fn equals(&mut self, from: usize, header: bool) -> Read {
let text = self.text;
if matches!(text.as_bytes().get(from), Some(b'"' | b'\'')) {
return match quoted_value_end(text, from, false) {
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
+ bytes[from..]
.iter()
.take_while(|b| b.is_ascii_alphanumeric() || **b == b'_')
.count();
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 replaced = !(escaped || bytes[from].is_ascii_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| !matches!(c, ' ' | '\t'));
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,
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;
}
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(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 (spans, runs) = pair_spans(text, Separator::Colon, matcher, 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, 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)
}
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;