use super::text::lines;
use crate::detectors::generic_token::{masking_lead_hides_value, normalize_name};
use crate::detectors::pattern::{self, Alphabet};
use crate::detectors::text;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const CREDENTIAL_SEGMENTS: &[&str] = &["key", "token", "secret", "apikey", "credential"];
const KEYWORD_WINDOW: usize = 32;
const CALL_WINDOW: usize = 256;
const HEADER_WINDOW: usize = 48;
pub(super) const MAX_HTTP_BLOCK_LINES: usize = 8;
pub(super) const MAX_SIBLING_LINES: usize = 6;
const ALL_KEYWORDS: &[&str] = &["mistral", "cohere", "ai21", "deepgram"];
const DEEPGRAM_API_DOMAIN: &str = "deepgram.com";
struct Spec {
type_name: &'static str,
len: usize,
alphabet: Alphabet,
keywords: &'static [&'static str],
exact_names: &'static [&'static str],
named_signal: &'static str,
constructor_signal: &'static str,
adjacent_signal: &'static str,
route_signal: &'static str,
sibling_signal: &'static str,
factory_callees: &'static [&'static str],
token_header: bool,
api_host_domain: Option<&'static str>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum HeaderContext {
Absent,
Keyword,
ProviderHost,
}
#[derive(Clone, Copy)]
struct LineContext<'a> {
header: HeaderContext,
keyword_on_line: bool,
model_route: bool,
provider_sibling: bool,
paired_name: Option<&'a str>,
}
const MISTRAL: Spec = Spec {
type_name: "mistral_api_key",
len: 32,
alphabet: pattern::is_alnum,
keywords: &["mistral"],
exact_names: &[],
named_signal: "mistral-named-assignment",
constructor_signal: "mistral-sdk-constructor",
adjacent_signal: "mistral-keyword-adjacent",
route_signal: "mistral-model-route",
sibling_signal: "mistral-provider-field",
factory_callees: &[],
token_header: false,
api_host_domain: None,
};
const COHERE: Spec = Spec {
type_name: "cohere_api_key",
len: 40,
alphabet: pattern::is_alnum,
keywords: &["cohere"],
exact_names: &["co_api_key"],
named_signal: "cohere-named-assignment",
constructor_signal: "cohere-sdk-constructor",
adjacent_signal: "cohere-keyword-adjacent",
route_signal: "cohere-model-route",
sibling_signal: "cohere-provider-field",
factory_callees: &[],
token_header: false,
api_host_domain: None,
};
const AI21: Spec = Spec {
type_name: "ai21_api_key",
len: 32,
alphabet: pattern::is_alnum,
keywords: &["ai21"],
exact_names: &[],
named_signal: "ai21-named-assignment",
constructor_signal: "ai21-sdk-constructor",
adjacent_signal: "ai21-keyword-adjacent",
route_signal: "ai21-model-route",
sibling_signal: "ai21-provider-field",
factory_callees: &[],
token_header: false,
api_host_domain: None,
};
const DEEPGRAM: Spec = Spec {
type_name: "deepgram_api_key",
len: 40,
alphabet: pattern::is_lower_alnum,
keywords: &["deepgram"],
exact_names: &[],
named_signal: "deepgram-named-assignment",
constructor_signal: "deepgram-sdk-constructor",
adjacent_signal: "deepgram-keyword-adjacent",
route_signal: "deepgram-model-route",
sibling_signal: "deepgram-provider-field",
factory_callees: &["createclient"],
token_header: true,
api_host_domain: Some("deepgram.com"),
};
fn is_boundary_byte(byte: u8) -> bool {
pattern::is_alnum(byte) || matches!(byte, b'_' | b'-')
}
fn scan_runs(line: &str, spec: &Spec) -> Vec<(usize, usize)> {
let bytes = line.as_bytes();
let mut matches = Vec::new();
let mut start = 0;
while start < bytes.len() {
if !(spec.alphabet)(bytes[start]) {
start += 1;
continue;
}
let run_end = pattern::run_end(bytes, start, spec.alphabet);
if run_end - start == spec.len
&& pattern::boundary_ok(bytes, start, run_end, is_boundary_byte)
{
matches.push((start, run_end));
}
start = run_end;
}
matches
}
fn name_has_provider(spec: &Spec, normalized: &str) -> bool {
spec.keywords
.iter()
.any(|keyword| normalized.contains(keyword))
|| spec.exact_names.iter().any(|name| {
normalized == *name
|| normalized.starts_with(&format!("{name}_"))
|| normalized.ends_with(&format!("_{name}"))
|| normalized.contains(&format!("_{name}_"))
})
}
fn is_credential_name(normalized: &str) -> bool {
normalized
.rsplit('_')
.next()
.is_some_and(|segment| CREDENTIAL_SEGMENTS.contains(&segment))
}
fn inside_provider_call(line: &str, spec: &Spec, end: usize, keyword_on_line: bool) -> bool {
let bytes = line.as_bytes();
let end = end.min(bytes.len());
let floor = end.saturating_sub(CALL_WINDOW);
let mut cursor = end;
while cursor > floor {
cursor -= 1;
match bytes[cursor] {
b')' => return false,
b'(' => {
let mut start = cursor;
while start > 0
&& (bytes[start - 1].is_ascii_alphanumeric()
|| matches!(bytes[start - 1], b'_' | b'.'))
{
start -= 1;
}
let callee = &line[start..cursor];
if spec
.keywords
.iter()
.any(|keyword| text::contains_ci(callee, keyword))
{
return true;
}
if keyword_on_line
&& callee.rsplit('.').next().is_some_and(|name| {
spec.factory_callees
.iter()
.any(|listed| name.eq_ignore_ascii_case(listed))
})
{
return true;
}
}
_ => {}
}
}
false
}
fn is_closed_string_argument(bytes: &[u8], start: usize, end: usize) -> bool {
let Some("e) = start.checked_sub(1).and_then(|at| bytes.get(at)) else {
return false;
};
if !matches!(quote, b'"' | b'\'') || bytes.get(end) != Some("e) {
return false;
}
let after = end + 1 + ascii_space_len(&bytes[end + 1..]);
bytes.get(after) == Some(&b')')
}
fn ascii_space_len(bytes: &[u8]) -> usize {
bytes
.iter()
.take_while(|&&byte| matches!(byte, b' ' | b'\t'))
.count()
}
fn enclosing_call_open(bytes: &[u8], end: usize) -> Option<usize> {
let floor = end.saturating_sub(CALL_WINDOW);
let mut depth = 0usize;
let mut cursor = end;
while cursor > floor {
cursor -= 1;
match bytes[cursor] {
b')' => depth += 1,
b'(' if depth == 0 => return Some(cursor),
b'(' => depth -= 1,
_ => {}
}
}
None
}
fn callee_chain(line: &str, open: usize) -> (String, bool) {
let bytes = line.as_bytes();
let floor = open.saturating_sub(CALL_WINDOW);
let mut start = open;
let mut pieces: Vec<&str> = Vec::new();
let mut piece_end = open;
let mut crossed_call = false;
while start > floor {
let byte = bytes[start - 1];
if byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.') {
start -= 1;
} else if byte == b')' {
let Some(group_open) = enclosing_call_open(bytes, start - 1) else {
break;
};
if group_open == 0 || !is_chain_byte(bytes[group_open - 1]) {
break;
}
pieces.push(&line[start..piece_end]);
pieces.push("()");
start = group_open;
piece_end = group_open;
crossed_call = true;
} else {
break;
}
}
pieces.push(&line[start..piece_end]);
pieces.reverse();
(pieces.concat(), crossed_call)
}
fn is_chain_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_'
}
fn names_host_under(line: &str, domain: &str) -> bool {
let bytes = line.as_bytes();
any_match_ci(bytes, domain, |at| {
let end = at + domain.len();
let after_ends_host = match bytes.get(end) {
None => true,
Some(b'.') => !bytes.get(end + 1).is_some_and(u8::is_ascii_alphanumeric),
Some(&byte) => !(byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')),
};
at > 0 && bytes[at - 1] == b'.' && after_ends_host
})
}
fn names_model_route(line: &str, spec: &Spec) -> bool {
let bytes = line.as_bytes();
spec.keywords.iter().any(|keyword| {
any_match_ci(bytes, keyword, |at| {
let end = at + keyword.len();
(at == 0 || !is_boundary_byte(bytes[at - 1]))
&& bytes.get(end) == Some(&b'/')
&& bytes.get(end + 1).is_some_and(u8::is_ascii_alphanumeric)
})
})
}
fn is_token_subprotocol(bytes: &[u8], start: usize) -> bool {
let window = &bytes[start.saturating_sub(HEADER_WINDOW)..start];
let Ok(window) = std::str::from_utf8(window) else {
return false;
};
let before = window.as_bytes();
let spaces: &[u8] = b" \t";
let trim = |bytes: &'_ [u8]| -> usize {
bytes
.iter()
.rposition(|byte| !spaces.contains(byte))
.map_or(0, |last| last + 1)
};
let strip = |bytes: &'_ [u8], suffix: &str| -> Option<usize> {
let suffix = suffix.as_bytes();
let start = bytes.len().checked_sub(suffix.len())?;
bytes[start..].eq_ignore_ascii_case(suffix).then_some(start)
};
if matches!(before.last(), Some(b'"' | b'\'')) {
let head = &before[..before.len() - 1];
let head = &head[..trim(head)];
if head.last() == Some(&b',') {
let head = &head[..head.len() - 1];
let head = &head[..trim(head)];
return ["\"token\"", "'token'"].iter().any(|quoted| {
strip(head, quoted).is_some_and(|open| {
let open = &head[..open];
open[..trim(open)].ends_with(b"[")
})
});
}
}
let head = &before[..trim(before)];
if head.last() != Some(&b',') {
return false;
}
let head = &head[..head.len() - 1];
let head = &head[..trim(head)];
let Some(at) = strip(head, "token") else {
return false;
};
let head = &head[..at];
let head = &head[..trim(head)];
if head.last() != Some(&b':') {
return false;
}
let head = &head[..head.len() - 1];
let Some(at) = strip(head, "sec-websocket-protocol") else {
return false;
};
!head[..at]
.last()
.is_some_and(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
}
fn names_provider_field(line: &str, keywords: &[&str]) -> bool {
let bytes = line.as_bytes();
let is_ident = |byte: u8| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-');
any_match_ci(bytes, "provider", |at| {
if at > 0 && is_ident(bytes[at - 1]) {
return false;
}
let mut cursor = at + "provider".len();
cursor += ascii_run(bytes, cursor, |byte| matches!(byte, b'"' | b'\'' | b'\\'));
cursor += ascii_run(bytes, cursor, |byte| matches!(byte, b' ' | b'\t'));
if !matches!(bytes.get(cursor), Some(b':' | b'=')) {
return false;
}
cursor += 1;
cursor += ascii_run(bytes, cursor, |byte| {
matches!(byte, b' ' | b'\t' | b'"' | b'\'' | b'\\')
});
keywords.iter().any(|keyword| {
text::starts_with_ci(line, cursor, keyword)
&& !bytes
.get(cursor + keyword.len())
.is_some_and(|&byte| is_ident(byte))
})
})
}
fn any_match_ci(bytes: &[u8], needle: &str, mut visit: impl FnMut(usize) -> bool) -> bool {
debug_assert!(!needle.is_empty());
let mut from = 0;
while let Some(at) = text::find_ci(bytes, from, needle.as_bytes()) {
if visit(at) {
return true;
}
from = at + needle.len();
}
false
}
fn ascii_run(bytes: &[u8], start: usize, pred: fn(u8) -> bool) -> usize {
bytes.get(start..).map_or(0, |rest| {
rest.iter().take_while(|&&byte| pred(byte)).count()
})
}
fn yaml_sibling_names_provider(
input: &str,
line_start: usize,
column: usize,
keywords: &[&str],
) -> bool {
let mut start = line_start;
for _ in 0..MAX_SIBLING_LINES {
let Some((above_start, above_end)) = text::previous_line(input, start) else {
return false;
};
match sibling_line(&input[above_start..above_end], column, keywords) {
SiblingLine::Provider => return true,
SiblingLine::Sibling => start = above_start,
SiblingLine::End => return false,
}
}
false
}
enum SiblingLine {
Provider,
Sibling,
End,
}
fn sibling_line(line: &str, column: usize, keywords: &[&str]) -> SiblingLine {
let Some(parsed) = text::item_key_line(line) else {
return SiblingLine::End;
};
if parsed.column != column {
return SiblingLine::End;
}
if parsed.key == "provider"
&& text::item_name_scalar(line, parsed.rest).is_some_and(|value| {
keywords
.iter()
.any(|keyword| value.eq_ignore_ascii_case(keyword))
})
{
return SiblingLine::Provider;
}
if parsed.item_start {
SiblingLine::End
} else {
SiblingLine::Sibling
}
}
#[cfg(test)]
pub(crate) fn has_open_provider_sibling(input: &str) -> bool {
has_open_provider_sibling_in(&super::lookback_tail(input))
}
pub(crate) fn has_open_provider_sibling_in(tail: &[&str]) -> bool {
let tail = text::tail_lines(tail, MAX_SIBLING_LINES);
let Some(column) = tail
.last()
.and_then(|line| text::item_key_line(line))
.map(|parsed| parsed.column)
else {
return false;
};
for line in tail.iter().rev() {
match sibling_line(line, column, ALL_KEYWORDS) {
SiblingLine::Provider => return true,
SiblingLine::Sibling => {}
SiblingLine::End => return false,
}
}
false
}
enum HttpLine {
Request(bool),
Header(bool),
Other,
}
fn request_line_target(line: &str) -> Option<&str> {
let (method, rest) = line.split_once(' ')?;
if method.is_empty() || !method.bytes().all(|byte| byte.is_ascii_uppercase()) {
return None;
}
let (target, version) = rest.split_once(' ')?;
(!target.is_empty() && version.starts_with("HTTP/")).then_some(target)
}
fn strip_indent(line: &str) -> &str {
line.trim_start_matches([' ', '\t'])
}
fn http_header_name(line: &str) -> Option<&str> {
let line = strip_indent(line);
let name_len = line
.bytes()
.take_while(|&byte| byte.is_ascii_alphanumeric() || byte == b'-')
.count();
(name_len > 0 && line.as_bytes().get(name_len) == Some(&b':')).then(|| &line[..name_len])
}
fn http_line(line: &str, domain: &str) -> HttpLine {
let line = strip_indent(line.strip_suffix('\r').unwrap_or(line));
if let Some(target) = request_line_target(line) {
return HttpLine::Request(names_host_under(target, domain));
}
match http_header_name(line) {
Some(name) => {
HttpLine::Header(name.eq_ignore_ascii_case("host") && names_host_under(line, domain))
}
None => HttpLine::Other,
}
}
fn http_block_names_host(input: &str, line_start: usize, domain: &str) -> bool {
let mut start = line_start;
for _ in 0..MAX_HTTP_BLOCK_LINES {
let Some((above_start, above_end)) = text::previous_line(input, start) else {
return false;
};
match http_line(&input[above_start..above_end], domain) {
HttpLine::Request(names_host) => return names_host,
HttpLine::Header(true) => return true,
HttpLine::Header(false) => start = above_start,
HttpLine::Other => return false,
}
}
false
}
#[cfg(test)]
pub(crate) fn has_open_deepgram_request(input: &str) -> bool {
has_open_deepgram_request_in(&super::lookback_tail(input))
}
pub(crate) fn has_open_deepgram_request_in(tail: &[&str]) -> bool {
for line in text::tail_lines(tail, MAX_HTTP_BLOCK_LINES).iter().rev() {
match http_line(line, DEEPGRAM_API_DOMAIN) {
HttpLine::Request(names_host) => return names_host,
HttpLine::Header(true) => return true,
HttpLine::Header(false) => {}
HttpLine::Other => return false,
}
}
false
}
fn contains_keyword_ci(window: &str, spec: &Spec) -> Option<usize> {
let lowered = window.to_ascii_lowercase();
spec.keywords
.iter()
.filter_map(|keyword| lowered.rfind(keyword).map(|at| at + keyword.len()))
.max()
}
fn context(
line: &str,
spec: &Spec,
start: usize,
end: usize,
line_context: &LineContext<'_>,
) -> Option<(Confidence, &'static str)> {
let header_context = line_context.header;
let bytes = line.as_bytes();
let key = text::assignment_key(bytes, start)
.and_then(|key| std::str::from_utf8(key).ok())
.or_else(|| text::keyed_store_name(line, start));
if let Some(key) = key {
let key_start = key.as_ptr() as usize - bytes.as_ptr() as usize;
let key = match line_context.paired_name {
Some(paired) if key == "value" => paired,
_ => key,
};
let normalized = normalize_name(key);
if line_context.provider_sibling
&& (is_credential_name(&normalized) || normalized == "auth")
&& !masking_lead_hides_value(&normalized, &line[start..end])
{
return Some((Confidence::High, spec.sibling_signal));
}
if !is_credential_name(&normalized) {
return None;
}
if name_has_provider(spec, &normalized) {
return Some((Confidence::High, spec.named_signal));
}
if inside_provider_call(line, spec, key_start, line_context.keyword_on_line) {
return Some((Confidence::High, spec.constructor_signal));
}
if line_context.model_route && !masking_lead_hides_value(&normalized, &line[start..end]) {
return Some((Confidence::High, spec.route_signal));
}
let window =
String::from_utf8_lossy(&bytes[key_start.saturating_sub(KEYWORD_WINDOW)..key_start])
.into_owned();
let keyword_end = contains_keyword_ci(&window, spec)?;
let gap = window.get(keyword_end..)?;
if gap
.bytes()
.all(|byte| !matches!(byte, b';' | b',' | b'=' | b')' | b'(' | b'{'))
{
return Some((Confidence::Medium, spec.adjacent_signal));
}
return None;
}
let mut cursor = start;
while cursor > 0 && matches!(bytes[cursor - 1], b' ' | b'\t' | b'"' | b'\'') {
cursor -= 1;
}
if cursor > 0
&& bytes[cursor - 1] == b'('
&& inside_provider_call(line, spec, cursor, line_context.keyword_on_line)
{
return Some((Confidence::High, spec.constructor_signal));
}
if is_closed_string_argument(bytes, start, end) {
if cursor > 0 && bytes[cursor - 1] == b'(' {
let (chain, crossed_call) = callee_chain(line, cursor - 1);
if crossed_call
&& contains_keyword_ci(&chain, spec).is_some()
&& chain
.rsplit('.')
.next()
.is_some_and(|method| is_credential_name(&normalize_name(method)))
{
return Some((Confidence::High, spec.constructor_signal));
}
}
if cursor > 0
&& bytes[cursor - 1] == b','
&& let Some(open) = enclosing_call_open(bytes, cursor - 1)
{
let (chain, _) = callee_chain(line, open);
if contains_keyword_ci(&chain, spec).is_some() {
return Some((Confidence::High, spec.constructor_signal));
}
}
}
if spec.token_header {
token_header_context(bytes, start, cursor, header_context)
} else {
None
}
}
fn token_header_context(
bytes: &[u8],
start: usize,
cursor: usize,
header_context: HeaderContext,
) -> Option<(Confidence, &'static str)> {
if is_token_subprotocol(bytes, start) {
match header_context {
HeaderContext::ProviderHost => {
return Some((Confidence::High, "deepgram-host-token-subprotocol"));
}
HeaderContext::Keyword => {
return Some((Confidence::Medium, "deepgram-token-subprotocol"));
}
HeaderContext::Absent => {}
}
}
if cursor < start {
let before = String::from_utf8_lossy(&bytes[cursor.saturating_sub(HEADER_WINDOW)..cursor])
.to_ascii_lowercase();
let scheme = before.trim_end();
if let Some(head) = scheme.strip_suffix("token")
&& head.ends_with([' ', '\t', '"', '\'', ':', '='])
{
let head = head.trim_end_matches([' ', '\t', '"', '\'']);
let header = head
.strip_suffix(':')
.or_else(|| head.strip_suffix('='))
.map(|name| name.trim_end_matches([' ', '\t', '"', '\'']));
if header.is_some_and(|name| name.ends_with("authorization")) {
match header_context {
HeaderContext::ProviderHost => {
return Some((Confidence::High, "deepgram-host-token-header"));
}
HeaderContext::Keyword => {
return Some((Confidence::Medium, "deepgram-token-header"));
}
HeaderContext::Absent => {}
}
}
}
}
None
}
fn contains_ascii_ci(haystack: &[u8], needle: &[u8]) -> bool {
let len = needle.len();
if len == 0 {
return true;
}
if haystack.len() < len {
return false;
}
let first_lower = needle[0].to_ascii_lowercase();
let first_upper = needle[0].to_ascii_uppercase();
let last_start = haystack.len() - len;
let mut at = 0;
while at <= last_start {
let Some(offset) = haystack[at..=last_start]
.iter()
.position(|&byte| byte == first_lower || byte == first_upper)
else {
return false;
};
let candidate = at + offset;
if haystack[candidate..candidate + len].eq_ignore_ascii_case(needle) {
return true;
}
at = candidate + 1;
}
false
}
fn may_have_provider_context(text: &str, spec: &Spec) -> bool {
let bytes = text.as_bytes();
spec.keywords
.iter()
.any(|keyword| contains_ascii_ci(bytes, keyword.as_bytes()))
|| spec.exact_names.iter().any(|name| {
name.rsplit('_')
.all(|segment| contains_ascii_ci(bytes, segment.as_bytes()))
})
}
fn provider_word_bit(word: &str) -> Option<u8> {
Some(match word {
"mistral" => 1,
"cohere" => 2,
"ai21" => 4,
"deepgram" => 8,
"co" => 16,
"api" => 32,
"key" => 64,
_ => return None,
})
}
const PROVIDER_WORDS: [(&[u8], u8); 7] = [
(b"mistral", 1),
(b"cohere", 2),
(b"ai21", 4),
(b"deepgram", 8),
(b"co", 16),
(b"api", 32),
(b"key", 64),
];
fn provider_word_mask(bytes: &[u8]) -> u8 {
const FIRST: [u8; 256] = {
let mut first = [0u8; 256];
let mut word = 0;
while word < PROVIDER_WORDS.len() {
let (text, bit) = PROVIDER_WORDS[word];
first[text[0] as usize] |= bit;
first[text[0].to_ascii_uppercase() as usize] |= bit;
word += 1;
}
first
};
const ALL: u8 = 127;
let mut found = 0u8;
for (at, &byte) in bytes.iter().enumerate() {
let candidates = FIRST[usize::from(byte)] & !found;
if candidates == 0 {
continue;
}
for (word, bit) in PROVIDER_WORDS {
if candidates & bit != 0
&& bytes
.get(at..at + word.len())
.is_some_and(|window| window.eq_ignore_ascii_case(word))
{
found |= bit;
}
}
if found == ALL {
break;
}
}
found
}
fn may_have_provider_context_whole(input: &str, spec: &Spec) -> bool {
let Some(mask) = super::prefilter::provider_word_mask(input, provider_word_mask) else {
return may_have_provider_context(input, spec);
};
let bit = |word: &str| provider_word_bit(word).map(|bit| mask & bit != 0);
let mut answer = false;
for keyword in spec.keywords {
match bit(keyword) {
Some(found) => answer |= found,
None => return may_have_provider_context(input, spec),
}
}
for name in spec.exact_names {
let mut all = true;
for segment in name.rsplit('_') {
match bit(segment) {
Some(found) => all &= found,
None => return may_have_provider_context(input, spec),
}
}
answer |= all;
}
#[cfg(debug_assertions)]
assert_eq!(answer, may_have_provider_context(input, spec));
answer
}
fn detect_spec(input: &str, spec: &Spec) -> Vec<Candidate> {
let mut candidates = Vec::new();
if !may_have_provider_context_whole(input, spec) {
return candidates;
}
let multi_line = input.contains(['\n', '\r']);
let provider_word = multi_line && contains_ascii_ci(input.as_bytes(), b"provider");
for (line_start, line_end) in lines(input) {
let line = &input[line_start..line_end];
let on_line = !multi_line || may_have_provider_context(line, spec);
let key_line = if multi_line {
text::item_key_line(line)
} else {
None
};
let pair_line = key_line
.as_ref()
.is_some_and(|parsed| parsed.key == "value");
let sibling_line =
provider_word && key_line.as_ref().is_some_and(|parsed| !parsed.item_start);
let header_line =
multi_line && spec.api_host_domain.is_some() && http_header_name(line).is_some();
if !on_line && !pair_line && !sibling_line && !header_line {
continue;
}
let runs = scan_runs(line, spec);
if runs.is_empty() {
continue;
}
let paired_name = if pair_line {
text::list_item_paired_name(input, (line_start, line_end))
} else {
None
};
let provider_sibling = names_provider_field(line, spec.keywords)
|| (sibling_line
&& key_line.as_ref().is_some_and(|parsed| {
yaml_sibling_names_provider(input, line_start, parsed.column, spec.keywords)
}));
let block_host = header_line
&& spec
.api_host_domain
.is_some_and(|domain| http_block_names_host(input, line_start, domain));
if !on_line
&& !block_host
&& !provider_sibling
&& !paired_name.is_some_and(|name| may_have_provider_context(name, spec))
{
continue;
}
let keyword_on_line = on_line && contains_keyword_ci(line, spec).is_some();
let header = if !spec.token_header {
HeaderContext::Absent
} else if block_host
|| (keyword_on_line
&& spec
.api_host_domain
.is_some_and(|domain| names_host_under(line, domain)))
{
HeaderContext::ProviderHost
} else if keyword_on_line {
HeaderContext::Keyword
} else {
HeaderContext::Absent
};
let line_context = LineContext {
header,
keyword_on_line,
model_route: on_line && names_model_route(line, spec),
provider_sibling,
paired_name,
};
for (start, end) in runs {
if text::is_repeated_character_filler(&line[start..end])
|| text::is_labelled_digest(line, start)
{
continue;
}
let Some((confidence, signal)) = context(line, spec, start, end, &line_context) else {
continue;
};
let Some(range) = ByteRange::new(line_start + start, line_start + end) else {
continue;
};
candidates.push(
Candidate::built_in(spec.type_name, confidence, range)
.with_specificity(Specificity::Provider)
.with_signals([signal]),
);
}
}
candidates
}
macro_rules! keyword_gated_detector {
($struct_name:ident, $id:literal, $spec:expr) => {
pub(super) struct $struct_name;
impl Detector for $struct_name {
fn id(&self) -> &'static str {
$id
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
Ok(detect_spec(input, &$spec))
}
}
};
}
keyword_gated_detector!(MistralApiKeyDetector, "mistral-api-key", MISTRAL);
keyword_gated_detector!(CohereApiKeyDetector, "cohere-api-key", COHERE);
keyword_gated_detector!(Ai21ApiKeyDetector, "ai21-api-key", AI21);
keyword_gated_detector!(DeepgramApiKeyDetector, "deepgram-api-key", DEEPGRAM);
#[cfg(test)]
mod tests {
use super::*;
fn body(len: usize, seed: &str) -> String {
seed.chars().cycle().take(len).collect()
}
fn alnum32() -> String {
body(32, "aB3dE5gH7jK9mN1pQ3sT5vW7yZ9xC2")
}
fn alnum40() -> String {
body(40, "zY9xW7vU5tS3rQ1pO9nM7lK5jI3hG1fE")
}
fn lower40() -> String {
body(40, "q7w3e9r1t5y8u2i4o6p0a")
}
fn run(spec: &Spec, input: &str) -> Vec<Candidate> {
detect_spec(input, spec)
}
fn assert_exact(spec: &Spec, input: &str, value: &str, confidence: Confidence) {
let found = run(spec, input);
assert_eq!(found.len(), 1, "{input}");
let range = found[0].range();
assert_eq!(&input[range.start()..range.end()], value, "{input}");
assert_eq!(found[0].confidence(), confidence, "{input}");
assert_eq!(found[0].type_name(), spec.type_name);
}
#[test]
fn fixture_lengths_are_the_inferred_lengths() {
assert_eq!(alnum32().len(), 32);
assert_eq!(alnum40().len(), 40);
assert_eq!(lower40().len(), 40);
}
#[test]
fn named_assignments_are_high_confidence_exact_spans() {
let m = alnum32();
let c = alnum40();
let d = lower40();
for input in [
format!("MISTRAL_API_KEY={m}"),
format!("export MISTRAL_API_KEY=\"{m}\""),
format!("{{\"mistralApiKey\": \"{m}\"}}"),
format!("mistral_api_key: {m}"),
] {
assert_exact(&MISTRAL, &input, &m, Confidence::High);
}
for input in [
format!("CO_API_KEY={c}"),
format!("COHERE_API_KEY='{c}'"),
format!("cohere.token: {c}"),
] {
assert_exact(&COHERE, &input, &c, Confidence::High);
}
assert_exact(&AI21, &format!("AI21_API_KEY={m}"), &m, Confidence::High);
for input in [
format!("DEEPGRAM_API_KEY={d}"),
format!("deepgram_api_key = \"{d}\""),
] {
assert_exact(&DEEPGRAM, &input, &d, Confidence::High);
}
}
#[test]
fn sdk_constructor_arguments_are_high_confidence() {
let m = alnum32();
let c = alnum40();
let d = lower40();
assert_exact(
&MISTRAL,
&format!("client = Mistral(api_key=\"{m}\")"),
&m,
Confidence::High,
);
assert_exact(
&MISTRAL,
&format!("const c = new Mistral({{ apiKey: \"{m}\" }});"),
&m,
Confidence::High,
);
assert_exact(
&COHERE,
&format!("co = cohere.ClientV2(api_key=\"{c}\")"),
&c,
Confidence::High,
);
assert_exact(
&COHERE,
&format!("co = cohere.Client(\"{c}\")"),
&c,
Confidence::High,
);
assert_exact(
&COHERE,
&format!("new CohereClient({{ token: \"{c}\" }})"),
&c,
Confidence::High,
);
assert_exact(
&AI21,
&format!("AI21Client(api_key='{m}')"),
&m,
Confidence::High,
);
assert_exact(
&DEEPGRAM,
&format!("dg = DeepgramClient(api_key=\"{d}\")"),
&d,
Confidence::High,
);
assert_exact(
&DEEPGRAM,
&format!("dg = DeepgramClient(\"{d}\")"),
&d,
Confidence::High,
);
}
#[test]
fn issue_932_same_line_forms_are_recognized() {
let c = alnum40();
let d = lower40();
assert_exact(
&DEEPGRAM,
&format!(
"http --verbose POST https://api.deepgram.com/v1/listen 'Authorization:Token {d}' < a.wav"
),
&d,
Confidence::High,
);
assert_exact(
&DEEPGRAM,
&format!("var client = deepgram.NewRESTWithDefaults(context.Background(), \"{d}\")"),
&d,
Confidence::High,
);
assert_exact(
&DEEPGRAM,
&format!("c := deepgram.New(ctx, `x`, \"{d}\" )"),
&d,
Confidence::High,
);
assert_exact(
&COHERE,
&format!(
"Cohere cohere = Cohere.builder().token(\"{c}\").clientName(\"search-api\").build();"
),
&c,
Confidence::High,
);
assert_exact(
&COHERE,
&format!("var co = CohereClient.builder().apiKey('{c}').build();"),
&c,
Confidence::High,
);
}
#[test]
fn issue_1018_a_model_route_qualifies_an_unmasked_credential_key() {
let c = alnum40();
for input in [
format!(
"18:22:04 - LiteLLM Proxy:DEBUG: router.py:1841 - cohere/command-r-plus call failed; masked_api_key={c} reason=AuthenticationError"
),
format!("cohere/command-r-plus call failed; api_key={c}"),
format!("model=cohere/command-r redacted_api_key=\"{c}\""),
] {
assert_exact(&COHERE, &input, &c, Confidence::High);
}
let m = alnum32();
assert_exact(
&MISTRAL,
&format!("mistral/mistral-large-latest failed; masked_api_key={m}"),
&m,
Confidence::High,
);
let masked = format!("{}{}{}", &c[..4], "*".repeat(32), &c[36..]);
assert!(
run(
&COHERE,
&format!("cohere/command-r masked_api_key={masked}")
)
.is_empty()
);
}
#[test]
fn issue_1017_the_retention_hints_hold_exactly_the_windows_the_detector_reads() {
for open in [
"GET wss://api.deepgram.com/v1/listen HTTP/1.1\n",
"POST /v1/chat HTTP/1.1\nHost: api.deepgram.com\n",
"POST /v1/chat HTTP/1.1\r\nHost: api.deepgram.com\r\nAccept: */*\r\n",
] {
assert!(has_open_deepgram_request(open), "{open:?}");
}
let long_request = format!(
"GET /v1/listen HTTP/1.1\nHost: api.deepgram.com\n{}",
"X-Pad: 1\n".repeat(MAX_HTTP_BLOCK_LINES)
);
for closed in [
"",
"GET wss://api.example.invalid/v1/listen HTTP/1.1\n",
"POST /v1/chat HTTP/1.1\nHost: api.example.invalid\n",
"POST /v1/chat HTTP/1.1\nHost: api.deepgram.com\n\n",
"Host: api.deepgram.com\nsome body text\n",
long_request.as_str(),
] {
assert!(!has_open_deepgram_request(closed), "{closed:?}");
}
for open in [
"stt:\n provider: deepgram\n",
"stt:\n provider: cohere\n model: x\n",
"- provider: mistral\n",
] {
assert!(has_open_provider_sibling(open), "{open:?}");
}
let long_mapping = format!(
"stt:\n provider: deepgram\n{}",
" pad: 1\n".repeat(MAX_SIBLING_LINES)
);
for closed in [
"",
"stt:\n provider: whisper\n",
"stt:\n provider: deepgram\n\n",
"stt:\n provider: deepgram\n nested: 1\n",
"- provider: deepgram\n- other: 1\n",
long_mapping.as_str(),
] {
assert!(!has_open_provider_sibling(closed), "{closed:?}");
}
}
#[test]
fn issue_1017_forms_are_recognized_and_their_twins_are_not() {
let d = lower40();
assert_exact(
&DEEPGRAM,
&format!("const deepgram = createClient(\"{d}\");"),
&d,
Confidence::High,
);
assert_exact(
&DEEPGRAM,
&format!(
"GET /v1/listen HTTP/1.1\nHost: api.deepgram.com\nSec-WebSocket-Protocol: token, {d}"
),
&d,
Confidence::High,
);
assert_exact(
&DEEPGRAM,
&format!("{{\"provider\": \"deepgram\", \"api_key\": \"{d}\"}}"),
&d,
Confidence::High,
);
assert_exact(
&COHERE,
&format!("llm:\n provider: cohere\n api_key: {}", alnum40()),
&alnum40(),
Confidence::High,
);
for input in [
format!("const widget = createClient(\"{d}\");"),
format!("Sec-WebSocket-Protocol: token, {d}"),
format!("X-Sec-WebSocket-Protocol-Other: token, {d} deepgram"),
format!("{{\"provider\":\"deepgram\",\"request_id\":\"{d}\"}}"),
format!("stt:\n provider: deepgram\n project_id: {d}"),
] {
assert!(run(&DEEPGRAM, &input).is_empty(), "{input}");
}
}
#[test]
fn issue_932_benign_twins_stay_silent() {
let c = alnum40();
let d = lower40();
for input in [
format!(
"http POST https://api.example-speech.test/v1/listen 'Authorization:Token {d}'"
),
format!("http POST https://api.deepgram.com/v1/listen 'Authorization:Bearer {d}'"),
format!("deepgram.NewRESTWithDefaults(ctx, \"{d}\", opts)"),
format!("speech.NewRESTWithDefaults(context.Background(), \"{d}\")"),
format!("deepgram.NewRESTWithDefaults(ctx, {d})"),
format!("deepgram.NewRESTWithDefaults(ctx, \"{}\")", &d[..39]),
format!("Cohere.builder().clientName(\"{d}\").build();"),
format!("Other.builder().token(\"{d}\").build();"),
format!("load(\"cohere\").token(\"{d}\")"),
format!("DEBUG: cohere/command-r-plus call failed; request_id={c}"),
format!("DEBUG: mycohere/command-r call failed; api_key={c}"),
format!("DEBUG: cohere/ call failed; api_key={c}"),
format!(
"DEBUG: cohere/command-r-plus call failed on retry; hashed_api_key={}",
"0123456789abcdef".repeat(3).get(..40).unwrap_or_default()
),
] {
assert!(run(&DEEPGRAM, &input).is_empty(), "{input}");
assert!(run(&COHERE, &input).is_empty(), "{input}");
}
}
#[test]
fn a_keyword_adjacent_key_and_a_keyword_only_deepgram_token_header_are_medium() {
let m = alnum32();
let d = lower40();
assert_exact(
&MISTRAL,
&format!("# Mistral API key: {m}"),
&m,
Confidence::Medium,
);
for input in [
format!("# deepgram smoke test: Authorization: Token {d}"),
format!("curl -H 'Authorization: Token {d}' https://deepgram.example.test/v1"),
format!("curl -H 'Authorization: Token {d}' https://api.deepgram.com.example.test/"),
format!("curl -H 'Authorization: Token {d}' https://api.deepgram.company/v1 deepgram"),
] {
assert_exact(&DEEPGRAM, &input, &d, Confidence::Medium);
}
}
#[test]
fn a_deepgram_token_header_on_a_request_to_the_deepgram_api_host_is_high() {
let d = lower40();
for input in [
format!("curl -H 'Authorization: Token {d}' https://api.deepgram.com/v1/projects"),
format!("curl -H \"Authorization: Token {d}\" https://API.Deepgram.com/v1/listen"),
format!("http POST https://api.eu.deepgram.com/v1/listen 'Authorization:Token {d}'"),
format!(
"headers = {{\"Authorization\": \"Token {d}\", \"host\": \"api.deepgram.com\"}}"
),
] {
assert_exact(&DEEPGRAM, &input, &d, Confidence::High);
}
assert!(
run(
&DEEPGRAM,
&format!("GET https://api.deepgram.com/v1/x?id={d}")
)
.is_empty()
);
}
#[test]
fn bare_values_and_unrelated_keys_are_not_findings() {
let m = alnum32();
let c = alnum40();
let d = lower40();
for input in [
m.clone(),
format!("hash {m}"),
format!("API_KEY={m}"),
format!("OPENAI_API_KEY={m}"),
format!("mistral is fine, id {m}"),
format!("Client(api_key=\"{m}\")"),
format!("Authorization: Token {m}"),
] {
assert!(run(&MISTRAL, &input).is_empty(), "{input}");
assert!(run(&AI21, &input).is_empty(), "{input}");
}
assert!(run(&COHERE, &c).is_empty());
assert!(run(&COHERE, &format!("PICO_API_KEY={c}")).is_empty());
assert!(run(&COHERE, &format!("cohere_api_key value {c}")).is_empty());
assert!(run(&DEEPGRAM, &format!("Authorization: Token {d}")).is_empty());
assert!(run(&DEEPGRAM, &format!("Authorization: Bearer {d} deepgram")).is_empty());
}
#[test]
fn id_like_and_non_credential_siblings_are_not_findings() {
let m = alnum32();
let c = alnum40();
let d = lower40();
for input in [
format!("MISTRAL_KEY_ID={m}"),
format!("MISTRAL_MODEL={m}"),
format!("Mistral(model=\"{m}\")"),
format!("AI21_ORG_ID={m}"),
format!("AI21_TEAM_ID={m}"),
] {
assert!(run(&MISTRAL, &input).is_empty(), "{input}");
assert!(run(&AI21, &input).is_empty(), "{input}");
}
assert!(run(&COHERE, &format!("COHERE_ORG_ID={c}")).is_empty());
assert!(run(&COHERE, &format!("cohere.ClientV2(base_url=\"{c}\")")).is_empty());
assert!(run(&DEEPGRAM, &format!("DEEPGRAM_PROJECT_ID={d}")).is_empty());
assert!(run(&DEEPGRAM, &format!("DEEPGRAM_API_KEY_ID={d}")).is_empty());
}
#[test]
fn placeholders_fillers_and_digests_are_not_findings() {
let m = alnum32();
for input in [
"MISTRAL_API_KEY=your_api_key_here".to_owned(),
"MISTRAL_API_KEY=<your-mistral-key>".to_owned(),
"MISTRAL_API_KEY=${MISTRAL_API_KEY}".to_owned(),
format!("MISTRAL_API_KEY={}", "x".repeat(32)),
format!("MISTRAL_API_KEY={}", "0".repeat(32)),
format!("MISTRAL_API_KEY=md5:{m}"),
"Mistral(api_key=os.environ[\"MISTRAL_API_KEY\"])".to_owned(),
] {
assert!(run(&MISTRAL, &input).is_empty(), "{input}");
}
assert!(run(&DEEPGRAM, &format!("DEEPGRAM_API_KEY={}", "a".repeat(40))).is_empty());
}
#[test]
fn twins_with_the_wrong_length_or_alphabet_are_not_findings() {
let m = alnum32();
let c = alnum40();
let d = lower40();
for value in [
body(31, &m),
body(33, &m),
format!("{}_{}", &m[..15], &m[16..]),
format!("{}-{}", &m[..15], &m[16..]),
format!("{m}{m}"),
] {
let input = format!("MISTRAL_API_KEY={value}");
assert!(run(&MISTRAL, &input).is_empty(), "{input}");
}
assert!(run(&COHERE, &format!("CO_API_KEY={}", body(39, &c))).is_empty());
assert!(run(&COHERE, &format!("CO_API_KEY={}", body(41, &c))).is_empty());
assert!(
run(
&DEEPGRAM,
&format!("DEEPGRAM_API_KEY={}", d.to_ascii_uppercase())
)
.is_empty()
);
assert!(run(&DEEPGRAM, &format!("DEEPGRAM_API_KEY={}", body(39, &d))).is_empty());
assert!(run(&AI21, &format!("AI21_API_KEY={}", body(40, &m))).is_empty());
}
#[test]
fn a_value_is_not_reported_for_the_wrong_provider() {
let m = alnum32();
assert!(run(&AI21, &format!("MISTRAL_API_KEY={m}")).is_empty());
assert!(run(&MISTRAL, &format!("AI21_API_KEY={m}")).is_empty());
assert!(run(&MISTRAL, &format!("Cohere(api_key=\"{m}\")")).is_empty());
}
#[test]
fn context_on_a_different_line_is_not_adjacent() {
let m = alnum32();
let input = format!("Mistral(\n api_key=\"{m}\"\n)");
assert!(run(&MISTRAL, &input).is_empty());
let input = format!("MISTRAL_API_KEY=\n{m}");
assert!(run(&MISTRAL, &input).is_empty());
}
#[test]
fn every_value_on_a_line_is_judged_alone_and_scanning_is_deterministic() {
let m = alnum32();
let other = body(32, "Zz9Yy8Xx7Ww6Vv5Uu4Tt3Ss2Rr1Qq0");
let input = format!("MISTRAL_API_KEY={m} SECOND={other}\r\nMISTRAL_API_KEY={other}");
let first = run(&MISTRAL, &input);
assert_eq!(first.len(), 2);
assert_eq!(first, run(&MISTRAL, &input));
}
#[test]
fn a_unicode_prefix_keeps_byte_offsets_exact() {
let m = alnum32();
let input = format!("한글 MISTRAL_API_KEY={m}");
assert_exact(&MISTRAL, &input, &m, Confidence::High);
}
#[test]
fn a_long_line_of_near_misses_stays_bounded() {
let input = format!("MISTRAL_API_KEY={}", "a".repeat(200_000));
assert!(run(&MISTRAL, &input).is_empty());
let input = "Mistral(".repeat(20_000);
assert!(run(&MISTRAL, &input).is_empty());
}
}
#[cfg(test)]
mod case_insensitive_differential_tests {
use super::*;
use crate::test_rng::{BOUNDARY_PIECES, XorShift32};
const SPECS: [&Spec; 4] = [&MISTRAL, &COHERE, &AI21, &DEEPGRAM];
fn old_names_host_under(line: &str, domain: &str) -> bool {
let lowered = line.to_ascii_lowercase();
let bytes = lowered.as_bytes();
lowered.match_indices(domain).any(|(at, _)| {
let end = at + domain.len();
let after_ends_host = match bytes.get(end) {
None => true,
Some(b'.') => !bytes.get(end + 1).is_some_and(u8::is_ascii_alphanumeric),
Some(&byte) => !(byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')),
};
at > 0 && bytes[at - 1] == b'.' && after_ends_host
})
}
fn old_names_model_route(line: &str, spec: &Spec) -> bool {
let lowered = line.to_ascii_lowercase();
let bytes = lowered.as_bytes();
spec.keywords.iter().any(|keyword| {
lowered.match_indices(keyword).any(|(at, _)| {
let end = at + keyword.len();
(at == 0 || !is_boundary_byte(bytes[at - 1]))
&& bytes.get(end) == Some(&b'/')
&& bytes.get(end + 1).is_some_and(u8::is_ascii_alphanumeric)
})
})
}
fn old_names_provider_field(line: &str, keywords: &[&str]) -> bool {
let lowered = line.to_ascii_lowercase();
let bytes = lowered.as_bytes();
let is_ident = |byte: u8| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-');
lowered.match_indices("provider").any(|(at, field)| {
if at > 0 && is_ident(bytes[at - 1]) {
return false;
}
let mut cursor = at + field.len();
cursor += ascii_run(bytes, cursor, |byte| matches!(byte, b'"' | b'\'' | b'\\'));
cursor += ascii_run(bytes, cursor, |byte| matches!(byte, b' ' | b'\t'));
if !matches!(bytes.get(cursor), Some(b':' | b'=')) {
return false;
}
cursor += 1;
cursor += ascii_run(bytes, cursor, |byte| {
matches!(byte, b' ' | b'\t' | b'"' | b'\'' | b'\\')
});
keywords.iter().any(|keyword| {
lowered[cursor..].starts_with(keyword)
&& !bytes
.get(cursor + keyword.len())
.is_some_and(|&byte| is_ident(byte))
})
})
}
fn old_is_token_subprotocol(bytes: &[u8], start: usize) -> bool {
let window = &bytes[start.saturating_sub(HEADER_WINDOW)..start];
let Ok(window) = std::str::from_utf8(window) else {
return false;
};
let before = window.to_ascii_lowercase();
let spaces: &[char] = &[' ', '\t'];
if let Some(head) = before.strip_suffix(['"', '\''])
&& let Some(head) = head.trim_end_matches(spaces).strip_suffix(',')
{
let head = head.trim_end_matches(spaces);
return ["\"token\"", "'token'"].iter().any(|quoted| {
head.strip_suffix(quoted)
.is_some_and(|open| open.trim_end_matches(spaces).ends_with('['))
});
}
before
.trim_end_matches(spaces)
.strip_suffix(',')
.and_then(|head| head.trim_end_matches(spaces).strip_suffix("token"))
.and_then(|head| head.trim_end_matches(spaces).strip_suffix(':'))
.and_then(|head| head.strip_suffix("sec-websocket-protocol"))
.is_some_and(|lead| {
!lead
.bytes()
.last()
.is_some_and(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
})
}
fn old_inside_provider_call(
line: &str,
spec: &Spec,
end: usize,
keyword_on_line: bool,
) -> bool {
let bytes = line.as_bytes();
let end = end.min(bytes.len());
let floor = end.saturating_sub(CALL_WINDOW);
let mut cursor = end;
while cursor > floor {
cursor -= 1;
match bytes[cursor] {
b')' => return false,
b'(' => {
let mut start = cursor;
while start > 0
&& (bytes[start - 1].is_ascii_alphanumeric()
|| matches!(bytes[start - 1], b'_' | b'.'))
{
start -= 1;
}
let callee = line[start..cursor].to_ascii_lowercase();
if spec.keywords.iter().any(|keyword| callee.contains(keyword)) {
return true;
}
if keyword_on_line
&& callee
.rsplit('.')
.next()
.is_some_and(|name| spec.factory_callees.contains(&name))
{
return true;
}
}
_ => {}
}
}
false
}
const WORDS: &[&str] = &[
"deepgram",
"DeepGram",
"DEEPGRAM",
"deepgram.com",
"API.DEEPGRAM.COM",
".deepgram.com",
"mistral",
"Mistral",
"cohere",
"COHERE",
"ai21",
"AI21",
"provider",
"Provider",
"PROVIDER",
"\"provider\":",
"provider=",
"/",
"model",
"createClient",
"createclient",
"CREATECLIENT",
"(",
")",
"new ",
"Sec-WebSocket-Protocol",
"sec-websocket-protocol",
"token",
"TOKEN",
"\"token\"",
"'Token'",
"HOST: ",
"GET ",
"https://",
"\u{212a}",
];
fn lines() -> Vec<String> {
let mut rng = XorShift32::new(0x1086_0003);
let mut pieces: Vec<&str> = BOUNDARY_PIECES.to_vec();
pieces.extend_from_slice(WORDS);
let mut out = vec![String::new()];
out.extend(WORDS.iter().map(|word| (*word).to_owned()));
for _ in 0..5000 {
out.push(rng.text(&pieces, 9));
}
out
}
#[test]
fn host_route_and_provider_field_match_the_lowercasing_implementation() {
for line in lines() {
assert_eq!(
names_host_under(&line, DEEPGRAM_API_DOMAIN),
old_names_host_under(&line, DEEPGRAM_API_DOMAIN),
"{line:?}"
);
for spec in SPECS {
assert_eq!(
names_model_route(&line, spec),
old_names_model_route(&line, spec),
"{line:?}"
);
assert_eq!(
names_provider_field(&line, spec.keywords),
old_names_provider_field(&line, spec.keywords),
"{line:?}"
);
}
}
}
#[test]
fn token_subprotocol_matches_the_lowercasing_implementation() {
for line in lines() {
let bytes = line.as_bytes();
for start in 0..=bytes.len() {
assert_eq!(
is_token_subprotocol(bytes, start),
old_is_token_subprotocol(bytes, start),
"{line:?} at {start}"
);
}
}
}
#[test]
fn provider_call_matches_the_lowercasing_implementation() {
for line in lines() {
let len = line.len();
for spec in SPECS {
for end in [0, len / 2, len, len + 3] {
for keyword_on_line in [false, true] {
assert_eq!(
inside_provider_call(&line, spec, end, keyword_on_line),
old_inside_provider_call(&line, spec, end, keyword_on_line),
"{line:?} end {end}"
);
}
}
}
}
}
#[test]
fn positive_shapes_in_any_case_match_the_lowercasing_implementation() {
let shapes: [(&str, usize, bool); 8] = [
("Sec-WebSocket-Protocol: token, ", 0, true),
("SEC-WEBSOCKET-PROTOCOL:\tTOKEN ,\t", 0, true),
("x-Sec-WebSocket-Protocol: token, ", 0, false),
("[\"token\", \"", 0, true),
("[ 'TOKEN' , '", 0, true),
("\u{e9}[\"Token\", \"", 0, true),
("\"token\", \"", 0, false),
("Sec-WebSocket-Protocol: token ", 0, false),
];
for (text, _, expected) in shapes {
let bytes = text.as_bytes();
let start = bytes.len();
assert_eq!(old_is_token_subprotocol(bytes, start), expected, "{text:?}");
assert_eq!(is_token_subprotocol(bytes, start), expected, "{text:?}");
}
for (line, expected) in [
("API.Deepgram.COM/v1", true),
("api.deepgram.com.example.test", false),
("Deepgram.com", false),
] {
assert_eq!(old_names_host_under(line, DEEPGRAM_API_DOMAIN), expected);
assert_eq!(names_host_under(line, DEEPGRAM_API_DOMAIN), expected);
}
for (line, keywords, expected) in [
("\"Provider\": \"DeepGram\"", DEEPGRAM.keywords, true),
("PROVIDER = 'cohere'", COHERE.keywords, true),
("provider: deepgramx", DEEPGRAM.keywords, false),
] {
assert_eq!(old_names_provider_field(line, keywords), expected);
assert_eq!(names_provider_field(line, keywords), expected);
}
assert!(names_model_route("COHERE/command-r", &COHERE));
assert!(old_names_model_route("COHERE/command-r", &COHERE));
}
#[test]
fn the_needles_the_helpers_rely_on_are_lowercase_ascii() {
for spec in SPECS {
for needle in spec.keywords.iter().chain(spec.factory_callees) {
assert!(!needle.is_empty());
assert!(
needle
.bytes()
.all(|b| !b.is_ascii_uppercase() && b.is_ascii())
);
}
}
assert!(
DEEPGRAM_API_DOMAIN
.bytes()
.all(|b| b.is_ascii() && !b.is_ascii_uppercase())
);
}
#[test]
fn the_shared_provider_word_mask_matches_the_per_spec_gates() {
use crate::detectors::prefilter::ScanScope;
let pieces: Vec<&str> = [
"mistral",
"MISTRAL",
"Mistra",
"cohere",
"Cohere",
"COHERE",
"coher",
"co",
"Co",
"api",
"API",
"ap",
"key",
"KEY",
"ke",
"ai21",
"AI21",
"ai2",
"deepgram",
"DeepGram",
"deepgra",
"co_api_key",
"CO_API_KEY",
"coApiKey",
"co.api.key",
"co-api-key",
"\u{212a}ey",
"\u{200b}",
"é",
" ",
"\n",
"=",
"x",
]
.into_iter()
.chain(BOUNDARY_PIECES.iter().copied())
.collect();
let mut rng = XorShift32::new(0x1092);
for _ in 0..6000 {
let text = rng.text(&pieces, 8);
let bytes = text.as_bytes();
let oracle = PROVIDER_WORDS.iter().fold(0u8, |mask, (word, bit)| {
if contains_ascii_ci(bytes, word) {
mask | bit
} else {
mask
}
});
assert_eq!(provider_word_mask(bytes), oracle, "{text:?}");
let _scope = ScanScope::enter(&text);
for spec in SPECS {
assert_eq!(
may_have_provider_context_whole(&text, spec),
may_have_provider_context(&text, spec),
"{text:?}"
);
}
let other = text.clone();
for spec in SPECS {
assert_eq!(
may_have_provider_context_whole(&other, spec),
may_have_provider_context(&other, spec)
);
}
}
for spec in SPECS {
for word in spec
.keywords
.iter()
.copied()
.chain(spec.exact_names.iter().flat_map(|name| name.rsplit('_')))
{
assert!(provider_word_bit(word).is_some(), "{word}");
}
}
}
}