use crate::detectors::pattern::{RunCursor, is_alnum_dash};
use crate::detectors::prefilter::Literals;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const MIN_ID_LEN: usize = 5;
const MIN_SECRET_LEN: usize = 34;
const URL_PATH_PREFIX: &[u8] = b"/bot";
const ID_SEPARATOR_PAIRS: [&str; 10] = ["0:", "1:", "2:", "3:", "4:", "5:", "6:", "7:", "8:", "9:"];
fn is_ascii_digit(byte: u8) -> bool {
byte.is_ascii_digit()
}
pub(super) struct TelegramBotTokenDetector;
impl Detector for TelegramBotTokenDetector {
fn id(&self) -> &'static str {
"telegram-bot-token"
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
let bytes = input.as_bytes();
let mut digit_ends = RunCursor::new(bytes, is_ascii_digit);
let mut secret_ends = RunCursor::new(bytes, is_alnum_dash);
let mut candidates = Vec::new();
let mut start = 0usize;
while start < bytes.len() {
let is_digit_run_start =
bytes[start].is_ascii_digit() && (start == 0 || !bytes[start - 1].is_ascii_digit());
if !is_digit_run_start {
start += 1;
continue;
}
let Some(end) = match_at(bytes, &mut digit_ends, &mut secret_ends, start) else {
start += 1;
continue;
};
if boundary_ok(bytes, start, end)
&& let Some(range) = ByteRange::new(start, end)
{
candidates.push(
Candidate::built_in("telegram_bot_token", Confidence::High, range)
.with_specificity(Specificity::Provider)
.with_signal_pack(crate::types::signal_pack!(
"telegram-documented-id-colon-secret-shape"
)),
);
}
start = end.max(start + 1);
}
Ok(candidates)
}
}
fn match_at(
bytes: &[u8],
digit_ends: &mut RunCursor<'_>,
secret_ends: &mut RunCursor<'_>,
start: usize,
) -> Option<usize> {
let id_end = digit_ends.end(start);
if id_end - start < MIN_ID_LEN {
return None;
}
if bytes.get(id_end) != Some(&b':') {
return None;
}
let secret_start = id_end + 1;
let secret_end = secret_ends.end(secret_start);
if secret_end - secret_start < MIN_SECRET_LEN {
return None;
}
if is_canonical_uuid(&bytes[secret_start..secret_end]) {
return None;
}
Some(secret_end)
}
const UUID_HYPHENS: [usize; 4] = [8, 13, 18, 23];
const UUID_LEN: usize = 36;
fn is_canonical_uuid(segment: &[u8]) -> bool {
segment.len() == UUID_LEN
&& segment.iter().enumerate().all(|(index, &byte)| {
if UUID_HYPHENS.contains(&index) {
byte == b'-'
} else {
byte.is_ascii_hexdigit()
}
})
}
fn boundary_ok(bytes: &[u8], start: usize, end: usize) -> bool {
let start_ok =
start == 0 || !is_alnum_dash(bytes[start - 1]) || bytes[..start].ends_with(URL_PATH_PREFIX);
let end_ok = end >= bytes.len() || !is_alnum_dash(bytes[end]);
start_ok && end_ok
}
pub(super) const REQUIRED_LITERALS: &[Literals] = &[Literals::Strs(&ID_SEPARATOR_PAIRS)];
#[cfg(test)]
mod tests {
use super::*;
const ID: &str = "123456";
const SECRET: &str = "ABC-DEF1234ghIkl-zyx57W2v1u123ew11";
fn token() -> String {
format!("{ID}:{SECRET}")
}
fn detect(input: &str) -> Vec<Candidate> {
TelegramBotTokenDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
#[test]
fn documented_example_segments_match_their_own_minimums() {
assert_eq!(ID.len(), MIN_ID_LEN + 1);
assert_eq!(SECRET.len(), MIN_SECRET_LEN);
}
#[test]
fn detects_the_documented_example_bare() {
let value = token();
let candidates = detect(&value);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "telegram_bot_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!("TELEGRAM_BOT_TOKEN={value}"),
format!("bot_token={value}"),
format!("{{\"botToken\": \"{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 detects_the_token_embedded_in_the_documented_bot_api_url_and_selects_only_the_token() {
let value = token();
let input = format!("https://api.telegram.org/bot{value}/getMe");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1);
let (start, end) = (candidates[0].range().start(), candidates[0].range().end());
assert_eq!(&input[start..end], value);
assert_eq!(&input[..start], "https://api.telegram.org/bot");
}
#[test]
fn detects_an_id_shorter_than_the_documented_example_at_the_minimum() {
let short_id = &ID[1..];
assert_eq!(short_id.len(), MIN_ID_LEN);
let value = format!("{short_id}:{SECRET}");
let candidates = detect(&value);
assert_eq!(candidates.len(), 1);
assert_eq!(
candidates[0].range(),
ByteRange::new(0, value.len()).unwrap()
);
}
#[test]
fn detects_a_secret_longer_than_the_documented_example() {
let input = format!("{ID}:{SECRET}EXTRA-TAIL-BYTES-PAST-THE-MINIMUM");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(
candidates[0].range(),
ByteRange::new(0, input.len()).unwrap()
);
}
#[test]
fn rejects_an_id_one_byte_below_the_minimum() {
let too_short = &ID[2..];
assert_eq!(too_short.len(), MIN_ID_LEN - 1);
assert!(detect(&format!("{too_short}:{SECRET}")).is_empty());
}
#[test]
fn rejects_a_secret_one_byte_below_the_minimum() {
let short_secret = &SECRET[..SECRET.len() - 1];
assert!(detect(&format!("{ID}:{short_secret}")).is_empty());
}
#[test]
fn rejects_a_missing_separator() {
assert!(detect(&format!("{ID}-{SECRET}")).is_empty());
assert!(detect(&format!("{ID}{SECRET}")).is_empty());
}
#[test]
fn rejects_a_secret_broken_by_an_out_of_alphabet_byte_before_the_minimum() {
let broken = format!("{} {}", &SECRET[..10], &SECRET[11..]);
assert!(detect(&format!("{ID}:{broken}")).is_empty());
}
#[test]
fn rejects_the_id_embedded_in_a_wider_identifier() {
assert!(detect(&format!("x{}", token())).is_empty());
}
#[test]
fn rejects_an_atlassian_account_id_with_a_uuid_secret_segment() {
for input in [
"557058:0f3c9a4e-7b21-4d8e-9a6c-2e5b8d1f7c30".to_string(),
"{\"accountId\": \"557058:0F3C9A4E-7B21-4D8E-9A6C-2E5B8D1F7C30\"}\n".to_string(),
"assignee=712020:0f3c9a4e-7b21-4d8e-9a6c-2e5b8d1f7c30\r\n".to_string(),
] {
assert!(detect(&input).is_empty(), "{input}");
}
}
#[test]
fn detects_a_secret_that_is_near_but_not_exactly_a_uuid() {
for secret in [
"0f3c9a4e7-b21-4d8e-9a6c-2e5b8d1f7c30",
"0f3c9a4e-7b21-4d8e-9a6c-2e5b8d1f7c3g",
"0f3c9a4e-7b21-4d8e-9a6c-2e5b8d1f7c30ab",
] {
let value = format!("{ID}:{secret}");
let candidates = detect(&value);
assert_eq!(candidates.len(), 1, "{secret}");
assert_eq!(
candidates[0].range(),
ByteRange::new(0, value.len()).unwrap(),
"{secret}"
);
}
}
#[test]
fn rejects_a_bare_numeric_id_with_no_secret() {
assert!(detect("chat_id: 123456789").is_empty());
}
#[test]
fn rejects_a_public_bot_handle() {
assert!(detect("Message @ExampleBot to get started").is_empty());
}
#[test]
fn rejects_a_masked_value() {
assert_eq!(
detect(&format!("{ID}:{}", "*".repeat(MIN_SECRET_LEN))).len(),
0
);
}
#[test]
fn rejects_an_environment_variable_reference() {
assert!(detect(&format!("{ID}:${{TELEGRAM_BOT_TOKEN}}")).is_empty());
}
#[test]
fn rejects_a_malformed_numeric_colon_string() {
assert!(detect("1694812800:0").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 input = token();
assert_eq!(detect(&input), detect(&input));
}
#[test]
fn stays_bounded_over_a_long_run_of_rejected_near_misses() {
let input = format!("{}!{}", token(), "1:x!".repeat(10_000));
let candidates = detect(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(
candidates[0].range(),
ByteRange::new(0, token().len()).unwrap()
);
}
}