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};
fn is_lower_hex(byte: u8) -> bool {
byte.is_ascii_digit() || byte.is_ascii_lowercase() && byte <= b'f'
}
const API_KEY_LEN: usize = 32;
const LEGACY_APPLICATION_KEY_LEN: usize = 40;
const VENDOR_KEYWORD: &str = "datadog";
const API_KEY_MARKERS: &[&str] = &[
"datadog_api_key",
"datadog-api-key",
"datadogapikey",
"dd_api_key",
"dd-api-key",
"ddapikey",
];
const LEGACY_APPLICATION_KEY_MARKERS: &[&str] = &[
"datadog_application_key",
"datadog-application-key",
"datadogapplicationkey",
"datadog_app_key",
"datadog-app-key",
"datadogappkey",
"dd_application_key",
"dd-application-key",
"ddapplicationkey",
"dd_app_key",
"dd-app-key",
"ddappkey",
];
fn line_contains_ci(line: &str, needle: &str) -> bool {
text::contains_ci(line, needle)
}
fn scan_bare_secret_runs(
input: &str,
exact_len: usize,
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 == exact_len && pattern::boundary_ok(bytes, start, run_end, boundary) {
matches.push((start, run_end));
}
start = run_end;
}
matches
}
fn detect_context_gated(
input: &str,
exact_len: usize,
type_name: &'static str,
specific_markers: &[&str],
specific_signal: &str,
) -> 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, exact_len, is_lower_hex, pattern::is_alnum);
if raw_matches.is_empty() {
return;
}
let (confidence, signal) = if specific_markers
.iter()
.any(|marker| line_contains_ci(line, marker))
{
(Confidence::High, specific_signal)
} else if line_contains_ci(line, VENDOR_KEYWORD) {
(Confidence::Medium, "datadog-keyword-cooccurrence")
} else {
return;
};
for (relative_start, relative_end) in raw_matches {
if text::is_repeated_character_filler(&line[relative_start..relative_end]) {
continue;
}
let Some(range) =
ByteRange::new(line_start + relative_start, line_start + relative_end)
else {
continue;
};
let (confidence, signal) = if confidence == Confidence::Medium
&& text::is_provider_named_assignment(line, relative_start, &[VENDOR_KEYWORD])
{
(Confidence::High, "datadog-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 DatadogApiKeyDetector;
impl Detector for DatadogApiKeyDetector {
fn id(&self) -> &'static str {
"datadog-api-key"
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
Ok(detect_context_gated(
input,
API_KEY_LEN,
"datadog_api_key",
API_KEY_MARKERS,
"datadog-api-key-marker-cooccurrence",
))
}
}
const CURRENT_APPLICATION_KEY_PREFIX: &str = "ddapp_";
const CURRENT_APPLICATION_KEY_BODY_LEN: usize = 34;
const CURRENT_APPLICATION_KEY_SIGNALS: [&str; 2] = [
"datadog-application-key-documented-prefix",
"datadog-application-key-documented-length",
];
const CURRENT_APPLICATION_KEY_BOUNDARY: Alphabet = pattern::is_alnum_dash;
pub(super) const DATADOG_APPLICATION_KEY: KnownFormatProviderDetector =
KnownFormatProviderDetector::new(
"datadog-application-key",
"datadog_application_key",
&[PrefixShape::exact(
CURRENT_APPLICATION_KEY_PREFIX,
CURRENT_APPLICATION_KEY_BODY_LEN,
pattern::is_alnum,
&CURRENT_APPLICATION_KEY_SIGNALS,
)],
CURRENT_APPLICATION_KEY_BOUNDARY,
);
pub(super) struct DatadogApplicationKeyLegacyDetector;
impl Detector for DatadogApplicationKeyLegacyDetector {
fn id(&self) -> &'static str {
"datadog-application-key-legacy"
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
Ok(detect_context_gated(
input,
LEGACY_APPLICATION_KEY_LEN,
"datadog_application_key_legacy",
LEGACY_APPLICATION_KEY_MARKERS,
"datadog-application-key-marker-cooccurrence",
))
}
}
#[cfg(test)]
mod tests {
use super::*;
const API_KEY: &str = "3f2504e04f8940c496395c07f7c60000";
const LEGACY_APPLICATION_KEY: &str = "fedcba9876543210fedcba9876543210fedcba98";
const KEY_RECORD_ID: &str = "a1b2c3d4e5";
const CURRENT_APPLICATION_KEY_BODY: &str = "SYNTHETIC0REVOKED0AppKeyBody012345";
fn detect_api_key(input: &str) -> Vec<Candidate> {
DatadogApiKeyDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
fn detect_application_key_legacy(input: &str) -> Vec<Candidate> {
DatadogApplicationKeyLegacyDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
fn detect_application_key_current(input: &str) -> Vec<Candidate> {
DATADOG_APPLICATION_KEY
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
fn current_application_key() -> String {
format!("{CURRENT_APPLICATION_KEY_PREFIX}{CURRENT_APPLICATION_KEY_BODY}")
}
#[test]
fn fixtures_are_the_documented_lengths() {
assert_eq!(API_KEY.len(), 32);
assert_eq!(LEGACY_APPLICATION_KEY.len(), 40);
assert_eq!(
CURRENT_APPLICATION_KEY_BODY.len(),
CURRENT_APPLICATION_KEY_BODY_LEN
);
}
#[test]
fn detects_an_api_key_named_by_a_specific_marker_at_high_confidence() {
let input = format!("DD_API_KEY={API_KEY}");
let candidates = detect_api_key(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "datadog_api_key");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
let start = input.rfind(API_KEY).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + API_KEY.len()).unwrap()
);
}
#[test]
fn detects_an_api_key_via_the_documented_header_marker() {
let input = format!("DD-API-KEY: {API_KEY}");
let candidates = detect_api_key(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::High);
}
#[test]
fn detects_an_api_key_named_by_the_datadog_keyword_at_medium_confidence() {
let input = format!("my datadog secret is {API_KEY}");
let candidates = detect_api_key(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::Medium);
let start = input.rfind(API_KEY).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + API_KEY.len()).unwrap()
);
}
#[test]
fn rejects_a_bare_api_key_with_no_context() {
assert_eq!(detect_api_key(API_KEY).len(), 0);
}
#[test]
fn rejects_a_bare_dd_mention_with_no_key_type_wording() {
assert_eq!(detect_api_key(&format!("dd {API_KEY}")).len(), 0);
}
#[test]
fn rejects_an_api_key_whose_context_is_on_a_different_line() {
let input = format!("DD_API_KEY=\n{API_KEY}\n");
assert_eq!(detect_api_key(&input).len(), 0);
}
#[test]
fn rejects_an_uppercase_hex_run() {
let upper = API_KEY.to_ascii_uppercase();
assert_eq!(detect_api_key(&format!("datadog {upper}")).len(), 0);
}
#[test]
fn rejects_a_run_one_byte_short_of_the_required_length() {
let short = &API_KEY[..API_KEY.len() - 1];
assert_eq!(detect_api_key(&format!("datadog {short}")).len(), 0);
}
#[test]
fn rejects_a_run_one_byte_longer_than_the_required_length_rather_than_truncating() {
let long = format!("{API_KEY}0");
assert_eq!(detect_api_key(&format!("datadog {long}")).len(), 0);
}
#[test]
fn rejects_a_key_record_id_by_length() {
assert_eq!(
detect_api_key(&format!("DD_API_KEY={KEY_RECORD_ID}")).len(),
0
);
}
#[test]
fn rejects_a_repeated_character_filler_value() {
assert_eq!(
detect_api_key(&format!("datadog {}", "0".repeat(API_KEY_LEN))).len(),
0
);
}
#[test]
fn rejects_a_placeholder_style_run_of_x_characters() {
assert_eq!(
detect_api_key(&format!("DD_API_KEY={}", "x".repeat(API_KEY_LEN))).len(),
0
);
}
#[test]
fn rejects_an_environment_variable_reference() {
assert_eq!(detect_api_key("datadog DD_API_KEY=${DD_API_KEY}").len(), 0);
}
#[test]
fn finds_a_qualified_match_in_json() {
let input = format!("{{\"datadog_api_key\": \"{API_KEY}\"}}");
let candidates = detect_api_key(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::High);
}
#[test]
fn finds_a_qualified_match_in_yaml() {
let input = format!("datadog:\n api_key: {API_KEY}\n");
assert_eq!(detect_api_key(&input).len(), 0);
}
#[test]
fn finds_a_qualified_match_across_crlf_and_a_unicode_prefix() {
let input = format!("# \u{1F511} caf\u{e9}\r\nDD_API_KEY={API_KEY}\r\n");
let candidates = detect_api_key(&input);
assert_eq!(candidates.len(), 1);
let start = input.rfind(API_KEY).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + API_KEY.len()).unwrap()
);
}
#[test]
fn finds_deterministic_findings_across_repeated_calls() {
let input = format!("DD_API_KEY={API_KEY}");
assert_eq!(detect_api_key(&input), detect_api_key(&input));
}
#[test]
fn stays_bounded_over_a_long_context_free_line_packed_with_candidates() {
let input = format!("{API_KEY} ").repeat(10_000);
assert_eq!(detect_api_key(&input).len(), 0);
}
#[test]
fn every_candidate_on_a_context_bearing_line_is_reported() {
let input = format!("DD_API_KEY={API_KEY} {API_KEY}");
let candidates = detect_api_key(&input);
assert_eq!(candidates.len(), 2);
assert!(
candidates
.iter()
.all(|candidate| candidate.confidence() == Confidence::High)
);
}
#[test]
fn detects_the_current_application_key_with_no_context_needed() {
let value = current_application_key();
let candidates = detect_application_key_current(&value);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "datadog_application_key");
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()
);
}
#[test]
fn rejects_a_current_body_one_byte_short_of_the_documented_length() {
let short_body = &CURRENT_APPLICATION_KEY_BODY[..CURRENT_APPLICATION_KEY_BODY_LEN - 1];
assert!(
detect_application_key_current(&format!(
"{CURRENT_APPLICATION_KEY_PREFIX}{short_body}"
))
.is_empty()
);
}
#[test]
fn rejects_a_current_body_one_byte_longer_than_the_documented_length() {
assert!(
detect_application_key_current(&format!(
"{CURRENT_APPLICATION_KEY_PREFIX}{CURRENT_APPLICATION_KEY_BODY}a"
))
.is_empty()
);
}
#[test]
fn rejects_undocumented_near_miss_prefixes() {
for input in [
format!("ddap_{CURRENT_APPLICATION_KEY_BODY}"),
format!("DDAPP_{CURRENT_APPLICATION_KEY_BODY}"),
format!("ddapi_{CURRENT_APPLICATION_KEY_BODY}"),
format!("ddapp-{CURRENT_APPLICATION_KEY_BODY}"),
] {
assert!(detect_application_key_current(&input).is_empty(), "{input}");
}
}
#[test]
fn rejects_a_body_containing_an_underscore() {
let body_with_underscore = format!(
"{}_",
&CURRENT_APPLICATION_KEY_BODY[..CURRENT_APPLICATION_KEY_BODY_LEN - 1]
);
assert_eq!(body_with_underscore.len(), CURRENT_APPLICATION_KEY_BODY_LEN);
assert!(
detect_application_key_current(&format!(
"{CURRENT_APPLICATION_KEY_PREFIX}{body_with_underscore}"
))
.is_empty()
);
}
#[test]
fn rejects_the_prefix_embedded_in_a_wider_identifier() {
assert!(
detect_application_key_current(&format!("legacy_{}", current_application_key()))
.is_empty()
);
assert!(
detect_application_key_current(&format!("{}_backup", current_application_key()))
.is_empty()
);
}
#[test]
fn accepts_a_doc_style_x_filled_placeholder_built_from_valid_alphabet_characters() {
assert_eq!(
detect_application_key_current(&format!(
"{CURRENT_APPLICATION_KEY_PREFIX}{}",
"x".repeat(CURRENT_APPLICATION_KEY_BODY_LEN)
))
.len(),
1
);
}
#[test]
fn accepts_env_json_yaml_and_quoted_contexts() {
let value = current_application_key();
for input in [
format!("DD_APPLICATION_KEY={value}"),
format!("{{\"applicationKey\": \"{value}\"}}"),
format!("application_key: {value}"),
format!("application_key=\"{value}\""),
] {
let candidates = detect_application_key_current(&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_current_match_across_crlf_and_a_unicode_prefix() {
let value = current_application_key();
let input = format!("# \u{1F511} caf\u{e9}\r\n{value}\r\n");
let candidates = detect_application_key_current(&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_current_findings_across_repeated_calls() {
let value = current_application_key();
assert_eq!(
detect_application_key_current(&value),
detect_application_key_current(&value)
);
}
#[test]
fn reports_a_repeated_identical_current_value_once_per_occurrence() {
let value = current_application_key();
let input = format!("{value} {value}");
assert_eq!(detect_application_key_current(&input).len(), 2);
}
#[test]
fn stays_bounded_over_a_long_run_of_current_near_miss_prefixes() {
let short_body = &CURRENT_APPLICATION_KEY_BODY[..CURRENT_APPLICATION_KEY_BODY_LEN - 1];
let input = format!("{CURRENT_APPLICATION_KEY_PREFIX}{short_body} ").repeat(10_000);
assert_eq!(detect_application_key_current(&input).len(), 0);
}
#[test]
fn detects_an_application_key_named_by_a_specific_marker_at_high_confidence() {
let input = format!("DD_APPLICATION_KEY={LEGACY_APPLICATION_KEY}");
let candidates = detect_application_key_legacy(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "datadog_application_key_legacy");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
let start = input.rfind(LEGACY_APPLICATION_KEY).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + LEGACY_APPLICATION_KEY.len()).unwrap()
);
}
#[test]
fn detects_an_application_key_via_the_documented_header_marker() {
let input = format!("DD-APPLICATION-KEY: {LEGACY_APPLICATION_KEY}");
let candidates = detect_application_key_legacy(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::High);
}
#[test]
fn detects_an_application_key_via_the_shorter_app_key_marker() {
let input = format!("DD_APP_KEY={LEGACY_APPLICATION_KEY}");
let candidates = detect_application_key_legacy(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::High);
}
#[test]
fn detects_an_application_key_named_by_the_datadog_keyword_at_medium_confidence() {
let input = format!("{{\"note\": \"datadog\", \"value\": \"{LEGACY_APPLICATION_KEY}\"}}");
let candidates = detect_application_key_legacy(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::Medium);
}
#[test]
fn rejects_a_bare_application_key_with_no_context() {
assert_eq!(
detect_application_key_legacy(LEGACY_APPLICATION_KEY).len(),
0
);
}
#[test]
fn rejects_an_application_key_whose_context_is_on_a_different_line() {
let input = format!("DD_APPLICATION_KEY=\n{LEGACY_APPLICATION_KEY}\n");
assert_eq!(detect_application_key_legacy(&input).len(), 0);
}
#[test]
fn rejects_an_application_key_run_one_byte_short_of_the_required_length() {
let short = &LEGACY_APPLICATION_KEY[..LEGACY_APPLICATION_KEY.len() - 1];
assert_eq!(
detect_application_key_legacy(&format!("datadog {short}")).len(),
0
);
}
#[test]
fn rejects_an_application_key_that_is_really_an_api_key_length() {
assert_eq!(
detect_application_key_legacy(&format!("DD_APPLICATION_KEY={API_KEY}")).len(),
0
);
}
#[test]
fn does_not_cross_match_an_api_key_marked_line_as_an_application_key() {
assert_eq!(
detect_application_key_legacy(&format!("DD_API_KEY={LEGACY_APPLICATION_KEY}")).len(),
0
);
}
#[test]
fn a_ddapp_prefixed_value_is_not_also_reported_by_the_legacy_detector() {
let value = current_application_key();
let input = format!("DD_APPLICATION_KEY={value}");
assert_eq!(detect_application_key_legacy(&input).len(), 0);
}
#[test]
fn finds_deterministic_findings_across_repeated_calls_for_application_key() {
let input = format!("DD_APPLICATION_KEY={LEGACY_APPLICATION_KEY}");
assert_eq!(
detect_application_key_legacy(&input),
detect_application_key_legacy(&input)
);
}
#[test]
fn stays_bounded_over_a_long_context_free_line_packed_with_application_key_candidates() {
let input = format!("{LEGACY_APPLICATION_KEY} ").repeat(10_000);
assert_eq!(detect_application_key_legacy(&input).len(), 0);
}
}