trusty_code/permissions/redact.rs
1//! Credential scrubbing for a published permission subject (#7948).
2//!
3//! Why: an `Event::PermissionRequested` carries the command an operator is
4//! asked to approve, which routinely carries the credential it needs
5//! (`GITHUB_TOKEN=ghp_... gh pr create`). The event reaches every attached
6//! client and the session ring buffer, so the credential must not survive.
7//! What: `redact_subject`.
8//! Test: `permissions::tests::gate_tests::redacts_*`.
9
10use std::sync::LazyLock;
11
12use regex::Regex;
13
14/// How many characters of a subject reach the event stream.
15const SUBJECT_PREVIEW_CHARS: usize = 500;
16
17/// Redact credential-shaped text out of a subject, then bound its length.
18///
19/// Why: see the module docs.
20/// What: replaces the VALUE of a `NAME=value` assignment whose name looks like
21/// a secret (token/secret/password/key/auth/credential, any case) or is an
22/// all-caps environment-variable name, and the value of an `Authorization:`,
23/// `Proxy-Authorization:`, or `X-Api-Key:` header; then bounds the result to
24/// 500 characters. A best-effort scrub of the SHAPES a credential is passed
25/// in, not a secret scanner — a positional secret (`curl -u user:pass`) is not
26/// detectable from text alone.
27/// Test: `redacts_a_lowercase_token_assignment`,
28/// `redacts_an_uppercase_env_assignment`, `redacts_an_authorization_header`,
29/// `leaves_an_ordinary_command_untouched`, `bounds_the_subject_to_500_chars`.
30pub fn redact_subject(subject: &str) -> String {
31 static SECRET_ASSIGNMENT: LazyLock<Regex> = LazyLock::new(|| {
32 Regex::new(
33 r"(?i)\b([A-Za-z0-9_.-]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|credential)[A-Za-z0-9_.-]*)=(\S+)",
34 )
35 .expect("static redaction pattern compiles")
36 });
37 static ENV_ASSIGNMENT: LazyLock<Regex> = LazyLock::new(|| {
38 Regex::new(r"\b([A-Z][A-Z0-9_]{2,})=(\S+)").expect("static redaction pattern compiles")
39 });
40 // The header value runs to the closing quote, not the first space:
41 // in `Authorization: Bearer sk-live-xyz` the SECOND token is the secret.
42 static HEADER: LazyLock<Regex> = LazyLock::new(|| {
43 Regex::new("(?i)\\b(authorization|x-api-key|proxy-authorization):[^'\"\n]*")
44 .expect("static redaction pattern compiles")
45 });
46
47 let redacted = SECRET_ASSIGNMENT.replace_all(subject, "$1=<redacted>");
48 let redacted = ENV_ASSIGNMENT.replace_all(&redacted, "$1=<redacted>");
49 let redacted = HEADER.replace_all(&redacted, "$1: <redacted>");
50 crate::events::preview(&redacted, SUBJECT_PREVIEW_CHARS)
51}