Skip to main content

ward/
output.rs

1use serde_json::Value;
2
3pub struct Match {
4    pub category: &'static str,
5    pub matched_text: String,
6}
7
8pub fn pass() {
9    println!("{{\"continue\": true}}");
10}
11
12/// PostToolUse: the tool already ran, so instead of blocking we rewrite the
13/// tool output via `hookSpecificOutput.updatedToolOutput` with matches masked.
14pub fn redact_output(guard_name: &str, tool_response: &Value, matches: &[Match]) {
15    // Dedup needles (the same secret can match multiple tiers) and replace
16    // longest-first so a secret nested inside a larger match is never orphaned.
17    let mut needles: Vec<&Match> = Vec::new();
18    for m in matches {
19        if !m.matched_text.is_empty() && !needles.iter().any(|n| n.matched_text == m.matched_text) {
20            needles.push(m);
21        }
22    }
23    needles.sort_by_key(|m| std::cmp::Reverse(m.matched_text.len()));
24
25    // A match found in the joined scan text but absent from any single string
26    // (e.g. spanning a join boundary) can't be masked in place — withhold
27    // the whole output rather than risk a partial leak.
28    let maskable = needles
29        .iter()
30        .all(|m| value_contains(tool_response, &m.matched_text));
31
32    let updated = if maskable {
33        let mut redacted = tool_response.clone();
34        for m in &needles {
35            let marker = format!("[WARD {} REDACTED: {}]", guard_name, m.category);
36            replace_in_value(&mut redacted, &m.matched_text, &marker);
37        }
38        match redacted {
39            Value::String(s) => s,
40            other => other.to_string(),
41        }
42    } else {
43        let categories: Vec<&str> = matches.iter().map(|m| m.category).collect();
44        format!(
45            "[WARD {}] Tool output withheld: detected {}",
46            guard_name,
47            categories.join(", ")
48        )
49    };
50
51    let response = serde_json::json!({
52        "hookSpecificOutput": {
53            "hookEventName": "PostToolUse",
54            "updatedToolOutput": updated,
55        }
56    });
57    println!("{response}");
58}
59
60fn value_contains(value: &Value, needle: &str) -> bool {
61    match value {
62        Value::String(s) => s.contains(needle),
63        Value::Object(map) => map.values().any(|v| value_contains(v, needle)),
64        Value::Array(arr) => arr.iter().any(|v| value_contains(v, needle)),
65        _ => false,
66    }
67}
68
69fn replace_in_value(value: &mut Value, needle: &str, replacement: &str) {
70    match value {
71        Value::String(s) => {
72            if s.contains(needle) {
73                *s = s.replace(needle, replacement);
74            }
75        }
76        Value::Object(map) => {
77            for v in map.values_mut() {
78                replace_in_value(v, needle, replacement);
79            }
80        }
81        Value::Array(arr) => {
82            for v in arr.iter_mut() {
83                replace_in_value(v, needle, replacement);
84            }
85        }
86        _ => {}
87    }
88}
89
90pub fn block(guard_name: &str, matches: &[Match]) {
91    let descriptions: Vec<String> = matches
92        .iter()
93        .map(|m| {
94            let redacted = redact(&m.matched_text);
95            format!("{} ({})", m.category, redacted)
96        })
97        .collect();
98
99    eprintln!(
100        "WARD {} BLOCKED: Detected {}.\nRemove the sensitive data before proceeding.\nIf this is a false positive, run `ward disable -m 5` to skip scanning briefly.",
101        guard_name,
102        descriptions.join(", ")
103    );
104}
105
106/// Redact the middle of a matched string, keeping first/last few chars
107fn redact(s: &str) -> String {
108    let len = s.len();
109    if len <= 6 {
110        return "*".repeat(len);
111    }
112    let keep = 3.min(len / 4);
113    format!(
114        "{}{}{}",
115        &s[..keep],
116        "*".repeat(len - keep * 2),
117        &s[len - keep..]
118    )
119}