use crate::detectors::additional_providers::TypedKnownFormatProviderDetector;
use crate::detectors::pattern::{self, PrefixShape};
const BODY_LEN: usize = 32;
const API_TOKEN: &str = "crates_io_api_token";
const TRUSTED_PUBLISHING_TOKEN: &str = "crates_io_trusted_publishing_token";
const SIGNALS: [&str; 2] = ["crates-io-generator-prefix", "crates-io-generator-length"];
pub(super) const CRATES_IO: TypedKnownFormatProviderDetector =
TypedKnownFormatProviderDetector::new(
"crates-io-token",
&[
PrefixShape::exact("cio_tp_", BODY_LEN, pattern::is_alnum, &SIGNALS),
PrefixShape::exact("cio", BODY_LEN, pattern::is_alnum, &SIGNALS),
],
&[TRUSTED_PUBLISHING_TOKEN, API_TOKEN],
pattern::is_alnum_dash,
);
#[cfg(test)]
mod tests {
use super::*;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const ALNUM: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
fn filler(len: usize, seed: usize) -> String {
(0..len)
.map(|i| char::from(ALNUM[(i * 7 + seed * 13 + i / 5) % ALNUM.len()]))
.collect()
}
fn api_token() -> String {
format!("cio{}", filler(BODY_LEN, 1))
}
fn trusted_publishing_token() -> String {
format!("cio_tp_{}", filler(BODY_LEN, 2))
}
fn detect(input: &str) -> Vec<Candidate> {
CRATES_IO
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
fn assert_single(input: &str, token: &str, type_name: &str) {
let candidates = detect(input);
assert_eq!(candidates.len(), 1, "{input}");
let start = input.find(token).unwrap();
assert_eq!(candidates[0].type_name(), type_name, "{input}");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + token.len()).unwrap(),
"{input}"
);
}
fn contexts(token: &str) -> Vec<String> {
vec![
token.to_owned(),
format!("CARGO_REGISTRY_TOKEN={token}"),
format!("export CARGO_REGISTRY_TOKEN=\"{token}\""),
format!("[registry]\ntoken = \"{token}\"\n"),
format!("cargo publish --token {token}"),
format!("Authorization: {token}"),
format!("{{\"token\": \"{token}\"}}"),
format!("{{\"api_key\": \"{token}\"}}"),
format!("env:\n CARGO_REGISTRY_TOKEN: {token}\n"),
format!("Here is my token {token} can you debug this?"),
format!("The token is {token}."),
]
}
#[test]
fn both_shapes_are_detected_in_every_context() {
let api = api_token();
let trusted = trusted_publishing_token();
assert_eq!(api.len(), 35);
assert_eq!(trusted.len(), 39);
for input in contexts(&api) {
assert_single(&input, &api, API_TOKEN);
}
for input in contexts(&trusted) {
assert_single(&input, &trusted, TRUSTED_PUBLISHING_TOKEN);
}
assert_eq!(CRATES_IO.id(), "crates-io-token");
}
#[test]
fn a_wrong_check_character_is_still_reported() {
for last in ["A", "z", "0", "9"] {
let token = format!("cio_tp_{}{last}", filler(31, 2));
assert_single(&token, &token, TRUSTED_PUBLISHING_TOKEN);
}
}
#[test]
fn near_miss_twins_are_rejected() {
let body = filler(BODY_LEN, 1);
let mut dashed = body.clone();
dashed.replace_range(10..11, "-");
let mut underscored = body.clone();
underscored.replace_range(10..11, "_");
let api = api_token();
let trusted = trusted_publishing_token();
for input in [
format!("cio{}", filler(31, 1)),
format!("cio{}", filler(33, 1)),
format!("cio{dashed}"),
format!("cio{underscored}"),
format!("CIO{body}"),
format!("cio_tp_{}", filler(31, 2)),
format!("cio_tp_{}", filler(33, 2)),
format!("CIO_TP_{body}"),
format!("cio_tp-{body}"),
format!("x{api}"),
format!("_{api}"),
format!("-{api}"),
format!("{api}x"),
format!("{api}_x"),
format!("x{trusted}"),
format!("{trusted}-1"),
] {
assert!(detect(&input).is_empty(), "{input}");
}
}
#[test]
fn benign_cio_text_is_not_claimed() {
for input in [
"the ciound buffer".to_owned(),
"cio_config = load()".to_owned(),
"CARGO_REGISTRY_TOKEN=${{ secrets.CRATES_TOKEN }}".to_owned(),
"cargo publish --token cio...".to_owned(),
format!("hash=cio{}", filler(61, 3)),
format!("{}cio{}", filler(16, 4), filler(BODY_LEN, 4)),
] {
assert!(detect(&input).is_empty(), "{input}");
}
}
#[test]
fn repeated_tokens_are_reported_once_each_and_a_glued_run_never() {
let api = api_token();
assert_eq!(detect(&format!("{api} {api}")).len(), 2);
assert!(detect(&api.repeat(200)).is_empty());
assert!(detect(&"cio".repeat(20_000)).is_empty());
assert!(detect(&"cio_tp_".repeat(10_000)).is_empty());
}
}