use crate::detectors::pattern::{self, Alphabet, RunLength};
use crate::detectors::text;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
fn is_lower_hex(byte: u8) -> bool {
byte.is_ascii_digit() || byte.is_ascii_lowercase() && byte <= b'f'
}
const SECRET_LEN: usize = 32;
const CONTEXT_KEYWORD: &str = "twilio";
fn line_contains_ci(line: &str, needle: &str) -> bool {
text::contains_ci(line, needle)
}
fn line_has_paired_identifier(line: &str, prefix: &str, alphabet: Alphabet) -> bool {
!pattern::scan_prefixed_runs(
line,
&[prefix],
RunLength::Exact(SECRET_LEN),
alphabet,
alphabet,
)
.is_empty()
}
fn scan_bare_secret_runs(
input: &str,
alphabet: Alphabet,
boundary: Alphabet,
) -> Vec<(usize, usize)> {
let bytes = input.as_bytes();
let mut matches = Vec::new();
let mut start = 0;
while start < bytes.len() {
if !alphabet(bytes[start]) {
start += 1;
continue;
}
let run_end = pattern::run_end(bytes, start, alphabet);
if run_end - start == SECRET_LEN && pattern::boundary_ok(bytes, start, run_end, boundary) {
matches.push((start, run_end));
}
start = run_end;
}
matches
}
const CLI_TABLE_MAX_DATA_ROWS: usize = 4;
pub(super) const CLI_TABLE_LOOKBACK_LINES: usize = CLI_TABLE_MAX_DATA_ROWS + 1;
const AUTH_TOKEN_COLUMN: &str = "auth token";
fn words(line: &str) -> impl Iterator<Item = &str> {
line.split([' ', '\t', '\r'])
.filter(|word| !word.is_empty())
}
fn is_twilio_cli_command(line: &str) -> bool {
let mut words = words(line).peekable();
if words
.peek()
.is_some_and(|first| *first != "twilio" && first.ends_with(['$', '%', '>', '#']))
{
words.next();
}
words.next() == Some("twilio") && words.next().is_some_and(|command| command.contains(':'))
}
fn auth_token_column(line: &str) -> Option<usize> {
let bytes = line.as_bytes();
let len = AUTH_TOKEN_COLUMN.len();
(0..=bytes.len().checked_sub(len)?).find(|&at| {
text::starts_with_ci(line, at, AUTH_TOKEN_COLUMN)
&& (at == 0 || matches!(bytes[at - 1], b' ' | b'\t'))
&& bytes
.get(at + len)
.is_none_or(|&byte| matches!(byte, b' ' | b'\t' | b'\r'))
})
}
fn is_cli_table_data_row(line: &str) -> bool {
words(line).next().is_some() && !is_twilio_cli_command(line)
}
fn open_cli_table_column(previous: &[&str]) -> Option<usize> {
for (rows, index) in (0..previous.len()).rev().enumerate() {
if rows >= CLI_TABLE_MAX_DATA_ROWS {
return None;
}
let line = previous[index];
if index > 0
&& is_twilio_cli_command(previous[index - 1])
&& let Some(column) = auth_token_column(line)
{
return Some(column);
}
if !is_cli_table_data_row(line) {
return None;
}
}
None
}
#[cfg(test)]
pub(crate) fn has_open_twilio_cli_table(input: &str) -> bool {
has_open_twilio_cli_table_in(&super::lookback_tail(input))
}
pub(crate) fn has_open_twilio_cli_table_in(tail: &[&str]) -> bool {
let tail = text::tail_lines(tail, CLI_TABLE_LOOKBACK_LINES);
tail.last().is_some_and(|last| is_twilio_cli_command(last))
|| open_cli_table_column(tail).is_some()
}
fn is_cell_at_column(line: &str, start: usize, end: usize, column: usize) -> bool {
start == column
&& line.as_bytes()[..start]
.last()
.is_none_or(|&byte| matches!(byte, b' ' | b'\t'))
&& line
.as_bytes()
.get(end)
.is_none_or(|&byte| matches!(byte, b' ' | b'\t' | b'\r'))
}
#[allow(clippy::too_many_arguments)]
fn detect_context_gated(
input: &str,
alphabet: Alphabet,
boundary: Alphabet,
identifier_prefix: &str,
identifier_alphabet: Alphabet,
type_name: &'static str,
identifier_signal: &str,
cli_table: bool,
) -> Vec<Candidate> {
let mut candidates = Vec::new();
text::for_each_long_run_line(input, |line_start, line_end| {
let line = &input[line_start..line_end];
let raw_matches = scan_bare_secret_runs(line, alphabet, boundary);
if raw_matches.is_empty() {
return;
}
let line_context =
if line_has_paired_identifier(line, identifier_prefix, identifier_alphabet) {
Some((Confidence::High, identifier_signal))
} else if line_contains_ci(line, CONTEXT_KEYWORD) {
Some((Confidence::Medium, "twilio-keyword-cooccurrence"))
} else {
None
};
let table_column = if line_context.is_none() && cli_table {
let previous = text::preceding_lines(input, line_start, CLI_TABLE_LOOKBACK_LINES);
open_cli_table_column(&previous)
} else {
None
};
if line_context.is_none() && table_column.is_none() {
return;
}
for (relative_start, relative_end) in raw_matches {
if text::is_repeated_character_filler(&line[relative_start..relative_end])
|| text::is_labelled_digest(line, relative_start)
{
continue;
}
let (confidence, signal) = match (line_context, table_column) {
(Some(context), _) => context,
(None, Some(column))
if is_cell_at_column(line, relative_start, relative_end, column) =>
{
(Confidence::High, "twilio-cli-table")
}
_ => continue,
};
let Some(range) =
ByteRange::new(line_start + relative_start, line_start + relative_end)
else {
continue;
};
let (confidence, signal) = if confidence == Confidence::Medium
&& line_context.is_some()
&& text::is_provider_named_assignment(line, relative_start, &[CONTEXT_KEYWORD])
{
(Confidence::High, "twilio-named-assignment")
} else {
(confidence, signal)
};
candidates.push(
Candidate::built_in(type_name, confidence, range)
.with_specificity(Specificity::Provider)
.with_signals([signal]),
);
}
});
candidates
}
pub(super) struct TwilioAuthTokenDetector;
impl Detector for TwilioAuthTokenDetector {
fn id(&self) -> &'static str {
"twilio-auth-token"
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
Ok(detect_context_gated(
input,
is_lower_hex,
pattern::is_alnum,
"AC",
is_lower_hex,
"twilio_auth_token",
"twilio-account-sid-cooccurrence",
true,
))
}
}
pub(super) struct TwilioApiKeySecretDetector;
impl Detector for TwilioApiKeySecretDetector {
fn id(&self) -> &'static str {
"twilio-api-key-secret"
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
Ok(detect_context_gated(
input,
pattern::is_alnum,
pattern::is_alnum,
"SK",
pattern::is_alnum,
"twilio_api_key_secret",
"twilio-api-key-sid-cooccurrence",
false,
))
}
}
#[cfg(test)]
mod tests {
use super::*;
const ACCOUNT_SID: &str = "AC0123456789abcdef0123456789abcde0";
const AUTH_TOKEN: &str = "fedcba9876543210fedcba9876543210";
const API_KEY_SID: &str = "SKaB3dE5gH7jK9mN1pQ3sT5vW7yZ9AbC3d";
const API_KEY_SECRET: &str = "zY9xW7vU5tS3rQ1pO9nM7lK5jI3hG1fE";
fn detect_auth_token(input: &str) -> Vec<Candidate> {
TwilioAuthTokenDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
fn detect_api_key_secret(input: &str) -> Vec<Candidate> {
TwilioApiKeySecretDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
#[test]
fn account_sid_and_auth_token_fixtures_are_exactly_thirty_four_and_thirty_two_bytes() {
assert_eq!(ACCOUNT_SID.len(), 34);
assert_eq!(AUTH_TOKEN.len(), 32);
assert_eq!(API_KEY_SID.len(), 34);
assert_eq!(API_KEY_SECRET.len(), 32);
}
#[test]
fn detects_an_auth_token_alongside_an_account_sid_at_high_confidence() {
let input = format!("{ACCOUNT_SID} {AUTH_TOKEN}");
let candidates = detect_auth_token(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "twilio_auth_token");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
let start = input.rfind(AUTH_TOKEN).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + AUTH_TOKEN.len()).unwrap()
);
}
#[test]
fn detects_an_auth_token_under_a_twilio_named_key_at_high_confidence() {
let input = format!("TWILIO_AUTH_TOKEN={AUTH_TOKEN}");
let candidates = detect_auth_token(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::High);
let start = input.rfind(AUTH_TOKEN).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + AUTH_TOKEN.len()).unwrap()
);
}
#[test]
fn rejects_a_bare_auth_token_with_no_context() {
assert_eq!(detect_auth_token(AUTH_TOKEN).len(), 0);
}
#[test]
fn rejects_an_auth_token_whose_context_is_on_a_different_line() {
let input = format!("{ACCOUNT_SID}\n{AUTH_TOKEN}\n");
assert_eq!(detect_auth_token(&input).len(), 0);
}
#[test]
fn rejects_an_uppercase_hex_run() {
let upper: String = AUTH_TOKEN.to_ascii_uppercase();
assert_eq!(detect_auth_token(&format!("twilio {upper}")).len(), 0);
}
#[test]
fn rejects_a_run_one_byte_short_of_the_required_length() {
let short = &AUTH_TOKEN[..AUTH_TOKEN.len() - 1];
assert_eq!(detect_auth_token(&format!("twilio {short}")).len(), 0);
}
#[test]
fn rejects_a_run_one_byte_longer_than_the_required_length_rather_than_truncating() {
let long = format!("{AUTH_TOKEN}0");
assert_eq!(detect_auth_token(&format!("twilio {long}")).len(), 0);
}
#[test]
fn rejects_a_repeated_character_filler_value() {
assert_eq!(
detect_auth_token(&format!("twilio {}", "0".repeat(SECRET_LEN))).len(),
0
);
}
#[test]
fn rejects_an_environment_variable_reference() {
assert_eq!(
detect_auth_token("twilio TWILIO_AUTH_TOKEN=${TWILIO_AUTH_TOKEN}").len(),
0
);
}
#[test]
fn does_not_flag_a_bare_account_sid_by_itself() {
assert_eq!(detect_auth_token(ACCOUNT_SID).len(), 0);
}
#[test]
fn does_not_flag_the_account_sids_own_body_as_a_second_candidate() {
let input = format!("{ACCOUNT_SID} {AUTH_TOKEN}");
let candidates = detect_auth_token(&input);
assert_eq!(candidates.len(), 1);
}
#[test]
fn detects_an_api_key_secret_alongside_an_api_key_sid_at_high_confidence() {
let input = format!("{API_KEY_SID} {API_KEY_SECRET}");
let candidates = detect_api_key_secret(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "twilio_api_key_secret");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
let start = input.rfind(API_KEY_SECRET).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + API_KEY_SECRET.len()).unwrap()
);
}
#[test]
fn detects_an_api_key_secret_under_a_twilio_named_key_at_high_confidence() {
let input = format!("{{\"twilioApiKeySecret\": \"{API_KEY_SECRET}\"}}");
let candidates = detect_api_key_secret(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::High);
let start = input.rfind(API_KEY_SECRET).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + API_KEY_SECRET.len()).unwrap()
);
}
#[test]
fn rejects_a_bare_api_key_secret_with_no_context() {
assert_eq!(detect_api_key_secret(API_KEY_SECRET).len(), 0);
}
#[test]
fn rejects_an_api_key_secret_whose_context_is_on_a_different_line() {
let input = format!("{API_KEY_SID}\n{API_KEY_SECRET}\n");
assert_eq!(detect_api_key_secret(&input).len(), 0);
}
#[test]
fn does_not_flag_a_bare_api_key_sid_by_itself() {
assert_eq!(detect_api_key_secret(API_KEY_SID).len(), 0);
}
#[test]
fn rejects_a_placeholder_style_run_of_x_characters() {
assert_eq!(
detect_api_key_secret(&format!("twilio {}", "X".repeat(SECRET_LEN))).len(),
0
);
}
#[test]
fn finds_a_qualified_match_across_crlf_and_a_unicode_prefix() {
let input = format!("# \u{1F511} caf\u{e9}\r\ntwilio {AUTH_TOKEN}\r\n");
let candidates = detect_auth_token(&input);
assert_eq!(candidates.len(), 1);
let start = input.rfind(AUTH_TOKEN).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + AUTH_TOKEN.len()).unwrap()
);
}
#[test]
fn finds_deterministic_findings_across_repeated_calls() {
let input = format!("{ACCOUNT_SID} {AUTH_TOKEN}");
assert_eq!(detect_auth_token(&input), detect_auth_token(&input));
}
#[test]
fn stays_bounded_over_a_long_context_free_line_packed_with_candidates() {
let input = format!("{AUTH_TOKEN} ").repeat(10_000);
assert_eq!(detect_auth_token(&input).len(), 0);
}
#[test]
fn every_candidate_on_a_context_bearing_line_is_reported() {
let input = format!("{ACCOUNT_SID} {AUTH_TOKEN} {AUTH_TOKEN}");
let candidates = detect_auth_token(&input);
assert_eq!(candidates.len(), 2);
assert!(
candidates
.iter()
.all(|candidate| candidate.confidence() == Confidence::High)
);
}
#[test]
fn rejects_a_hash_algorithm_labelled_digest_on_a_twilio_line() {
for input in [
format!("twilio-9.3.0.tar.gz md5={AUTH_TOKEN}"),
format!("twilio-9.3.0.tar.gz MD5={AUTH_TOKEN}"),
format!("twilio checksum sha256: {AUTH_TOKEN}"),
format!("twilio@sha256:{AUTH_TOKEN}"),
format!("{ACCOUNT_SID} md5={AUTH_TOKEN}"),
] {
assert!(detect_auth_token(&input).is_empty(), "{input}");
}
assert!(detect_api_key_secret(&format!("twilio md5={API_KEY_SECRET}")).is_empty());
}
#[test]
fn a_digest_label_elsewhere_on_the_line_does_not_hide_a_real_auth_token() {
let input = format!("TWILIO_AUTH_TOKEN={AUTH_TOKEN}");
let candidates = detect_auth_token(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].range().start(), 18);
assert_eq!(candidates[0].range().end(), 50);
for input in [
format!("twilio md5=ok token={AUTH_TOKEN}"),
format!("TWILIO_AUTH_TOKEN_MD5X={AUTH_TOKEN}"),
format!("twilio xmd5={AUTH_TOKEN}"),
] {
assert_eq!(detect_auth_token(&input).len(), 1, "{input}");
}
}
fn profiles_table(header: &str, rows: &str) -> String {
format!("$ twilio profiles:list --properties authToken\n{header}\n{rows}")
}
#[test]
fn detects_an_auth_token_in_the_auth_token_column_of_a_twilio_cli_table() {
for rows in [
format!("prod {AUTH_TOKEN}\n"),
format!("dev fedcba98\nprod {AUTH_TOKEN}\n"),
format!("prod {AUTH_TOKEN}"),
] {
let input = profiles_table("ID Auth Token", &rows);
let found = detect_auth_token(&input);
assert_eq!(found.len(), 1, "{input:?}");
let range = found[0].range();
assert_eq!(&input[range.start()..range.end()], AUTH_TOKEN);
assert_eq!(found[0].confidence(), Confidence::High);
}
let crlf = profiles_table("ID Auth Token", &format!("prod {AUTH_TOKEN}\n"))
.replace('\n', "\r\n");
assert_eq!(detect_auth_token(&crlf).len(), 1);
}
#[test]
fn rejects_a_cli_table_value_outside_the_auth_token_column_or_window() {
for input in [
profiles_table("ID Account SID", &format!("prod {AUTH_TOKEN}\n")),
profiles_table("ID Auth Token", &format!("prod {AUTH_TOKEN}\n")),
format!("ID Auth Token\nprod {AUTH_TOKEN}\n"),
format!("$ gh auth status\nID Auth Token\nprod {AUTH_TOKEN}\n"),
profiles_table("ID Auth Token", &format!("\nprod {AUTH_TOKEN}\n")),
profiles_table(
"ID Auth Token",
&format!(
"{}prod {AUTH_TOKEN}\n",
"dev x\n".repeat(CLI_TABLE_MAX_DATA_ROWS)
),
),
] {
assert!(detect_auth_token(&input).is_empty(), "{input:?}");
}
let input = profiles_table(
"ID Auth Token",
&format!(
"{}prod {AUTH_TOKEN}\n",
"dev x\n".repeat(CLI_TABLE_MAX_DATA_ROWS - 1)
),
);
assert_eq!(detect_auth_token(&input).len(), 1);
assert!(detect_api_key_secret(&input).is_empty());
}
#[test]
fn the_retention_hint_holds_exactly_the_cli_table_window_open() {
for open in [
"$ twilio profiles:list --properties authToken\n",
"twilio api:core:messages:list\n",
"$ twilio profiles:list\nID Auth Token\n",
"$ twilio profiles:list\nID Auth Token\ndev x\n",
] {
assert!(has_open_twilio_cli_table(open), "{open:?}");
}
for closed in [
"",
"twilio is a provider\n",
"$ twilio profiles:list\nID Account SID\n",
"$ twilio profiles:list\nID Auth Token\n\n",
&format!(
"$ twilio profiles:list\nID Auth Token\n{}",
"dev x\n".repeat(CLI_TABLE_MAX_DATA_ROWS)
),
] {
assert!(!has_open_twilio_cli_table(closed), "{closed:?}");
}
}
}