110 lines
5.2 KiB
Rust
110 lines
5.2 KiB
Rust
//! 秘密遮罩: keys, tokens and passwords written as text are replaced with •••• before the text is
|
||
//! kept somewhere it doesn't need them — the log file, a crash report, the steps the phone shows.
|
||
//! What a known format looks like (GitLab glpat-, GitHub ghp_/github_pat_, sk-, xai-, AWS AKIA,
|
||
//! Slack xox, Google AIza, a private key block, a Bearer header, a JWT) and any `NAME=value`
|
||
//! whose name says it is a secret (…TOKEN, …SECRET, …PASSWORD, …API_KEY…). Like grok-build's
|
||
//! xai-grok-secrets sanitizer.
|
||
//!
|
||
//! Not used on what a step needs to run again: the work log (oplog) replays a step after a crash
|
||
//! with the arguments it had, so a masked key there would break it. The model sees what it was
|
||
//! given (it may need a token to set a connector up).
|
||
|
||
use regex::{Captures, Regex};
|
||
use std::borrow::Cow;
|
||
use std::sync::OnceLock;
|
||
|
||
/// What a secret becomes.
|
||
pub const MASK: &str = "••••";
|
||
|
||
struct Rule {
|
||
re: Regex,
|
||
/// The group kept in front of the mask (a format's prefix, a variable's name and its `=`).
|
||
keep: usize,
|
||
}
|
||
|
||
fn rules() -> &'static [Rule] {
|
||
static R: OnceLock<Vec<Rule>> = OnceLock::new();
|
||
R.get_or_init(|| {
|
||
let r = |p: &str, keep: usize| Rule { re: Regex::new(p).expect("secret pattern"), keep };
|
||
vec![
|
||
// A private key block: the whole block.
|
||
r(r"(-----BEGIN [A-Z ]*PRIVATE KEY-----)[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----", 1),
|
||
r(r"\b(glpat-)[A-Za-z0-9_\-.]{20,}", 1),
|
||
r(r"\b(gh[pousr]_)[A-Za-z0-9]{30,}", 1),
|
||
r(r"\b(github_pat_)[A-Za-z0-9_]{40,}", 1),
|
||
r(r"\b(sk-(?:ant-|proj-)?)[A-Za-z0-9_\-]{20,}", 1),
|
||
r(r"\b(xai-)[A-Za-z0-9]{20,}", 1),
|
||
r(r"\b((?:AKIA|ASIA))[0-9A-Z]{16}\b", 1),
|
||
r(r"\b(xox[abprs]-)[A-Za-z0-9\-]{10,}", 1),
|
||
r(r"\b(AIza)[0-9A-Za-z_\-]{35}", 1),
|
||
r(r"\b(eyJ)[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}", 1),
|
||
r(r"(?i)\b(Bearer\s+)[A-Za-z0-9._\-~+/]{12,}=*", 1),
|
||
r(r"(?i)\b(Basic\s+)[A-Za-z0-9+/]{12,}=*", 1),
|
||
// NAME=value / NAME: value / "name": "value" with a name that says secret.
|
||
r(r#"(?i)((?:["']?)[A-Z0-9_\-]*(?:TOKEN|SECRET|PASSWORD|PASSWD|PASSPHRASE|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|CLIENT_?SECRET)[A-Z0-9_\-]*["']?\s*[=:]\s*["']?)[^\s"',;&]{6,}"#, 1),
|
||
]
|
||
})
|
||
}
|
||
|
||
/// The text with every secret it shows replaced (borrowed when there was none).
|
||
pub fn mask(text: &str) -> Cow<'_, str> {
|
||
let mut out: Cow<str> = Cow::Borrowed(text);
|
||
for rule in rules() {
|
||
if rule.re.is_match(&out) {
|
||
let next = rule.re.replace_all(&out, |c: &Captures| format!("{}{MASK}", c.get(rule.keep).map(|m| m.as_str()).unwrap_or(""))).into_owned();
|
||
out = Cow::Owned(next);
|
||
}
|
||
}
|
||
out
|
||
}
|
||
|
||
/// Whether the text shows a secret.
|
||
#[cfg(test)]
|
||
pub fn has_secret(text: &str) -> bool {
|
||
rules().iter().any(|r| r.re.is_match(text))
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn known_formats_are_masked_with_their_prefix_kept() {
|
||
let cases = [
|
||
("token glpat-AbCdEfGhIjKlMnOpQrSt12 ok", "token glpat-•••• ok"),
|
||
("ghp_0123456789abcdefghijABCDEFGHIJ012345", "ghp_••••"),
|
||
("github_pat_11ABCDEFG0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGH", "github_pat_••••"),
|
||
("key sk-proj-abcdefghijklmnopqrstuvwx1234", "key sk-proj-••••"),
|
||
("sk-ant-api03-abcdefghijklmnopqrstuvwxyz", "sk-ant-••••"),
|
||
("xai-ABCDEFGHIJKLMNOPQRSTUVWXYZ012345", "xai-••••"),
|
||
("AKIAIOSFODNN7EXAMPLE", "AKIA••••"),
|
||
("xoxb-1234567890-abcdefghij", "xoxb-••••"),
|
||
("AIzaSyA-0123456789abcdefghijklmnopqrstu", "AIza••••"),
|
||
("Authorization: Bearer abc.DEF_ghi-jkl123", "Authorization: Bearer ••••"),
|
||
("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U", "eyJ••••"),
|
||
];
|
||
for (input, want) in cases {
|
||
assert_eq!(mask(input), want, "{input}");
|
||
assert!(has_secret(input), "{input}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn a_secret_named_variable_keeps_its_name() {
|
||
assert_eq!(mask("GITLAB_PERSONAL_ACCESS_TOKEN=_hZFE6ya-m2LjH4qWrtyuW86MQ"), "GITLAB_PERSONAL_ACCESS_TOKEN=••••");
|
||
assert_eq!(mask(r#"{"password": "hunter2-long"}"#), r#"{"password": "••••"}"#);
|
||
assert_eq!(mask("export OPENAI_API_KEY='abcdef123456' && run"), "export OPENAI_API_KEY='••••' && run");
|
||
assert_eq!(mask("DB_PASSWORD: s3cr3t!x"), "DB_PASSWORD: ••••");
|
||
let pem = "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXk\nAAAA\n-----END OPENSSH PRIVATE KEY-----";
|
||
assert_eq!(mask(pem), "-----BEGIN OPENSSH PRIVATE KEY-----••••");
|
||
}
|
||
|
||
#[test]
|
||
fn ordinary_text_is_left_alone() {
|
||
for s in ["已新增連接器「gitlab」,正在連線。", "tokens: 1234 used", "password", "the key is in the drawer", "sk-short", "Bearer x", "GITLAB_API_URL=https://gitlab.example.com/api/v4"] {
|
||
assert!(matches!(mask(s), Cow::Borrowed(_)), "{s}");
|
||
assert!(!has_secret(s), "{s}");
|
||
}
|
||
}
|
||
}
|