use crate::detectors::pattern::{self, RunLength};
use crate::detectors::prefilter::Literals;
use crate::detectors::text;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const USER_API_KEY_PREFIX: &str = "NRAK-";
const USER_API_KEY_BODY_LEN: usize = 27;
const LICENSE_KEY_LEN: usize = 40;
const LICENSE_KEY_MARKER: &str = "FFFFNRAL";
const LICENSE_KEY_MARKED_BODY_LEN: usize = LICENSE_KEY_LEN - LICENSE_KEY_MARKER.len();
const LICENSE_KEY_EU_PREFIX: &str = "eu01xx";
const LICENSE_KEY_EU_BODY_LEN: usize = LICENSE_KEY_MARKED_BODY_LEN - LICENSE_KEY_EU_PREFIX.len();
const CONTEXT_KEYWORDS: [&str; 4] = ["newrelic", "new_relic", "new-relic", "new relic"];
const NAMED_ASSIGNMENT_KEYWORDS: [&str; 2] = ["newrelic", "new_relic"];
fn is_lower_hex(byte: u8) -> bool {
byte.is_ascii_digit() || byte.is_ascii_lowercase() && byte <= b'f'
}
pub(super) struct NewRelicUserApiKeyDetector;
impl Detector for NewRelicUserApiKeyDetector {
fn id(&self) -> &'static str {
"new-relic-user-api-key"
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
let mut candidates = Vec::new();
for (start, end) in pattern::scan_prefixed_runs(
input,
&[USER_API_KEY_PREFIX],
RunLength::Exact(USER_API_KEY_BODY_LEN),
pattern::is_upper_alnum,
pattern::is_alnum,
) {
if text::is_repeated_character_filler(&input[start + USER_API_KEY_PREFIX.len()..end]) {
continue;
}
let Some(range) = ByteRange::new(start, end) else {
continue;
};
candidates.push(
Candidate::built_in("new_relic_user_api_key", Confidence::High, range)
.with_specificity(Specificity::Provider)
.with_signals([
"new-relic-documented-prefix",
"exact-length-upper-alnum-body",
]),
);
}
Ok(candidates)
}
}
fn line_has_context_keyword(line: &str) -> bool {
CONTEXT_KEYWORDS
.iter()
.any(|needle| text::contains_ci(line, needle))
}
pub(super) struct NewRelicLicenseKeyDetector;
impl Detector for NewRelicLicenseKeyDetector {
fn id(&self) -> &'static str {
"new-relic-license-key"
}
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 has_keyword = line_has_context_keyword(line);
if !has_keyword && !line.contains(LICENSE_KEY_MARKER) {
return;
}
let push = |candidates: &mut Vec<Candidate>, start: usize, end: usize, marked: bool| {
let Some(range) = ByteRange::new(line_start + start, line_start + end) else {
return;
};
let signals: &[&str] = match (has_keyword, marked) {
(true, true) => &[
"new-relic-keyword-cooccurrence",
"new-relic-license-key-suffix-marker",
],
(true, false) => &["new-relic-keyword-cooccurrence"],
(false, _) => &["new-relic-license-key-suffix-marker"],
};
let named = has_keyword
&& text::is_provider_named_assignment(line, start, &NAMED_ASSIGNMENT_KEYWORDS);
let confidence = if named {
Confidence::High
} else {
Confidence::Medium
};
candidates.push(
Candidate::built_in("new_relic_license_key", confidence, range)
.with_specificity(Specificity::Provider)
.with_signals(
signals
.iter()
.copied()
.chain(named.then_some("new-relic-named-assignment")),
),
);
};
let bytes = line.as_bytes();
let mut start = 0usize;
while start < bytes.len() {
if !is_lower_hex(bytes[start]) {
start += 1;
continue;
}
let run_end = pattern::run_end(bytes, start, is_lower_hex);
let key_end = if has_keyword && run_end - start == LICENSE_KEY_LEN {
Some(run_end)
} else if run_end - start == LICENSE_KEY_MARKED_BODY_LEN
&& line[run_end..].starts_with(LICENSE_KEY_MARKER)
{
Some(run_end + LICENSE_KEY_MARKER.len())
} else {
None
};
if let Some(key_end) = key_end
&& pattern::boundary_ok(bytes, start, key_end, pattern::is_alnum)
&& !text::is_repeated_character_filler(&line[start..run_end])
{
push(&mut candidates, start, key_end, key_end != run_end);
}
start = run_end;
}
let mut ends = pattern::RunCursor::new(bytes, is_lower_hex);
for (prefix_at, _) in line.match_indices(LICENSE_KEY_EU_PREFIX) {
let body_start = prefix_at + LICENSE_KEY_EU_PREFIX.len();
let body_end = ends.end(body_start);
let key_end = body_end + LICENSE_KEY_MARKER.len();
if body_end - body_start == LICENSE_KEY_EU_BODY_LEN
&& line[body_end..].starts_with(LICENSE_KEY_MARKER)
&& pattern::boundary_ok(bytes, prefix_at, key_end, pattern::is_alnum)
&& !text::is_repeated_character_filler(&line[body_start..body_end])
{
push(&mut candidates, prefix_at, key_end, true);
}
}
});
super::sort_candidates_by_start(&mut candidates);
Ok(candidates)
}
}
pub(super) const USER_REQUIRED_LITERALS: &[Literals] = &[Literals::Strs(&[USER_API_KEY_PREFIX])];
#[cfg(test)]
mod tests {
use super::*;
const USER_API_KEY_BODY: &str = "SYNTHETICREVOKEDNEWRELICUSA";
const LICENSE_KEY: &str = "0123456789abcdef0123456789abcdef01234567";
fn user_api_key() -> String {
format!("{USER_API_KEY_PREFIX}{USER_API_KEY_BODY}")
}
fn detect_user_api_key(input: &str) -> Vec<Candidate> {
NewRelicUserApiKeyDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
fn detect_license_key(input: &str) -> Vec<Candidate> {
NewRelicLicenseKeyDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
#[test]
fn fixtures_are_exactly_documented_length() {
assert_eq!(USER_API_KEY_BODY.len(), USER_API_KEY_BODY_LEN);
assert_eq!(LICENSE_KEY.len(), LICENSE_KEY_LEN);
}
#[test]
fn detects_the_synthetic_user_api_key() {
let value = user_api_key();
let candidates = detect_user_api_key(&value);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "new_relic_user_api_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 detects_the_user_api_key_bare_in_env_and_control_contexts() {
let value = user_api_key();
for input in [
value.clone(),
format!("NEW_RELIC_API_KEY={value}"),
format!("api_key: {value}"),
format!("{{\"apiKey\": \"{value}\"}}"),
] {
let candidates = detect_user_api_key(&input);
assert_eq!(candidates.len(), 1, "{input}");
let (start, end) = (candidates[0].range().start(), candidates[0].range().end());
assert_eq!(&input[start..end], value, "{input}");
}
}
#[test]
fn rejects_a_user_api_key_body_one_byte_short_of_the_required_length() {
let short = &USER_API_KEY_BODY[..USER_API_KEY_BODY.len() - 1];
assert!(detect_user_api_key(&format!("{USER_API_KEY_PREFIX}{short}")).is_empty());
}
#[test]
fn rejects_a_user_api_key_body_one_byte_longer_than_the_required_length_rather_than_truncating()
{
let long = format!("{USER_API_KEY_BODY}A");
assert!(detect_user_api_key(&format!("{USER_API_KEY_PREFIX}{long}")).is_empty());
}
#[test]
fn rejects_a_legacy_admin_key_prefix() {
assert!(detect_user_api_key(&format!("NRAA-{USER_API_KEY_BODY}")).is_empty());
}
#[test]
fn rejects_a_lowercase_user_api_key_body() {
let lower = USER_API_KEY_BODY.to_ascii_lowercase();
assert!(detect_user_api_key(&format!("{USER_API_KEY_PREFIX}{lower}")).is_empty());
}
#[test]
fn rejects_a_masked_user_api_key() {
assert!(
detect_user_api_key(&format!("{USER_API_KEY_PREFIX}{}", "X".repeat(27))).is_empty()
);
}
#[test]
fn rejects_a_user_api_key_environment_variable_reference() {
assert!(
detect_user_api_key(&format!("{USER_API_KEY_PREFIX}${{NEW_RELIC_API_KEY}}")).is_empty()
);
}
#[test]
fn rejects_a_user_api_key_embedded_in_a_wider_identifier() {
let value = user_api_key();
assert!(detect_user_api_key(&format!("x{value}")).is_empty());
assert!(detect_user_api_key(&format!("{value}x")).is_empty());
}
#[test]
fn does_not_flag_a_bare_short_application_or_account_id() {
assert!(detect_user_api_key("accountId: 1234567890").is_empty());
}
#[test]
fn finds_a_user_api_key_match_across_crlf_and_a_unicode_prefix() {
let value = user_api_key();
let input = format!("# \u{1F511} caf\u{e9}\r\n{value}\r\n");
let candidates = detect_user_api_key(&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_user_api_key_findings_across_repeated_calls() {
let input = user_api_key();
assert_eq!(detect_user_api_key(&input), detect_user_api_key(&input));
}
#[test]
fn stays_bounded_over_a_long_run_of_rejected_user_api_key_prefixes() {
let input = format!("{}!{}", user_api_key(), "NRAK-!".repeat(10_000));
let candidates = detect_user_api_key(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(
candidates[0].range(),
ByteRange::new(0, user_api_key().len()).unwrap()
);
}
#[test]
fn detects_a_license_key_named_by_a_new_relic_keyword() {
for input in [
format!("NEW_RELIC_LICENSE_KEY={LICENSE_KEY}"),
format!("newrelic.license_key: {LICENSE_KEY}"),
format!("# New Relic license key: {LICENSE_KEY}"),
format!("{{\"new-relic-license-key\": \"{LICENSE_KEY}\"}}"),
] {
let candidates = detect_license_key(&input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(candidates[0].type_name(), "new_relic_license_key");
let expected = if input.starts_with('#') {
Confidence::Medium
} else {
Confidence::High
};
assert_eq!(candidates[0].confidence(), expected, "{input}");
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
let start = input.rfind(LICENSE_KEY).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + LICENSE_KEY.len()).unwrap()
);
}
}
const CURRENT_KEY: &str = "0123456789abcdef0123456789abcdefFFFFNRAL";
const EU_KEY: &str = "eu01xx0123456789abcdef0123456789FFFFNRAL";
#[test]
fn current_generation_fixtures_are_exactly_forty_bytes() {
assert_eq!(CURRENT_KEY.len(), LICENSE_KEY_LEN);
assert_eq!(EU_KEY.len(), LICENSE_KEY_LEN);
}
#[test]
fn detects_the_current_generation_license_key_named_by_a_keyword() {
for key in [CURRENT_KEY, EU_KEY] {
for input in [
format!("newrelic {key}"),
format!("NEW_RELIC_LICENSE_KEY={key}"),
format!("{{\"new-relic-license-key\": \"{key}\"}}"),
format!("newrelic '{key}'"),
format!("# \u{1F511} caf\u{e9}\r\nnewrelic {key}\r\n"),
] {
let candidates = detect_license_key(&input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(candidates[0].type_name(), "new_relic_license_key");
let expected = if input.contains('=') || input.contains(':') {
Confidence::High
} else {
Confidence::Medium
};
assert_eq!(candidates[0].confidence(), expected, "{input}");
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
let start = input.rfind(key).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + key.len()).unwrap()
);
}
}
}
#[test]
fn detects_a_current_generation_license_key_with_no_keyword_on_the_line() {
for key in [CURRENT_KEY, EU_KEY] {
for input in [
key.to_owned(),
format!("common: &default_settings\n license_key: '{key}'\n"),
format!("exports.config = {{\n license_key: '{key}',\n}}\n"),
format!("POST /log/v1 HTTP/1.1\nX-License-Key: {key}\n"),
format!("global:\n licenseKey: {key}\n"),
] {
let candidates = detect_license_key(&input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(candidates[0].type_name(), "new_relic_license_key");
assert_eq!(candidates[0].confidence(), Confidence::Medium);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
let start = input.find(key).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + key.len()).unwrap()
);
}
}
}
#[test]
fn keeps_the_keyword_gate_on_the_legacy_shape_beside_a_context_free_marked_key() {
let input = format!("license_key: {CURRENT_KEY} commit {LICENSE_KEY}");
let candidates = detect_license_key(&input);
assert_eq!(candidates.len(), 1);
let start = input.find(CURRENT_KEY).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + CURRENT_KEY.len()).unwrap()
);
}
#[test]
fn rejects_marked_lookalikes_with_the_wrong_body_length_and_no_keyword() {
let short = &CURRENT_KEY[1..];
let long = format!("0{CURRENT_KEY}");
for input in [
format!("license_key: {short}"),
format!("license_key: {long}"),
"commit 9b2f47c1e08d3a65f4c7b29e1d0a86f3c5e71b24".to_owned(),
format!("license_key: x{CURRENT_KEY}"),
format!("license_key: {CURRENT_KEY}x"),
] {
assert!(detect_license_key(&input).is_empty(), "{input}");
}
}
#[test]
fn rejects_current_generation_keys_with_the_wrong_body_length() {
let long = format!("0{CURRENT_KEY}");
let short = &CURRENT_KEY[1..];
let eu_long = format!("eu01xx0{}", &EU_KEY[6..]);
let eu_short = format!("eu01xx{}", &EU_KEY[7..]);
for key in [long, short.to_owned(), eu_long, eu_short] {
assert!(
detect_license_key(&format!("newrelic {key}")).is_empty(),
"{key}"
);
}
}
#[test]
fn rejects_a_current_generation_key_with_a_wrong_marker_or_case() {
for key in [
CURRENT_KEY.replace("FFFFNRAL", "FFFFNRAK"),
CURRENT_KEY.replace("FFFFNRAL", "ffffnral"),
CURRENT_KEY.replace("FFFFNRAL", "NRAL"),
CURRENT_KEY.replace(
"0123456789abcdef0123456789abcdef",
"0123456789ABCDEF0123456789ABCDEF",
),
EU_KEY.replace("eu01xx", "EU01XX"),
EU_KEY.replace("eu01xx", "us01xx"),
] {
assert!(
detect_license_key(&format!("newrelic {key}")).is_empty(),
"{key}"
);
}
}
#[test]
fn rejects_a_current_generation_key_embedded_in_a_wider_identifier() {
for key in [CURRENT_KEY, EU_KEY] {
assert!(detect_license_key(&format!("newrelic x{key}")).is_empty());
assert!(detect_license_key(&format!("newrelic {key}x")).is_empty());
assert!(detect_license_key(&format!("newrelic {key}0")).is_empty());
}
}
#[test]
fn rejects_a_masked_current_generation_key() {
let masked = format!("{}FFFFNRAL", "0".repeat(32));
let masked_eu = format!("eu01xx{}FFFFNRAL", "0".repeat(26));
assert!(detect_license_key(&format!("newrelic {masked}")).is_empty());
assert!(detect_license_key(&format!("newrelic {masked_eu}")).is_empty());
let placeholder = format!("{}FFFFNRAL", "*".repeat(32));
assert!(detect_license_key(&format!("newrelic {placeholder}")).is_empty());
}
#[test]
fn reports_every_license_key_generation_on_one_line_in_order() {
let input = format!("newrelic {EU_KEY} {LICENSE_KEY} {CURRENT_KEY}");
let candidates = detect_license_key(&input);
assert_eq!(candidates.len(), 3);
let starts: Vec<usize> = candidates.iter().map(|c| c.range().start()).collect();
assert!(starts.windows(2).all(|pair| pair[0] < pair[1]));
}
#[test]
fn stays_bounded_over_a_long_line_of_rejected_current_generation_candidates() {
let input = format!(
"newrelic {}",
format!("{} ", &CURRENT_KEY[1..]).repeat(10_000)
);
assert!(detect_license_key(&input).is_empty());
let eu = format!("newrelic {}", "eu01xx".repeat(10_000));
assert!(detect_license_key(&eu).is_empty());
}
#[test]
fn rejects_a_bare_license_key_with_no_context() {
assert!(detect_license_key(LICENSE_KEY).is_empty());
}
#[test]
fn rejects_a_license_key_whose_context_is_on_a_different_line() {
let input = format!("# new relic\n{LICENSE_KEY}\n");
assert!(detect_license_key(&input).is_empty());
}
#[test]
fn rejects_an_uppercase_hex_run() {
let upper = LICENSE_KEY.to_ascii_uppercase();
assert!(detect_license_key(&format!("newrelic {upper}")).is_empty());
}
#[test]
fn rejects_a_license_key_one_byte_short_of_the_required_length() {
let short = &LICENSE_KEY[..LICENSE_KEY.len() - 1];
assert!(detect_license_key(&format!("newrelic {short}")).is_empty());
}
#[test]
fn rejects_a_license_key_one_byte_longer_than_the_required_length_rather_than_truncating() {
let long = format!("{LICENSE_KEY}0");
assert!(detect_license_key(&format!("newrelic {long}")).is_empty());
}
#[test]
fn rejects_a_masked_license_key() {
assert!(
detect_license_key(&format!("newrelic {}", "0".repeat(LICENSE_KEY_LEN))).is_empty()
);
}
#[test]
fn rejects_a_license_key_environment_variable_reference() {
assert!(
detect_license_key("newrelic NEW_RELIC_LICENSE_KEY=${NEW_RELIC_LICENSE_KEY}")
.is_empty()
);
}
#[test]
fn finds_a_qualified_license_key_match_across_crlf_and_a_unicode_prefix() {
let input = format!("# \u{1F511} caf\u{e9}\r\nnewrelic {LICENSE_KEY}\r\n");
let candidates = detect_license_key(&input);
assert_eq!(candidates.len(), 1);
let start = input.rfind(LICENSE_KEY).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + LICENSE_KEY.len()).unwrap()
);
}
#[test]
fn finds_deterministic_license_key_findings_across_repeated_calls() {
let input = format!("newrelic {LICENSE_KEY}");
assert_eq!(detect_license_key(&input), detect_license_key(&input));
}
#[test]
fn stays_bounded_over_a_long_context_free_line_packed_with_license_key_candidates() {
let input = format!("{LICENSE_KEY} ").repeat(10_000);
assert_eq!(detect_license_key(&input).len(), 0);
}
#[test]
fn stays_bounded_over_a_long_context_free_line_of_rejected_marked_candidates() {
let input = format!("{} ", &CURRENT_KEY[1..]).repeat(10_000);
assert!(detect_license_key(&input).is_empty());
}
#[test]
fn every_license_key_candidate_on_a_context_bearing_line_is_reported() {
let input = format!("newrelic {LICENSE_KEY} {LICENSE_KEY}");
let candidates = detect_license_key(&input);
assert_eq!(candidates.len(), 2);
assert!(
candidates
.iter()
.all(|candidate| candidate.confidence() == Confidence::Medium)
);
}
}