pub(super) fn is_js_whitespace(ch: char) -> bool {
ch.is_whitespace() || ch == '\u{FEFF}'
}
pub(super) fn is_js_line_terminator(ch: char) -> bool {
matches!(ch, '\n' | '\r' | '\u{2028}' | '\u{2029}')
}
pub(super) fn is_horizontal_js_whitespace(ch: char) -> bool {
is_js_whitespace(ch) && !is_js_line_terminator(ch)
}
pub(super) fn char_at(input: &str, pos: usize) -> Option<char> {
input.get(pos..)?.chars().next()
}
pub(super) fn prev_char(input: &str, pos: usize) -> Option<char> {
input.get(..pos)?.chars().next_back()
}
pub(super) fn is_line_start(input: &str, pos: usize) -> bool {
pos == 0 || prev_char(input, pos).is_some_and(is_js_line_terminator)
}
pub(super) fn line_end_from(bytes: &[u8], start: usize) -> (usize, usize) {
let mut at = start;
while at < bytes.len() {
match bytes[at] {
b'\n' => return (at, at + 1),
b'\r' if bytes.get(at + 1).is_some_and(|&next| next != b'\n') => {
return (at + 1, at + 1);
}
_ => at += 1,
}
}
(bytes.len(), bytes.len() + 1)
}
pub(super) fn lines(input: &str) -> impl Iterator<Item = (usize, usize)> + '_ {
let bytes = input.as_bytes();
let mut start = 0usize;
std::iter::from_fn(move || {
if start > bytes.len() {
return None;
}
let at = next_line_byte(bytes, start);
let (end, next) = match (bytes.get(at), bytes.get(at + 1)) {
(Some(b'\n'), _) => (at, at + 1),
(Some(_), Some(b'\n')) => (at + 1, at + 2),
(Some(_), Some(_)) => (at + 1, at + 1),
(Some(_), None) | (None, _) => (bytes.len(), bytes.len() + 1),
};
let line = (start, end);
start = next;
Some(line)
})
}
fn next_line_byte(bytes: &[u8], from: usize) -> usize {
const ONES: u64 = u64::from_le_bytes([0x01; 8]);
const HIGHS: u64 = u64::from_le_bytes([0x80; 8]);
const NEWLINES: u64 = u64::from_le_bytes([b'\n'; 8]);
const RETURNS: u64 = u64::from_le_bytes([b'\r'; 8]);
let mut at = from;
while let Some(chunk) = bytes.get(at..at + 8) {
let mut word = [0u8; 8];
word.copy_from_slice(chunk);
let word = u64::from_le_bytes(word);
let newline = word ^ NEWLINES;
let carriage_return = word ^ RETURNS;
let found = ((newline.wrapping_sub(ONES) & !newline)
| (carriage_return.wrapping_sub(ONES) & !carriage_return))
& HIGHS;
if found != 0 {
return at + (found.trailing_zeros() / 8) as usize;
}
at += 8;
}
bytes[at.min(bytes.len())..]
.iter()
.position(|&byte| byte == b'\n' || byte == b'\r')
.map_or(bytes.len(), |offset| at + offset)
}
pub(super) fn line_around(input: &str, start: usize, end: usize) -> (usize, usize) {
let bytes = input.as_bytes();
let line_start = if start > 0 && bytes[start - 1] == b'\r' && bytes.get(start) != Some(&b'\n') {
start
} else {
line_start_before(input, start)
};
(line_start, line_end_from(bytes, end).0)
}
pub(super) fn line_start_before(input: &str, end: usize) -> usize {
let head = &input[..end];
let after_newline = head.rfind('\n').map_or(0, |at| at + 1);
let line = &input[after_newline..end];
let line = line.strip_suffix('\r').unwrap_or(line);
line.rfind('\r')
.map_or(after_newline, |offset| after_newline + offset + 1)
}
#[cfg(test)]
pub(super) fn last_lines(input: &str, count: usize) -> Vec<&str> {
let complete = input.strip_suffix('\n').unwrap_or(input);
let bytes = complete.as_bytes();
let mut tail = Vec::with_capacity(count);
let mut end = bytes.len();
while tail.len() < count {
let start = line_start_before(complete, end);
tail.push(&complete[start..end]);
if start == 0 {
break;
}
end = if bytes[start - 1] == b'\n' {
start - 1
} else {
start
};
}
tail.reverse();
tail
}
pub(super) fn tail_lines<'t, 'a>(tail: &'t [&'a str], count: usize) -> &'t [&'a str] {
&tail[tail.len().saturating_sub(count)..]
}
pub(super) fn skip_while_chars(input: &str, start: usize, pred: fn(char) -> bool) -> usize {
let mut cursor = start;
while let Some(ch) = char_at(input, cursor) {
if pred(ch) {
cursor += ch.len_utf8();
} else {
break;
}
}
cursor
}
pub(super) fn rskip_while_chars(input: &str, end: usize, pred: fn(char) -> bool) -> usize {
let mut cursor = end;
while let Some(ch) = prev_char(input, cursor) {
if pred(ch) {
cursor -= ch.len_utf8();
} else {
break;
}
}
cursor
}
pub(super) fn ascii_run_len(bytes: &[u8], start: usize, pred: fn(u8) -> bool) -> usize {
let mut end = start;
while end < bytes.len() && pred(bytes[end]) {
end += 1;
}
end - start
}
pub(super) fn starts_with_ci(input: &str, pos: usize, literal: &str) -> bool {
let literal = literal.as_bytes();
input
.as_bytes()
.get(pos..pos + literal.len())
.is_some_and(|window| window.eq_ignore_ascii_case(literal))
}
pub(super) fn find_ci(bytes: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
const ONES: u64 = u64::from_le_bytes([0x01; 8]);
const HIGHS: u64 = u64::from_le_bytes([0x80; 8]);
let Some(&first) = needle.first() else {
return (from <= bytes.len()).then_some(from);
};
let last_start = bytes.len().checked_sub(needle.len())?;
let lower = first.to_ascii_lowercase();
let upper = first.to_ascii_uppercase();
let lower_word = u64::from_le_bytes([lower; 8]);
let upper_word = u64::from_le_bytes([upper; 8]);
let mut at = from;
while at <= last_start {
let mut found = None;
while at <= last_start {
if let Some(chunk) = bytes.get(at..at + 8) {
let mut word = [0u8; 8];
word.copy_from_slice(chunk);
let word = u64::from_le_bytes(word);
let lo = word ^ lower_word;
let up = word ^ upper_word;
let marks = ((lo.wrapping_sub(ONES) & !lo) | (up.wrapping_sub(ONES) & !up)) & HIGHS;
if marks == 0 {
at += 8;
continue;
}
at += (marks.trailing_zeros() / 8) as usize;
found = Some(at);
break;
}
if bytes[at] == lower || bytes[at] == upper {
found = Some(at);
break;
}
at += 1;
}
let candidate = found?;
if candidate > last_start {
return None;
}
if bytes[candidate..candidate + needle.len()].eq_ignore_ascii_case(needle) {
return Some(candidate);
}
at = candidate + 1;
}
None
}
pub(super) fn contains_ci(haystack: &str, needle: &str) -> bool {
find_ci(haystack.as_bytes(), 0, needle.as_bytes()).is_some()
}
pub(super) fn ends_with_ci(value: &str, suffix: &str) -> bool {
let bytes = value.as_bytes();
let suffix = suffix.as_bytes();
bytes.len() >= suffix.len() && bytes[bytes.len() - suffix.len()..].eq_ignore_ascii_case(suffix)
}
pub(super) fn matches_placeholder_vocabulary(
value: &str,
exact_words: &[&str],
digit_suffix_words: &[&str],
) -> bool {
fn strip_trailing_digits(token: &str) -> &str {
token.trim_end_matches(|ch: char| ch.is_ascii_digit())
}
let is_listed =
|token: &str, words: &[&str]| words.iter().any(|word| token.eq_ignore_ascii_case(word));
let token_is_placeholder = |token: &str| {
is_listed(token, exact_words) || {
let core = strip_trailing_digits(token);
core.len() < token.len() && is_listed(core, digit_suffix_words)
}
};
let tokens = || {
value
.split(|ch: char| !ch.is_ascii_alphanumeric())
.filter(|token| !token.is_empty())
};
let joined_len: usize = tokens().map(str::len).sum();
if joined_len == 0 {
return false;
}
let joined_is_listed = exact_words.iter().any(|word| {
word.len() == joined_len
&& word
.bytes()
.zip(tokens().flat_map(str::bytes))
.all(|(a, b)| a.eq_ignore_ascii_case(&b))
});
joined_is_listed || tokens().all(token_is_placeholder)
}
pub(super) fn is_repeated_character_filler(value: &str) -> bool {
let mut chars = value.chars();
let Some(first) = chars.next() else {
return false;
};
let mut count = 1usize;
for ch in chars {
if ch != first {
return false;
}
count += 1;
}
count >= 3
}
const PLACEHOLDER_LEAD_WORDS: &[&str] = &["your", "insert", "enter", "paste", "replace"];
const PLACEHOLDER_CREDENTIAL_WORDS: &[&str] = &[
"access",
"account",
"admin",
"api",
"app",
"auth",
"bearer",
"bot",
"client",
"deploy",
"id",
"integration",
"internal",
"jwt",
"key",
"oauth",
"oauth2",
"org",
"personal",
"project",
"refresh",
"secret",
"service",
"session",
"signing",
"token",
"user",
"webhook",
"here",
"with",
];
const PLACEHOLDER_PROVIDER_WORDS: &[&str] = &[
"ai",
"ai21",
"anthropic",
"cohere",
"convex",
"deepgram",
"deepseek",
"elevenlabs",
"exa",
"fal",
"figma",
"fireworks",
"gemini",
"groq",
"huggingface",
"mistral",
"openai",
"openrouter",
"perplexity",
"replicate",
"tavily",
"together",
"xai",
];
const PLACEHOLDER_PASSWORD_WORDS: &[&str] = &["password", "passwd", "pwd", "passphrase"];
const PLACEHOLDER_SERVICE_WORDS: &[&str] = &[
"adobe",
"airtable",
"asana",
"atlas",
"box",
"canva",
"contentful",
"database",
"db",
"dropbox",
"elastic",
"hubspot",
"instagram",
"jfrog",
"meta",
"mongodb",
"private",
"salesforce",
"spotify",
"zendesk",
"zoom",
];
pub(super) fn is_placeholder_credential_word(word: &str) -> bool {
PLACEHOLDER_CREDENTIAL_WORDS
.iter()
.any(|listed| word.eq_ignore_ascii_case(listed))
}
const PLACEHOLDER_CREDENTIAL_NOUNS: &[&str] = &["jwt", "key", "secret", "token"];
fn is_placeholder_provider_word(word: &str) -> bool {
PLACEHOLDER_PROVIDER_WORDS
.iter()
.chain(super::generic_token::DEDICATED_PROVIDER_SEGMENTS)
.any(|listed| word.eq_ignore_ascii_case(listed))
}
pub(super) fn is_glued_instructional_placeholder(value: &str) -> bool {
if value.len() > GLUED_PLACEHOLDER_STACK_BOUND {
return is_glued_instructional_placeholder_heap(value);
}
if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_alphabetic()) {
return false;
}
let bytes = value.as_bytes();
let Some(lead) = PLACEHOLDER_LEAD_WORDS
.iter()
.find(|lead| starts_with_ascii_ci(bytes, lead.as_bytes()))
else {
return false;
};
glued_placeholder_split(&bytes[lead.len()..])
}
fn glued_placeholder_split(rest: &[u8]) -> bool {
let len = rest.len();
debug_assert!(len <= GLUED_PLACEHOLDER_STACK_BOUND);
let mut reachable = [false; GLUED_PLACEHOLDER_STACK_BOUND + 1];
let mut with_noun = [false; GLUED_PLACEHOLDER_STACK_BOUND + 1];
reachable[0] = true;
for start in 0..len {
if !reachable[start] {
continue;
}
for word in glued_placeholder_words() {
if starts_with_ascii_ci(&rest[start..], word.as_bytes()) {
let end = start + word.len();
reachable[end] = true;
with_noun[end] |= with_noun[start] || PLACEHOLDER_CREDENTIAL_NOUNS.contains(word);
}
}
}
len > 0 && reachable[len] && with_noun[len]
}
const GLUED_PLACEHOLDER_STACK_BOUND: usize = 256;
fn starts_with_ascii_ci(haystack: &[u8], prefix: &[u8]) -> bool {
haystack.len() >= prefix.len() && haystack[..prefix.len()].eq_ignore_ascii_case(prefix)
}
fn glued_placeholder_words() -> impl Iterator<Item = &'static &'static str> {
PLACEHOLDER_CREDENTIAL_WORDS
.iter()
.chain(PLACEHOLDER_PROVIDER_WORDS)
.chain(super::generic_token::DEDICATED_PROVIDER_SEGMENTS)
.chain(PLACEHOLDER_LEAD_WORDS)
}
fn is_glued_instructional_placeholder_heap(value: &str) -> bool {
if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_alphabetic()) {
return false;
}
let lower = value.to_ascii_lowercase();
let Some(rest) = PLACEHOLDER_LEAD_WORDS
.iter()
.find_map(|lead| lower.strip_prefix(lead))
else {
return false;
};
let words = || {
PLACEHOLDER_CREDENTIAL_WORDS
.iter()
.chain(PLACEHOLDER_PROVIDER_WORDS)
.chain(super::generic_token::DEDICATED_PROVIDER_SEGMENTS)
.chain(PLACEHOLDER_LEAD_WORDS)
};
let len = rest.len();
let mut reachable = vec![false; len + 1];
let mut with_noun = vec![false; len + 1];
reachable[0] = true;
for start in 0..len {
if !reachable[start] {
continue;
}
for word in words() {
if rest[start..].starts_with(word) {
let end = start + word.len();
reachable[end] = true;
with_noun[end] |= with_noun[start] || PLACEHOLDER_CREDENTIAL_NOUNS.contains(word);
}
}
}
len > 0 && reachable[len] && with_noun[len]
}
pub(super) fn is_lead_word_phrase_placeholder(value: &str) -> bool {
let one_case = |word: &str| {
!word.is_empty()
&& (word.bytes().all(|byte| byte.is_ascii_lowercase())
|| word.bytes().all(|byte| byte.is_ascii_uppercase()))
};
let listed =
|word: &str, words: &[&str]| words.iter().any(|listed| word.eq_ignore_ascii_case(listed));
let mut words = value.split(['_', '-']);
let Some(lead) = words.next() else {
return false;
};
if !one_case(lead) || !listed(lead, PLACEHOLDER_LEAD_WORDS) {
return false;
}
let mut later = 0usize;
let mut has_noun = false;
for word in words {
if !one_case(word) {
return false;
}
later += 1;
has_noun |= listed(word, PLACEHOLDER_CREDENTIAL_NOUNS);
}
later >= 1 && has_noun
}
pub(super) fn is_glued_my_placeholder(value: &str) -> bool {
let Some(rest) = value.strip_prefix("my") else {
return false;
};
if rest.is_empty() || !rest.bytes().all(|byte| byte.is_ascii_lowercase()) {
return false;
}
let len = rest.len();
let mut reached = vec![[[false; 2]; 2]; len + 1];
reached[0][0][0] = true;
for start in 0..len {
for word in PLACEHOLDER_CREDENTIAL_WORDS {
if !rest[start..].starts_with(word) {
continue;
}
let end = start + word.len();
let is_noun = PLACEHOLDER_CREDENTIAL_NOUNS.contains(word);
for many in 0..2 {
for noun in 0..2 {
if reached[start][many][noun] {
let next_many = usize::from(many == 1 || start > 0);
reached[end][next_many][usize::from(noun == 1 || is_noun)] = true;
}
}
}
}
}
reached[len][1][1]
}
pub(super) fn is_instructional_token_placeholder(value: &str) -> bool {
let is_listed =
|word: &str, words: &[&str]| words.iter().any(|listed| word.eq_ignore_ascii_case(listed));
let mut words = value.split(['_', '-', '.']);
let Some(lead) = words.next() else {
return false;
};
if !is_listed(lead, PLACEHOLDER_LEAD_WORDS) {
return false;
}
let mut saw_noun = false;
let mut count = 0usize;
for word in words {
if !is_listed(word, PLACEHOLDER_CREDENTIAL_WORDS)
&& !is_listed(word, PLACEHOLDER_PASSWORD_WORDS)
&& !is_listed(word, PLACEHOLDER_SERVICE_WORDS)
&& !is_listed(word, PLACEHOLDER_LEAD_WORDS)
&& !is_placeholder_provider_word(word)
{
return false;
}
saw_noun |= is_listed(word, PLACEHOLDER_CREDENTIAL_NOUNS)
|| is_listed(word, PLACEHOLDER_PASSWORD_WORDS);
count += 1;
}
count > 0 && saw_noun
}
const DIGEST_ALGORITHM_LABELS: &[&str] = &[
"md5", "sha1", "sha-1", "sha224", "sha-224", "sha256", "sha-256", "sha384", "sha-384",
"sha512", "sha-512", "sha3-256", "sha3-512", "blake2b", "blake2s", "blake3",
];
pub(super) fn starts_with_digest_label(value: &str) -> bool {
let bytes = value.as_bytes();
let rest = match bytes.split_at_checked("hmac-".len()) {
Some((head, rest)) if head.eq_ignore_ascii_case(b"hmac-") => rest,
_ => bytes,
};
DIGEST_ALGORITHM_LABELS.iter().any(|label| {
rest.split_at_checked(label.len())
.is_some_and(|(head, after)| {
head.eq_ignore_ascii_case(label.as_bytes())
&& matches!(after.first(), Some(b':' | b'='))
})
})
}
pub(super) fn is_labelled_digest(input: &str, start: usize) -> bool {
let bytes = input.as_bytes();
let mut cursor = start;
while cursor > 0 && matches!(bytes[cursor - 1], b' ' | b'\t') {
cursor -= 1;
}
if cursor == 0 || !matches!(bytes[cursor - 1], b'=' | b':') {
return false;
}
let label_end = cursor - 1;
DIGEST_ALGORITHM_LABELS.iter().any(|label| {
label_end >= label.len()
&& starts_with_ci(input, label_end - label.len(), label)
&& (label_end == label.len()
|| !bytes[label_end - label.len() - 1].is_ascii_alphanumeric())
})
}
pub(super) fn is_fully_delimited(value: &str, open: &str, close: &str) -> bool {
value.starts_with(open) && value.ends_with(close) && value.len() >= open.len() + close.len()
}
pub(super) fn is_template_reference(value: &str) -> bool {
is_fully_delimited(value, "{{", "}}")
}
pub(super) fn is_command_substitution_reference(value: &str) -> bool {
is_fully_delimited(value, "$(", ")")
}
pub(super) fn is_ruby_interpolation_reference(value: &str) -> bool {
is_fully_delimited(value, "#{", "}")
}
pub(super) const OPENCODE_REFERENCE_OPENERS: &[&str] = &["{env:", "{file:"];
pub(super) fn is_opencode_reference(value: &str) -> bool {
OPENCODE_REFERENCE_OPENERS
.iter()
.any(|open| is_fully_delimited(value, open, "}"))
}
pub(super) fn starts_with_bare_dollar_reference(value: &str) -> bool {
value.as_bytes().first() == Some(&b'$')
&& char_at(value, 1).is_some_and(|second| second.is_ascii_alphabetic() || second == '_')
}
pub(super) fn is_env_var_identifier(value: &str) -> bool {
let mut chars = value.chars();
match chars.next() {
Some(first) if first.is_ascii_alphabetic() || first == '_' => {}
_ => return false,
}
chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
}
pub(super) fn is_windows_env_reference(value: &str) -> bool {
value
.strip_prefix('%')
.and_then(|rest| rest.strip_suffix('%'))
.is_some_and(is_env_var_identifier)
}
const NON_CREDENTIAL_KEY_SEGMENTS: &[&str] = &[
"id", "ids", "uuid", "sid", "name", "url", "uri", "host", "hostname", "domain", "region",
"org", "site", "endpoint", "email", "user", "username", "account", "project", "version",
"slug", "commit", "sha", "branch", "tag", "number",
];
fn is_assignment_key_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-')
}
pub(super) fn assignment_key(line: &[u8], value_start: usize) -> Option<&[u8]> {
let mut end = value_start.min(line.len());
let mut has_operator = false;
while end > 0 && matches!(line[end - 1], b' ' | b'\t' | b'"' | b'\'' | b'=' | b':') {
has_operator |= matches!(line[end - 1], b'=' | b':');
end -= 1;
}
let mut start = end;
while start > 0 && is_assignment_key_byte(line[start - 1]) {
start -= 1;
}
(has_operator && start < end).then_some(&line[start..end])
}
pub(super) fn is_non_credential_assignment(line: &str, value_start: usize) -> bool {
assignment_key(line.as_bytes(), value_start)
.and_then(|key| std::str::from_utf8(key).ok())
.is_some_and(|key| {
super::generic_token::normalize_name(key)
.rsplit('_')
.next()
.is_some_and(|segment| NON_CREDENTIAL_KEY_SEGMENTS.contains(&segment))
})
}
pub(super) fn is_provider_named_assignment(
line: &str,
value_start: usize,
keywords: &[&str],
) -> bool {
let Some(key) = assignment_key(line.as_bytes(), value_start) else {
return false;
};
let Ok(key) = std::str::from_utf8(key) else {
return false;
};
let normalized = super::generic_token::normalize_name(key);
if normalized
.rsplit('_')
.next()
.is_some_and(|segment| NON_CREDENTIAL_KEY_SEGMENTS.contains(&segment))
{
return false;
}
if keywords.iter().any(|keyword| normalized.contains(keyword)) {
return true;
}
super::generic_token::is_high_signal_name(&normalized)
&& keywords.iter().any(|keyword| contains_ci(line, keyword))
}
const ENV_STORE_CALLEES: &[&str] = &["setdefault", "putenv", "setenv"];
const MAX_STORE_PREFIX: usize = 160;
pub(super) struct StorePrefix {
pub(super) name_start: usize,
pub(super) name_end: usize,
pub(super) value_start: usize,
pub(super) call: bool,
}
pub(super) fn keyed_store_prefix(input: &str, open: usize) -> Option<StorePrefix> {
let bytes = input.as_bytes();
let call = match bytes.get(open)? {
b'[' => {
let target = *bytes.get(open.checked_sub(1)?)?;
if !(target.is_ascii_alphanumeric() || matches!(target, b'_' | b')' | b']')) {
return None;
}
false
}
b'(' => {
let callee_end = open;
let callee_start = callee_end
- bytes[..callee_end]
.iter()
.rev()
.take_while(|&&byte| byte.is_ascii_alphanumeric() || byte == b'_')
.count();
if !ENV_STORE_CALLEES.contains(&&input[callee_start..callee_end]) {
return None;
}
true
}
_ => return None,
};
let horizontal = |byte: u8| matches!(byte, b' ' | b'\t');
let mut at = open + 1;
if call {
at += ascii_run_len(bytes, at, horizontal);
}
let quote = *bytes
.get(at)
.filter(|&&byte| matches!(byte, b'"' | b'\''))?;
at += 1;
let name_start = at;
if !bytes
.get(at)
.is_some_and(|&byte| byte.is_ascii_alphabetic() || byte == b'_')
{
return None;
}
at += ascii_run_len(bytes, at, |byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-')
});
let name_end = at;
if name_end - name_start > 128 || bytes.get(at) != Some("e) {
return None;
}
at += 1;
at += ascii_run_len(bytes, at, horizontal);
if call {
if bytes.get(at) != Some(&b',') {
return None;
}
at += 1;
} else {
if bytes.get(at) != Some(&b']') {
return None;
}
at += 1;
at += ascii_run_len(bytes, at, horizontal);
if bytes.get(at) != Some(&b'=') || bytes.get(at + 1) == Some(&b'=') {
return None;
}
at += 1;
}
at += ascii_run_len(bytes, at, horizontal);
Some(StorePrefix {
name_start,
name_end,
value_start: at,
call,
})
}
pub(super) fn keyed_store_name(line: &str, value_start: usize) -> Option<&str> {
let bytes = line.as_bytes();
let quote_at = value_start.checked_sub(1)?;
if !matches!(bytes.get(quote_at), Some(b'"' | b'\'')) {
return None;
}
let floor = quote_at.saturating_sub(MAX_STORE_PREFIX);
for open in (floor..quote_at).rev() {
if !matches!(bytes[open], b'[' | b'(') {
continue;
}
if let Some(prefix) = keyed_store_prefix(line, open)
&& prefix.value_start == quote_at
{
return Some(&line[prefix.name_start..prefix.name_end]);
}
}
None
}
pub(super) struct ItemKeyLine<'a> {
pub(super) column: usize,
pub(super) item_start: bool,
pub(super) key: &'a str,
pub(super) rest: usize,
}
pub(super) fn item_key_line(line: &str) -> Option<ItemKeyLine<'_>> {
let bytes = line.as_bytes();
let mut at = bytes.iter().take_while(|&&byte| byte == b' ').count();
let mut item_start = false;
if bytes.get(at) == Some(&b'-') && bytes.get(at + 1) == Some(&b' ') {
item_start = true;
at += 1;
at += bytes[at..].iter().take_while(|&&byte| byte == b' ').count();
}
let column = at;
if !bytes
.get(at)
.is_some_and(|&byte| byte.is_ascii_alphabetic() || byte == b'_')
{
return None;
}
at += bytes[at..]
.iter()
.take_while(|&&byte| byte.is_ascii_alphanumeric() || byte == b'_')
.count();
let key = &line[column..at];
if bytes.get(at) != Some(&b':') {
return None;
}
at += 1;
match bytes.get(at) {
None | Some(b' ' | b'\t' | b'\r') => Some(ItemKeyLine {
column,
item_start,
key,
rest: at,
}),
_ => None,
}
}
pub(super) fn item_name_scalar(line: &str, rest: usize) -> Option<&str> {
let bytes = line.as_bytes();
let mut at = rest + ascii_run_len(bytes, rest, |byte| matches!(byte, b' ' | b'\t'));
let quote = bytes
.get(at)
.copied()
.filter(|&byte| matches!(byte, b'"' | b'\''));
if quote.is_some() {
at += 1;
}
let start = at;
if !bytes
.get(at)
.is_some_and(|&byte| byte.is_ascii_alphabetic() || byte == b'_')
{
return None;
}
at += ascii_run_len(bytes, at, |byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-')
});
let end = at;
if end - start > 128 {
return None;
}
if let Some(quote) = quote {
if bytes.get(at) != Some("e) {
return None;
}
at += 1;
}
let tail = line[at..].trim_start_matches([' ', '\t']);
(tail.is_empty() || tail == "\r" || tail.starts_with('#')).then_some(&line[start..end])
}
pub(super) fn previous_line(input: &str, line_start: usize) -> Option<(usize, usize)> {
if line_start == 0 {
return None;
}
let end = if input.as_bytes()[line_start - 1] == b'\n' {
line_start - 1
} else {
line_start
};
Some((line_start_before(input, end), end))
}
const LONG_RUN_MIN: usize = 32;
const fn long_run_table() -> [bool; 256] {
let mut table = [false; 256];
let mut byte = 0u8;
loop {
table[byte as usize] =
byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'=' | b'_' | b'-');
if byte == u8::MAX {
break;
}
byte += 1;
}
table
}
static LONG_RUN_BYTES: [bool; 256] = long_run_table();
pub(super) fn long_run_line_spans(input: &str) -> Vec<(usize, usize)> {
let bytes = input.as_bytes();
let mut spans = Vec::new();
let mut floor = 0usize;
let mut probe = LONG_RUN_MIN - 1;
while probe < bytes.len() {
if probe < floor {
probe += LONG_RUN_MIN * (floor - probe).div_ceil(LONG_RUN_MIN);
continue;
}
if !LONG_RUN_BYTES[usize::from(bytes[probe])] {
probe += LONG_RUN_MIN;
continue;
}
let mut start = probe;
while start > floor && LONG_RUN_BYTES[usize::from(bytes[start - 1])] {
start -= 1;
}
let mut end = probe + 1;
while end < bytes.len() && LONG_RUN_BYTES[usize::from(bytes[end])] {
end += 1;
}
floor = end;
if end - start >= LONG_RUN_MIN {
let (line_end, next) = line_end_from(bytes, end);
spans.push((line_start_before(input, line_end), line_end));
floor = next.min(bytes.len());
}
}
spans
}
#[cfg(any(debug_assertions, test))]
pub(super) fn long_run_line_spans_by_line(input: &str) -> Vec<(usize, usize)> {
lines(input)
.filter(|&(start, end)| {
let mut run = 0usize;
input.as_bytes()[start..end].iter().any(|&byte| {
run = if LONG_RUN_BYTES[usize::from(byte)] {
run + 1
} else {
0
};
run >= LONG_RUN_MIN
})
})
.collect()
}
pub(super) fn preceding_lines(input: &str, line_start: usize, count: usize) -> Vec<&str> {
let mut previous = Vec::with_capacity(count);
let mut at = line_start;
while previous.len() < count {
let Some((start, end)) = previous_line(input, at) else {
break;
};
previous.push(&input[start..end]);
at = start;
}
previous.reverse();
previous
}
pub(super) fn for_each_long_run_line(input: &str, mut visit: impl FnMut(usize, usize)) {
if let Some(spans) = super::prefilter::long_run_lines(input) {
for &(start, end) in spans.iter() {
visit(start, end);
}
} else {
for (start, end) in lines(input) {
visit(start, end);
}
}
}
pub(super) fn next_line(input: &str, line_end: usize) -> Option<(usize, usize)> {
let bytes = input.as_bytes();
let start = match bytes.get(line_end) {
Some(b'\n') => line_end + 1,
Some(_) if line_end > 0 && bytes[line_end - 1] == b'\r' => line_end,
_ => return None,
};
Some((start, line_end_from(bytes, start).0.min(bytes.len())))
}
pub(super) fn list_item_paired_name(input: &str, line: (usize, usize)) -> Option<&str> {
let value_line = item_key_line(&input[line.0..line.1])?;
if value_line.key != "value" {
return None;
}
let other = if value_line.item_start {
next_line(input, line.1)?
} else {
previous_line(input, line.0)?
};
let other_text = &input[other.0..other.1];
let name_line = item_key_line(other_text)?;
(name_line.key == "name"
&& name_line.item_start != value_line.item_start
&& name_line.column == value_line.column)
.then(|| item_name_scalar(other_text, name_line.rest))
.flatten()
}
#[cfg(test)]
pub(crate) fn has_open_list_item_pair(input: &str) -> bool {
has_open_list_item_pair_in(&super::lookback_tail(input))
}
pub(crate) fn has_open_list_item_pair_in(tail: &[&str]) -> bool {
tail_lines(tail, 1).first().is_some_and(|line| {
item_key_line(line)
.is_some_and(|parsed| parsed.item_start && matches!(parsed.key, "name" | "value"))
})
}
#[cfg(test)]
mod provider_named_assignment_tests {
use super::is_provider_named_assignment;
const VALUE: &str = "SYNTHETIC_REVOKED_VALUE";
fn value_start(line: &str) -> usize {
line.find(VALUE).unwrap()
}
#[test]
fn a_key_naming_the_provider_qualifies() {
for line in [
format!("MAILCHIMP_API_KEY={VALUE}"),
format!("mailchimp.api_key: {VALUE}"),
format!("{{\"mailchimpApiKey\": \"{VALUE}\"}}"),
format!("export MAILCHIMP_KEY='{VALUE}'"),
] {
assert!(
is_provider_named_assignment(&line, value_start(&line), &["mailchimp"]),
"{line}"
);
}
}
#[test]
fn a_high_signal_key_on_a_line_naming_the_provider_qualifies() {
let line = format!("mailchimp.setConfig({{ apiKey: \"{VALUE}\" }})");
assert!(is_provider_named_assignment(
&line,
value_start(&line),
&["mailchimp"]
));
}
#[test]
fn identifier_keys_prose_and_other_keys_do_not_qualify() {
for line in [
format!("MAILCHIMP_LIST_ID={VALUE}"),
format!("MAILCHIMP_SERVER_URL={VALUE}"),
format!("# Mailchimp API key {VALUE}"),
format!("list_id: {VALUE} # mailchimp"),
format!("MAILCHIMP_API_KEY {VALUE}"),
format!("SENDGRID_API_KEY={VALUE}"),
] {
assert!(
!is_provider_named_assignment(&line, value_start(&line), &["mailchimp"]),
"{line}"
);
}
}
}
#[cfg(test)]
mod line_tests {
use super::{last_lines, line_around, lines};
fn split(input: &str) -> Vec<&str> {
lines(input)
.map(|(start, end)| &input[start..end])
.collect()
}
#[test]
fn lines_end_at_a_newline_and_after_a_lone_carriage_return() {
assert_eq!(split("a\nb"), ["a", "b"]);
assert_eq!(split("a\r\nb\r\n"), ["a\r", "b\r", ""]);
assert_eq!(split("a\rb\rc"), ["a\r", "b\r", "c"]);
assert_eq!(split("a\r\rb"), ["a\r", "\r", "b"]);
assert_eq!(split("a\r"), ["a\r"]);
assert_eq!(split(""), [""]);
}
fn generated_inputs() -> Vec<String> {
let alphabet = ["a", "\r", "\n", "\u{597D}"];
let mut inputs = Vec::new();
for len in 0..=6u32 {
for mut code in 0..4usize.pow(len) {
let mut symbols = Vec::new();
for _ in 0..len {
symbols.push(alphabet[code % 4]);
code /= 4;
}
let (head, tail) = symbols.split_at(symbols.len() / 2);
for padding in [0, 28, 31, 32, 33, 40] {
inputs.push(format!(
"{}{}{}",
head.concat(),
"a".repeat(padding),
tail.concat()
));
}
}
}
inputs
}
#[test]
fn lines_agree_with_the_byte_by_byte_line_end_over_generated_inputs() {
for input in generated_inputs() {
let mut expected = Vec::new();
let mut start = 0;
while start <= input.len() {
let (end, next) = super::line_end_from(input.as_bytes(), start);
expected.push((start, end));
start = next;
}
assert_eq!(lines(&input).collect::<Vec<_>>(), expected, "{input:?}");
}
}
fn long_run_inputs() -> Vec<String> {
let mut inputs = generated_inputs();
let pieces = [
"a",
"-",
"=",
"+",
"/",
"_",
" ",
"\r",
"\n",
"\r\n",
"\u{e9}",
"\u{597D}",
"0123456789abcdef",
"Z",
];
let mut state = 0x2545_f491_4f6c_dd1du64;
let mut next = move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
usize::try_from(state >> 33).unwrap()
};
for _ in 0..3000 {
let mut input = String::new();
for _ in 0..(next() % 24) {
let piece = pieces[next() % pieces.len()];
let repeat = if next() % 4 == 0 { 1 + next() % 40 } else { 1 };
for _ in 0..repeat {
input.push_str(piece);
}
}
inputs.push(input);
}
inputs
}
#[test]
fn long_run_line_spans_agree_with_the_line_by_line_walk() {
for input in long_run_inputs() {
assert_eq!(
super::long_run_line_spans(&input),
super::long_run_line_spans_by_line(&input),
"{input:?}"
);
}
assert!(super::long_run_line_spans("").is_empty());
}
#[test]
fn preceding_lines_are_the_lines_before_the_line_start() {
for input in long_run_inputs().iter().take(4000) {
let all: Vec<(usize, usize)> = lines(input).collect();
for (index, &(start, _)) in all.iter().enumerate() {
for count in [0, 1, 3, 5] {
let expected: Vec<&str> = all[index.saturating_sub(count)..index]
.iter()
.map(|&(from, to)| &input[from..to])
.collect();
assert_eq!(
super::preceding_lines(input, start, count),
expected,
"{input:?} {index} {count}"
);
}
}
}
}
#[test]
fn the_last_lines_are_the_tail_of_lines_over_generated_inputs() {
for input in generated_inputs() {
let complete = input.strip_suffix('\n').unwrap_or(&input);
let all = split(complete);
for count in 1..=4 {
let expected = &all[all.len().saturating_sub(count)..];
assert_eq!(last_lines(&input, count), expected, "{input:?} {count}");
}
}
}
#[test]
fn every_hint_window_of_the_shared_lookback_tail_is_its_own_last_lines() {
for input in generated_inputs() {
let tail = crate::detectors::lookback_tail(&input);
for count in 1..=super::super::MAX_LOOKBACK_LINES {
assert_eq!(
super::tail_lines(&tail, count),
last_lines(&input, count),
"{input:?} {count}"
);
}
}
}
#[test]
fn the_inline_lookback_tail_is_last_lines_for_every_count() {
for input in generated_inputs() {
for count in 0..=super::super::MAX_LOOKBACK_LINES + 1 {
let inline = crate::detectors::lookback_tail_lines(&input, count);
let expected = last_lines(&input, count.min(super::super::MAX_LOOKBACK_LINES));
assert_eq!(inline.as_slice(), expected, "{input:?} {count}");
}
}
assert!(
crate::detectors::LookbackTail::empty()
.as_slice()
.is_empty()
);
}
#[test]
fn the_line_around_a_span_is_the_line_that_holds_it() {
let input = "x\ra \"k\" b\r\ny";
let at = input.find("\"k\"").unwrap();
let (start, end) = line_around(input, at, at + 3);
assert_eq!(&input[start..end], "a \"k\" b\r");
}
}
#[cfg(test)]
mod list_item_pair_tests {
use super::{has_open_list_item_pair, lines, list_item_paired_name};
fn paired(input: &str) -> Option<&str> {
let line = lines(input)
.filter(|&(start, end)| start < end && !input[start..end].trim().is_empty())
.last()?;
list_item_paired_name(input, line)
}
#[test]
fn the_value_key_pairs_with_the_adjacent_name_of_its_item() {
assert_eq!(
paired(" - name: API_TOKEN\n value: x\n"),
Some("API_TOKEN")
);
assert_eq!(
paired("- name: 'CO_API_KEY'\r\n value: x\r\n"),
Some("CO_API_KEY")
);
assert_eq!(paired("- name: A\r value: x\r"), Some("A"));
let reverse = "- value: x\n name: B # c\n";
assert_eq!(list_item_paired_name(reverse, (0, 10)), Some("B"));
}
#[test]
fn anything_but_the_two_keys_of_one_item_is_not_a_pair() {
for input in [
"- name: A\n- value: x\n",
"- name: A\n value: x\n",
"- name: A\n image: b\n value: x\n",
"name: A\nvalue: x\n",
"- {name: A, value: x}\n",
"- name: A\n valueFrom: x\n",
"- name: two words\n value: x\n",
"- name: A\n\t value: x\n",
] {
assert_eq!(paired(input), None, "{input:?}");
}
}
#[test]
fn the_retention_hint_holds_exactly_an_item_opening_name_or_value_line() {
for open in [
"- name: A\n",
"env:\n - name: A\n",
" - value: x\r\n",
"- name: A\r",
] {
assert!(has_open_list_item_pair(open), "{open:?}");
}
for closed in [
"",
"- name: A\n value: x\n",
"- name: A\n\n",
" name: A\n",
"- image: A\n",
"- {name: A}\n",
] {
assert!(!has_open_list_item_pair(closed), "{closed:?}");
}
}
}
#[cfg(test)]
mod keyed_store_tests {
use super::{keyed_store_name, keyed_store_prefix};
#[test]
fn subscript_and_call_stores_name_their_value() {
let line = "os.environ[\"API_TOKEN\"] = \"v\"";
let prefix = keyed_store_prefix(line, 10).unwrap();
assert_eq!(&line[prefix.name_start..prefix.name_end], "API_TOKEN");
assert_eq!(prefix.value_start, line.len() - 3);
assert!(!prefix.call);
assert_eq!(keyed_store_name(line, line.len() - 2), Some("API_TOKEN"));
let call = "os.putenv( 'API_TOKEN' , 'v')";
assert_eq!(keyed_store_name(call, call.len() - 3), Some("API_TOKEN"));
assert!(keyed_store_prefix(call, 9).unwrap().call);
}
#[test]
fn comparisons_reads_and_other_callees_are_not_stores() {
for (line, open) in [
("x[\"A\"] == \"v\"", 1),
("x[\"A\"]", 1),
(" [\"A\"] = \"v\"", 1),
("x[A] = \"v\"", 1),
("x[\"A'] = \"v\"", 1),
("x[\"1A\"] = \"v\"", 1),
("get(\"A\", \"v\")", 3),
("setdefault(\"A\" \"v\")", 10),
] {
assert!(keyed_store_prefix(line, open).is_none(), "{line}");
}
assert_eq!(keyed_store_name("x = \"v\"", 5), None);
}
}
#[cfg(test)]
mod find_ci_tests {
use super::{contains_ci, find_ci, starts_with_ci};
fn find_oracle(haystack: &str, from: usize, needle: &str) -> Option<usize> {
let len = haystack.len();
if needle.len() > len {
return None;
}
(from..=len - needle.len()).find(|&pos| starts_with_ci(haystack, pos, needle))
}
#[test]
fn find_ci_equals_the_per_offset_oracle_on_random_and_boundary_inputs() {
let pieces = [
"a",
"K",
"e",
"y",
"KEY",
"api",
"Token",
"tOkEn",
"twilio",
"TWILIO",
"-",
"_",
" ",
"\u{e9}",
"\u{1F511}",
"\n",
"0",
"\u{212A}",
"secret",
];
let needles = [
"key",
"token",
"twilio",
"api-key",
"secret",
"a",
"k",
"0",
"dd-app-key",
"-x",
"",
];
let mut state: u64 = 0xD1B5_4A32_D192_ED03;
let mut next = move || {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(state >> 33) as usize
};
for _ in 0..4000 {
let mut input = String::new();
for _ in 0..next() % 40 {
input.push_str(pieces[next() % pieces.len()]);
}
for needle in needles {
let from = if input.is_empty() {
0
} else {
next() % (input.len() + 1)
};
assert_eq!(
find_ci(input.as_bytes(), from, needle.as_bytes()),
find_oracle(&input, from, needle),
"{input:?} {needle:?} {from}"
);
assert_eq!(
contains_ci(&input, needle),
find_oracle(&input, 0, needle).is_some()
);
}
}
}
#[test]
fn find_ci_handles_short_empty_and_out_of_range_inputs() {
assert_eq!(find_ci(b"", 0, b"key"), None);
assert_eq!(find_ci(b"", 0, b""), Some(0));
assert_eq!(find_ci(b"ab", 5, b"a"), None);
assert_eq!(find_ci(b"xxxxxxxxxxxxxxxKEY", 0, b"key"), Some(15));
assert_eq!(find_ci(b"xxxxxxxxxxxxxxxKE", 0, b"key"), None);
}
}
#[cfg(test)]
mod residual_allocation_tests {
use super::*;
use crate::test_rng::XorShift32;
const PIECES: &[&str] = &[
"your",
"insert",
"enter",
"paste",
"replace",
"key",
"secret",
"token",
"jwt",
"api",
"KEY",
"YOUR",
"Token",
"example",
"EXAMPLE",
"changeme",
"change",
"me",
"redacted",
"password",
"12",
"7",
"_",
"-",
"_",
"-",
"__",
".",
":",
"=",
" ",
"md5",
"sha256",
"SHA-256",
"hmac-",
"HMAC-",
"sha3-512",
"blake3",
"\u{e9}",
"\u{212a}",
"\u{1f600}",
"x",
];
fn old_vocabulary(value: &str, exact: &[&str], digit: &[&str]) -> bool {
fn strip(token: &str) -> &str {
token.trim_end_matches(|ch: char| ch.is_ascii_digit())
}
let is_listed =
|token: &str, words: &[&str]| words.iter().any(|word| token.eq_ignore_ascii_case(word));
let token_is_placeholder = |token: &str| {
is_listed(token, exact) || {
let core = strip(token);
core.len() < token.len() && is_listed(core, digit)
}
};
let tokens: Vec<&str> = value
.split(|ch: char| !ch.is_ascii_alphanumeric())
.filter(|token| !token.is_empty())
.collect();
if tokens.is_empty() {
return false;
}
let joined: String = tokens.concat();
is_listed(&joined, exact) || tokens.iter().all(|token| token_is_placeholder(token))
}
fn old_digest_label(value: &str) -> bool {
let lower = value.to_ascii_lowercase();
let rest = lower.strip_prefix("hmac-").unwrap_or(&lower);
DIGEST_ALGORITHM_LABELS.iter().any(|label| {
rest.strip_prefix(label)
.is_some_and(|after| after.starts_with(':') || after.starts_with('='))
})
}
fn old_lead_phrase(value: &str) -> bool {
let words: Vec<&str> = value.split(['_', '-']).collect();
let one_case = |word: &str| {
!word.is_empty()
&& (word.bytes().all(|byte| byte.is_ascii_lowercase())
|| word.bytes().all(|byte| byte.is_ascii_uppercase()))
};
let listed = |word: &str, words: &[&str]| {
words.iter().any(|listed| word.eq_ignore_ascii_case(listed))
};
words.len() >= 2
&& words.iter().all(|word| one_case(word))
&& listed(words[0], PLACEHOLDER_LEAD_WORDS)
&& words[1..]
.iter()
.any(|word| listed(word, PLACEHOLDER_CREDENTIAL_NOUNS))
}
#[test]
fn vocabulary_matches_collecting_form() {
let exact = [
"example",
"replaceme",
"changeme",
"redacted",
"yourkey",
"password",
];
let digit = ["example", "changeme", "redacted"];
let mut rng = XorShift32::new(0x1121_0001);
let mut matched = 0;
for _ in 0..20_000 {
let value = rng.text(PIECES, 6);
let expected = old_vocabulary(&value, &exact, &digit);
matched += usize::from(expected);
assert_eq!(
matches_placeholder_vocabulary(&value, &exact, &digit),
expected,
"{value:?}"
);
}
assert!(matched > 100, "generator must reach the accepting branch");
}
#[test]
fn digest_label_matches_lowercasing_form() {
let mut rng = XorShift32::new(0x1121_0002);
let mut matched = 0;
for _ in 0..20_000 {
let lead = ["", "hmac-", "HMAC-", "Hmac-"][rng.below(4)];
let label = ["md5", "SHA256", "sha-256", "sha3-512", "Blake3", "shax"][rng.below(6)];
let sep = [":", "=", "-", " ", ""][rng.below(5)];
let value = format!("{lead}{label}{sep}{}", rng.text(PIECES, 3));
let expected = old_digest_label(&value);
matched += usize::from(expected);
assert_eq!(starts_with_digest_label(&value), expected, "{value:?}");
}
assert!(matched > 100, "generator must reach the accepting branch");
for fixed in [
"", "hmac", "hmac-", "sha256", "sha256:", "SHA256=", "xsha256:",
] {
assert_eq!(
starts_with_digest_label(fixed),
old_digest_label(fixed),
"{fixed:?}"
);
}
}
#[test]
fn lead_phrase_matches_collecting_form() {
let mut rng = XorShift32::new(0x1121_0003);
let mut matched = 0;
for _ in 0..30_000 {
let lead = ["your", "YOUR", "Insert", "paste", "x"][rng.below(5)];
let sep = ["_", "-", "", "__"][rng.below(4)];
let noun = ["key", "KEY", "secret", "Token", "jwt", "api", "id"][rng.below(7)];
let value = format!("{lead}{sep}{noun}{}", rng.text(PIECES, 4));
let expected = old_lead_phrase(&value);
matched += usize::from(expected);
assert_eq!(
is_lead_word_phrase_placeholder(&value),
expected,
"{value:?}"
);
}
assert!(matched > 50, "generator must reach the accepting branch");
for fixed in [
"",
"_",
"your",
"your_key",
"your__key",
"your_key_",
"YOUR-KEY",
"Your_key",
] {
assert_eq!(
is_lead_word_phrase_placeholder(fixed),
old_lead_phrase(fixed),
"{fixed:?}"
);
}
}
}
#[cfg(test)]
mod glued_placeholder_stack_tests {
use super::*;
use crate::test_rng::XorShift32;
const PIECES: &[&str] = &[
"your", "YOUR", "Insert", "enter", "paste", "replace", "key", "secret", "TOKEN", "jwt",
"api", "access", "openai", "github", "stripe", "x", "zz", "_", "9", "\u{212a}", "\u{e9}",
"example", "my",
];
fn assert_same(value: &str) {
assert_eq!(
is_glued_instructional_placeholder(value),
is_glued_instructional_placeholder_heap(value),
"{value:?}"
);
}
#[test]
fn word_lists_are_lowercase_ascii() {
for word in glued_placeholder_words() {
assert!(
word.is_ascii() && !word.bytes().any(|b| b.is_ascii_uppercase()),
"{word} must be ASCII without uppercase"
);
}
}
#[test]
fn seeded_values_match_heap_implementation() {
let mut rng = XorShift32::new(0x1162);
for _ in 0..20_000 {
assert_same(&rng.text(PIECES, 12));
}
let mut accepted = 0;
for _ in 0..20_000 {
let value = format!("your{}", rng.text(&PIECES[4..18], 10));
assert_same(&value);
accepted += usize::from(is_glued_instructional_placeholder(&value));
}
assert!(accepted > 100, "generator must reach accepted values");
}
#[test]
fn known_values_and_boundaries() {
for value in [
"",
"your",
"yourkey",
"YourSecretToken",
"yourapikey",
"yourkeyx",
"replaceopenaikey",
"your_key",
"yourK",
"pasteyourjwt",
"yourgithubtoken",
"yourdummy",
] {
assert_same(value);
}
assert!(is_glued_instructional_placeholder("YourSecretToken"));
assert!(!is_glued_instructional_placeholder("your"));
assert!(!is_glued_instructional_placeholder("yourk\u{212a}ey"));
}
#[test]
fn lengths_around_the_stack_bound_match() {
for unit in ["key", "token", "jwtapi"] {
for target in 240..=300 {
let mut value = String::from("your");
while value.len() < target {
value.push_str(unit);
}
for cut in [0, 1, 2] {
let mut candidate = value.clone();
candidate.truncate(candidate.len() - cut);
assert_same(&candidate);
candidate.push('q');
assert_same(&candidate);
candidate.make_ascii_uppercase();
assert_same(&candidate);
}
}
}
let exact = format!("your{}", "key".repeat(84));
assert_eq!(exact.len(), 256);
assert!(is_glued_instructional_placeholder(&exact));
let over = format!("your{}", "key".repeat(85));
assert_eq!(over.len(), 259);
assert!(is_glued_instructional_placeholder(&over));
let long_non_ascii = format!("your{}\u{e9}", "key".repeat(100));
assert!(!is_glued_instructional_placeholder(&long_non_ascii));
}
}