use crate::detectors::pattern::{self, RunCursor, is_alnum_dash};
use crate::detectors::prefilter::Literals;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const PREFIX: &[u8] = b"AAAA";
const BODY_LEN: usize = 7;
const SEPARATOR: u8 = b':';
const TAIL_LEN: usize = 140;
pub(super) struct FirebaseServerKeyDetector;
impl Detector for FirebaseServerKeyDetector {
fn id(&self) -> &'static str {
"firebase-server-key"
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
let bytes = input.as_bytes();
let Some(first) = pattern::find_literal(bytes, PREFIX, 0) else {
return Ok(Vec::new());
};
let mut body_ends = RunCursor::new(bytes, is_alnum_dash);
let mut tail_ends = RunCursor::new(bytes, is_alnum_dash);
let mut candidates = Vec::new();
let mut start = first;
while start < bytes.len() {
if !bytes[start..].starts_with(PREFIX) {
start += 1;
continue;
}
let Some(end) = match_at(bytes, &mut body_ends, &mut tail_ends, start) else {
start += 1;
continue;
};
if pattern::boundary_ok(bytes, start, end, is_alnum_dash)
&& let Some(range) = ByteRange::new(start, end)
{
candidates.push(
Candidate::built_in("firebase_server_key", Confidence::High, range)
.with_specificity(Specificity::Provider)
.with_signal_pack(crate::types::signal_pack!(
"firebase-documented-prefix",
"two-segment-exact-length"
)),
);
}
start = end;
}
Ok(candidates)
}
}
fn match_at(
bytes: &[u8],
body_ends: &mut RunCursor<'_>,
tail_ends: &mut RunCursor<'_>,
start: usize,
) -> Option<usize> {
let body_start = start + PREFIX.len();
if body_ends.end(body_start) < body_start + BODY_LEN {
return None;
}
let separator = body_start + BODY_LEN;
if bytes.get(separator) != Some(&SEPARATOR) {
return None;
}
let tail_start = separator + 1;
if tail_ends.end(tail_start) < tail_start + TAIL_LEN {
return None;
}
Some(tail_start + TAIL_LEN)
}
pub(super) const REQUIRED_LITERALS: &[Literals] = &[Literals::Bytes(&[PREFIX])];
#[cfg(test)]
mod tests {
use super::*;
const BODY: &str = "SYNREV0";
const TAIL: &str = "SYNTHETICREVOKEDFIREBASEFCMLEGACYSERVERKEYFIXTUREPADDING0123456789SYNTHETICREVOKEDFIREBASEFCMLEGACYSERVERKEYFIXTUREPADDING0123456789ABCDWXYZ";
fn token() -> String {
format!("AAAA{BODY}:{TAIL}")
}
fn detect(input: &str) -> Vec<Candidate> {
FirebaseServerKeyDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
#[test]
fn fixture_segments_are_exactly_documented_length() {
assert_eq!(BODY.len(), BODY_LEN);
assert_eq!(TAIL.len(), TAIL_LEN);
}
#[test]
fn detects_a_synthetic_key_with_provider_specificity() {
let value = token();
let candidates = detect(&value);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "firebase_server_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_key_bare_in_env_and_service_worker_contexts() {
let value = token();
for input in [
value.clone(),
format!("FCM_SERVER_KEY={value}"),
format!("\"serverKey\": \"{value}\""),
format!("const SERVER_KEY = '{value}';"),
] {
let candidates = detect(&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 accepts_punctuation_boundaries() {
let value = token();
let input = format!("({value}).");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(
candidates[0].range(),
ByteRange::new(1, value.len() + 1).unwrap()
);
}
#[test]
fn rejects_a_truncated_body_segment() {
let short_body = &BODY[..BODY_LEN - 1];
assert!(detect(&format!("AAAA{short_body}:{TAIL}")).is_empty());
}
#[test]
fn rejects_a_truncated_tail_segment() {
let short_tail = &TAIL[..TAIL_LEN - 1];
assert!(detect(&format!("AAAA{BODY}:{short_tail}")).is_empty());
}
#[test]
fn rejects_a_body_segment_longer_than_documented() {
assert!(detect(&format!("AAAA{BODY}A:{TAIL}")).is_empty());
}
#[test]
fn rejects_a_tail_segment_longer_than_documented() {
assert!(detect(&format!("AAAA{BODY}:{TAIL}A")).is_empty());
}
#[test]
fn rejects_a_malformed_separator() {
assert!(detect(&format!("AAAA{BODY}.{TAIL}")).is_empty());
assert!(detect(&format!("AAA-{BODY}:{TAIL}")).is_empty());
}
#[test]
fn rejects_the_prefix_alone() {
assert!(detect("AAAA").is_empty());
assert!(detect(&format!("AAAA{BODY}")).is_empty());
assert!(detect(&format!("AAAA{BODY}:")).is_empty());
}
#[test]
fn rejects_the_body_or_tail_embedded_in_a_wider_identifier() {
let value = token();
assert!(detect(&format!("x{value}")).is_empty());
assert!(detect(&format!("{value}x")).is_empty());
}
#[test]
fn rejects_a_masked_value() {
let masked_tail = "*".repeat(TAIL_LEN);
assert!(detect(&format!("AAAA{BODY}:{masked_tail}")).is_empty());
}
#[test]
fn rejects_an_environment_variable_reference() {
assert!(detect("${FCM_SERVER_KEY}").is_empty());
}
#[test]
fn finds_a_match_across_crlf_and_a_unicode_prefix() {
let value = token();
let input = format!("# \u{1F511} caf\u{e9}\r\n{value}\r\n");
let candidates = detect(&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 = token();
assert_eq!(detect(&value), detect(&value));
}
#[test]
fn stays_bounded_over_a_long_run_of_near_miss_prefixes() {
let short_body = &BODY[..BODY_LEN - 1];
let input = format!("AAAA{short_body}:{TAIL} ").repeat(2_000);
assert_eq!(detect(&input).len(), 0);
}
}