Skip to content

Find the holes before someone else does. A fast, 100% Rust vulnerability scanner: XSS, SQL injection, leaked secrets, dependency CVEs and AI agent setups.

fix(secrets): mask the value of a public env secret in the output (#115)

Onur Ugurea34fbc8a8bf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7c63c42..c5b53a4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,10 @@
- Secrets: `secret.env-file` and `secret.env-example-value` now catch base64 values ending in `=` padding and
passwords with `!@#$%^&*`. A value that is only `*` characters or starts with `$` (a reference like
`$POSTGRES_PASSWORD`) is skipped.
+- Secrets: `secret.public-env-secret` now replaces everything after the variable name on its line with `****`,
+ so its finding no longer prints the value, however it is written (`=`, `:`, `=>`,
+ `||`, `ENV NAME value`, ...). Before, the whole line was printed as is. Masking now keeps at most a third of a
+ secret, so a short value is not printed whole.
- Agent: an MCP config whose `npx` (or `pnpm dlx`) argument is empty or starts with a non-ASCII
character no longer crashes the scan.
- Scan: minified bundles, source maps, `.jsonl` and `.log` files, and images, fonts, archives, media and
diff --git a/src/rules.rs b/src/rules.rs
index 5eb8d53..ee6cd83 100644
--- a/src/rules.rs
+++ b/src/rules.rs
@@ -147,6 +147,15 @@ pub struct Meta<'a> {
pub fn finding(file: &FileInfo, text: &Text, line: usize, meta: Meta) -> Finding {
let raw = text.line(line).trim();
let snippet = match meta.secret {
+ // A name-only rule's "secret" is the rest of the line after the name: hide all of it
+ // (operators and quotes too, as they can be part of the value), only at the line's end.
+ Some(rest) if !rest.is_empty() && secrets::NAME_ONLY.contains(&meta.id) => {
+ match raw.strip_suffix(rest) {
+ Some(before) => shorten(&format!("{before}****")),
+ // Not expected: the rest of the line should end the line. Print nothing of it.
+ None => "****".to_string(),
+ }
+ }
Some(secret) if !secret.is_empty() => shorten(&raw.replace(secret, &mask(secret))),
_ => shorten(raw),
};
@@ -170,8 +179,25 @@ fn shorten(s: &str) -> String {
}
}
+/// Everything after a variable name on its own line, as the part to hide. The value may be
+/// written in many ways (`=v`, `: v`, `=> 'v'`, `|| "v"`, `"] = "v"`, `ENV NAME v`), so all of
+/// it is hidden rather than parsed. None when nothing is assigned: nothing follows, only `=` or
+/// `:` with nothing after it (`NAME=`), or only closing punctuation without any `=` or `:`
+/// (`NAME;`, `process.env.NAME)`, `env["NAME"]`).
+fn after_name(rest: &str) -> Option<&str> {
+ let tail = rest.lines().next().unwrap_or("").trim();
+ let nothing = matches!(tail, "" | "=" | ":")
+ || tail
+ .chars()
+ .all(|c| c.is_whitespace() || ";,)]}\"'`".contains(c));
+ (!nothing).then_some(tail)
+}
+
+/// The secret with all but its start hidden. At most 4 characters are kept, and never more
+/// than a third of the value, so a short password is not printed whole.
fn mask(secret: &str) -> String {
- let keep: String = secret.chars().take(4).collect();
+ let n = secret.chars().count();
+ let keep: String = secret.chars().take(4.min(n / 3)).collect();
format!("{keep}****")
}
@@ -190,19 +216,25 @@ pub fn check(file: &FileInfo, src: &str, include_tests: bool) -> Vec<Finding> {
}
for caps in c.re.captures_iter(src) {
let m = caps.get(0).expect("whole match");
- let secret = (c.rule.family == Family::Secret
- && !secrets::NAME_ONLY.contains(&c.rule.id))
- .then(|| {
- caps.iter()
- .skip(1)
- .flatten()
- .last()
- .unwrap_or(m)
- .as_str()
- .lines()
- .next()
- .unwrap_or("")
- });
+ // A name-only rule matches a variable name; what follows it on the line holds the
+ // value. It is read only for the finding that is kept (one per rule and line), so a
+ // long line with many names is not read again for each of them.
+ let name_only = secrets::NAME_ONLY.contains(&c.rule.id);
+ let secret = if c.rule.family != Family::Secret || name_only {
+ None
+ } else {
+ Some(
+ caps.iter()
+ .skip(1)
+ .flatten()
+ .last()
+ .unwrap_or(m)
+ .as_str()
+ .lines()
+ .next()
+ .unwrap_or(""),
+ )
+ };
let line = text.line_of(m.start());
if text.suppressed(line) {
continue;
@@ -228,7 +260,11 @@ pub fn check(file: &FileInfo, src: &str, include_tests: bool) -> Vec<Finding> {
severity: c.rule.severity,
message: c.rule.message,
fix: c.rule.fix,
- secret,
+ secret: if name_only {
+ after_name(&src[m.end()..])
+ } else {
+ secret
+ },
},
));
}
diff --git a/tests/cli.rs b/tests/cli.rs
index bf5f88d..64f5a32 100644
--- a/tests/cli.rs
+++ b/tests/cli.rs
@@ -474,3 +474,88 @@ fn secrets_are_redacted_in_every_output() {
"only the value is masked:\n{out}"
);
}
+
+#[test]
+fn public_env_secret_value_is_redacted() {
+ // `secret.public-env-secret` matches the variable name; the value given to it must not be
+ // printed either, in any output.
+ let value = common::fake("db-password");
+ let dir = std::env::temp_dir().join(format!("safe-anything-public-env-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ // Short values are joined from parts too, so the source holds no assignment that reads as a
+ // real password.
+ let (pin, pin2, first) = (
+ ["zq", "7Kx"].concat(),
+ ["Qv", "7k"].concat(),
+ ["Jq", "9xW"].concat(),
+ );
+ let (qm, quoted, colon) = (
+ ["?W", "z8k"].concat(),
+ ["Hk", "4w"].concat(),
+ ["Lm", "2z"].concat(),
+ );
+ // One finding per line; every way of giving the name a value must hide that value.
+ let lines = [
+ format!("export NEXT_PUBLIC_STRIPE_SECRET_KEY=\"{value}\""),
+ format!("VITE_ADMIN_PASSWORD={value}"),
+ format!("NUXT_PUBLIC_SMTP_PASSWORD = \"{value} and more\""),
+ format!("GATSBY_API_SECRET=pa,ss;{value}"),
+ format!("PUBLIC_PIN_PASSWORD={pin}"),
+ // A short value with a comment after it, a second name, a one-letter value.
+ format!("VITE_PIN_PASSWORD={pin2} # dev pin"),
+ format!("VITE_A_SECRET={first}; VITE_B_SECRET={value}"),
+ "echo NEXT_PUBLIC_ECHO_SECRET e".to_string(),
+ // Values that start with, or are made of, operator and bracket characters.
+ format!("VITE_QM_PASSWORD=\"{qm}\""),
+ "VITE_EQS_PASSWORD=\"====\"".to_string(),
+ "VITE_PUN_PASSWORD=\":;,\"".to_string(),
+ "VITE_BARE_PASSWORD=;,)]}".to_string(),
+ format!("ENV NEXT_PUBLIC_QUOTED_SECRET \":= '{quoted}'\""),
+ format!("VITE_COLON_PASSWORD:={colon}"),
+ format!("const NEXT_PUBLIC_API_SECRET: string = \"{value}\";"),
+ format!("$cfg = ['VITE_HASH_PASSWORD' => '{value}'];"),
+ format!("const k = process.env.VITE_FALLBACK_SECRET || \"{value}\";"),
+ format!("process.env[\"REACT_APP_IDX_SECRET\"] = \"{value}\";"),
+ format!("ENV NEXT_PUBLIC_DOCKER_SECRET {value}"),
+ format!("{{\"VITE_A_SECRET\": \"{first}\", \"VITE_B_SECRET\": \"{value}\"}}"),
+ format!("if (NEXT_PUBLIC_CMP_SECRET === \"{value}\") {{}}"),
+ format!("REACT_APP_DB_PASSWORD: '{value}'"),
+ format!("{{\"EXPO_PUBLIC_SERVICE_ROLE\": \"{value}\"}}"),
+ // Nothing after the name but punctuation: printed as is, still reported.
+ "const key = process.env.NEXT_PUBLIC_OPENAI_KEY;".to_string(),
+ "NEXT_PUBLIC_EMPTY_SECRET=".to_string(),
+ ];
+ std::fs::write(dir.join("vars.sh"), lines.join("\n") + "\n").unwrap();
+ let path = dir.to_string_lossy().into_owned();
+ for extra in [None, Some("--json"), Some("--sarif")] {
+ let mut args = vec![path.as_str(), "--offline"];
+ args.extend(extra);
+ let (_, out) = run(&args);
+ assert!(!out.contains(&value), "value leaked with {args:?}:\n{out}");
+ for part in [
+ "and more", "pa,ss", "zq7Kx", "Qv7k", "Jq9x", "?Wz8", "\"====", ":;,", ";,)]}", "Hk4w",
+ "Lm2z", ":= '",
+ ] {
+ assert!(!out.contains(part), "{part:?} leaked with {args:?}:\n{out}");
+ }
+ assert!(
+ out.matches("secret.public-env-secret").count() >= lines.len(),
+ "findings missing with {args:?}:\n{out}"
+ );
+ }
+ let (_, out) = run(&[&path, "--offline"]);
+ for kept in [
+ "VITE_ADMIN_PASSWORD****\n",
+ "echo NEXT_PUBLIC_ECHO_SECRET ****\n",
+ "ENV NEXT_PUBLIC_DOCKER_SECRET ****\n",
+ "process.env.NEXT_PUBLIC_OPENAI_KEY;",
+ "NEXT_PUBLIC_EMPTY_SECRET=\n",
+ ] {
+ assert!(
+ out.contains(kept),
+ "{kept:?} expected in the output:\n{out}"
+ );
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+}