use super::text::lines;
use crate::detectors::pattern::{self, Alphabet};
use crate::detectors::text;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const TOKEN_LEN: usize = 22;
const CONTEXT_KEYWORD: &str = "travis";
const BOUNDARY: Alphabet = pattern::is_alnum_dash;
fn is_boundary_byte(byte: u8) -> bool {
BOUNDARY(byte) || byte == b'_'
}
fn line_has_context_keyword(line: &str) -> bool {
text::contains_ci(line, CONTEXT_KEYWORD)
}
fn mixes_letters_and_digits(run: &[u8]) -> bool {
run.iter().any(u8::is_ascii_alphabetic) && run.iter().any(u8::is_ascii_digit)
}
pub(super) struct TravisCiApiTokenDetector;
impl Detector for TravisCiApiTokenDetector {
fn id(&self) -> &'static str {
"travisci-api-token"
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
let mut candidates = Vec::new();
for (line_start, line_end) in lines(input) {
let line = &input[line_start..line_end];
if !line_has_context_keyword(line) {
continue;
}
let bytes = line.as_bytes();
let mut start = 0usize;
while start < bytes.len() {
if !pattern::is_alnum(bytes[start]) {
start += 1;
continue;
}
let end = pattern::run_end(bytes, start, pattern::is_alnum);
let run = &bytes[start..end];
if end - start == TOKEN_LEN
&& pattern::boundary_ok(bytes, start, end, is_boundary_byte)
&& mixes_letters_and_digits(run)
&& !text::is_repeated_character_filler(&line[start..end])
&& !text::is_non_credential_assignment(line, start)
&& let Some(range) = ByteRange::new(line_start + start, line_start + end)
{
let (confidence, signal) =
if text::is_provider_named_assignment(line, start, &[CONTEXT_KEYWORD]) {
(Confidence::High, "travisci-named-assignment")
} else {
(Confidence::Medium, "travisci-keyword-cooccurrence")
};
candidates.push(
Candidate::built_in("travisci_api_token", confidence, range)
.with_specificity(Specificity::Provider)
.with_signals([signal, "tool-corroborated-length"]),
);
}
start = end;
}
}
Ok(candidates)
}
}
#[cfg(test)]
mod tests {
use super::*;
const TOKEN: &str = "Syn7hRevok3dTrvCi0Tok1";
const _: () = assert!(TOKEN.len() == TOKEN_LEN);
fn token() -> &'static str {
TOKEN
}
fn detect(input: &str) -> Vec<Candidate> {
TravisCiApiTokenDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
fn assert_single(input: &str, confidence: Confidence) {
let candidates = detect(input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(candidates[0].type_name(), "travisci_api_token");
assert_eq!(candidates[0].confidence(), confidence, "{input}");
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
let start = input.find(token()).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + TOKEN_LEN).unwrap(),
"{input}"
);
}
#[test]
fn a_travis_named_assignment_is_high_confidence() {
for input in [
format!("TRAVIS_TOKEN={}", token()),
format!("export TRAVIS_API_TOKEN=\"{}\"", token()),
format!("travis.api_token: {}", token()),
format!("{{\"travisApiToken\": \"{}\"}}", token()),
format!("travis_ci_token: '{}'", token()),
] {
assert_single(&input, Confidence::High);
}
}
#[test]
fn a_high_signal_key_on_a_travis_line_is_high_confidence() {
assert_single(
&format!("travis = TravisClient(api_key=\"{}\")", token()),
Confidence::High,
);
}
#[test]
fn a_travis_keyword_elsewhere_on_the_line_is_medium_confidence() {
for input in [
format!(
"curl -H \"Authorization: token {}\" https://api.travis-ci.com/user",
token()
),
format!("# Travis CI API token {}", token()),
format!("travis login --api-token {}", token()),
] {
assert_single(&input, Confidence::Medium);
}
}
#[test]
fn a_token_without_a_travis_keyword_on_its_line_is_not_reported() {
assert!(detect(token()).is_empty());
assert!(detect(&format!("TOKEN={}", token())).is_empty());
assert!(detect(&format!("# travis\nTOKEN={}", token())).is_empty());
}
#[test]
fn a_run_of_the_wrong_length_is_not_truncated_or_extended() {
let short = &token()[..TOKEN_LEN - 1];
let long = format!("{}9", token());
assert!(detect(&format!("TRAVIS_TOKEN={short}")).is_empty());
assert!(detect(&format!("TRAVIS_TOKEN={long}")).is_empty());
}
#[test]
fn a_run_inside_a_wider_identifier_is_not_reported() {
for input in [
format!("TRAVIS_TOKEN=x_{}", token()),
format!("TRAVIS_TOKEN={}_x", token()),
format!("TRAVIS_TOKEN=x-{}", token()),
format!("TRAVIS_TOKEN={}-x", token()),
] {
assert!(detect(&input).is_empty(), "{input}");
}
}
#[test]
fn letter_only_digit_only_and_filler_runs_are_not_reported() {
for value in [
"TravisContinuousIntegr",
"1234567890123456789012",
"aaaaaaaaaaaaaaaaaaaaaa",
"xxxxxxxxxxxxxxxxxxxxxx",
] {
assert_eq!(value.len(), TOKEN_LEN);
assert!(
detect(&format!("TRAVIS_TOKEN={value}")).is_empty(),
"{value}"
);
}
}
#[test]
fn identifier_keys_on_a_travis_line_are_not_reported() {
for key in [
"TRAVIS_REPO_SLUG",
"TRAVIS_BUILD_ID",
"travis_job_number",
"travisUrl",
] {
let input = format!("{key}={}", token());
assert!(detect(&input).is_empty(), "{input}");
}
}
#[test]
fn finds_a_token_across_crlf_and_a_unicode_prefix() {
let input = format!("# \u{1F511} caf\u{e9}\r\nTRAVIS_TOKEN={}\r\n", token());
let candidates = detect(&input);
assert_eq!(candidates.len(), 1);
let start = input.find(token()).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + TOKEN_LEN).unwrap()
);
}
#[test]
fn findings_are_deterministic_across_repeated_calls() {
let input = format!("TRAVIS_TOKEN={}", token());
assert_eq!(detect(&input), detect(&input));
}
}