use crate::detectors::additional_providers::KnownFormatProviderDetector;
use crate::detectors::pattern::{self, Alphabet, PrefixShape};
use crate::detectors::text;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const SECRET_PREFIX: &str = "cflt";
const PREFIXED_BODY_LEN: usize = 60;
const LEGACY_SECRET_LEN: usize = 64;
const CONTEXT_KEYWORD: &str = "confluent";
fn is_confluent_secret_boundary(byte: u8) -> bool {
pattern::is_base64_body(byte) || byte == b'_' || byte == b'-'
}
const CHECKSUM_LEN: usize = 6;
const PREFIXED_SIGNALS: [&str; 3] = [
"confluent-documented-prefix",
"base64-exact-length",
"crc32-checksum",
];
const CRC32_TABLE: [u32; 256] = {
let mut table = [0u32; 256];
let mut index = 0;
while index < 256 {
#[allow(clippy::cast_possible_truncation)]
let mut crc = index as u32;
let mut bit = 0;
while bit < 8 {
crc = if crc & 1 == 1 {
(crc >> 1) ^ 0xEDB8_8320
} else {
crc >> 1
};
bit += 1;
}
table[index] = crc;
index += 1;
}
table
};
fn crc32(bytes: &[u8]) -> u32 {
!bytes.iter().fold(!0u32, |crc, &byte| {
CRC32_TABLE[usize::from(crc.to_le_bytes()[0] ^ byte)] ^ (crc >> 8)
})
}
const STANDARD_BASE64: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
fn documented_checksum(body: &[u8]) -> [u8; CHECKSUM_LEN] {
let [b0, b1, b2, b3] = crc32(body).to_le_bytes();
let sextets = [
b0 >> 2,
((b0 & 0x03) << 4) | (b1 >> 4),
((b1 & 0x0f) << 2) | (b2 >> 6),
b2 & 0x3f,
b3 >> 2,
(b3 & 0x03) << 4,
];
sextets.map(|sextet| STANDARD_BASE64[usize::from(sextet)])
}
fn checksum_matches(bytes: &[u8], start: usize, end: usize) -> bool {
let body_start = start + SECRET_PREFIX.len();
let checksum_start = end - CHECKSUM_LEN;
documented_checksum(&bytes[body_start..checksum_start]) == bytes[checksum_start..end]
}
pub(super) const CONFLUENT_CLOUD_API_SECRET: KnownFormatProviderDetector =
KnownFormatProviderDetector::new(
"confluent-cloud-api-secret",
"confluent_cloud_api_secret",
&[PrefixShape::exact(
SECRET_PREFIX,
PREFIXED_BODY_LEN,
pattern::is_base64_body,
&PREFIXED_SIGNALS,
)
.with_post_check(checksum_matches)],
is_confluent_secret_boundary,
);
fn line_contains_ci(line: &str, needle: &str) -> bool {
text::contains_ci(line, needle)
}
fn scan_bare_legacy_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 == LEGACY_SECRET_LEN
&& pattern::boundary_ok(bytes, start, run_end, boundary)
{
matches.push((start, run_end));
}
start = run_end;
}
matches
}
pub(super) const PROPERTIES_LOOKBACK_LINES: usize = 3;
fn is_properties_line(line: &str) -> bool {
let trimmed = line.trim_start_matches([' ', '\t']);
if trimmed.starts_with(['#', '!']) {
return true;
}
let name_len = trimmed
.bytes()
.take_while(|&byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
.count();
name_len > 0 && matches!(trimmed.as_bytes().get(name_len), Some(b'=' | b':'))
}
fn ends_inside_confluent_properties(previous: &[&str]) -> bool {
for line in previous.iter().rev().take(PROPERTIES_LOOKBACK_LINES) {
if !is_properties_line(line) {
return false;
}
if line_contains_ci(line, CONTEXT_KEYWORD) {
return true;
}
}
false
}
fn is_basic_auth_user_info_secret(line: &str, value_start: usize) -> bool {
let trimmed_start = line.len() - line.trim_start_matches([' ', '\t']).len();
let Some(operator) = line[trimmed_start..]
.find(['=', ':'])
.map(|at| trimmed_start + at)
else {
return false;
};
let name = line[trimmed_start..operator].trim_end_matches([' ', '\t']);
let key_id = line[operator + 1..value_start]
.trim_start_matches([' ', '\t'])
.strip_suffix(':');
name.to_ascii_lowercase().ends_with("basic.auth.user.info")
&& key_id
.is_some_and(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_alphanumeric()))
}
#[cfg(test)]
pub(crate) fn has_open_confluent_properties(input: &str) -> bool {
has_open_confluent_properties_in(&super::lookback_tail(input))
}
pub(crate) fn has_open_confluent_properties_in(tail: &[&str]) -> bool {
ends_inside_confluent_properties(text::tail_lines(tail, PROPERTIES_LOOKBACK_LINES))
}
pub(super) struct ConfluentLegacyApiSecretDetector;
impl Detector for ConfluentLegacyApiSecretDetector {
fn id(&self) -> &'static str {
"confluent-cloud-api-secret-legacy"
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
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_legacy_runs(line, pattern::is_base64_body, is_confluent_secret_boundary);
if raw_matches.is_empty() {
return;
}
let same_line = line_contains_ci(line, CONTEXT_KEYWORD);
let in_properties_block = !same_line && {
let previous = text::preceding_lines(input, line_start, PROPERTIES_LOOKBACK_LINES);
ends_inside_confluent_properties(&previous)
};
if !same_line && !in_properties_block {
return;
}
for (relative_start, relative_end) in raw_matches {
if !same_line && !is_basic_auth_user_info_secret(line, relative_start) {
continue;
}
let value = &line[relative_start..relative_end];
if value.starts_with(SECRET_PREFIX)
|| text::is_repeated_character_filler(value)
|| text::is_labelled_digest(line, relative_start)
{
continue;
}
let Some(range) =
ByteRange::new(line_start + relative_start, line_start + relative_end)
else {
continue;
};
let (confidence, signal) = if !same_line {
(Confidence::High, "confluent-properties-block")
} else if text::is_provider_named_assignment(
line,
relative_start,
&[CONTEXT_KEYWORD],
) {
(Confidence::High, "confluent-named-assignment")
} else {
(Confidence::Medium, "confluent-keyword-cooccurrence")
};
candidates.push(
Candidate::built_in("confluent_cloud_api_secret_legacy", confidence, range)
.with_specificity(Specificity::Provider)
.with_signals([signal]),
);
}
});
Ok(candidates)
}
}
#[cfg(test)]
mod tests {
use super::*;
const PREFIXED_BODY: &str = "SYNTHETIC0REVOKED0PrefixedSecretValue0ABCDEFGHIJKLMNOPn2NMow";
const _: () = assert!(PREFIXED_BODY.len() == PREFIXED_BODY_LEN);
const LEGACY_BODY: &str = "SYNTHETIC0REVOKED0LegacyBareSecretValue0NoPrefix0ABCDEFGHIJKLMNO";
const _: () = assert!(LEGACY_BODY.len() == LEGACY_SECRET_LEN);
const KEY_ID: &str = "SYNTHETICKEYID01";
const _: () = assert!(KEY_ID.len() == 16);
fn prefixed_secret() -> String {
format!("{SECRET_PREFIX}{PREFIXED_BODY}")
}
fn detect_prefixed(input: &str) -> Vec<Candidate> {
CONFLUENT_CLOUD_API_SECRET
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
fn detect_legacy(input: &str) -> Vec<Candidate> {
ConfluentLegacyApiSecretDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
#[test]
fn detects_a_prefixed_secret_with_no_context_needed() {
let value = prefixed_secret();
let candidates = detect_prefixed(&value);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "confluent_cloud_api_secret");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
assert_eq!(
candidates[0].range(),
ByteRange::new(0, value.len()).unwrap()
);
}
const CANONICAL_BODY: &str = "SYNTHETIC0REVOKED0ConfluentChecksumFixture0ABCDEFGHIJK";
const _: () = assert!(CANONICAL_BODY.len() == PREFIXED_BODY_LEN - CHECKSUM_LEN);
#[test]
fn computes_the_ieee_crc32_check_value() {
assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
assert_eq!(crc32(b""), 0);
}
#[test]
fn computes_the_documented_little_endian_standard_base64_checksum() {
assert_eq!(&documented_checksum(CANONICAL_BODY.as_bytes()), b"E3aswA");
let body = &PREFIXED_BODY.as_bytes()[..PREFIXED_BODY_LEN - CHECKSUM_LEN];
assert_eq!(
&documented_checksum(body),
&PREFIXED_BODY.as_bytes()[PREFIXED_BODY_LEN - CHECKSUM_LEN..]
);
}
#[test]
fn accepts_only_the_documented_checksum() {
let valid = format!("{SECRET_PREFIX}{CANONICAL_BODY}E3aswA");
assert_eq!(detect_prefixed(&valid).len(), 1);
for checksum in ["A3aswA", "wKx2Ew", "pw1DTQ"] {
let input = format!("{SECRET_PREFIX}{CANONICAL_BODY}{checksum}");
assert!(detect_prefixed(&input).is_empty(), "{checksum}");
}
}
#[test]
fn rejects_a_valid_checksum_after_a_changed_body_byte() {
let mut body = PREFIXED_BODY.to_owned();
body.replace_range(0..1, "T");
assert!(detect_prefixed(&format!("{SECRET_PREFIX}{body}")).is_empty());
}
#[test]
fn rejects_a_prefixed_body_one_byte_short_of_the_documented_length() {
let short_body = &PREFIXED_BODY[..PREFIXED_BODY_LEN - 1];
assert!(detect_prefixed(&format!("{SECRET_PREFIX}{short_body}")).is_empty());
}
#[test]
fn rejects_a_prefixed_body_one_byte_longer_than_the_documented_length() {
assert!(detect_prefixed(&format!("{SECRET_PREFIX}{PREFIXED_BODY}a")).is_empty());
}
#[test]
fn rejects_undocumented_near_miss_prefixes() {
for input in [
format!("clft{PREFIXED_BODY}"),
format!("Cflt{PREFIXED_BODY}"),
format!("cfltx{PREFIXED_BODY}"),
format!("cfl{PREFIXED_BODY}"),
] {
assert!(detect_prefixed(&input).is_empty(), "{input}");
}
}
#[test]
fn rejects_the_prefix_embedded_in_a_wider_identifier() {
assert!(detect_prefixed(&format!("legacy_{}", prefixed_secret())).is_empty());
assert!(detect_prefixed(&format!("{}_backup", prefixed_secret())).is_empty());
}
#[test]
fn rejects_a_doc_style_placeholder_value() {
assert!(detect_prefixed(&format!("{SECRET_PREFIX}${{CONFLUENT_API_SECRET}}")).is_empty());
}
#[test]
fn never_flags_a_bare_key_id_by_itself() {
assert!(detect_prefixed(KEY_ID).is_empty());
assert!(detect_legacy(&format!("confluent {KEY_ID}")).is_empty());
}
#[test]
fn rejects_benign_confluent_context_with_no_secret_present() {
for input in [
"bootstrap.servers=pkc-abc123.us-east-1.aws.confluent.cloud:9092",
"cluster_id: lkc-abc123",
"schema.registry.url=https://lsrc-abc123.us-east-1.aws.confluent.cloud",
] {
assert!(detect_prefixed(input).is_empty(), "{input}");
assert!(detect_legacy(input).is_empty(), "{input}");
}
}
#[test]
fn rejects_a_hash_algorithm_labelled_legacy_shaped_digest() {
for input in [
format!("image: confluentinc/cp-server@sha256:{LEGACY_BODY}"),
format!("image: confluentinc/cp-server@SHA256:{LEGACY_BODY}"),
format!("confluent-7.6.0.tar.gz sha256={LEGACY_BODY}"),
format!("confluent checksum sha-256: {LEGACY_BODY}"),
] {
assert!(detect_legacy(&input).is_empty(), "{input}");
}
}
#[test]
fn a_digest_label_does_not_hide_a_legacy_secret_after_an_ordinary_name() {
let input = format!("CONFLUENT_API_SECRET={LEGACY_BODY}");
let candidates = detect_legacy(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].range().start(), 21);
assert_eq!(candidates[0].range().end(), 85);
let input = format!("confluent image@sha256:abc api_secret={LEGACY_BODY}");
assert_eq!(detect_legacy(&input).len(), 1);
}
#[test]
fn accepts_env_json_yaml_and_quoted_contexts() {
let value = prefixed_secret();
for input in [
format!("CONFLUENT_CLOUD_API_SECRET={value}"),
format!("{{\"apiSecret\": \"{value}\"}}"),
format!("sasl.password: {value}"),
format!("sasl.password=\"{value}\""),
] {
let candidates = detect_prefixed(&input);
assert_eq!(candidates.len(), 1, "{input}");
let start = input.rfind(&value).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + value.len()).unwrap(),
"{input}"
);
}
}
#[test]
fn finds_a_match_across_crlf_and_a_unicode_prefix() {
let value = prefixed_secret();
let input = format!("# \u{1F511} caf\u{e9}\r\n{value}\r\n");
let candidates = detect_prefixed(&input);
assert_eq!(candidates.len(), 1);
let start = input.find(&value).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + value.len()).unwrap()
);
}
#[test]
fn finds_deterministic_findings_across_repeated_calls() {
let value = prefixed_secret();
assert_eq!(detect_prefixed(&value), detect_prefixed(&value));
}
#[test]
fn reports_a_repeated_identical_value_once_per_occurrence() {
let value = prefixed_secret();
let input = format!("{value} {value}");
assert_eq!(detect_prefixed(&input).len(), 2);
}
#[test]
fn stays_bounded_over_a_long_run_of_near_miss_prefixes() {
let short_body = &PREFIXED_BODY[..PREFIXED_BODY_LEN - 1];
let input = format!("{SECRET_PREFIX}{short_body} ").repeat(10_000);
assert_eq!(detect_prefixed(&input).len(), 0);
}
#[test]
fn detects_a_legacy_secret_under_a_confluent_named_key_at_high_confidence() {
let input = format!("CONFLUENT_API_SECRET={LEGACY_BODY}");
let candidates = detect_legacy(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(
candidates[0].type_name(),
"confluent_cloud_api_secret_legacy"
);
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
let start = input.rfind(LEGACY_BODY).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + LEGACY_BODY.len()).unwrap()
);
}
#[test]
fn never_reports_a_cflt_led_run_as_a_legacy_secret() {
for checksum in ["E3aswA", "A3aswA"] {
let input = format!("CONFLUENT_CLOUD_API_SECRET=cflt{CANONICAL_BODY}{checksum}");
assert!(detect_legacy(&input).is_empty(), "{checksum}");
}
}
#[test]
fn rejects_a_bare_legacy_secret_with_no_context() {
assert!(detect_legacy(LEGACY_BODY).is_empty());
}
#[test]
fn rejects_a_legacy_secret_whose_context_is_on_a_different_line() {
let input = format!("# confluent cluster credentials\n{LEGACY_BODY}\n");
assert!(detect_legacy(&input).is_empty());
}
#[test]
fn rejects_a_legacy_body_one_byte_short_or_long() {
assert!(
detect_legacy(&format!(
"confluent {}",
&LEGACY_BODY[..LEGACY_SECRET_LEN - 1]
))
.is_empty()
);
assert!(detect_legacy(&format!("confluent {LEGACY_BODY}a")).is_empty());
}
#[test]
fn rejects_a_repeated_character_filler_value() {
assert!(detect_legacy(&format!("confluent {}", "a".repeat(LEGACY_SECRET_LEN))).is_empty());
}
#[test]
fn rejects_an_environment_variable_reference() {
assert!(detect_legacy("confluent CONFLUENT_API_SECRET=${CONFLUENT_API_SECRET}").is_empty());
}
#[test]
fn matches_confluent_keyword_case_insensitively() {
for keyword in ["Confluent", "CONFLUENT", "confluent"] {
let input = format!("{keyword}_SECRET={LEGACY_BODY}");
assert_eq!(detect_legacy(&input).len(), 1, "{keyword}");
}
}
#[test]
fn finds_a_qualified_legacy_match_across_crlf_and_a_unicode_prefix() {
let input = format!("# \u{1F511} caf\u{e9}\r\nconfluent {LEGACY_BODY}\r\n");
let candidates = detect_legacy(&input);
assert_eq!(candidates.len(), 1);
let start = input.rfind(LEGACY_BODY).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + LEGACY_BODY.len()).unwrap()
);
}
#[test]
fn finds_deterministic_legacy_findings_across_repeated_calls() {
let input = format!("confluent {LEGACY_BODY}");
assert_eq!(detect_legacy(&input), detect_legacy(&input));
}
#[test]
fn stays_bounded_over_a_long_context_free_line_packed_with_candidates() {
let input = format!("{LEGACY_BODY} ").repeat(10_000);
assert_eq!(detect_legacy(&input).len(), 0);
}
fn schema_registry_config(url: &str, separator: &str, secret: &str) -> String {
format!(
"schema.registry.url={url}\n{separator}basic.auth.credentials.source=USER_INFO\n\
basic.auth.user.info={KEY_ID}:{secret}\n"
)
}
#[test]
fn detects_a_basic_auth_user_info_secret_below_a_confluent_registry_url() {
let url = "https://psrc-3n9vd.us-east-2.aws.confluent.cloud";
for input in [
schema_registry_config(url, "", LEGACY_BODY),
schema_registry_config(url, "# client\n", LEGACY_BODY),
format!(
"schema.registry.url: {url}\nschema.registry.basic.auth.user.info: {KEY_ID}:{LEGACY_BODY}"
),
schema_registry_config(url, "", LEGACY_BODY).replace('\n', "\r\n"),
] {
let found = detect_legacy(&input);
assert_eq!(found.len(), 1, "{input:?}");
let range = found[0].range();
assert_eq!(&input[range.start()..range.end()], LEGACY_BODY);
assert_eq!(found[0].confidence(), Confidence::High);
}
}
#[test]
fn rejects_a_properties_block_without_confluent_context_nearby() {
let url = "https://psrc-3n9vd.us-east-2.aws.confluent.cloud";
for input in [
schema_registry_config("https://registry.example.test", "", LEGACY_BODY),
schema_registry_config(url, "\n", LEGACY_BODY),
schema_registry_config(url, "see the wiki for rotation\n", LEGACY_BODY),
schema_registry_config(url, "a=1\nb=2\n", LEGACY_BODY),
format!("schema.registry.url={url}\nssl.truststore.password={LEGACY_BODY}\n"),
format!("schema.registry.url={url}\nbasic.auth.user.info={LEGACY_BODY}\n"),
] {
assert!(detect_legacy(&input).is_empty(), "{input:?}");
}
}
#[test]
fn the_retention_hint_holds_exactly_the_properties_window_open() {
for open in [
"bootstrap.servers=pkc-1.confluent.cloud:9092\n",
"schema.registry.url=https://psrc-1.confluent.cloud\na=1\nb=2\n",
"# confluent cloud\n",
] {
assert!(has_open_confluent_properties(open), "{open:?}");
}
for closed in [
"",
"schema.registry.url=https://registry.example.test\n",
"schema.registry.url=https://psrc-1.confluent.cloud\na=1\nb=2\nc=3\n",
"schema.registry.url=https://psrc-1.confluent.cloud\n\n",
"we use confluent cloud\n",
] {
assert!(!has_open_confluent_properties(closed), "{closed:?}");
}
}
}