use crate::detectors::pattern::{self, RunCursor, is_alnum};
use crate::detectors::prefilter::Literals;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const PREFIX: &[u8] = b"glsa_";
const BODY_LEN: usize = 32;
const SEPARATOR: u8 = b'_';
const CHECKSUM_LEN: usize = 8;
fn is_hex(byte: u8) -> bool {
byte.is_ascii_hexdigit()
}
pub(super) struct GrafanaServiceAccountTokenDetector;
impl Detector for GrafanaServiceAccountTokenDetector {
fn id(&self) -> &'static str {
"grafana-service-account-token"
}
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 alnum_ends = RunCursor::new(bytes, is_alnum);
let mut hex_ends = RunCursor::new(bytes, is_hex);
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 alnum_ends, &mut hex_ends, start) else {
start += 1;
continue;
};
if pattern::boundary_ok(bytes, start, end, pattern::is_alnum_dash)
&& let Some(range) = ByteRange::new(start, end)
{
candidates.push(
Candidate::built_in("grafana_service_account_token", Confidence::High, range)
.with_specificity(Specificity::Provider)
.with_signal_pack(crate::types::signal_pack!(
"grafana-documented-prefix",
"two-segment-exact-length"
)),
);
}
start = end;
}
Ok(candidates)
}
}
fn match_at(
bytes: &[u8],
alnum_ends: &mut RunCursor<'_>,
hex_ends: &mut RunCursor<'_>,
start: usize,
) -> Option<usize> {
let body_start = start + PREFIX.len();
if alnum_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 checksum_start = separator + 1;
if hex_ends.end(checksum_start) < checksum_start + CHECKSUM_LEN {
return None;
}
Some(checksum_start + CHECKSUM_LEN)
}
pub(super) const REQUIRED_LITERALS: &[Literals] = &[Literals::Bytes(&[PREFIX])];
#[cfg(test)]
mod tests {
use super::*;
const BODY: &str = "SYNTHETICREVOKEDGRAFANASATOKEN01";
const CHECKSUM: &str = "deadbeef";
fn token() -> String {
format!("glsa_{BODY}_{CHECKSUM}")
}
fn detect(input: &str) -> Vec<Candidate> {
GrafanaServiceAccountTokenDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
#[test]
fn fixture_segments_are_exactly_documented_length() {
assert_eq!(BODY.len(), BODY_LEN);
assert_eq!(CHECKSUM.len(), CHECKSUM_LEN);
}
#[test]
fn detects_a_synthetic_token_with_provider_specificity() {
let value = token();
let candidates = detect(&value);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "grafana_service_account_token");
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_token_bare_in_env_and_control_contexts() {
let value = token();
for input in [
value.clone(),
format!("GRAFANA_SA_TOKEN={value}"),
format!("grafana_service_account_token: {value}"),
format!("{{\"token\": \"{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!("glsa_{short_body}_{CHECKSUM}")).is_empty());
}
#[test]
fn rejects_a_truncated_checksum_segment() {
let short_checksum = &CHECKSUM[..CHECKSUM_LEN - 1];
assert!(detect(&format!("glsa_{BODY}_{short_checksum}")).is_empty());
}
#[test]
fn rejects_a_body_segment_longer_than_documented() {
assert!(detect(&format!("glsa_{BODY}A_{CHECKSUM}")).is_empty());
}
#[test]
fn rejects_a_checksum_segment_longer_than_documented() {
assert!(detect(&format!("glsa_{BODY}_{CHECKSUM}a")).is_empty());
}
#[test]
fn rejects_a_malformed_separator() {
assert!(detect(&format!("glsa_{BODY}.{CHECKSUM}")).is_empty());
assert!(detect(&format!("glsa-{BODY}_{CHECKSUM}")).is_empty());
}
#[test]
fn rejects_a_non_hex_checksum() {
assert!(detect(&format!("glsa_{BODY}_SYNTHETIC")).is_empty());
}
#[test]
fn rejects_the_prefix_alone() {
assert!(detect("glsa_").is_empty());
assert!(detect(&format!("glsa_{BODY}")).is_empty());
}
#[test]
fn rejects_the_body_or_checksum_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() {
assert!(detect("glsa_********************************_********").is_empty());
}
#[test]
fn rejects_an_environment_variable_reference() {
assert!(detect("${GRAFANA_SA_TOKEN}").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!("glsa_{short_body}_{CHECKSUM} ").repeat(10_000);
assert_eq!(detect(&input).len(), 0);
}
}