feat(fermata): a Write or Edit that adds a mask is stopped; masked output says so
count_masks counts runs of exactly five stars, or <REDACTED: marks under typed and named; absent counts 0. write_pairs gives each change's text before and after. The guard denies when a change holds more marks than what it replaces, and a Write's "before" is the file on disk, read only if the new text holds a mark. Both projects of a path call decide. on_mask_write = "allow" turns it off. The refusal says "ask the user", names the setting and quotes nothing. Each PostToolUse that masked adds a note beside the output. cli_hook_fail_closed: a masked Write's only note is now the masks note, asserted exactly, in place of "no note".
This commit is contained in:
+43
-1
@@ -152,6 +152,9 @@ fn session_dir(cwd: Option<&Path>) -> Option<PathBuf> {
|
|||||||
/// The refusal text of the failure paths. It names files, never their contents.
|
/// The refusal text of the failure paths. It names files, never their contents.
|
||||||
const FIX_OR_CHANGE: &str = "and on_parse_error = \"deny\" is set. Fix the file or change the setting.";
|
const FIX_OR_CHANGE: &str = "and on_parse_error = \"deny\" is set. Fix the file or change the setting.";
|
||||||
|
|
||||||
|
/// Beside every output that was masked: the write guard does not see a shell's writes.
|
||||||
|
const MASKS_NOTE: &str = "[fermata] Values in this output are masked. Do not write them back into a file.";
|
||||||
|
|
||||||
/// `path` as the project knows it.
|
/// `path` as the project knows it.
|
||||||
fn shown_path(path: &Path, root: &Path) -> String {
|
fn shown_path(path: &Path, root: &Path) -> String {
|
||||||
path.strip_prefix(root).unwrap_or(path).display().to_string()
|
path.strip_prefix(root).unwrap_or(path).display().to_string()
|
||||||
@@ -195,6 +198,41 @@ fn gate_policy(root: &Path) -> Result<Policy, Decision> {
|
|||||||
Ok(policy)
|
Ok(policy)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The write guard, under `root`'s settings: a call that would add a mask to `path` is
|
||||||
|
/// stopped. A mask stands for a value fermata hid, and an agent that read one and writes
|
||||||
|
/// it back corrupts the file. Nothing here quotes the text.
|
||||||
|
fn mask_guard(adapter: &dyn dirigent_fermata::harness::HarnessAdapter, call: &dirigent_fermata::harness::ToolCall, path: &Path, root: &Path) -> Decision {
|
||||||
|
use dirigent_fermata::core::secrets::{config::GuardAction, count_masks};
|
||||||
|
|
||||||
|
let pairs = adapter.write_pairs(call);
|
||||||
|
if pairs.is_empty() {
|
||||||
|
return Decision::Allow;
|
||||||
|
}
|
||||||
|
let (config, _) = SecretsConfig::load_or_default(root);
|
||||||
|
if config.enforcement.on_mask_write == GuardAction::Allow {
|
||||||
|
return Decision::Allow;
|
||||||
|
}
|
||||||
|
let style = config.redaction.style;
|
||||||
|
let adds_a_mask = pairs.iter().any(|(before, after)| {
|
||||||
|
let masks = count_masks(style, after);
|
||||||
|
masks > 0
|
||||||
|
&& masks > match before {
|
||||||
|
Some(text) => count_masks(style, text),
|
||||||
|
None => std::fs::read(path).map_or(0, |bytes| count_masks(style, &String::from_utf8_lossy(&bytes))),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if !adds_a_mask {
|
||||||
|
return Decision::Allow;
|
||||||
|
}
|
||||||
|
Decision::Deny(Reason {
|
||||||
|
message: format!(
|
||||||
|
"[fermata] Write stopped: this adds a mask to {}. A mask stands for a value fermata hid from you, so writing one corrupts the file. Keep the text that was there, or ask the user: the setting is [enforcement] on_mask_write.",
|
||||||
|
shown_path(path, root),
|
||||||
|
),
|
||||||
|
rule: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// Handle a PreToolUse hook event (policy gate).
|
/// Handle a PreToolUse hook event (policy gate).
|
||||||
///
|
///
|
||||||
/// Fail-open unless `on_parse_error = "deny"` is set: see [`gate_failure`]. A tool
|
/// Fail-open unless `on_parse_error = "deny"` is set: see [`gate_failure`]. A tool
|
||||||
@@ -238,7 +276,10 @@ fn run_pre_tool_use(
|
|||||||
roots.dedup();
|
roots.dedup();
|
||||||
let decisions = roots.iter().map(|root| match gate_policy(root) {
|
let decisions = roots.iter().map(|root| match gate_policy(root) {
|
||||||
Err(decision) => decision,
|
Err(decision) => decision,
|
||||||
Ok(policy) => policy.check(op, &path).unwrap_or_else(|e| check_failed(root, &e)),
|
Ok(policy) => {
|
||||||
|
let rules = policy.check(op, &path).unwrap_or_else(|e| check_failed(root, &e));
|
||||||
|
merge_worst(Some(rules), mask_guard(adapter, &call, &path, root))
|
||||||
|
}
|
||||||
});
|
});
|
||||||
decisions.fold(None, |worst, decision| Some(merge_worst(worst, decision))).unwrap_or(Decision::Allow)
|
decisions.fold(None, |worst, decision| Some(merge_worst(worst, decision))).unwrap_or(Decision::Allow)
|
||||||
}
|
}
|
||||||
@@ -365,6 +406,7 @@ fn run_post_tool_use(
|
|||||||
OutputEdit::Unchanged => None,
|
OutputEdit::Unchanged => None,
|
||||||
OutputEdit::Replaced { output, redactions } => {
|
OutputEdit::Replaced { output, redactions } => {
|
||||||
eprintln!("fermata: redacted {redactions} secret(s) from {} output", payload.tool_name);
|
eprintln!("fermata: redacted {redactions} secret(s) from {} output", payload.tool_name);
|
||||||
|
notes.push(MASKS_NOTE.to_string());
|
||||||
Some(output)
|
Some(output)
|
||||||
}
|
}
|
||||||
// The harness would reject a masked replacement and use the original.
|
// The harness would reject a masked replacement and use the original.
|
||||||
|
|||||||
@@ -12,5 +12,5 @@ pub mod value_class;
|
|||||||
pub use config::{KeyMatcher, SecretsConfig};
|
pub use config::{KeyMatcher, SecretsConfig};
|
||||||
pub use manifest::{unmaskable_reason, Manifest, ManifestError, SecretFileSet, UnmaskableFile};
|
pub use manifest::{unmaskable_reason, Manifest, ManifestError, SecretFileSet, UnmaskableFile};
|
||||||
pub use parser::{parse_secret_file, FileFormat, ParseError, SecretEntry};
|
pub use parser::{parse_secret_file, FileFormat, ParseError, SecretEntry};
|
||||||
pub use redactor::{RedactedText, Redaction, Redactor};
|
pub use redactor::{count_masks, RedactedText, Redaction, Redactor};
|
||||||
pub use scanner::{Confidence, Finding, Scanner};
|
pub use scanner::{Confidence, Finding, Scanner};
|
||||||
|
|||||||
@@ -172,6 +172,16 @@ impl Redactor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How many of `style`'s marks `text` holds. A mask is a run of exactly five `*`, so that
|
||||||
|
/// a banner or a rule of stars counts for nothing. `absent` leaves no mark to find.
|
||||||
|
pub fn count_masks(style: RedactionStyle, text: &str) -> usize {
|
||||||
|
match style {
|
||||||
|
RedactionStyle::Masked => text.split(|c| c != '*').filter(|run| run.len() == 5).count(),
|
||||||
|
RedactionStyle::Typed | RedactionStyle::Named => text.matches("<REDACTED:").count(),
|
||||||
|
RedactionStyle::Absent => 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// A stretch of text to mask, named after the longest match in it.
|
/// A stretch of text to mask, named after the longest match in it.
|
||||||
struct MaskedRange {
|
struct MaskedRange {
|
||||||
start: usize,
|
start: usize,
|
||||||
|
|||||||
@@ -65,6 +65,16 @@ impl HarnessAdapter for ClaudeAdapter {
|
|||||||
Ok(serde_json::to_vec(&out)?)
|
Ok(serde_json::to_vec(&out)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn write_pairs(&self, call: &ToolCall) -> Vec<(Option<String>, String)> {
|
||||||
|
let input = &call.raw["tool_input"];
|
||||||
|
match call.tool_name.as_str() {
|
||||||
|
"Write" => text_field(input, "content").map(|after| (None, after)).into_iter().collect(),
|
||||||
|
"Edit" => edit_pair(input).into_iter().collect(),
|
||||||
|
"MultiEdit" => input["edits"].as_array().map_or_else(Vec::new, |edits| edits.iter().filter_map(edit_pair).collect()),
|
||||||
|
_ => Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// -- PostToolUse -------------------------------------------------------
|
// -- PostToolUse -------------------------------------------------------
|
||||||
|
|
||||||
fn parse_post_tool_use(&self, input: &[u8]) -> Result<PostToolUsePayload, AdapterError> {
|
fn parse_post_tool_use(&self, input: &[u8]) -> Result<PostToolUsePayload, AdapterError> {
|
||||||
@@ -169,6 +179,15 @@ fn payload_cwd(v: &Value) -> Option<PathBuf> {
|
|||||||
v.get("cwd").and_then(Value::as_str).map(PathBuf::from)
|
v.get("cwd").and_then(Value::as_str).map(PathBuf::from)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn text_field(value: &Value, field: &str) -> Option<String> {
|
||||||
|
value.get(field).and_then(Value::as_str).map(str::to_string)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An edit's text before and after. With no `old_string` it adds all it holds.
|
||||||
|
fn edit_pair(edit: &Value) -> Option<(Option<String>, String)> {
|
||||||
|
Some((Some(text_field(edit, "old_string").unwrap_or_default()), text_field(edit, "new_string")?))
|
||||||
|
}
|
||||||
|
|
||||||
fn is_mcp(payload: &PostToolUsePayload) -> bool {
|
fn is_mcp(payload: &PostToolUsePayload) -> bool {
|
||||||
payload.tool_name.starts_with("mcp__")
|
payload.tool_name.starts_with("mcp__")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -118,6 +118,10 @@ pub trait HarnessAdapter {
|
|||||||
/// Render a policy `Decision` back to the harness's PreToolUse wire format.
|
/// Render a policy `Decision` back to the harness's PreToolUse wire format.
|
||||||
fn render_decision(&self, call: &ToolCall, decision: &Decision) -> Result<Vec<u8>, AdapterError>;
|
fn render_decision(&self, call: &ToolCall, decision: &Decision) -> Result<Vec<u8>, AdapterError>;
|
||||||
|
|
||||||
|
/// The (text before, text after) of each change a call makes to a file's text.
|
||||||
|
/// `None` before: the whole file, which is what is on disk. Empty for any other call.
|
||||||
|
fn write_pairs(&self, call: &ToolCall) -> Vec<(Option<String>, String)>;
|
||||||
|
|
||||||
// -- PostToolUse -------------------------------------------------------
|
// -- PostToolUse -------------------------------------------------------
|
||||||
|
|
||||||
/// Parse a PostToolUse hook payload (tool name, input, response).
|
/// Parse a PostToolUse hook payload (tool name, input, response).
|
||||||
|
|||||||
@@ -278,11 +278,12 @@ fn a_typo_in_botsecrets_keeps_the_other_layers_and_the_default_list() {
|
|||||||
assert!(!note.contains("polcy"), "{tool}: {note}");
|
assert!(!note.contains("polcy"), "{tool}: {note}");
|
||||||
}
|
}
|
||||||
|
|
||||||
// A Write costs the session no line for it, masked or not.
|
// A Write costs the session no line for it, masked or not: a masked one says only
|
||||||
|
// that it was masked.
|
||||||
assert_eq!(tool_output(&p, "Write", "clean"), json!({}));
|
assert_eq!(tool_output(&p, "Write", "clean"), json!({}));
|
||||||
let out = tool_output(&p, "Write", VALUE);
|
let out = tool_output(&p, "Write", VALUE);
|
||||||
assert!(!out.to_string().contains(VALUE), "{out}");
|
assert!(!out.to_string().contains(VALUE), "{out}");
|
||||||
assert!(out["hookSpecificOutput"].get("additionalContext").is_none(), "{out}");
|
assert_eq!(out["hookSpecificOutput"]["additionalContext"], "[fermata] Values in this output are masked. Do not write them back into a file.", "{out}");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A broken user-global layer: the project's own rules stand.
|
/// A broken user-global layer: the project's own rules stand.
|
||||||
|
|||||||
@@ -0,0 +1,303 @@
|
|||||||
|
//! The write guard: a Write, Edit or MultiEdit that adds a mask is stopped, because an
|
||||||
|
//! agent that read `*****` and writes it back corrupts the file. Each output that was
|
||||||
|
//! masked says so beside it. All values here are fake.
|
||||||
|
|
||||||
|
use assert_cmd::Command;
|
||||||
|
use dirigent_fermata::core::secrets::config::RedactionStyle;
|
||||||
|
use dirigent_fermata::core::secrets::{count_masks, Manifest, Redactor, SecretEntry};
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use std::fs;
|
||||||
|
use tempfile::TempDir;
|
||||||
|
|
||||||
|
const MASK: &str = "*****";
|
||||||
|
const NOTE: &str = "[fermata] Values in this output are masked. Do not write them back into a file.";
|
||||||
|
/// Text around a mask, which a refusal must not quote.
|
||||||
|
const NEIGHBOUR: &str = "fake-neighbouring-text";
|
||||||
|
|
||||||
|
struct Project {
|
||||||
|
dir: TempDir,
|
||||||
|
home: TempDir,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn project(files: &[(&str, &str)]) -> Project {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
fs::write(dir.path().join(".botignore"), "").unwrap();
|
||||||
|
for (name, content) in files {
|
||||||
|
fs::write(dir.path().join(name), content).unwrap();
|
||||||
|
}
|
||||||
|
Project { dir, home: tempfile::tempdir().unwrap() }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Project {
|
||||||
|
fn hook(&self, event: &str, payload: Value) -> Value {
|
||||||
|
let output = Command::cargo_bin("fermata")
|
||||||
|
.unwrap()
|
||||||
|
.args(["hook", "--event", event, "--harness", "claude"])
|
||||||
|
.current_dir(self.dir.path())
|
||||||
|
.env("HOME", self.home.path())
|
||||||
|
.write_stdin(payload.to_string())
|
||||||
|
.assert()
|
||||||
|
.success()
|
||||||
|
.get_output()
|
||||||
|
.clone();
|
||||||
|
let stderr = String::from_utf8(output.stderr).unwrap();
|
||||||
|
assert!(!stderr.contains(NEIGHBOUR), "stderr quotes the content: {stderr}");
|
||||||
|
serde_json::from_slice(&output.stdout).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pre(&self, tool: &str, input: Value) -> Value {
|
||||||
|
self.hook("pre-tool-use", json!({"tool_name": tool, "tool_input": input}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn file(&self, name: &str) -> String {
|
||||||
|
self.dir.path().join(name).display().to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(&self, name: &str, content: &str) -> Value {
|
||||||
|
self.pre("Write", json!({"file_path": self.file(name), "content": content}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn edit(&self, old: &str, new: &str) -> Value {
|
||||||
|
self.pre("Edit", json!({"file_path": self.file("a.txt"), "old_string": old, "new_string": new}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn multi_edit(&self, edits: &[(&str, &str)]) -> Value {
|
||||||
|
let edits: Vec<Value> = edits.iter().map(|(old, new)| json!({"old_string": old, "new_string": new})).collect();
|
||||||
|
self.pre("MultiEdit", json!({"file_path": self.file("a.txt"), "edits": edits}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn post(&self, tool: &str, response: Value) -> Value {
|
||||||
|
self.hook("post-tool-use", json!({"tool_name": tool, "tool_input": {}, "tool_response": response}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn styled(style: &str) -> String {
|
||||||
|
format!("[redaction]\nstyle = \"{style}\"\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_denied(out: &Value) {
|
||||||
|
let specific = &out["hookSpecificOutput"];
|
||||||
|
assert_eq!(specific["permissionDecision"], "deny", "{out}");
|
||||||
|
let reason = specific["permissionDecisionReason"].as_str().unwrap();
|
||||||
|
assert!(reason.contains("ask the user") && reason.contains("on_mask_write"), "{reason}");
|
||||||
|
assert!(!reason.contains(NEIGHBOUR), "{reason}");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_silent(out: &Value) {
|
||||||
|
assert_eq!(*out, json!({}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Write
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_write_of_a_new_file_with_a_mask_is_denied() {
|
||||||
|
let p = project(&[]);
|
||||||
|
assert_denied(&p.write("new.txt", &format!("key = {MASK}\n{NEIGHBOUR}\n")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_write_of_a_file_already_holding_the_mask_passes() {
|
||||||
|
let p = project(&[("a.txt", "a = *****\n")]);
|
||||||
|
assert_silent(&p.write("a.txt", &format!("{NEIGHBOUR}\na = {MASK}\n")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_write_with_more_masks_than_the_file_on_disk_is_denied() {
|
||||||
|
let p = project(&[("a.txt", "a = *****\n")]);
|
||||||
|
assert_denied(&p.write("a.txt", &format!("a = {MASK}\nb = {MASK}\n")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_write_with_no_mask_passes() {
|
||||||
|
let p = project(&[]);
|
||||||
|
assert_silent(&p.write("new.txt", "plain text\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The masks of a file that is not UTF-8 are still the file's.
|
||||||
|
#[test]
|
||||||
|
fn the_masks_of_a_binary_file_on_disk_count() {
|
||||||
|
let p = project(&[]);
|
||||||
|
fs::write(p.dir.path().join("a.bin"), b"\xff\xfe ***** \x00\n").unwrap();
|
||||||
|
assert_silent(&p.write("a.bin", MASK));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The file is the one the session means, not one in this process's directory.
|
||||||
|
#[test]
|
||||||
|
fn a_relative_path_is_the_sessions() {
|
||||||
|
let launch = project(&[]);
|
||||||
|
let session = project(&[("a.txt", "a = *****\n")]);
|
||||||
|
let payload = |content: &str| {
|
||||||
|
json!({"tool_name": "Write", "cwd": session.dir.path(), "tool_input": {"file_path": "a.txt", "content": content}})
|
||||||
|
};
|
||||||
|
assert_silent(&launch.hook("pre-tool-use", payload(MASK)));
|
||||||
|
assert_denied(&launch.hook("pre-tool-use", payload(&format!("{MASK} {MASK}"))));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Edit, MultiEdit
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_edit_adding_a_mask_is_denied() {
|
||||||
|
let p = project(&[]);
|
||||||
|
assert_denied(&p.edit("key = old", &format!("key = {MASK}")));
|
||||||
|
assert_denied(&p.edit(&format!("a = {MASK}"), &format!("a = {MASK}\nb = {MASK}")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_edit_keeping_or_removing_a_mask_passes() {
|
||||||
|
let p = project(&[]);
|
||||||
|
assert_silent(&p.edit(&format!("a = {MASK}"), &format!("a = {MASK} # {NEIGHBOUR}")));
|
||||||
|
assert_silent(&p.edit(&format!("a = {MASK}"), "a = read from the environment"));
|
||||||
|
assert_silent(&p.edit("plain", "text"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_multi_edit_is_judged_edit_by_edit() {
|
||||||
|
let p = project(&[]);
|
||||||
|
assert_denied(&p.multi_edit(&[("plain", "text"), ("key = old", &format!("key = {MASK}"))]));
|
||||||
|
assert_silent(&p.multi_edit(&[("plain", "text"), (&format!("a = {MASK}"), &format!("b = {MASK}"))]));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// The setting
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn on_mask_write_allow_passes_each_tool() {
|
||||||
|
let p = project(&[(".botsecrets", "[enforcement]\non_mask_write = \"allow\"\n")]);
|
||||||
|
assert_silent(&p.write("new.txt", MASK));
|
||||||
|
assert_silent(&p.edit("old", MASK));
|
||||||
|
assert_silent(&p.multi_edit(&[("old", MASK)]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A typo costs its layer, and the default of the guard stands.
|
||||||
|
#[test]
|
||||||
|
fn a_broken_config_keeps_the_guard() {
|
||||||
|
let p = project(&[(".botsecrets", "[polcy]\nx = 1\n")]);
|
||||||
|
assert_denied(&p.write("new.txt", MASK));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The session's project and the file's each decide, and the worst stands.
|
||||||
|
#[test]
|
||||||
|
fn the_sessions_project_guards_a_write_into_another() {
|
||||||
|
let session = project(&[]);
|
||||||
|
let other = project(&[(".botsecrets", "[enforcement]\non_mask_write = \"allow\"\n")]);
|
||||||
|
assert_denied(&session.write(&other.file("new.txt"), MASK));
|
||||||
|
assert_silent(&other.write(&other.file("new.txt"), MASK));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// What counts as a mask
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_banner_or_a_rule_of_stars_is_no_mask() {
|
||||||
|
let p = project(&[]);
|
||||||
|
for text in ["/***********/", "****", "******", "/* ****************************** */", "a ** b *** c"] {
|
||||||
|
assert_silent(&p.write("new.txt", text));
|
||||||
|
assert_silent(&p.edit("old", text));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn count_masks_counts_each_styles_marks() {
|
||||||
|
use RedactionStyle::{Absent, Masked, Named, Typed};
|
||||||
|
for (style, text, count) in [
|
||||||
|
(Masked, "", 0),
|
||||||
|
(Masked, "*****", 1),
|
||||||
|
(Masked, "a ***** b ***** c", 2),
|
||||||
|
(Masked, "*****\n*****", 2),
|
||||||
|
(Masked, "x*****y", 1),
|
||||||
|
(Masked, "****", 0),
|
||||||
|
(Masked, "******", 0),
|
||||||
|
(Masked, "/***********/", 0),
|
||||||
|
(Masked, "<REDACTED:string:5>", 0),
|
||||||
|
(Typed, "<REDACTED:string:5> <REDACTED:string:7>", 2),
|
||||||
|
(Typed, "*****", 0),
|
||||||
|
(Named, "<REDACTED:API_TOKEN>", 1),
|
||||||
|
(Named, "*****", 0),
|
||||||
|
(Absent, "***** <REDACTED:API_TOKEN>", 0),
|
||||||
|
] {
|
||||||
|
assert_eq!(count_masks(style, text), count, "{style:?} {text:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the redactor writes is what the guard counts, one mark per value, in each style.
|
||||||
|
#[test]
|
||||||
|
fn count_masks_finds_what_the_redactor_writes() {
|
||||||
|
let entry = SecretEntry { key: "API_TOKEN".into(), value: SECRET.into(), source: "/p/.env".into() };
|
||||||
|
let manifest = Manifest::from_entries(vec![entry]);
|
||||||
|
let text = format!("a {SECRET} b {SECRET} c");
|
||||||
|
for (style, count) in [(RedactionStyle::Masked, 2), (RedactionStyle::Typed, 2), (RedactionStyle::Named, 2), (RedactionStyle::Absent, 0)] {
|
||||||
|
let redacted = Redactor::new(&manifest, style).redact(&text);
|
||||||
|
assert_eq!(count_masks(style, &redacted.text), count, "{style:?}: {}", redacted.text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn typed_and_named_marks_count_under_their_styles() {
|
||||||
|
let p = project(&[(".botsecrets", &styled("typed"))]);
|
||||||
|
assert_denied(&p.write("new.txt", "key = <REDACTED:string:12>\n"));
|
||||||
|
assert_silent(&p.edit("a = <REDACTED:string:12>", "b = <REDACTED:string:12>"));
|
||||||
|
assert_silent(&p.write("new.txt", MASK));
|
||||||
|
|
||||||
|
let p = project(&[(".botsecrets", &styled("named"))]);
|
||||||
|
assert_denied(&p.write("new.txt", "key = <REDACTED:API_TOKEN>\n"));
|
||||||
|
assert_denied(&p.edit("old", "<REDACTED:API_TOKEN>"));
|
||||||
|
assert_silent(&p.write("new.txt", MASK));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_absent_style_has_no_mark_to_count() {
|
||||||
|
let p = project(&[(".botsecrets", &styled("absent"))]);
|
||||||
|
assert_silent(&p.write("new.txt", MASK));
|
||||||
|
assert_silent(&p.edit("old", "<REDACTED:API_TOKEN>"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The stated limit: only the three tools that write a file's text are read.
|
||||||
|
#[test]
|
||||||
|
fn a_shell_command_that_writes_is_not_checked() {
|
||||||
|
let p = project(&[]);
|
||||||
|
assert_silent(&p.pre("Bash", json!({"command": "echo '*****' > new.txt"})));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// The note beside masked output
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const SECRET: &str = "fake-token-4242-abcdef";
|
||||||
|
|
||||||
|
fn with_secret() -> Project {
|
||||||
|
project(&[(".env", &format!("API_TOKEN={SECRET}\n"))])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn masked_output_says_so_beside_it() {
|
||||||
|
let p = with_secret();
|
||||||
|
let bash = json!({"stdout": format!("token {SECRET}"), "stderr": "", "interrupted": false, "isImage": false});
|
||||||
|
let write = json!({"type": "create", "filePath": "/p/x", "content": SECRET, "structuredPatch": [], "originalFile": null});
|
||||||
|
for (tool, response) in [("Bash", bash), ("Write", write)] {
|
||||||
|
let out = p.post(tool, response);
|
||||||
|
assert_eq!(out["hookSpecificOutput"]["additionalContext"], NOTE, "{tool}: {out}");
|
||||||
|
assert!(!out.to_string().contains(SECRET), "{tool}: {out}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn output_with_nothing_masked_has_no_note() {
|
||||||
|
let out = with_secret().post("Bash", json!({"stdout": "clean", "stderr": "", "interrupted": false, "isImage": false}));
|
||||||
|
assert_silent(&out);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_note_stands_beside_the_heuristic_warning() {
|
||||||
|
let p = with_secret();
|
||||||
|
let stdout = format!("{SECRET} ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij");
|
||||||
|
let out = p.post("Bash", json!({"stdout": stdout, "stderr": "", "interrupted": false, "isImage": false}));
|
||||||
|
let context = out["hookSpecificOutput"]["additionalContext"].as_str().unwrap();
|
||||||
|
assert!(context.starts_with(NOTE) && context.contains("WARNING"), "{context}");
|
||||||
|
assert!(!context.contains("ghp_"), "{context}");
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user