use super::pattern;
use super::text::{
is_command_substitution_reference, is_opencode_reference, is_repeated_character_filler,
is_ruby_interpolation_reference, is_template_reference, is_windows_env_reference,
matches_placeholder_vocabulary, starts_with_bare_dollar_reference,
};
use crate::detectors::prefilter::Literals;
use crate::entropy::shannon_entropy;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const SCHEMES: [&str; 14] = [
"postgresql",
"postgres",
"mysql",
"mariadb",
"mongodb+srv",
"mongodb",
"redis",
"rediss",
"amqp",
"amqps",
"https",
"http",
"ftps",
"ftp",
];
const MAX_PASSWORD_LENGTH: usize = 4_096;
const MAX_AUTHORITY_LENGTH: usize = 8_192;
const DRIVER_SUFFIX_DIALECTS: [&str; 4] = ["postgresql", "postgres", "mysql", "mariadb"];
const MAX_DRIVER_LENGTH: usize = 32;
const MAX_SCHEME_SPAN: usize = {
let mut longest = 0;
let mut index = 0;
while index < SCHEMES.len() {
if SCHEMES[index].len() > longest {
longest = SCHEMES[index].len();
}
index += 1;
}
longest + 1 + MAX_DRIVER_LENGTH
};
struct SchemeMatch {
start: usize,
end: usize,
scheme: &'static str,
driver_suffix: bool,
}
fn driver_suffix_end(bytes: &[u8], at: usize) -> Option<usize> {
if bytes.get(at) != Some(&b'+') {
return None;
}
let driver_start = at + 1;
let driver_len = bytes[driver_start..]
.iter()
.take(MAX_DRIVER_LENGTH + 1)
.take_while(|&&byte| byte.is_ascii_alphanumeric() || byte == b'_')
.count();
(1..=MAX_DRIVER_LENGTH)
.contains(&driver_len)
.then_some(driver_start + driver_len)
}
const SCHEME_SEPARATOR: &str = "://";
fn find_next_scheme(input: &str, from: usize) -> Option<SchemeMatch> {
let bytes = input.as_bytes();
let mut position = from;
let mut separator = None;
while position <= bytes.len() {
if separator.is_none_or(|at| at < position) {
separator = Some(pattern::find_literal(
bytes,
SCHEME_SEPARATOR.as_bytes(),
position,
)?);
}
if let Some(at) = separator
&& at > position + MAX_SCHEME_SPAN
{
position = at - MAX_SCHEME_SPAN;
}
for scheme in SCHEMES {
let name_end = position + scheme.len();
if name_end > bytes.len()
|| !bytes[position..name_end].eq_ignore_ascii_case(scheme.as_bytes())
{
continue;
}
let (separator, driver_suffix) = match driver_suffix_end(bytes, name_end) {
Some(driver_end) if DRIVER_SUFFIX_DIALECTS.contains(&scheme) => (driver_end, true),
_ => (name_end, false),
};
let end = separator + SCHEME_SEPARATOR.len();
if end <= bytes.len() && bytes[separator..end] == *SCHEME_SEPARATOR.as_bytes() {
return Some(SchemeMatch {
start: position,
end,
scheme,
driver_suffix,
});
}
}
position += 1;
}
None
}
fn is_scheme_char(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'.' | b'-')
}
fn is_authority_terminator(byte: u8) -> bool {
matches!(
byte,
b' ' | b'\t'
| b'\n'
| 0x0B
| 0x0C
| b'\r'
| b'/'
| b'?'
| b'#'
| b'"'
| b'\''
| b'<'
| b'>'
| b'\\'
)
}
fn authority_end(input: &str, start: usize, opened_by_single_quote: bool) -> Option<usize> {
let bytes = input.as_bytes();
let mut end = start;
let mut in_userinfo = true;
while end < bytes.len() {
let byte = bytes[end];
let literal_quote = byte == b'\'' && in_userinfo && !opened_by_single_quote;
if is_authority_terminator(byte) && !literal_quote {
break;
}
if byte == b'@' {
in_userinfo = false;
}
if end - start >= MAX_AUTHORITY_LENGTH {
return None;
}
end += 1;
}
Some(end)
}
fn single_at(authority: &str) -> Option<usize> {
let first = authority.find('@')?;
if first == 0 || authority.rfind('@') != Some(first) {
return None;
}
Some(first)
}
pub(super) fn is_placeholder(value: &str) -> bool {
const NAMES: [&str; 10] = [
"password",
"secret",
"example",
"sample",
"placeholder",
"redacted",
"changeme",
"mysecretpassword",
"changeit",
"supersecretpassword",
];
const DIGIT_SUFFIX_NAMES: [&str; 6] = [
"example",
"sample",
"placeholder",
"redacted",
"changeme",
"changeit",
];
if matches_placeholder_vocabulary(value, &NAMES, &DIGIT_SUFFIX_NAMES) {
return true;
}
if value.len() >= 2 && value.starts_with('<') && value.ends_with('>') {
let inner = &value[1..value.len() - 1];
if !inner.is_empty() && !inner.contains('>') {
return true;
}
}
if value.len() >= 3 && value.starts_with("${") && value.ends_with('}') {
let inner = &value[2..value.len() - 1];
if !inner.is_empty() && !inner.contains('}') {
return true;
}
}
if is_interpolation_or_env_reference(value) {
return true;
}
if is_repeated_character_filler(value) {
return true;
}
if is_fill_in_password_prose(value) {
return true;
}
false
}
fn is_interpolation_or_env_reference(value: &str) -> bool {
starts_with_bare_dollar_reference(value)
|| is_command_substitution_reference(value)
|| is_template_reference(value)
|| is_ruby_interpolation_reference(value)
|| is_opencode_reference(value)
|| is_windows_env_reference(value)
}
fn is_fill_in_password_prose(value: &str) -> bool {
const PREFIXES: [&str; 3] = ["insert", "replace", "todo"];
let mut first = "";
let mut last = "";
let mut count = 0u8;
let mut has_password = false;
for token in value.split(['_', '-']).filter(|token| !token.is_empty()) {
if count == 0 {
first = token;
}
last = token;
count = count.saturating_add(1);
has_password |= token.eq_ignore_ascii_case("password");
}
if count < 2 {
return false;
}
if last.eq_ignore_ascii_case("here") {
return true;
}
has_password
&& PREFIXES
.iter()
.any(|prefix| first.eq_ignore_ascii_case(prefix))
}
fn is_userinfo_char(byte: u8) -> bool {
byte.is_ascii_alphanumeric()
|| matches!(
byte,
b'.' | b'_'
| b'~'
| b'!'
| b'$'
| b'&'
| b'\''
| b'('
| b')'
| b'*'
| b'+'
| b','
| b';'
| b'='
| b':'
| b'-'
)
}
fn has_valid_userinfo_encoding(value: &str) -> bool {
let bytes = value.as_bytes();
let mut index = 0;
while index < bytes.len() {
if bytes[index] == b'%' {
let valid_escape = bytes.get(index + 1).is_some_and(u8::is_ascii_hexdigit)
&& bytes.get(index + 2).is_some_and(u8::is_ascii_hexdigit);
if !valid_escape {
return false;
}
index += 3;
} else if is_userinfo_char(bytes[index]) {
index += 1;
} else {
return false;
}
}
true
}
fn is_valid_ipv4_octet(part: &str) -> bool {
let bytes = part.as_bytes();
let well_formed = match bytes.len() {
1 => bytes[0].is_ascii_digit(),
2 | 3 => {
bytes[0].is_ascii_digit()
&& bytes[0] != b'0'
&& bytes[1..].iter().all(u8::is_ascii_digit)
}
_ => false,
};
well_formed && part.parse::<u16>().is_ok_and(|value| value <= 255)
}
fn is_valid_ipv4(value: &str) -> bool {
let mut count = 0u8;
for part in value.split('.') {
count += 1;
if count > 4 || !is_valid_ipv4_octet(part) {
return false;
}
}
count == 4
}
fn is_hex_group(group: &str) -> bool {
(1..=4).contains(&group.len()) && group.bytes().all(|byte| byte.is_ascii_hexdigit())
}
fn is_valid_ipv6(value: &str) -> bool {
if !value.contains(':') {
return false;
}
let compression = value.find("::");
if compression != value.rfind("::") {
return false;
}
let (head, tail) = match compression {
None => (value, ""),
Some(index) => (&value[..index], &value[index + 2..]),
};
let mut groups = [head, tail]
.into_iter()
.filter(|side| !side.is_empty())
.flat_map(|side| side.split(':'))
.peekable();
let mut units = 0u32;
while let Some(group) = groups.next() {
if group.is_empty() {
return false;
}
if group.contains('.') {
if groups.peek().is_some() || !is_valid_ipv4(group) {
return false;
}
units += 2;
} else {
if !is_hex_group(group) {
return false;
}
units += 1;
}
}
if compression.is_none() {
units == 8
} else {
units < 8
}
}
fn is_valid_port(value: &str) -> bool {
(1..=5).contains(&value.len())
&& value.bytes().all(|byte| byte.is_ascii_digit())
&& value.parse::<u32>().is_ok_and(|port| port <= 65_535)
}
fn is_reg_name_label(label: &str) -> bool {
let bytes = label.as_bytes();
!bytes.is_empty()
&& bytes[0].is_ascii_alphanumeric()
&& bytes[bytes.len() - 1].is_ascii_alphanumeric()
&& bytes
.iter()
.all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-')
}
fn is_reg_name(value: &str) -> bool {
!value.is_empty() && value.split('.').all(is_reg_name_label)
}
fn has_valid_host_and_port(value: &str) -> bool {
if let Some(rest) = value.strip_prefix('[') {
return match rest.find(']') {
None => false,
Some(close) => {
if !is_valid_ipv6(&rest[..close]) {
return false;
}
let suffix = &rest[close + 1..];
suffix.is_empty() || (suffix.starts_with(':') && is_valid_port(&suffix[1..]))
}
};
}
match value.rfind(':') {
None => is_reg_name(value),
Some(separator) => {
is_reg_name(&value[..separator]) && is_valid_port(&value[separator + 1..])
}
}
}
fn has_valid_mongo_host_list(value: &str) -> bool {
value.split(',').all(has_valid_host_and_port)
}
fn has_valid_srv_host(value: &str) -> bool {
!value.contains(',')
&& !value.contains(':')
&& is_reg_name(value)
&& value.split('.').count() >= 3
}
fn has_valid_host_for_scheme(scheme: &str, value: &str) -> bool {
match scheme {
"mongodb" => has_valid_mongo_host_list(value),
"mongodb+srv" => has_valid_srv_host(value),
_ => has_valid_host_and_port(value),
}
}
const AZURE_ACCOUNT_KEY_ANCHOR: &str = "AccountKey=";
const AZURE_PROTOCOL_KEY: &str = "DefaultEndpointsProtocol";
const AZURE_ACCOUNT_NAME_KEY: &str = "AccountName";
const AZURE_ACCOUNT_KEY_KEY: &str = "AccountKey";
const AZURE_ENDPOINT_SUFFIX_KEY: &str = "EndpointSuffix";
const MAX_AZURE_SEGMENT_LENGTH: usize = 8_192;
const MIN_AZURE_ACCOUNT_KEY_LENGTH: usize = 24;
const KNOWN_AZURE_ENDPOINT_SUFFIXES: [&str; 3] = [
"core.windows.net",
"core.usgovcloudapi.net",
"core.chinacloudapi.cn",
];
fn is_identifier_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_'
}
fn is_azure_segment_terminator(byte: u8) -> bool {
matches!(
byte,
b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r' | b'"' | b'\'' | b'<' | b'>' | b'\\'
)
}
fn find_next_literal(input: &str, literal: &str, from: usize) -> Option<usize> {
pattern::find_literal(input.as_bytes(), literal.as_bytes(), from)
}
fn azure_segment_bounds(input: &str, anchor: usize) -> Option<(usize, usize)> {
let bytes = input.as_bytes();
let mut start = anchor;
while start > 0 && !is_azure_segment_terminator(bytes[start - 1]) {
if anchor - start >= MAX_AZURE_SEGMENT_LENGTH {
return None;
}
start -= 1;
}
let mut end = anchor;
while end < bytes.len() && !is_azure_segment_terminator(bytes[end]) {
if end - anchor >= MAX_AZURE_SEGMENT_LENGTH {
return None;
}
end += 1;
}
Some((start, end))
}
#[derive(Default)]
struct AzureFields<'a> {
protocol: Option<&'a str>,
account_name: Option<&'a str>,
endpoint_suffix: Option<&'a str>,
account_key: Option<(&'a str, usize)>,
}
impl AzureFields<'_> {
fn is_complete(&self) -> bool {
self.protocol.is_some()
&& self.account_name.is_some()
&& self.endpoint_suffix.is_some()
&& self.account_key.is_some()
}
}
fn parse_azure_fields(segment: &str, segment_start: usize) -> AzureFields<'_> {
let mut fields = AzureFields::default();
let mut offset = 0usize;
for pair in segment.split(';') {
if let Some(equals) = pair.find('=') {
let key = &pair[..equals];
let value = &pair[equals + 1..];
match key {
AZURE_PROTOCOL_KEY => {
fields.protocol.get_or_insert(value);
}
AZURE_ACCOUNT_NAME_KEY => {
fields.account_name.get_or_insert(value);
}
AZURE_ENDPOINT_SUFFIX_KEY => {
fields.endpoint_suffix.get_or_insert(value);
}
AZURE_ACCOUNT_KEY_KEY => {
fields
.account_key
.get_or_insert((value, segment_start + offset + equals + 1));
}
_ => {}
}
if fields.is_complete() {
break;
}
}
offset += pair.len() + 1;
}
fields
}
fn is_valid_azure_account_key(value: &str) -> bool {
let bytes = value.as_bytes();
if bytes.len() < MIN_AZURE_ACCOUNT_KEY_LENGTH || !bytes.len().is_multiple_of(4) {
return false;
}
let mut padding = 0usize;
for (index, &byte) in bytes.iter().enumerate() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'+' | b'/' if padding == 0 => {}
b'=' if index >= bytes.len().saturating_sub(2) => {
padding += 1;
}
_ => return false,
}
}
true
}
fn azure_account_key_range(fields: &AzureFields<'_>) -> Option<ByteRange> {
let protocol = fields.protocol?;
if !protocol.eq_ignore_ascii_case("https") && !protocol.eq_ignore_ascii_case("http") {
return None;
}
if fields.account_name?.is_empty() {
return None;
}
if !KNOWN_AZURE_ENDPOINT_SUFFIXES.contains(&fields.endpoint_suffix?) {
return None;
}
let (value, value_start) = fields.account_key?;
if !is_valid_azure_account_key(value) {
return None;
}
ByteRange::new(value_start, value_start + value.len())
}
#[derive(Clone, Copy)]
struct AzureSegment {
start: usize,
end: usize,
key_range: Option<ByteRange>,
}
fn azure_storage_candidate(
input: &str,
anchor: usize,
cache: &mut Option<AzureSegment>,
) -> Option<Candidate> {
let reusable = cache.filter(|segment| {
anchor >= segment.start
&& anchor < segment.end
&& anchor - segment.start <= MAX_AZURE_SEGMENT_LENGTH
&& segment.end - anchor <= MAX_AZURE_SEGMENT_LENGTH
});
let segment = if let Some(segment) = reusable {
segment
} else {
let (start, end) = azure_segment_bounds(input, anchor)?;
let fields = parse_azure_fields(&input[start..end], start);
let segment = AzureSegment {
start,
end,
key_range: azure_account_key_range(&fields),
};
*cache = Some(segment);
segment
};
let range = segment.key_range?;
Some(
Candidate::built_in("connection_string_password", Confidence::High, range)
.with_specificity(Specificity::Structural)
.with_signals(vec!["azure-storage-account-key", "known-endpoint-suffix"]),
)
}
fn azure_candidates(input: &str, candidates: &mut Vec<Candidate>) {
let mut position = 0;
let mut cache = None;
while let Some(anchor) = find_next_literal(input, AZURE_ACCOUNT_KEY_ANCHOR, position) {
position = anchor + 1;
if anchor > 0 && is_identifier_byte(input.as_bytes()[anchor - 1]) {
continue;
}
if let Some(candidate) = azure_storage_candidate(input, anchor, &mut cache) {
candidates.push(candidate);
}
}
}
fn is_mongodb_scheme(scheme: &str) -> bool {
matches!(scheme, "mongodb" | "mongodb+srv")
}
fn mongodb_run_end(input: &str, start: usize, opened_by_single_quote: bool) -> Option<usize> {
let bytes = input.as_bytes();
let mut end = start;
while end < bytes.len() {
let byte = bytes[end];
let literal_quote = byte == b'\'' && !opened_by_single_quote;
let terminator =
!matches!(byte, b'/' | b'?' | b'#') && is_authority_terminator(byte) && !literal_quote;
if terminator {
break;
}
if end - start >= MAX_AUTHORITY_LENGTH {
return None;
}
end += 1;
}
Some(end)
}
fn mongodb_relaxed_password(
input: &str,
user_info_start: usize,
scheme: &str,
opened_by_single_quote: bool,
) -> Option<(usize, usize)> {
let run_end = mongodb_run_end(input, user_info_start, opened_by_single_quote)?;
let run = &input[user_info_start..run_end];
let first_stop = run.find(['/', '?', '#']).unwrap_or(run.len());
let authority0 = &run[..first_stop];
let host_is_valid = |at: usize| {
let host_region = &run[at + 1..];
let host_end = host_region
.find(['/', '?', '#'])
.unwrap_or(host_region.len());
host_end > 0 && has_valid_host_for_scheme(scheme, &host_region[..host_end])
};
let at = if let Some(last) = authority0.rfind('@') {
host_is_valid(last).then_some(last)?
} else {
if has_valid_mongo_host_list(authority0) {
return None;
}
run.match_indices('@')
.map(|(at, _)| at)
.find(|&at| host_is_valid(at))?
};
let user_info = &run[..at];
let separator = user_info.find(':')?;
let user = &user_info[..separator];
let password = &user_info[separator + 1..];
if user.is_empty()
|| !user
.bytes()
.all(|byte| is_userinfo_char(byte) || byte == b'%')
|| password.is_empty()
|| password.len() > MAX_PASSWORD_LENGTH
|| is_placeholder(password)
{
return None;
}
let start = user_info_start + separator + 1;
Some((start, start + password.len()))
}
fn mongodb_relaxed_candidates(input: &str, candidates: &mut Vec<Candidate>) {
let mut position = 0;
while let Some(scheme_match) = find_next_scheme(input, position) {
position = scheme_match.end;
if !is_mongodb_scheme(scheme_match.scheme)
|| (scheme_match.start > 0 && is_scheme_char(input.as_bytes()[scheme_match.start - 1]))
{
continue;
}
let opened_by_single_quote =
scheme_match.start > 0 && input.as_bytes()[scheme_match.start - 1] == b'\'';
let Some((start, end)) = mongodb_relaxed_password(
input,
scheme_match.end,
scheme_match.scheme,
opened_by_single_quote,
) else {
continue;
};
if candidates
.iter()
.any(|candidate| candidate.range().start() < end && start < candidate.range().end())
{
continue;
}
if let Some(range) = ByteRange::new(start, end) {
candidates.push(
Candidate::built_in("connection_string_password", Confidence::Medium, range)
.with_specificity(Specificity::Structural)
.with_signals(vec![
"credential-bearing-authority",
"supported-scheme",
"mongodb-relaxed-userinfo",
]),
);
}
}
}
pub struct ConnectionStringDetector;
impl Detector for ConnectionStringDetector {
fn id(&self) -> &'static str {
"connection-string"
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
let mut candidates = Vec::new();
let mut position = 0;
while let Some(scheme_match) = find_next_scheme(input, position) {
position = scheme_match.end;
if scheme_match.start > 0 && is_scheme_char(input.as_bytes()[scheme_match.start - 1]) {
continue;
}
let user_info_start = scheme_match.end;
let opened_by_single_quote =
scheme_match.start > 0 && input.as_bytes()[scheme_match.start - 1] == b'\'';
let Some(authority_stop) =
authority_end(input, user_info_start, opened_by_single_quote)
else {
continue;
};
let authority = &input[user_info_start..authority_stop];
let Some(at) = single_at(authority) else {
continue;
};
let user_info = &authority[..at];
let scheme = scheme_match.scheme;
let password_only_redis =
user_info.find(':') == Some(0) && matches!(scheme, "redis" | "rediss");
let separator = match user_info.find(':') {
None => continue,
Some(0) if !password_only_redis => continue,
Some(separator) if separator == user_info.len() - 1 => continue,
Some(separator) => separator,
};
let password = &user_info[separator + 1..];
if password.len() > MAX_PASSWORD_LENGTH || is_placeholder(password) {
continue;
}
if !has_valid_userinfo_encoding(user_info)
|| !has_valid_host_for_scheme(scheme, &authority[at + 1..])
{
continue;
}
let start = user_info_start + separator + 1;
let end = start + password.len();
let confidence = if password.len() >= 12 && shannon_entropy(password) >= 2.5 {
Confidence::High
} else {
Confidence::Medium
};
let mut signals = vec!["credential-bearing-authority", "supported-scheme"];
if password_only_redis {
signals.push("redis-password-only");
}
if scheme == "mongodb" && authority.contains(',') {
signals.push("mongodb-seed-list");
}
if scheme_match.driver_suffix {
signals.push("driver-qualified-scheme");
}
if let Some(range) = ByteRange::new(start, end) {
candidates.push(
Candidate::built_in("connection_string_password", confidence, range)
.with_specificity(Specificity::Structural)
.with_signals(signals),
);
}
}
mongodb_relaxed_candidates(input, &mut candidates);
azure_candidates(input, &mut candidates);
Ok(candidates)
}
}
pub(super) const REQUIRED_LITERALS: &[Literals] = &[Literals::Strs(&[
SCHEME_SEPARATOR,
AZURE_ACCOUNT_KEY_ANCHOR,
])];
#[cfg(test)]
mod tests {
use super::*;
fn detect(input: &str) -> Vec<Candidate> {
ConnectionStringDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
fn spans(candidates: &[Candidate]) -> Vec<(usize, usize)> {
candidates
.iter()
.map(|c| (c.range().start(), c.range().end()))
.collect()
}
#[test]
fn selects_only_the_password_in_a_postgres_authority() {
let input = "postgres://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost/db";
let password_start = input.find("SYNTHETIC").unwrap();
let found = detect(input);
assert_eq!(
spans(&found),
[(password_start, input.len() - "@localhost/db".len())]
);
assert_eq!(found[0].type_name(), "connection_string_password");
assert_eq!(found[0].effective_specificity(), Specificity::Structural);
}
#[test]
fn selects_a_mongodb_seed_list_password_once() {
let input = "mongodb://fixture:SYNTHETIC_REVOKED_DB_VALUE@db0.example.test:27017,db1.example.test:27018/db";
let password_start = input.find("SYNTHETIC").unwrap();
let password_end = password_start + "SYNTHETIC_REVOKED_DB_VALUE".len();
assert_eq!(spans(&detect(input)), [(password_start, password_end)]);
}
#[test]
fn rejects_srv_authorities_with_multiple_hosts() {
let input =
"mongodb+srv://fixture:SYNTHETIC_REVOKED_DB_VALUE@db0.example.test,db1.example.test/db";
assert_eq!(detect(input), Vec::new());
}
#[test]
fn selects_redis_password_only_authentication() {
let input = "redis://:SYNTHETIC_REVOKED_DB_VALUE@cache.example.test:6379/0";
let password_start = input.find("SYNTHETIC").unwrap();
let found = detect(input);
assert_eq!(
spans(&found),
[(
password_start,
password_start + "SYNTHETIC_REVOKED_DB_VALUE".len()
)]
);
assert!(
found[0]
.signals()
.contains(&"redis-password-only".to_string())
);
}
#[test]
fn requires_immediate_backtrack_between_prefix_schemes() {
for (input, scheme) in [
(
"postgres://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost/db",
"postgres",
),
(
"postgresql://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost/db",
"postgresql",
),
(
"mysql://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost:3306/db",
"mysql",
),
(
"mariadb://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost:3306/db",
"mariadb",
),
(
"mongodb+srv://fixture:SYNTHETIC_REVOKED_DB_VALUE@cluster0.example.mongodb.net/db",
"mongodb+srv",
),
(
"mongodb://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost:27017/db",
"mongodb",
),
(
"redis://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost:6379/0",
"redis",
),
(
"rediss://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost:6379/0",
"rediss",
),
(
"amqp://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost/vh",
"amqp",
),
(
"amqps://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost/vh",
"amqps",
),
] {
let found = detect(input);
assert_eq!(found.len(), 1, "{input}");
let _ = scheme;
}
}
#[test]
fn host_only_url_has_no_credential() {
assert_eq!(detect("postgres://localhost/example"), Vec::new());
}
#[test]
fn a_user_only_authority_with_no_separator_has_no_credential() {
assert_eq!(
detect("postgres://fixtureuser@localhost/example"),
Vec::new()
);
}
#[test]
fn obvious_placeholder_is_ignored() {
assert_eq!(
detect("postgres://fixture:password@localhost/example"),
Vec::new()
);
}
#[test]
fn well_known_vendor_default_passwords_are_ignored_across_schemes() {
for (scheme, authority) in [
("postgres", "fixture:mysecretpassword@localhost/example"),
("mysql", "fixture:mysecretpassword@db.example.test/example"),
("mariadb", "fixture:changeit@db.example.test/example"),
("redis", ":supersecretpassword@cache.example.test:6379/0"),
("mongodb", "fixture:changeit@db0.example.test:27017/db"),
] {
let input = format!("{scheme}://{authority}");
assert_eq!(
detect(&input),
Vec::new(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn well_known_vendor_default_passwords_are_case_insensitive() {
assert_eq!(
detect("postgres://fixture:MySecretPassword@localhost/example"),
Vec::new()
);
}
#[test]
fn a_near_miss_of_a_well_known_vendor_default_password_is_still_detected() {
let candidates = detect("postgres://fixture:mysecretpasswore@localhost/example");
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "connection_string_password");
}
#[test]
fn an_appended_digit_does_not_defeat_the_vendor_default_exclusion() {
assert_eq!(
detect("postgres://user:changeme2@host/db"),
Vec::new(),
"\"postgres://user:changeme2@host/db\" should have no findings"
);
}
#[test]
fn a_placeholder_word_embedded_in_a_larger_password_is_still_detected() {
let input = "postgres://fixture:SecretSyntheticRevokedContext9fQ@localhost/example";
let candidates = detect(input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "connection_string_password");
}
#[test]
fn repeated_character_filler_passwords_are_ignored() {
for password in ["xxxxxxxxxxxx", "00000000000"] {
let input = format!("postgres://fixture:{password}@localhost/example");
assert_eq!(
detect(&input),
Vec::new(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn a_near_miss_of_repeated_character_filler_is_still_detected() {
let candidates = detect("postgres://fixture:xxxxxxxxxxxy@localhost/example");
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "connection_string_password");
}
#[test]
fn fill_in_your_own_value_prose_placeholders_are_ignored() {
for password in [
"your_password_here",
"insert-password-here",
"REPLACE_ME_PASSWORD",
"TODO_SET_PASSWORD",
"root_password_here",
] {
let input = format!("postgres://fixture:{password}@localhost/example");
assert_eq!(
detect(&input),
Vec::new(),
"expected no findings for {input:?}"
);
}
}
fn oracle_is_fill_in_password_prose(value: &str) -> bool {
const PREFIXES: [&str; 3] = ["insert", "replace", "todo"];
let tokens: Vec<&str> = value
.split(['_', '-'])
.filter(|token| !token.is_empty())
.collect();
if tokens.len() < 2 {
return false;
}
if tokens[tokens.len() - 1].eq_ignore_ascii_case("here") {
return true;
}
PREFIXES
.iter()
.any(|prefix| tokens[0].eq_ignore_ascii_case(prefix))
&& tokens
.iter()
.any(|token| token.eq_ignore_ascii_case("password"))
}
fn assert_prose_matches_oracle(input: &str) {
assert_eq!(
is_fill_in_password_prose(input),
oracle_is_fill_in_password_prose(input),
"{input:?}"
);
}
#[test]
fn fill_in_prose_matches_the_collecting_oracle_on_named_shapes() {
let shapes = [
"",
"_",
"-",
"__",
"_-_-",
"here",
"_here",
"here_",
"x_here",
"x-HERE",
"x_Here_",
"_x_here_",
"here_x",
"here_here",
"your_password_here",
"your_password_here_now",
"insert-password-here",
"REPLACE_ME_PASSWORD",
"TODO_SET_PASSWORD",
"todo_password",
"todo-PassWord-x",
"todo_passwords",
"todo_password_",
"_todo_password",
"x_todo_password",
"password_todo",
"insert",
"insert_",
"insert_x",
"insert__password",
"insert_xpassword",
"inserts_password",
"replace_me_password_here_not",
"replace_me_password_here",
"a_b",
"a-b",
"ab",
"pass_word",
"password",
"PASSWORD_HERE",
"Pass\u{ff3f}word_here",
"todo_pass\u{e9}word",
"\u{e9}_here",
"todo_\u{fb00}",
"todo\u{0}_password",
"todo password",
"x.here",
"x_here\u{0}",
"tod\u{0130}_password",
];
for shape in shapes {
assert_prose_matches_oracle(shape);
}
assert!(is_fill_in_password_prose("your_password_here"));
assert!(is_fill_in_password_prose("TODO_SET_PASSWORD"));
assert!(!is_fill_in_password_prose("here"));
assert!(!is_fill_in_password_prose("todo_passwords"));
assert!(!is_fill_in_password_prose("password_todo"));
}
#[test]
fn fill_in_prose_matches_the_collecting_oracle_exhaustively_on_token_alphabets() {
let atoms = [
"_", "-", "here", "HERE", "password", "PassWord", "todo", "insert", "replace", "x",
];
let mut sequences: Vec<String> = vec![String::new()];
for _ in 0..6 {
let mut next = Vec::new();
for text in &sequences {
assert_prose_matches_oracle(text);
for atom in atoms {
let mut grown = text.clone();
grown.push_str(atom);
next.push(grown);
}
}
sequences = next;
}
for text in &sequences {
assert_prose_matches_oracle(text);
}
}
#[test]
fn fill_in_prose_matches_the_collecting_oracle_on_generated_and_long_inputs() {
let atoms: [&str; 16] = [
"_", "-", "__", "here", "Here", "password", "PASSWORD", "todo", "TODO", "insert",
"replace", "x9", "\u{e9}", "\u{ff3f}", "\u{fb00}", "pass",
];
let mut state = 0x2545_f491_4f6c_dd1d_u64;
for _ in 0..40_000 {
let mut input = String::new();
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
let pieces = usize::try_from(state % 12).unwrap();
for _ in 0..pieces {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
input.push_str(atoms[usize::try_from(state % 16).unwrap()]);
}
assert_prose_matches_oracle(&input);
}
let long = [
"a_".repeat(50_000),
format!("{}here", "a_".repeat(50_000)),
format!("todo{}password", "_x".repeat(50_000)),
format!("todo{}", "_x".repeat(50_000)),
format!("{}password_x", "x_".repeat(50_000)),
"_".repeat(100_000),
"-_".repeat(60_000),
format!("{}a", "_".repeat(100_000)),
format!("a{}here", "-".repeat(100_000)),
format!("{}_here", "x".repeat(100_000)),
format!("todo_{}", "password".repeat(10_000)),
];
for input in &long {
assert_prose_matches_oracle(input);
}
}
#[test]
fn a_near_miss_of_fill_in_prose_is_still_detected() {
let candidates = detect("postgres://fixture:my_password_over_there@localhost/example");
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "connection_string_password");
}
#[test]
fn a_braced_env_reference_password_is_ignored() {
assert_eq!(
detect("postgres://app:${DB_PASSWORD}@db.internal:5432/example"),
Vec::new()
);
}
#[test]
fn a_bare_shell_env_reference_password_is_ignored() {
for password in ["$DB_PASSWORD", "$_FOO"] {
let input = format!("postgres://app:{password}@db.internal:5432/example");
assert_eq!(
detect(&input),
Vec::new(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn a_powershell_env_reference_password_is_ignored() {
assert_eq!(
detect("postgres://app:$env:DB_PASSWORD@db.internal:5432/example"),
Vec::new()
);
}
#[test]
fn a_command_substitution_reference_password_is_ignored() {
for password in ["$(db_password)", "$(pass_show_db_prod)"] {
let input = format!("postgres://app:{password}@db.internal:5432/example");
assert_eq!(
detect(&input),
Vec::new(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn a_template_reference_password_is_ignored() {
assert_eq!(
detect("postgres://app:{{db_password}}@db.internal:5432/example"),
Vec::new()
);
}
#[test]
fn a_ruby_interpolation_reference_password_is_ignored() {
assert_eq!(
detect("postgres://app:#{db_password}@db.internal:5432/example"),
Vec::new()
);
}
#[test]
fn an_opencode_env_reference_password_is_ignored() {
assert_eq!(
detect("postgres://app:{env:DB_PASSWORD}@db.internal:5432/example"),
Vec::new()
);
}
#[test]
fn a_windows_env_reference_password_is_ignored() {
assert_eq!(
detect("postgres://app:%DB_PASSWORD%@db.internal:5432/example"),
Vec::new()
);
}
#[test]
fn a_real_looking_password_alongside_the_interpolation_forms_is_still_detected() {
let candidates = detect("postgres://app:SYNTHETICREVOKEDPW0000@db.internal:5432/x");
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "connection_string_password");
}
#[test]
fn a_password_starting_with_dollar_but_not_a_recognized_reference_form_is_still_detected() {
let candidates = detect("postgres://app:$3cretSyntheticRevoked@db.internal:5432/example");
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "connection_string_password");
}
#[test]
fn a_password_merely_containing_dollar_is_still_detected() {
let candidates = detect("postgres://app:abcSyntheticRevoked$Def@db.internal:5432/example");
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "connection_string_password");
}
#[test]
fn a_command_substitution_opener_without_its_closing_paren_is_still_detected() {
let candidates =
detect("postgres://app:$(SyntheticRevokedPassword@db.internal:5432/example");
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "connection_string_password");
}
#[test]
fn empty_password_userinfo_is_ignored() {
assert_eq!(detect("postgres://fixture:@localhost/example"), Vec::new());
}
#[test]
fn empty_password_userinfo_is_credential_free_across_amqp_and_related_schemes() {
for (scheme, authority) in [
("amqp", "fixture:@localhost:5672/vhost"),
("amqps", "fixture:@localhost:5671/vhost"),
("rediss", ":@localhost:6380/0"),
("mongodb+srv", "fixture:@cluster0.example.mongodb.net/db"),
] {
let input = format!("{scheme}://{authority}");
assert_eq!(
detect(&input),
Vec::new(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn a_reserved_documentation_host_does_not_suppress_detection() {
for input in [
"postgres://produser:SyntheticProdPassw0rdNotReal9@db.example.com:5432/proddb",
"mongodb+srv://produser:SyntheticProdPassw0rdNotReal9@cluster0.example.mongodb.net/proddb",
] {
let candidates = detect(input);
assert_eq!(candidates.len(), 1, "expected one finding for {input:?}");
assert_eq!(candidates[0].type_name(), "connection_string_password");
}
}
#[test]
fn malformed_percent_escape_invalidates_the_authority() {
assert_eq!(
detect("postgres://fixture:SYNTHETIC%GGREVOKED@localhost/example"),
Vec::new()
);
}
#[test]
fn overlong_password_is_ignored_in_bounded_time() {
let input = format!("postgres://fixture:{}@localhost/db", "A".repeat(100_000));
assert_eq!(detect(&input), Vec::new());
}
#[test]
fn overlong_malformed_authority_is_abandoned_after_a_fixed_bound() {
let input = format!("postgres://fixture:{}@localhost/db", "%2".repeat(50_000));
assert_eq!(detect(&input), Vec::new());
}
fn find_next_scheme_every_offset(input: &str, from: usize) -> Option<(usize, usize, bool)> {
let bytes = input.as_bytes();
(from..=bytes.len()).find_map(|position| {
SCHEMES.iter().find_map(|scheme| {
let name_end = position + scheme.len();
if name_end > bytes.len()
|| !bytes[position..name_end].eq_ignore_ascii_case(scheme.as_bytes())
{
return None;
}
let (separator, driver_suffix) = match driver_suffix_end(bytes, name_end) {
Some(driver_end) if DRIVER_SUFFIX_DIALECTS.contains(scheme) => {
(driver_end, true)
}
_ => (name_end, false),
};
let end = separator + 3;
(end <= bytes.len() && bytes[separator..end] == *b"://").then_some((
position,
end,
driver_suffix,
))
})
})
}
#[test]
fn the_separator_skip_finds_the_same_scheme_as_trying_every_offset() {
let longest_driver = "d".repeat(MAX_DRIVER_LENGTH);
let filler = "x".repeat(3 * MAX_SCHEME_SPAN);
let inputs = [
String::new(),
"://".to_owned(),
format!("{filler}://{filler}"),
format!("{filler}mongodb+srv://u:p@h {filler}postgresql+{longest_driver}://u:p@h"),
format!("{filler}postgresql+{longest_driver}d://u:p@h redis://:p@h"),
format!("rediss://:p@h{filler}HTTPS://u:p@h{filler}ftp:/x ftps://"),
format!("{filler}mysql+a://{filler}amqp://amqps://"),
];
for input in &inputs {
for from in 0..=input.len() {
assert_eq!(
find_next_scheme(input, from).map(|found| (
found.start,
found.end,
found.driver_suffix
)),
find_next_scheme_every_offset(input, from),
"{input:?} from {from}"
);
}
}
}
#[test]
fn a_sql_dialect_with_a_driver_suffix_is_detected() {
for input in [
"postgresql+psycopg://report:SYNTHETICq8vN3xR7tLm2@db.example.test:5432/reports",
"postgresql+psycopg://report:SYNTHETICq8vN3xR7tLm2@[2001:db8::10]:5432/reports",
"postgres+asyncpg://report:SYNTHETICq8vN3xR7tLm2@db.example.test/reports",
"MYSQL+PyMySQL://report:SYNTHETICq8vN3xR7tLm2@db.example.test/reports",
"mariadb+mariadbconnector://report:SYNTHETICq8vN3xR7tLm2@db.example.test/reports",
"create_engine(\"mysql+mysql_connector://report:SYNTHETICq8vN3xR7tLm2@db.example.test/r\")",
] {
let candidates = detect(input);
assert_eq!(candidates.len(), 1, "{input}");
let range = candidates[0].range();
assert_eq!(&input[range.start()..range.end()], "SYNTHETICq8vN3xR7tLm2");
assert!(
candidates[0]
.signals()
.iter()
.any(|signal| signal == "driver-qualified-scheme"),
"{input}"
);
}
for input in [
"redis+sentinel://report:SYNTHETICq8vN3xR7tLm2@cache.example.test/0",
"https+unix://report:SYNTHETICq8vN3xR7tLm2@www.example.test/",
"postgresql+://report:SYNTHETICq8vN3xR7tLm2@db.example.test/reports",
&format!(
"postgresql+{}://report:SYNTHETICq8vN3xR7tLm2@db.example.test/r",
"d".repeat(MAX_DRIVER_LENGTH + 1)
),
"postgresql+psy-copg://report:SYNTHETICq8vN3xR7tLm2@db.example.test/reports",
"postgresql+psycopg://report:<password>@db.example.test/reports",
"postgresql+psycopg://report@db.example.test/reports",
] {
assert!(detect(input).is_empty(), "{input}");
}
}
#[test]
fn unsupported_scheme_is_ignored() {
assert_eq!(
detect("gopher://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost/db"),
Vec::new()
);
}
#[test]
fn web_and_ftp_url_userinfo_passwords_are_detected() {
for (input, value) in [
(
"https://fixture:SYNTHETIC%20revoked@www.example.test/",
"SYNTHETIC%20revoked",
),
(
"remote = https://fixture:SYNTHETICq8vN3xR7tLm2@repo.example.test/repo.git",
"SYNTHETICq8vN3xR7tLm2",
),
(
"HTTP_PROXY=http://fixture:SYNTHETIC_REVOKED_PROXY_VALUE@proxy.example.test:3128",
"SYNTHETIC_REVOKED_PROXY_VALUE",
),
(
"ftp://fixture:SYNTHETIC_REVOKED_FTP_VALUE@ftp.example.test/pub",
"SYNTHETIC_REVOKED_FTP_VALUE",
),
] {
let candidates = detect(input);
assert_eq!(candidates.len(), 1, "{input}");
let range = candidates[0].range();
assert_eq!(&input[range.start()..range.end()], value, "{input}");
}
for input in [
"https://fixture@www.example.test/",
"https://www.example.test:8443/",
"mailto:fixture@example.test",
"https://fixture:<password>@www.example.test/",
"https://fixture:${PASSWORD}@www.example.test/",
] {
assert!(detect(input).is_empty(), "{input}");
}
}
#[test]
fn a_scheme_embedded_in_a_longer_identifier_is_ignored() {
assert_eq!(
detect("xmongodb://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost:27017/db"),
Vec::new()
);
}
#[test]
fn id_is_stable() {
assert_eq!(ConnectionStringDetector.id(), "connection-string");
}
#[test]
fn a_standard_mongodb_srv_host_is_recognized() {
let input =
"mongodb+srv://fixture:SYNTHETIC_REVOKED_DB_VALUE@cluster0.example.mongodb.net/db";
let password_start = input.find("SYNTHETIC").unwrap();
let found = detect(input);
assert_eq!(
spans(&found),
[(
password_start,
password_start + "SYNTHETIC_REVOKED_DB_VALUE".len()
)]
);
}
#[test]
fn ipv6_host_with_a_valid_hex_group_is_accepted() {
let input = "postgres://fixture:SYNTHETIC_REVOKED_DB_VALUE@[2001:db8::1]:5432/db";
assert_eq!(detect(input).len(), 1);
}
#[test]
fn ipv6_host_with_a_non_hex_group_is_rejected() {
assert_eq!(
detect("postgres://fixture:SYNTHETIC_REVOKED_DB_VALUE@[2001:db8::g]/db"),
Vec::new()
);
}
fn oracle_is_valid_ipv4(value: &str) -> bool {
let parts: Vec<&str> = value.split('.').collect();
parts.len() == 4 && parts.iter().all(|part| is_valid_ipv4_octet(part))
}
fn oracle_is_valid_ipv6(value: &str) -> bool {
if !value.contains(':') {
return false;
}
let compression = value.find("::");
if compression != value.rfind("::") {
return false;
}
let sides: Vec<&str> = match compression {
None => vec![value],
Some(index) => vec![&value[..index], &value[index + 2..]],
};
let groups: Vec<&str> = sides
.into_iter()
.filter(|side| !side.is_empty())
.flat_map(|side| side.split(':'))
.collect();
if groups.iter().any(|group| group.is_empty()) {
return false;
}
let last = groups.len().saturating_sub(1);
let mut units = 0u32;
for (index, group) in groups.iter().enumerate() {
if group.contains('.') {
if index != last || !oracle_is_valid_ipv4(group) {
return false;
}
units += 2;
} else {
if !is_hex_group(group) {
return false;
}
units += 1;
}
}
if compression.is_none() {
units == 8
} else {
units < 8
}
}
fn assert_ip_matches_oracle(input: &str) {
assert_eq!(
is_valid_ipv4(input),
oracle_is_valid_ipv4(input),
"ipv4 {input:?}"
);
assert_eq!(
is_valid_ipv6(input),
oracle_is_valid_ipv6(input),
"ipv6 {input:?}"
);
}
fn assert_every_string_matches_oracle(alphabet: &[char], max_len: usize) {
let mut current: Vec<String> = vec![String::new()];
for _ in 0..=max_len {
let mut next = Vec::new();
for text in ¤t {
assert_ip_matches_oracle(text);
if text.chars().count() < max_len {
for ch in alphabet {
let mut grown = text.clone();
grown.push(*ch);
next.push(grown);
}
}
}
if next.is_empty() {
break;
}
current = next;
}
}
#[test]
fn ip_validation_matches_the_collecting_oracle_on_named_shapes() {
let shapes = [
"",
":",
"::",
":::",
"::::",
"1::",
"::1",
"1::1",
"1::1::1",
"1:2:3:4:5:6:7:8",
"1:2:3:4:5:6:7",
"1:2:3:4:5:6:7:8:9",
"1:2:3:4:5:6:7::",
"::2:3:4:5:6:7:8",
"1:2:3:4:5:6::8",
"1::3:4:5:6:7:8",
"2001:db8::ff00:42:8329",
"2001:db8:0:0:0:0:0:1",
"2001:0db8:85a3:0000:0000:8a2e:0370:7334",
"2001:0db8:85a3:0000:0000:8a2e:0370:73345",
"2001:db8::g",
":1:2:3:4:5:6:7",
"1:2:3:4:5:6:7:",
"1:2:3:4:5:6:1.2.3.4",
"1:2:3:4:5:6:7:1.2.3.4",
"::1.2.3.4",
"::ffff:192.0.2.128",
"::192.0.2.128:1",
"1.2.3.4::",
"1.2.3.4:1",
"::1.2.3",
"::1.2.3.4.5",
"::1.2.3.256",
"::1.2.3.04",
"::1.2.3.",
"::.1.2.3",
"1:2:3:4:5:6:7:8.9.10.11",
"1.2.3.4",
"0.0.0.0",
"255.255.255.255",
"256.1.1.1",
"01.1.1.1",
"1.1.1.1.",
".1.1.1.1",
"1..1.1",
"1.1.1",
"1.1.1.1.1",
"1.1.1.1.1.1.1.1.1.1",
"999.1.1.1",
"1.1.1.0001",
"a.b.c.d",
"\u{0661}.1.1.1",
"\u{ff11}.1.1.1",
"::\u{ff11}",
"1:2:\u{e9}::",
"\u{1f512}::1",
"::1\u{0}",
" ::1",
"::1 ",
];
for shape in shapes {
assert_ip_matches_oracle(shape);
}
assert!(is_valid_ipv4("192.0.2.128"));
assert!(is_valid_ipv6("2001:db8::ff00:42:8329"));
assert!(is_valid_ipv6("::ffff:192.0.2.128"));
assert!(is_valid_ipv6("1:2:3:4:5:6:1.2.3.4"));
assert!(!is_valid_ipv6("1:2:3:4:5:6:7:1.2.3.4"));
assert!(!is_valid_ipv6("::192.0.2.128:1"));
}
#[test]
fn ip_validation_matches_the_collecting_oracle_exhaustively_on_small_alphabets() {
assert_every_string_matches_oracle(&['0', '2', '5', ':', '.', 'f'], 7);
assert_every_string_matches_oracle(&[':', '.', '1', 'g'], 10);
assert_every_string_matches_oracle(&[':', '.', '1', '\u{e9}', '\u{ff11}'], 7);
}
#[test]
fn ip_validation_matches_the_collecting_oracle_on_generated_inputs() {
let atoms: [&str; 24] = [
"0",
"1",
"9",
"25",
"255",
"256",
"0f",
"ffff",
"fffff",
"g",
":",
"::",
".",
"..",
"1.2.3.4",
"01.2.3.4",
"192.0.2.1",
"::",
":",
":",
"\u{e9}",
"\u{ff11}",
"-",
"%",
];
let mut state = 0x9e37_79b9_7f4a_7c15_u64;
for _ in 0..40_000 {
let mut input = String::new();
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
let pieces = usize::try_from(state % 14).unwrap();
for _ in 0..pieces {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
input.push_str(atoms[usize::try_from(state % 24).unwrap()]);
}
assert_ip_matches_oracle(&input);
}
}
#[test]
fn ip_validation_matches_the_collecting_oracle_on_long_inputs() {
let eight = "1:2:3:4:5:6:7:8";
let mut inputs = vec![
"1:".repeat(5_000),
":".repeat(10_000),
".".repeat(10_000),
"1.".repeat(5_000),
format!("{}1", "1:".repeat(5_000)),
format!("::{}", "1:".repeat(5_000)),
format!("{}::", "1:".repeat(5_000)),
format!("{eight}{}", ":1".repeat(5_000)),
format!("{}::1.2.3.4", "1:".repeat(3)),
format!("{}.4", "1.2.3".repeat(3_000)),
format!("::{}", "1.".repeat(4_000)),
];
for count in 0..=12 {
inputs.push(vec!["1"; count].join(":"));
inputs.push(format!("::{}", vec!["1"; count].join(":")));
inputs.push(format!("{}::", vec!["1"; count].join(":")));
inputs.push(vec!["1"; count].join("."));
}
for input in &inputs {
assert_ip_matches_oracle(input);
}
}
#[test]
fn a_unicode_host_label_is_not_an_ascii_reg_name_and_is_rejected() {
assert_eq!(
detect("postgres://fixture:SYNTHETIC_REVOKED_DB_VALUE@café.example.test/db"),
Vec::new()
);
}
#[test]
fn an_unescaped_at_in_the_password_makes_the_authority_boundary_ambiguous() {
assert_eq!(
detect("redis://:pass@word@cache.example.test:6379/0"),
Vec::new()
);
}
#[test]
fn an_unescaped_slash_in_the_password_ends_the_authority_before_its_at() {
assert_eq!(detect("postgres://fixture:pa/ss@localhost/db"), Vec::new());
}
#[test]
fn a_percent_encoded_reserved_delimiter_in_the_password_is_kept_undecoded() {
let input = "postgres://fixture:SYNTHETIC%3AREVOKED@localhost/db";
let password_start = input.find("SYNTHETIC").unwrap();
let found = detect(input);
assert_eq!(
spans(&found),
[(password_start, password_start + "SYNTHETIC%3AREVOKED".len())]
);
}
#[test]
fn a_query_string_with_no_path_terminates_the_authority() {
let input = "postgres://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost?sslmode=require";
assert_eq!(detect(input).len(), 1);
}
#[test]
fn a_fragment_with_no_path_terminates_the_authority() {
let input = "postgres://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost#primary";
assert_eq!(detect(input).len(), 1);
}
#[test]
fn a_port_above_the_valid_range_is_rejected() {
assert_eq!(
detect("postgres://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost:70000/db"),
Vec::new()
);
}
#[test]
fn a_port_longer_than_five_digits_is_rejected() {
assert_eq!(
detect("postgres://fixture:SYNTHETIC_REVOKED_DB_VALUE@localhost:123456/db"),
Vec::new()
);
}
const AZURE_ACCOUNT_NAME: &str = "fixturestorageaccount";
const AZURE_ACCOUNT_KEY: &str =
"U1lOVEhFVElDLVJFVk9LRUQtQVpVUkUtU1RPUkFHRS1BQ0NPVU5ULUtFWS1GSVhUVVJFLTAwMDAwMDAwMDA=";
#[test]
fn selects_only_the_account_key_in_an_azure_storage_connection_string() {
let input = format!(
"DefaultEndpointsProtocol=https;AccountName={AZURE_ACCOUNT_NAME};AccountKey={AZURE_ACCOUNT_KEY};EndpointSuffix=core.windows.net"
);
let key_start = input.find(AZURE_ACCOUNT_KEY).unwrap();
let found = detect(&input);
assert_eq!(
spans(&found),
[(key_start, key_start + AZURE_ACCOUNT_KEY.len())]
);
assert_eq!(found[0].type_name(), "connection_string_password");
assert_eq!(found[0].effective_specificity(), Specificity::Structural);
assert_eq!(found[0].confidence(), Confidence::High);
}
#[test]
fn the_http_protocol_variant_is_also_recognized() {
let input = format!(
"DefaultEndpointsProtocol=http;AccountName={AZURE_ACCOUNT_NAME};AccountKey={AZURE_ACCOUNT_KEY};EndpointSuffix=core.windows.net"
);
assert_eq!(detect(&input).len(), 1);
}
#[test]
fn sovereign_cloud_endpoint_suffixes_are_recognized() {
for suffix in ["core.usgovcloudapi.net", "core.chinacloudapi.cn"] {
let input = format!(
"DefaultEndpointsProtocol=https;AccountName={AZURE_ACCOUNT_NAME};AccountKey={AZURE_ACCOUNT_KEY};EndpointSuffix={suffix}"
);
assert_eq!(detect(&input).len(), 1, "{suffix}");
}
}
struct RefAzureField<'a> {
key: &'a str,
value: &'a str,
value_start: usize,
}
fn ref_parse_azure_fields(segment: &str, segment_start: usize) -> Vec<RefAzureField<'_>> {
let mut fields = Vec::new();
let mut offset = 0usize;
for pair in segment.split(';') {
if let Some(equals) = pair.find('=') {
fields.push(RefAzureField {
key: &pair[..equals],
value: &pair[equals + 1..],
value_start: segment_start + offset + equals + 1,
});
}
offset += pair.len() + 1;
}
fields
}
fn ref_azure_storage_candidate(input: &str, anchor: usize) -> Option<Candidate> {
let (segment_start, segment_end) = azure_segment_bounds(input, anchor)?;
let fields = ref_parse_azure_fields(&input[segment_start..segment_end], segment_start);
let protocol = fields
.iter()
.find(|field| field.key == AZURE_PROTOCOL_KEY)?;
if !protocol.value.eq_ignore_ascii_case("https")
&& !protocol.value.eq_ignore_ascii_case("http")
{
return None;
}
let account_name = fields
.iter()
.find(|field| field.key == AZURE_ACCOUNT_NAME_KEY)?;
if account_name.value.is_empty() {
return None;
}
let endpoint_suffix = fields
.iter()
.find(|field| field.key == AZURE_ENDPOINT_SUFFIX_KEY)?;
if !KNOWN_AZURE_ENDPOINT_SUFFIXES.contains(&endpoint_suffix.value) {
return None;
}
let account_key = fields
.iter()
.find(|field| field.key == AZURE_ACCOUNT_KEY_KEY)?;
if !is_valid_azure_account_key(account_key.value) {
return None;
}
let range = ByteRange::new(
account_key.value_start,
account_key.value_start + account_key.value.len(),
)?;
Some(
Candidate::built_in("connection_string_password", Confidence::High, range)
.with_specificity(Specificity::Structural)
.with_signals(vec!["azure-storage-account-key", "known-endpoint-suffix"]),
)
}
fn reference_azure_candidates(input: &str) -> Vec<Candidate> {
let mut out = Vec::new();
let mut position = 0;
while let Some(anchor) = find_next_literal(input, AZURE_ACCOUNT_KEY_ANCHOR, position) {
position = anchor + 1;
if anchor > 0 && is_identifier_byte(input.as_bytes()[anchor - 1]) {
continue;
}
if let Some(candidate) = ref_azure_storage_candidate(input, anchor) {
out.push(candidate);
}
}
out
}
fn azure_only(candidates: Vec<Candidate>) -> Vec<Candidate> {
candidates
.into_iter()
.filter(|c| c.signals().iter().any(|s| s == "azure-storage-account-key"))
.collect()
}
fn assert_azure_matches_reference(input: &str) {
assert_eq!(
format!("{:?}", azure_only(detect(input))),
format!("{:?}", reference_azure_candidates(input)),
"cached Azure detection diverged from the reference for a {}-byte input",
input.len()
);
}
#[test]
fn azure_segment_reuse_matches_the_reference_on_generated_inputs() {
let key = AZURE_ACCOUNT_KEY;
let atoms = [
"DefaultEndpointsProtocol=https".to_string(),
"DefaultEndpointsProtocol=ftp".to_string(),
"DefaultEndpointsProtocol=HTTP".to_string(),
"AccountName=synthetic".to_string(),
"AccountName=".to_string(),
"EndpointSuffix=core.windows.net".to_string(),
"EndpointSuffix=example.invalid".to_string(),
format!("AccountKey={key}"),
"AccountKey=short".to_string(),
"AccountKey=!!!!!!!!!!!!!!!!!!!!!!!!".to_string(),
"noequals".to_string(),
String::new(),
"\u{ac00}=\u{1f642}".to_string(),
];
let separators = [";", ";", ";", " ", "\n", "\"", ";;"];
let mut seed = 0x1131_u64;
let mut next = move || {
seed = seed
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(seed >> 33) as usize
};
for _ in 0..4_000 {
let count = next() % 14;
let mut input = String::new();
for _ in 0..count {
input.push_str(&atoms[next() % atoms.len()]);
input.push_str(separators[next() % separators.len()]);
}
assert_azure_matches_reference(&input);
}
}
#[test]
fn azure_segment_reuse_matches_the_reference_at_the_segment_limit() {
let key = AZURE_ACCOUNT_KEY;
let base = format!(
"DefaultEndpointsProtocol=https;AccountName=synthetic;EndpointSuffix=core.windows.net;AccountKey={key}"
);
for width in [
8_000, 8_100, 8_191, 8_192, 8_193, 8_300, 16_383, 16_384, 16_385,
] {
let filler = "x".repeat(width);
for input in [
format!("{base};{filler};AccountKey={key}"),
format!("AccountKey={key};{filler};{base}"),
format!("{filler};{base};AccountKey={key};{filler}"),
format!("{base};AccountKey={key};{filler};AccountKey={key}"),
format!(
"AccountKey=short;{filler};AccountKey={key};DefaultEndpointsProtocol=https;AccountName=a;EndpointSuffix=core.windows.net"
),
] {
assert_azure_matches_reference(&input);
}
}
let invalid_first = format!(
"DefaultEndpointsProtocol=https;AccountName=synthetic;EndpointSuffix=core.windows.net;AccountKey=short;AccountKey={key}"
);
assert_azure_matches_reference(&invalid_first);
assert_azure_matches_reference(&format!("{base}\n").repeat(40));
assert_azure_matches_reference(&format!(
"{base}{}",
format!(";AccountKey={key}").repeat(99)
));
assert_azure_matches_reference(&format!(
"{base}\n{}",
format!(";AccountKey={key}").repeat(5)
));
}
#[test]
fn azure_storage_fields_are_recognized_in_any_order() {
let input = format!(
"AccountName={AZURE_ACCOUNT_NAME};EndpointSuffix=core.windows.net;AccountKey={AZURE_ACCOUNT_KEY};DefaultEndpointsProtocol=https"
);
let key_start = input.find(AZURE_ACCOUNT_KEY).unwrap();
let found = detect(&input);
assert_eq!(
spans(&found),
[(key_start, key_start + AZURE_ACCOUNT_KEY.len())]
);
}
#[test]
fn an_account_key_is_selected_despite_an_adjacent_shared_access_signature_field() {
let input = format!(
"DefaultEndpointsProtocol=https;AccountName={AZURE_ACCOUNT_NAME};AccountKey={AZURE_ACCOUNT_KEY};EndpointSuffix=core.windows.net;SharedAccessSignature=sv=2022-11-02&ss=bqtf&sig=SYNTHETIC-REVOKED-SAS-SIGNATURE-VALUE-NOT-REAL%3D"
);
let key_start = input.find(AZURE_ACCOUNT_KEY).unwrap();
let found = detect(&input);
assert_eq!(
spans(&found),
[(key_start, key_start + AZURE_ACCOUNT_KEY.len())],
"the trailing SAS field must not widen or displace the selected range"
);
}
#[test]
fn an_empty_account_key_value_is_ignored() {
let input = format!(
"DefaultEndpointsProtocol=https;AccountName={AZURE_ACCOUNT_NAME};AccountKey=;EndpointSuffix=core.windows.net"
);
assert_eq!(detect(&input), Vec::new());
}
#[test]
fn a_malformed_base64_account_key_is_ignored() {
let input = format!(
"DefaultEndpointsProtocol=https;AccountName={AZURE_ACCOUNT_NAME};AccountKey=not-a-valid-base64-key!!;EndpointSuffix=core.windows.net"
);
assert_eq!(detect(&input), Vec::new());
}
#[test]
fn an_account_name_with_no_account_key_field_is_ignored() {
let input = format!(
"DefaultEndpointsProtocol=https;AccountName={AZURE_ACCOUNT_NAME};EndpointSuffix=core.windows.net"
);
assert_eq!(detect(&input), Vec::new());
}
#[test]
fn a_shared_access_signature_field_with_no_account_key_is_ignored() {
let input = "BlobEndpoint=https://fixturestorageaccount.blob.core.windows.net/;SharedAccessSignature=sv=2022-11-02&ss=bqtf&srt=sco&sp=rwdlacupitfx&se=2030-01-01T00:00:00Z&st=2020-01-01T00:00:00Z&spr=https&sig=SYNTHETIC-REVOKED-SAS-SIGNATURE-VALUE-NOT-REAL%3D";
assert_eq!(detect(input), Vec::new());
}
#[test]
fn an_unrelated_semicolon_delimited_connection_string_is_ignored() {
let input = "Server=tcp:fixture.database.windows.net,1433;Database=fixturedb;IntegratedSecurity=true;Encrypt=true;TrustServerCertificate=false;";
assert_eq!(detect(input), Vec::new());
}
#[test]
fn an_unrecognized_endpoint_suffix_is_a_documented_false_negative() {
let input = format!(
"DefaultEndpointsProtocol=https;AccountName={AZURE_ACCOUNT_NAME};AccountKey={AZURE_ACCOUNT_KEY};EndpointSuffix=storage.contoso-sovereign.example"
);
assert_eq!(detect(&input), Vec::new());
}
#[test]
fn an_account_key_split_across_lines_is_a_documented_false_negative() {
let input = format!(
"DefaultEndpointsProtocol=https;AccountName={AZURE_ACCOUNT_NAME};AccountKey=short\n{AZURE_ACCOUNT_KEY};EndpointSuffix=core.windows.net"
);
assert_eq!(detect(&input), Vec::new());
}
#[test]
fn an_overlong_account_key_is_ignored_in_bounded_time() {
let input = format!(
"DefaultEndpointsProtocol=https;AccountName={AZURE_ACCOUNT_NAME};AccountKey={}{AZURE_ACCOUNT_KEY};EndpointSuffix=core.windows.net",
"A".repeat(100_000)
);
assert_eq!(detect(&input), Vec::new());
}
#[test]
fn a_key_shaped_field_name_that_merely_ends_in_accountkey_is_ignored() {
assert_eq!(
detect(
"MyAccountKey=U1lOVEhFVElDLVJFVk9LRUQtQVpVUkUtU1RPUkFHRS1BQ0NPVU5ULUtFWS1GSVhUVVJFLTAwMDAwMDAwMDA="
),
Vec::new()
);
}
}
#[cfg(test)]
mod case_insensitive_differential_tests {
use super::*;
use crate::test_rng::{BOUNDARY_PIECES, XorShift32};
fn old_is_fill_in_password_prose(value: &str) -> bool {
const PREFIXES: [&str; 3] = ["insert", "replace", "todo"];
let lower = value.to_ascii_lowercase();
let tokens: Vec<&str> = lower
.split(['_', '-'])
.filter(|token| !token.is_empty())
.collect();
if tokens.len() < 2 {
return false;
}
if tokens[tokens.len() - 1] == "here" {
return true;
}
PREFIXES.contains(&tokens[0]) && tokens.contains(&"password")
}
#[test]
fn fill_in_password_prose_matches_the_lowercasing_implementation() {
let words = [
"here",
"HERE",
"Here",
"insert",
"REPLACE",
"Todo",
"password",
"PASSWORD",
"PassWord",
"your",
"root",
"me",
"_",
"-",
"__",
"\u{212a}",
"h\u{e9}re",
];
let mut pieces: Vec<&str> = BOUNDARY_PIECES.to_vec();
pieces.extend_from_slice(&words);
let mut rng = XorShift32::new(0x1086_0002);
let mut inputs = vec![String::new(), "_".to_owned(), "a_here".to_owned()];
for _ in 0..6000 {
inputs.push(rng.text(&pieces, 7));
}
for value in inputs {
assert_eq!(
is_fill_in_password_prose(&value),
old_is_fill_in_password_prose(&value),
"{value:?}"
);
}
}
}