use super::text::lines;
use crate::detectors::pattern::{self, Alphabet};
use crate::detectors::prefilter::Literals;
use crate::detectors::text;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const TOKEN_PREFIX: &str = "00";
const BODY_LEN: usize = 40;
const SSWS_SCHEME: &str = "SSWS";
const CONTEXT_KEYWORD: &str = "okta";
fn is_body_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-'
}
const BOUNDARY: Alphabet = is_body_byte;
fn line_has_context_keyword(line: &str) -> bool {
text::contains_ci(line, CONTEXT_KEYWORD)
}
fn ssws_scheme_immediately_precedes(line: &str, start: usize) -> bool {
let bytes = line.as_bytes();
let mut pos = start;
while pos > 0 && matches!(bytes[pos - 1], b' ' | b'\t') {
pos -= 1;
}
if pos == start || pos < SSWS_SCHEME.len() {
return false;
}
let scheme_start = pos - SSWS_SCHEME.len();
text::starts_with_ci(line, scheme_start, SSWS_SCHEME)
&& (scheme_start == 0 || !is_body_byte(bytes[scheme_start - 1]))
}
pub(super) struct OktaApiTokenDetector;
impl Detector for OktaApiTokenDetector {
fn id(&self) -> &'static str {
"okta-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];
let has_keyword = line_has_context_keyword(line);
let bytes = line.as_bytes();
let literal = TOKEN_PREFIX.as_bytes();
let mut ends = pattern::RunCursor::new(bytes, is_body_byte);
let mut pos = 0usize;
while pos + literal.len() <= bytes.len() {
if &bytes[pos..pos + literal.len()] != literal {
pos += 1;
continue;
}
let body_start = pos + literal.len();
let body_end = ends.end(body_start);
let shape_ok = body_end - body_start == BODY_LEN
&& pattern::boundary_ok(bytes, pos, body_end, BOUNDARY)
&& !text::is_repeated_character_filler(&line[body_start..body_end]);
let gate = if !shape_ok {
None
} else if ssws_scheme_immediately_precedes(line, pos) {
Some((Confidence::High, "ssws-scheme-adjacency"))
} else if has_keyword
&& text::is_provider_named_assignment(line, pos, &[CONTEXT_KEYWORD])
{
Some((Confidence::High, "okta-named-assignment"))
} else if has_keyword {
Some((Confidence::Medium, "okta-keyword-cooccurrence"))
} else {
None
};
if let Some((confidence, signal)) = gate
&& let Some(range) = ByteRange::new(line_start + pos, line_start + body_end)
{
candidates.push(
Candidate::built_in("okta_api_token", confidence, range)
.with_specificity(Specificity::Provider)
.with_signals([signal]),
);
}
pos += literal.len();
}
}
Ok(candidates)
}
}
pub(super) const REQUIRED_LITERALS: &[Literals] = &[Literals::Strs(&[TOKEN_PREFIX])];
#[cfg(test)]
mod tests {
use super::*;
const BODY: &str = "SYNTHETICREVOKEDTOKENA0123456789abcdefgh";
const DASH_UNDERSCORE_BODY: &str = "SYNTHETIC-REVOKED_TOKEN-0123456789abcdef";
const _: () = assert!(BODY.len() == BODY_LEN);
const _: () = assert!(DASH_UNDERSCORE_BODY.len() == BODY_LEN);
fn token() -> String {
format!("{TOKEN_PREFIX}{BODY}")
}
fn detect(input: &str) -> Vec<Candidate> {
OktaApiTokenDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
#[test]
fn detects_the_token_alongside_an_ssws_scheme_at_high_confidence() {
for input in [
format!("Authorization: SSWS {}", token()),
format!("authorization: ssws {}", token()),
format!("Authorization:SSWS {}", token()),
format!("Authorization: Ssws\t{}", token()),
] {
let candidates = detect(&input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(candidates[0].type_name(), "okta_api_token");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
let start = input.rfind(&token()).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + token().len()).unwrap()
);
}
}
#[test]
fn detects_the_token_named_by_an_okta_keyword() {
for input in [
format!("OKTA_API_TOKEN={}", token()),
format!("okta.api_token: {}", token()),
format!("# Okta management API token: {}", token()),
format!("{{\"oktaApiToken\": \"{}\"}}", token()),
format!("okta_api_token: {}", token()),
] {
let candidates = detect(&input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(candidates[0].type_name(), "okta_api_token");
let expected = if input.starts_with('#') {
Confidence::Medium
} else {
Confidence::High
};
assert_eq!(candidates[0].confidence(), expected, "{input}");
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
}
}
#[test]
fn accepts_a_body_containing_dashes_and_underscores() {
let value = format!("{TOKEN_PREFIX}{DASH_UNDERSCORE_BODY}");
let input = format!("okta {value}");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::Medium);
}
#[test]
fn rejects_a_bare_value_with_no_context() {
assert!(detect(&token()).is_empty());
}
#[test]
fn rejects_context_on_a_different_line() {
let input = format!("# okta\n{}\n", token());
assert!(detect(&input).is_empty());
}
#[test]
fn rejects_an_ssws_scheme_glued_to_the_token_with_no_separating_space() {
assert!(detect(&format!("okta SSWS{}", token())).is_empty());
}
#[test]
fn matches_the_keyword_and_scheme_case_insensitively() {
assert_eq!(detect(&format!("OKTA {}", token())).len(), 1);
assert_eq!(detect(&format!("ssws {}", token())).len(), 1);
}
#[test]
fn rejects_a_body_one_byte_short_of_the_required_length() {
let short = &BODY[..BODY_LEN - 1];
assert!(detect(&format!("okta {TOKEN_PREFIX}{short}")).is_empty());
}
#[test]
fn rejects_a_body_one_byte_longer_than_the_required_length_rather_than_truncating() {
let long = format!("{BODY}0");
assert!(detect(&format!("okta {TOKEN_PREFIX}{long}")).is_empty());
}
#[test]
fn rejects_a_wrong_prefix() {
assert!(detect(&format!("okta 01{BODY}")).is_empty());
}
#[test]
fn rejects_a_masked_repeated_character_body() {
assert!(detect(&format!("okta {TOKEN_PREFIX}{}", "a".repeat(BODY_LEN))).is_empty());
}
#[test]
fn rejects_an_environment_variable_reference() {
assert!(detect("okta OKTA_API_TOKEN=${OKTA_API_TOKEN}").is_empty());
}
#[test]
fn rejects_a_tenant_domain() {
assert!(detect("okta https://dev-12345.okta.com/oauth2/default").is_empty());
}
#[test]
fn rejects_a_shorter_id_shaped_value_even_with_ssws_context() {
assert!(detect("Authorization: SSWS 00u1a2B3c4D5e6F7g8H9").is_empty());
}
#[test]
fn rejects_a_token_embedded_in_a_wider_identifier() {
let value = token();
assert!(detect(&format!("okta x{value}")).is_empty());
assert!(detect(&format!("okta {value}x")).is_empty());
}
#[test]
fn does_not_span_a_dot_delimited_jwt_even_with_context() {
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.\
eyJzdWIiOiIxMjM0NTY3ODkwIn0.\
dGhpc2lzYXNpZ25hdHVyZQ";
assert!(detect(&format!("Authorization: SSWS {jwt}")).is_empty());
}
#[test]
fn finds_a_match_across_crlf_and_a_unicode_prefix() {
let input = format!("# \u{1F511} caf\u{e9}\r\nokta {}\r\n", token());
let candidates = detect(&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 finds_deterministic_findings_across_repeated_calls() {
let input = format!("okta {}", token());
assert_eq!(detect(&input), detect(&input));
}
#[test]
fn every_candidate_on_a_context_bearing_line_is_reported() {
let input = format!("okta {} {}", token(), token());
let candidates = detect(&input);
assert_eq!(candidates.len(), 2);
assert!(
candidates
.iter()
.all(|candidate| candidate.confidence() == Confidence::Medium)
);
}
#[test]
fn stays_bounded_over_a_long_context_free_line_packed_with_candidates() {
let input = format!("{} ", token()).repeat(10_000);
assert_eq!(detect(&input).len(), 0);
}
}