use crate::detectors::additional_providers::KnownFormatProviderDetector;
use crate::detectors::pattern::{self, PrefixShape};
const PREFIX: &str = "napi_";
const MIN_BODY_LEN: usize = 64;
const SIGNALS: [&str; 2] = ["neon-documented-prefix", "tool-corroborated-body-floor"];
fn is_boundary_byte(byte: u8) -> bool {
pattern::is_alnum(byte) || matches!(byte, b'_' | b'-')
}
fn body_is_not_filler(bytes: &[u8], start: usize, end: usize) -> bool {
let body = &bytes[start + PREFIX.len()..end];
body.iter().any(|&byte| byte != body[0])
}
pub(super) const NEON: KnownFormatProviderDetector = KnownFormatProviderDetector::new(
"neon-api-key",
"neon_api_key",
&[
PrefixShape::at_least(PREFIX, MIN_BODY_LEN, pattern::is_alnum, &SIGNALS)
.with_post_check(body_is_not_filler),
],
is_boundary_byte,
);
#[cfg(test)]
mod tests {
use super::*;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const BODY: &str = "SyntheticRevokedNeonApiKey0000Fixture1111Body2222Padding33334444";
const _: () = assert!(BODY.len() == MIN_BODY_LEN);
fn key() -> String {
format!("{PREFIX}{BODY}")
}
fn detect(input: &str) -> Vec<Candidate> {
NEON.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
fn assert_key_at(input: &str, key: &str) {
let candidates = detect(input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(candidates[0].type_name(), "neon_api_key");
assert_eq!(candidates[0].confidence(), Confidence::High);
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(),
"{input}"
);
}
#[test]
fn detects_a_bare_key_and_a_key_in_common_contexts() {
let key = key();
for input in [
key.clone(),
format!("NEON_API_KEY={key}"),
format!("{{\"apiKey\": \"{key}\"}}"),
format!("Authorization: Bearer {key}"),
format!("neonctl projects list --api-key {key}"),
] {
assert_key_at(&input, &key);
}
}
#[test]
fn a_longer_body_is_read_to_the_end_of_its_run() {
let key = format!("{}9Z", key());
assert_key_at(&format!("NEON_API_KEY={key}"), &key);
}
#[test]
fn a_body_one_byte_short_of_the_floor_is_not_reported() {
let short = format!("{PREFIX}{}", &BODY[..MIN_BODY_LEN - 1]);
assert!(detect(&short).is_empty());
}
#[test]
fn a_key_inside_a_wider_identifier_is_not_reported() {
for input in [
format!("x{}", key()),
format!("x_{}", key()),
format!("{}_x", key()),
format!("{}-x", key()),
] {
assert!(detect(&input).is_empty(), "{input}");
}
}
#[test]
fn filler_placeholders_and_the_bare_prefix_are_not_reported() {
for input in [
format!("{PREFIX}{}", "0".repeat(MIN_BODY_LEN)),
format!("{PREFIX}{}", "x".repeat(MIN_BODY_LEN)),
"NEON_API_KEY=napi_".to_owned(),
"NEON_API_KEY=napi_short".to_owned(),
] {
assert!(detect(&input).is_empty(), "{input}");
}
}
#[test]
fn a_non_alphanumeric_byte_ends_the_body() {
let broken = format!("{PREFIX}{}!{}", &BODY[..32], &BODY[32..]);
assert!(detect(&broken).is_empty());
}
}