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};
const CURRENT_PREFIX: &str = "HRKU-AA";
const CURRENT_BODY_LEN: usize = 58;
const CURRENT_SIGNALS: [&str; 2] = ["heroku-documented-prefix", "heroku-documented-length"];
const UUID_PREFIX: &str = "HRKU-";
fn is_lower_uuid_after(bytes: &[u8], start: usize, end: usize) -> bool {
let body_start = start + UUID_PREFIX.len();
end - body_start == LEGACY_UUID_LEN
&& is_uuid_shape(bytes, body_start, end, pattern::is_lower_hex)
}
const CURRENT_BOUNDARY: Alphabet = pattern::is_alnum_dash;
pub(super) const HEROKU_API_KEY: KnownFormatProviderDetector = KnownFormatProviderDetector::new(
"heroku-api-key",
"heroku_api_key",
&[
PrefixShape::exact(
CURRENT_PREFIX,
CURRENT_BODY_LEN,
pattern::is_alnum_dash,
&CURRENT_SIGNALS,
),
PrefixShape::exact(
UUID_PREFIX,
LEGACY_UUID_LEN,
pattern::is_hex_or_dash,
&CURRENT_SIGNALS,
)
.with_post_check(is_lower_uuid_after),
],
CURRENT_BOUNDARY,
);
const CONTEXT_KEYWORD: &str = "heroku";
const LEGACY_UUID_LEN: usize = 36;
const UUID_DASH_OFFSETS: [usize; 4] = [8, 13, 18, 23];
const LEGACY_BOUNDARY: Alphabet = pattern::is_alnum_dash;
fn line_contains_ci(line: &str, needle: &str) -> bool {
text::contains_ci(line, needle)
}
fn scan_bare_legacy_runs(
input: &str,
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 == LEGACY_UUID_LEN
&& pattern::boundary_ok(bytes, start, run_end, boundary)
{
matches.push((start, run_end));
}
start = run_end;
}
matches
}
fn is_uuid_shape(bytes: &[u8], start: usize, end: usize, hex: Alphabet) -> bool {
(start..end).all(|index| {
let offset = index - start;
if UUID_DASH_OFFSETS.contains(&offset) {
bytes[index] == b'-'
} else {
hex(bytes[index])
}
})
}
fn is_assignment_gap(byte: u8) -> bool {
matches!(
byte,
b' ' | b'\t' | b'"' | b'\'' | b'`' | b'=' | b':' | b'>' | b'?' | b'|' | b','
)
}
fn is_key_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-')
}
fn assigned_key(bytes: &[u8], value_start: usize) -> &[u8] {
let mut end = value_start;
while end > 0 && is_assignment_gap(bytes[end - 1]) {
end -= 1;
}
let mut start = end;
while start > 0 && is_key_byte(bytes[start - 1]) {
start -= 1;
}
&bytes[start..end]
}
const IDENTIFIER_WORDS: [&[u8]; 2] = [b"id", b"uuid"];
fn is_identifier_key(key: &[u8]) -> bool {
let segment_start = key
.iter()
.rposition(|&byte| matches!(byte, b'_' | b'.' | b'-'))
.map_or(0, |index| index + 1);
let segment = &key[segment_start..];
IDENTIFIER_WORDS.iter().any(|word| {
if segment.eq_ignore_ascii_case(word) {
return true;
}
let Some(split) = segment
.len()
.checked_sub(word.len())
.filter(|&split| split > 0)
else {
return false;
};
let (head, tail) = segment.split_at(split);
tail.eq_ignore_ascii_case(word)
&& tail[0].is_ascii_uppercase()
&& head
.last()
.is_some_and(|&byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
})
}
fn is_filler_uuid(value: &str) -> bool {
let digits: String = value.chars().filter(|&ch| ch != '-').collect();
text::is_repeated_character_filler(&digits)
}
fn is_url_path_segment(bytes: &[u8], value_start: usize) -> bool {
value_start > 0 && bytes[value_start - 1] == b'/'
}
fn is_token_space(byte: u8) -> bool {
matches!(byte, b' ' | b'\t' | b'\r')
}
fn tokens(line: &str) -> impl Iterator<Item = &str> {
line.split([' ', '\t', '\r'])
.filter(|token| !token.is_empty())
}
const NETRC_MAX_CONTINUATION_LINES: usize = 2;
fn is_heroku_netrc_machine(line: &str) -> bool {
let mut words = tokens(line);
words.next() == Some("machine")
&& words
.next()
.is_some_and(|host| line_contains_ci(host, CONTEXT_KEYWORD))
&& !tokens(line).any(|token| token == "password")
}
fn is_netrc_continuation(line: &str) -> bool {
matches!(tokens(line).next(), Some("login" | "account"))
&& !tokens(line).any(|token| token == "password")
}
fn ends_inside_heroku_netrc_entry(previous: &[&str]) -> bool {
for (gap, line) in previous.iter().rev().enumerate() {
if is_heroku_netrc_machine(line) {
return true;
}
if gap >= NETRC_MAX_CONTINUATION_LINES || !is_netrc_continuation(line) {
return false;
}
}
false
}
fn follows_netrc_password_token(line: &[u8], value_start: usize) -> bool {
let mut end = value_start;
while end > 0 && is_token_space(line[end - 1]) {
end -= 1;
}
let keyword = b"password";
end < value_start
&& end >= keyword.len()
&& &line[end - keyword.len()..end] == keyword
&& (end == keyword.len() || is_token_space(line[end - keyword.len() - 1]))
}
fn is_heroku_auth_token_command(line: &str) -> bool {
if !line.contains("auth:token") {
return false;
}
let mut before_last = None;
let mut last = None;
for word in tokens(line) {
before_last = last;
last = Some(word);
}
before_last == Some("heroku") && last == Some("auth:token")
}
fn is_whole_line(line: &[u8], start: usize, end: usize) -> bool {
line[..start].iter().all(|&byte| is_token_space(byte))
&& line[end..].iter().all(|&byte| is_token_space(byte))
}
const AUTHORIZATIONS_MAX_ROWS: usize = 6;
pub(super) const LOOKBACK_LINES: usize = AUTHORIZATIONS_MAX_ROWS + 1;
fn is_heroku_authorizations_command(line: &str) -> bool {
if !line.contains("authorizations:") {
return false;
}
let mut previous = "";
tokens(line).any(|word| {
let hit = previous == "heroku"
&& word
.strip_prefix("authorizations:")
.is_some_and(|verb| !verb.is_empty());
previous = word;
hit
})
}
fn cli_table_label(line: &str) -> Option<&str> {
let (label, rest) = line.split_once(':')?;
let well_formed = !label.is_empty()
&& label.len() <= 24
&& label.split(' ').count() <= 3
&& label
.split(' ')
.all(|word| !word.is_empty() && word.bytes().all(|byte| byte.is_ascii_alphabetic()));
(well_formed && rest.bytes().next().is_none_or(is_token_space)).then_some(label)
}
fn ends_inside_heroku_authorizations_table(previous: &[&str]) -> bool {
for (gap, line) in previous.iter().rev().enumerate() {
if is_heroku_authorizations_command(line) {
return true;
}
if gap >= AUTHORIZATIONS_MAX_ROWS || cli_table_label(line).is_none() {
return false;
}
}
false
}
fn is_token_table_row_value(line: &str, value_start: usize, value_end: usize) -> bool {
let Some(label) = cli_table_label(line) else {
return false;
};
let bytes = line.as_bytes();
let after_colon = label.len() + 1;
label.eq_ignore_ascii_case("token")
&& value_start >= after_colon
&& bytes[after_colon..value_start]
.iter()
.all(|&byte| is_token_space(byte))
&& bytes[value_end..].iter().all(|&byte| is_token_space(byte))
}
#[cfg(test)]
pub(crate) fn has_open_heroku_legacy_context(input: &str) -> bool {
has_open_heroku_legacy_context_in(&super::lookback_tail(input))
}
pub(crate) fn has_open_heroku_legacy_context_in(tail: &[&str]) -> bool {
let tail = text::tail_lines(tail, LOOKBACK_LINES);
tail.last()
.is_some_and(|last| is_heroku_auth_token_command(last))
|| ends_inside_heroku_netrc_entry(tail)
|| ends_inside_heroku_authorizations_table(tail)
}
pub(super) struct HerokuApiKeyLegacyDetector;
impl Detector for HerokuApiKeyLegacyDetector {
fn id(&self) -> &'static str {
"heroku-api-key-legacy"
}
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 raw_matches = scan_bare_legacy_runs(line, pattern::is_hex_or_dash, LEGACY_BOUNDARY);
if raw_matches.is_empty() {
return;
}
let same_line = line_contains_ci(line, CONTEXT_KEYWORD);
let previous = text::preceding_lines(input, line_start, LOOKBACK_LINES);
let bytes = line.as_bytes();
for (relative_start, relative_end) in raw_matches {
let in_layout = (follows_netrc_password_token(bytes, relative_start)
&& ends_inside_heroku_netrc_entry(&previous))
|| (is_whole_line(bytes, relative_start, relative_end)
&& previous
.last()
.is_some_and(|line| is_heroku_auth_token_command(line)))
|| (is_token_table_row_value(line, relative_start, relative_end)
&& ends_inside_heroku_authorizations_table(&previous));
if !(same_line || in_layout)
|| !is_uuid_shape(bytes, relative_start, relative_end, pattern::is_hex)
|| is_filler_uuid(&line[relative_start..relative_end])
|| is_identifier_key(assigned_key(bytes, relative_start))
|| is_url_path_segment(bytes, relative_start)
{
continue;
}
let Some(range) =
ByteRange::new(line_start + relative_start, line_start + relative_end)
else {
continue;
};
let (confidence, signal) = if same_line
&& text::is_provider_named_assignment(line, relative_start, &[CONTEXT_KEYWORD])
{
(Confidence::High, "heroku-named-assignment")
} else if in_layout {
(Confidence::High, "heroku-cli-layout")
} else {
(Confidence::Medium, "heroku-keyword-cooccurrence")
};
candidates.push(
Candidate::built_in("heroku_api_key_legacy", confidence, range)
.with_specificity(Specificity::Provider)
.with_signals([signal]),
);
}
});
Ok(candidates)
}
}
#[cfg(test)]
mod tests {
use super::*;
const CURRENT_BODY: &str = "SYNTHETIC0REVOKED0HerokuOAuthAccessTokenBodyFixture0123456";
const _: () = assert!(CURRENT_BODY.len() == CURRENT_BODY_LEN);
const LEGACY_UUID: &str = "01234567-89ab-cdef-0123-456789abcdef";
const _: () = assert!(LEGACY_UUID.len() == LEGACY_UUID_LEN);
fn current_token() -> String {
format!("{CURRENT_PREFIX}{CURRENT_BODY}")
}
fn detect_current(input: &str) -> Vec<Candidate> {
HEROKU_API_KEY
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
fn detect_legacy(input: &str) -> Vec<Candidate> {
HerokuApiKeyLegacyDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
#[test]
fn detects_the_current_token_with_no_context_needed() {
let value = current_token();
let candidates = detect_current(&value);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "heroku_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 rejects_a_current_body_one_byte_short_of_the_documented_length() {
let short_body = &CURRENT_BODY[..CURRENT_BODY_LEN - 1];
assert!(detect_current(&format!("{CURRENT_PREFIX}{short_body}")).is_empty());
}
#[test]
fn rejects_a_current_body_one_byte_longer_than_the_documented_length() {
assert!(detect_current(&format!("{CURRENT_PREFIX}{CURRENT_BODY}a")).is_empty());
}
#[test]
fn rejects_undocumented_near_miss_prefixes() {
for input in [
format!("HRKU-AB{CURRENT_BODY}"),
format!("hrku-aa{CURRENT_BODY}"),
format!("HRKU{CURRENT_BODY}"),
format!("HRKU-A{CURRENT_BODY}"),
] {
assert!(detect_current(&input).is_empty(), "{input}");
}
}
#[test]
fn rejects_the_prefix_embedded_in_a_wider_identifier() {
assert!(detect_current(&format!("legacy_{}", current_token())).is_empty());
assert!(detect_current(&format!("{}_backup", current_token())).is_empty());
}
#[test]
fn rejects_a_masked_value() {
assert!(
detect_current(&format!("{CURRENT_PREFIX}{}", "*".repeat(CURRENT_BODY_LEN))).is_empty()
);
assert!(detect_current(&format!("{CURRENT_PREFIX}${{HEROKU_API_KEY}}")).is_empty());
}
#[test]
fn accepts_a_doc_style_x_filled_placeholder_built_from_valid_alphabet_characters() {
assert_eq!(
detect_current(&format!("{CURRENT_PREFIX}{}", "x".repeat(CURRENT_BODY_LEN))).len(),
1
);
}
#[test]
fn accepts_env_json_yaml_and_quoted_contexts() {
let value = current_token();
for input in [
format!("HEROKU_API_KEY={value}"),
format!("{{\"apiKey\": \"{value}\"}}"),
format!("authorization: Bearer {value}"),
format!("authorization=\"Bearer {value}\""),
] {
let candidates = detect_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_match_across_crlf_and_a_unicode_prefix() {
let value = current_token();
let input = format!("# \u{1F511} caf\u{e9}\r\n{value}\r\n");
let candidates = detect_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_findings_across_repeated_calls() {
let value = current_token();
assert_eq!(detect_current(&value), detect_current(&value));
}
#[test]
fn reports_a_repeated_identical_value_once_per_occurrence() {
let value = current_token();
let input = format!("{value} {value}");
assert_eq!(detect_current(&input).len(), 2);
}
#[test]
fn stays_bounded_over_a_long_run_of_near_miss_prefixes() {
let short_body = &CURRENT_BODY[..CURRENT_BODY_LEN - 1];
let input = format!("{CURRENT_PREFIX}{short_body} ").repeat(10_000);
assert_eq!(detect_current(&input).len(), 0);
}
const UUID_GENERATION: &str = "HRKU-5e7e71c0-0000-4000-8000-00000000fa11";
const _: () = assert!(UUID_GENERATION.len() == 41);
#[test]
fn detects_the_41_character_uuid_generation_with_no_context_needed() {
for (input, start) in [
(UUID_GENERATION.to_string(), 0),
(format!("HEROKU_API_KEY={UUID_GENERATION}\n"), 15),
(format!("Token: {UUID_GENERATION}\n"), 7),
(format!("{{\"access_token\": \"{UUID_GENERATION}\"}}"), 18),
(format!("app_id={UUID_GENERATION}"), 7),
] {
let candidates = detect_current(&input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(candidates[0].type_name(), "heroku_api_key");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + UUID_GENERATION.len()).unwrap(),
"{input}"
);
}
}
#[test]
fn rejects_near_misses_of_the_uuid_generation() {
let body = &UUID_GENERATION[UUID_PREFIX.len()..];
for input in [
format!("HEROKU_API_KEY={}\n", &UUID_GENERATION[..40]),
format!("HEROKU_API_KEY={UUID_GENERATION}0\n"),
format!("HEROKU_API_KEY=HRKU_{body}\n"),
format!("hrku-{body}"),
format!("HRKU-{}", body.to_ascii_uppercase()),
"HRKU-5e7e71c00-000-4000-8000-00000000fa11".to_string(),
"HRKU-5e7e71g0-0000-4000-8000-00000000fa11".to_string(),
format!("legacy_{UUID_GENERATION}"),
format!("{UUID_GENERATION}_backup"),
] {
assert!(detect_current(&input).is_empty(), "{input}");
}
}
#[test]
fn keeps_both_generations_apart_on_one_line() {
let current = current_token();
let input = format!("{UUID_GENERATION} {current}");
let candidates = detect_current(&input);
assert_eq!(candidates.len(), 2);
assert_eq!(candidates[0].range(), ByteRange::new(0, 41).unwrap());
assert_eq!(candidates[1].range(), ByteRange::new(42, 42 + 65).unwrap());
}
#[test]
fn the_legacy_detector_never_reports_the_uuid_inside_the_prefixed_generation() {
for input in [
format!("HEROKU_API_KEY={UUID_GENERATION}"),
format!("heroku {UUID_GENERATION}"),
] {
assert!(detect_legacy(&input).is_empty(), "{input}");
}
}
#[test]
fn detects_a_legacy_token_under_a_heroku_named_key_at_high_confidence() {
let input = format!("HEROKU_API_KEY={LEGACY_UUID}");
let candidates = detect_legacy(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "heroku_api_key_legacy");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
let start = input.rfind(LEGACY_UUID).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + LEGACY_UUID.len()).unwrap()
);
}
#[test]
fn rejects_a_bare_legacy_token_with_no_context() {
assert!(detect_legacy(LEGACY_UUID).is_empty());
}
#[test]
fn rejects_an_ordinary_uuid_such_as_an_app_or_release_id() {
for input in [
format!("app_id={LEGACY_UUID}"),
format!("release={LEGACY_UUID}"),
] {
assert!(detect_legacy(&input).is_empty(), "{input}");
}
}
#[test]
fn rejects_a_uuid_assigned_to_an_identifier_key_on_a_heroku_line() {
for input in [
format!("HEROKU_APP_ID={LEGACY_UUID}\n"),
format!("heroku_app_id: {LEGACY_UUID}"),
format!("HEROKU_RELEASE_ID = \"{LEGACY_UUID}\""),
format!("heroku-app-uuid={LEGACY_UUID}"),
format!("heroku.app.id={LEGACY_UUID}"),
format!("{{\"herokuAppId\": \"{LEGACY_UUID}\"}}"),
format!("{{\"herokuAppID\": \"{LEGACY_UUID}\"}}"),
format!("{{\"id\": \"{LEGACY_UUID}\", \"stack\": \"heroku-24\"}}"),
format!("heroku apps:info --json # UUID: {LEGACY_UUID}"),
] {
assert!(detect_legacy(&input).is_empty(), "{input}");
}
}
#[test]
fn keeps_a_token_assigned_to_a_key_whose_last_word_only_resembles_id() {
for key in [
"HEROKU_PAID",
"herokuPaid",
"HEROKU_IDENTITY_KEY",
"heroku_valid",
] {
let input = format!("{key}={LEGACY_UUID}");
assert_eq!(detect_legacy(&input).len(), 1, "{input}");
}
}
#[test]
fn judges_each_value_by_its_own_key_on_a_shared_line() {
let token = "fedcba98-7654-3210-fedc-ba9876543210";
let input = format!("HEROKU_APP_ID={LEGACY_UUID} HEROKU_API_KEY={token}");
let candidates = detect_legacy(&input);
assert_eq!(candidates.len(), 1);
let start = input.rfind(token).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + token.len()).unwrap()
);
}
#[test]
fn keeps_every_keyword_context_positive_shape() {
for input in [
format!("HEROKU_API_KEY={LEGACY_UUID}"),
format!("heroku_api_key: {LEGACY_UUID}\n"),
format!("heroku {LEGACY_UUID}"),
format!("password {LEGACY_UUID} # api.heroku.com\n"),
format!("secret_key={LEGACY_UUID} # heroku"),
format!("{{\"herokuApiKey\": \"{LEGACY_UUID}\"}}"),
] {
assert_eq!(detect_legacy(&input).len(), 1, "{input}");
}
}
#[test]
fn rejects_a_legacy_token_whose_context_is_on_a_different_line() {
let input = format!("# heroku account token\n{LEGACY_UUID}\n");
assert!(detect_legacy(&input).is_empty());
}
#[test]
fn rejects_a_legacy_body_one_byte_short_or_long() {
assert!(
detect_legacy(&format!("heroku {}", &LEGACY_UUID[..LEGACY_UUID_LEN - 1])).is_empty()
);
assert!(detect_legacy(&format!("heroku {LEGACY_UUID}a")).is_empty());
}
#[test]
fn rejects_a_uuid_with_a_dash_at_the_wrong_offset() {
let malformed = format!(
"{}-{}0",
&LEGACY_UUID[..UUID_DASH_OFFSETS[0] - 1],
&LEGACY_UUID[UUID_DASH_OFFSETS[0] + 1..]
);
assert_eq!(malformed.len(), LEGACY_UUID_LEN);
assert!(detect_legacy(&format!("heroku {malformed}")).is_empty());
}
#[test]
fn rejects_a_non_hex_letter_in_the_uuid_body() {
let mut malformed = LEGACY_UUID.to_string();
malformed.replace_range(0..1, "g");
assert!(detect_legacy(&format!("heroku {malformed}")).is_empty());
}
#[test]
fn matches_heroku_keyword_case_insensitively() {
for keyword in ["Heroku", "HEROKU", "heroku"] {
let input = format!("{keyword}_API_KEY={LEGACY_UUID}");
assert_eq!(detect_legacy(&input).len(), 1, "{keyword}");
}
}
#[test]
fn finds_a_qualified_legacy_match_across_crlf_and_a_unicode_prefix() {
let input = format!("# \u{1F511} caf\u{e9}\r\nheroku {LEGACY_UUID}\r\n");
let candidates = detect_legacy(&input);
assert_eq!(candidates.len(), 1);
let start = input.rfind(LEGACY_UUID).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + LEGACY_UUID.len()).unwrap()
);
}
#[test]
fn finds_deterministic_legacy_findings_across_repeated_calls() {
let input = format!("heroku {LEGACY_UUID}");
assert_eq!(detect_legacy(&input), detect_legacy(&input));
}
fn legacy_ranges(input: &str) -> Vec<(usize, usize)> {
detect_legacy(input)
.iter()
.map(|candidate| (candidate.range().start(), candidate.range().end()))
.collect()
}
#[test]
fn detects_the_password_of_a_multi_line_heroku_netrc_entry() {
let input = format!(
"machine api.heroku.com\n login someone@example.invalid\n password {LEGACY_UUID}\n"
);
assert_eq!(legacy_ranges(&input), [(66, 102)]);
for input in [
format!("machine git.heroku.com\npassword {LEGACY_UUID}\n"),
format!(
"machine api.heroku.com\r\n\tlogin a@example.invalid\r\n\tpassword {LEGACY_UUID}\r\n"
),
format!(
"machine api.heroku.com\n login a@example.invalid\n account x\n password {LEGACY_UUID}\n"
),
format!("machine api.heroku.com\n login a@example.invalid password {LEGACY_UUID}\n"),
] {
let found = detect_legacy(&input);
assert_eq!(found.len(), 1, "{input:?}");
assert_eq!(found[0].confidence(), Confidence::High, "{input:?}");
}
}
#[test]
fn rejects_a_netrc_password_outside_a_heroku_entry() {
for input in [
format!("machine example.com\n login a@example.invalid\n password {LEGACY_UUID}\n"),
format!(
"machine api.heroku.com\n login a\nmachine example.com\n password {LEGACY_UUID}\n"
),
format!("machine api.heroku.com password x\n password {LEGACY_UUID}\n"),
format!(
"machine api.heroku.com\n login a\n account b\n login c\n password {LEGACY_UUID}\n"
),
format!("machine api.heroku.com\n# note\n password {LEGACY_UUID}\n"),
format!("machine api.heroku.com\n login {LEGACY_UUID}\n"),
format!("machine api.heroku.com\n mypassword {LEGACY_UUID}\n"),
] {
assert!(detect_legacy(&input).is_empty(), "{input:?}");
}
}
#[test]
fn detects_heroku_auth_token_output_on_the_next_line() {
let input = format!("$ heroku auth:token\n{LEGACY_UUID}\n");
assert_eq!(legacy_ranges(&input), [(20, 56)]);
for input in [
format!("heroku auth:token\r\n{LEGACY_UUID}\r\n"),
format!("user@host:~$ heroku auth:token\n {LEGACY_UUID}"),
] {
let found = detect_legacy(&input);
assert_eq!(found.len(), 1, "{input:?}");
assert_eq!(found[0].confidence(), Confidence::High, "{input:?}");
}
}
#[test]
fn rejects_a_uuid_line_after_anything_but_the_auth_token_command() {
for input in [
format!("$ heroku apps:info\n{LEGACY_UUID}\n"),
format!("$ heroku auth:token --help\n{LEGACY_UUID}\n"),
format!("$ heroku auth:token\n\n{LEGACY_UUID}\n"),
format!("$ heroku auth:token\nid: {LEGACY_UUID}\n"),
format!("deploy notes\n{LEGACY_UUID}\n"),
] {
assert!(detect_legacy(&input).is_empty(), "{input:?}");
}
}
#[test]
fn rejects_a_uuid_in_a_heroku_api_url_path() {
for input in [
format!("GET https://api.heroku.com/apps/{LEGACY_UUID}/dynos\n"),
format!("curl https://api.heroku.com/apps/{LEGACY_UUID}"),
format!("heroku url: /releases/{LEGACY_UUID}?x=1"),
] {
assert!(detect_legacy(&input).is_empty(), "{input:?}");
}
assert_eq!(
legacy_ranges(&format!(
"GET https://api.heroku.com/apps/{LEGACY_UUID}/dynos\n"
)),
[]
);
let input = format!("curl -u :{LEGACY_UUID} https://api.heroku.com/apps");
assert_eq!(detect_legacy(&input).len(), 1);
}
fn authorizations_table(token_row: &str) -> String {
format!(
"$ heroku authorizations:info $AUTH_ID\nClient: <none>\nID: \
{LEGACY_UUID}\nDescription: ci deploy\nScope: global\n{token_row}\n\
Updated at: 2026-09-02T10:14:31Z\n"
)
}
#[test]
fn detects_the_token_row_of_a_heroku_authorizations_table() {
let value = "0123abcd-89ab-cdef-0123-456789abcdef";
for row in [format!("Token: {value}"), format!("token: {value} ")] {
let input = authorizations_table(&row);
let found = detect_legacy(&input);
assert_eq!(found.len(), 1, "{input:?}");
let range = found[0].range();
assert_eq!(&input[range.start()..range.end()], value);
assert_eq!(found[0].confidence(), Confidence::High);
}
let crlf = authorizations_table(&format!("Token: {value}")).replace('\n', "\r\n");
assert_eq!(detect_legacy(&crlf).len(), 1);
for command in [
"heroku authorizations:create -d ci",
"user@host:~$ heroku authorizations:rotate $ID",
] {
let input = format!("{command}\nScope: global\nToken: {value}\n");
assert_eq!(detect_legacy(&input).len(), 1, "{input:?}");
}
}
#[test]
fn rejects_a_uuid_outside_the_token_row_or_the_table_window() {
let value = "0123abcd-89ab-cdef-0123-456789abcdef";
for input in [
authorizations_table(&format!("Client ID: {value}")),
format!("Scope: global\nToken: {value}\n"),
format!("$ heroku apps:info\nScope: global\nToken: {value}\n"),
format!("$ heroku authorizations:info $ID\n\nToken: {value}\n"),
format!("$ heroku authorizations:info $ID\nToken: {value} (expired)\n"),
format!(
"$ heroku authorizations:info $ID\n{}Token: {value}\n",
"Scope: global\n".repeat(AUTHORIZATIONS_MAX_ROWS + 1)
),
] {
assert!(detect_legacy(&input).is_empty(), "{input:?}");
}
let input = format!(
"$ heroku authorizations:info $ID\n{}Token: {value}\n",
"Scope: global\n".repeat(AUTHORIZATIONS_MAX_ROWS)
);
assert_eq!(detect_legacy(&input).len(), 1);
}
#[test]
fn the_retention_hint_holds_exactly_the_multi_line_layouts_open() {
for open in [
"$ heroku authorizations:info $ID\n",
"$ heroku authorizations:info $ID\nClient: <none>\nScope: global\n",
"machine api.heroku.com\n",
"machine api.heroku.com\n login a@example.invalid\n",
"machine api.heroku.com\n login a\n account b\n",
"x\nmachine api.heroku.com\r\n",
"$ heroku auth:token\n",
] {
assert!(has_open_heroku_legacy_context(open), "{open:?}");
}
for closed in [
"",
"machine example.com\n",
"machine api.heroku.com password x\n",
"machine api.heroku.com\n login a\n account b\n login c\n",
"machine api.heroku.com\n password x\n",
"$ heroku auth:token\nx\n",
"heroku apps\n",
"$ heroku authorizations:info $ID\nfree text\n",
"$ heroku authorizations:info $ID\n\n",
"heroku authorizations\n",
] {
assert!(!has_open_heroku_legacy_context(closed), "{closed:?}");
}
}
#[test]
fn stays_bounded_over_a_long_context_free_line_packed_with_candidates() {
let input = format!("{LEGACY_UUID} ").repeat(10_000);
assert_eq!(detect_legacy(&input).len(), 0);
}
#[test]
fn rejects_an_all_one_digit_uuid_placeholder_under_heroku_context() {
for filler in [
"00000000-0000-0000-0000-000000000000",
"ffffffff-ffff-ffff-ffff-ffffffffffff",
] {
assert!(detect_legacy(&format!("HEROKU_API_KEY={filler}")).is_empty());
}
let near = "00000000-0000-0000-0000-000000000001";
assert_eq!(detect_legacy(&format!("HEROKU_API_KEY={near}")).len(), 1);
}
fn oracle_auth_token_command(line: &str) -> bool {
let words: Vec<&str> = tokens(line).collect();
words.ends_with(&["heroku", "auth:token"])
}
fn oracle_authorizations_command(line: &str) -> bool {
let words: Vec<&str> = tokens(line).collect();
words.windows(2).any(|pair| {
pair[0] == "heroku"
&& pair[1]
.strip_prefix("authorizations:")
.is_some_and(|verb| !verb.is_empty())
})
}
fn oracle_cli_table_label(line: &str) -> Option<&str> {
let (label, rest) = line.split_once(':')?;
let words: Vec<&str> = label.split(' ').collect();
let well_formed = !label.is_empty()
&& label.len() <= 24
&& words.len() <= 3
&& words.iter().all(|word| {
!word.is_empty() && word.bytes().all(|byte| byte.is_ascii_alphabetic())
});
(well_formed && rest.bytes().next().is_none_or(is_token_space)).then_some(label)
}
#[test]
fn command_and_label_judgments_match_the_collecting_oracles() {
const PARTS: &[&str] = &[
"heroku",
"auth:token",
"authorizations:",
"authorizations:info",
"authorizations:create",
"$",
"Client",
"Updated at",
"Token",
"Description",
"a",
"\u{e9}",
"1",
":",
" ",
" ",
"\t",
"\r",
"",
];
let mut state = 0x2545_F491_4F6C_DD1Du64;
let mut next = move |bound: usize| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
usize::try_from(state % u64::try_from(bound).unwrap()).unwrap()
};
for _ in 0..30_000 {
let mut line = String::new();
for _ in 0..next(9) {
line.push_str(PARTS[next(PARTS.len())]);
if next(3) > 0 {
line.push(' ');
}
}
assert_eq!(
is_heroku_auth_token_command(&line),
oracle_auth_token_command(&line),
"{line:?}"
);
assert_eq!(
is_heroku_authorizations_command(&line),
oracle_authorizations_command(&line),
"{line:?}"
);
assert_eq!(
cli_table_label(&line),
oracle_cli_table_label(&line),
"{line:?}"
);
}
}
}