use crate::detectors::pattern::{self, is_alnum};
use crate::detectors::prefilter::Literals;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const PREFIX_LEN: usize = 14;
const MARKER: &[u8] = b".atlasv1.";
const SUFFIX_LEN: usize = 67;
pub(super) struct TerraformCloudTokenDetector;
impl Detector for TerraformCloudTokenDetector {
fn id(&self) -> &'static str {
"terraform-cloud-token"
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
let bytes = input.as_bytes();
let Some(first) = find_marker(bytes, 0) else {
return Ok(Vec::new());
};
let mut alnum_ends = pattern::RunCursor::new(bytes, is_alnum);
let mut candidates = Vec::new();
let mut cursor = first;
while cursor < bytes.len() {
let Some(marker_start) = find_marker(bytes, cursor) else {
break;
};
if let Some(range) = match_at(bytes, &mut alnum_ends, marker_start) {
candidates.push(
Candidate::built_in("terraform_cloud_token", Confidence::High, range)
.with_specificity(Specificity::Provider)
.with_signal_pack(crate::types::signal_pack!(
"terraform-atlasv1-marker",
"documented-exact-length"
)),
);
cursor = range.end();
continue;
}
cursor = marker_start + 1;
}
Ok(candidates)
}
}
fn find_marker(bytes: &[u8], from: usize) -> Option<usize> {
if from > bytes.len() {
return None;
}
bytes[from..]
.windows(MARKER.len())
.position(|window| window == MARKER)
.map(|offset| from + offset)
}
fn match_at(
bytes: &[u8],
alnum_ends: &mut pattern::RunCursor<'_>,
marker_start: usize,
) -> Option<ByteRange> {
if marker_start < PREFIX_LEN {
return None;
}
let prefix_start = marker_start - PREFIX_LEN;
if !bytes[prefix_start..marker_start]
.iter()
.all(|&b| is_alnum(b))
{
return None;
}
if prefix_start > 0 && is_alnum(bytes[prefix_start - 1]) {
return None;
}
let suffix_start = marker_start + MARKER.len();
if alnum_ends.end(suffix_start) < suffix_start + SUFFIX_LEN {
return None;
}
let end = suffix_start + SUFFIX_LEN;
if end < bytes.len() && is_alnum(bytes[end]) {
return None;
}
ByteRange::new(prefix_start, end)
}
pub(super) const REQUIRED_LITERALS: &[Literals] = &[Literals::Bytes(&[MARKER])];
#[cfg(test)]
mod tests {
use super::*;
const PREFIX: &str = "SYNREV0REVOKED";
const SUFFIX: &str =
"SYNTHETICREVOKEDTERRAFORMCLOUDTOKENFIXTUREPADDING0123456789ABCDEFGHIJKLMNOPQR";
fn token() -> String {
format!("{PREFIX}.atlasv1.{}", &SUFFIX[..SUFFIX_LEN])
}
fn detect(input: &str) -> Vec<Candidate> {
TerraformCloudTokenDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
#[test]
fn fixture_segments_are_exactly_documented_length() {
assert_eq!(PREFIX.len(), PREFIX_LEN);
assert_eq!(SUFFIX[..SUFFIX_LEN].len(), SUFFIX_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(), "terraform_cloud_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_in_a_cli_credentials_block_dotenv_and_json() {
let value = token();
for input in [
value.clone(),
format!("TF_TOKEN_app_terraform_io={value}"),
format!("credentials \"app.terraform.io\" {{\n token = \"{value}\"\n}}"),
format!("{{\"credentials\": {{\"app.terraform.io\": {{\"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_prefix_segment() {
let short_prefix = &PREFIX[1..];
assert!(detect(&format!("{short_prefix}.atlasv1.{}", &SUFFIX[..SUFFIX_LEN])).is_empty());
}
#[test]
fn rejects_a_truncated_suffix_segment() {
let short_suffix = &SUFFIX[..SUFFIX_LEN - 1];
assert!(detect(&format!("{PREFIX}.atlasv1.{short_suffix}")).is_empty());
}
#[test]
fn rejects_a_prefix_segment_longer_than_documented() {
assert!(detect(&format!("X{PREFIX}.atlasv1.{}", &SUFFIX[..SUFFIX_LEN])).is_empty());
}
#[test]
fn rejects_a_suffix_segment_longer_than_documented() {
assert!(detect(&format!("{PREFIX}.atlasv1.{}", &SUFFIX[..=SUFFIX_LEN])).is_empty());
}
#[test]
fn rejects_a_malformed_marker() {
assert!(detect(&format!("{PREFIX}.atlasv2.{}", &SUFFIX[..SUFFIX_LEN])).is_empty());
assert!(detect(&format!("{PREFIX}atlasv1.{}", &SUFFIX[..SUFFIX_LEN])).is_empty());
assert!(detect(&format!("{PREFIX}.ATLASV1.{}", &SUFFIX[..SUFFIX_LEN])).is_empty());
}
#[test]
fn rejects_the_marker_alone() {
assert!(detect(".atlasv1.").is_empty());
assert!(detect(&format!("{PREFIX}.atlasv1.")).is_empty());
assert!(detect(".atlasv1.SYNTHETIC").is_empty());
}
#[test]
fn rejects_the_prefix_or_suffix_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_suffix = "*".repeat(SUFFIX_LEN);
assert!(detect(&format!("{PREFIX}.atlasv1.{masked_suffix}")).is_empty());
}
#[test]
fn rejects_an_environment_variable_reference() {
assert!(detect("${TF_TOKEN_app_terraform_io}").is_empty());
}
#[test]
fn rejects_the_official_documentation_placeholder() {
assert!(detect("xxxxxx.atlasv1.zzzzzzzzzzzzz").is_empty());
}
#[test]
fn accepts_a_doc_style_placeholder_built_from_valid_alphabet_characters() {
let input = format!(
"{}.atlasv1.{}",
"x".repeat(PREFIX_LEN),
"x".repeat(SUFFIX_LEN)
);
assert_eq!(detect(&input).len(), 1);
}
#[test]
fn a_trailing_comma_does_not_get_folded_into_or_suppress_the_match() {
let value = token();
let input = format!("Rotate {value}, then redeploy.");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1);
let start = "Rotate ".len();
let end = start + value.len();
assert_eq!(candidates[0].range(), ByteRange::new(start, end).unwrap());
}
#[test]
fn rejects_ordinary_terraform_configuration_and_workspace_identifiers() {
let input = concat!(
"terraform {\n",
" required_version = \">= 1.5.0\"\n",
" required_providers {\n",
" aws = {\n",
" source = \"hashicorp/aws\"\n",
" version = \"~> 5.0\"\n",
" }\n",
" }\n",
"}\n",
"# workspace ws-SYNTHETICREVOKEDWORKSPACEID, org-SYNTHETICREVOKEDORGID\n",
);
assert_eq!(detect(input).len(), 0);
}
#[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 reports_a_repeated_identical_value_once_per_occurrence() {
let value = token();
let input = format!("{value} {value}");
assert_eq!(detect(&input).len(), 2);
}
#[test]
fn stays_bounded_over_a_long_run_of_near_miss_markers() {
let short_suffix = &SUFFIX[..SUFFIX_LEN - 1];
let input = format!("{PREFIX}.atlasv1.{short_suffix} ").repeat(2_000);
assert_eq!(detect(&input).len(), 0);
}
}