wallfacer-core 0.8.1

Runtime fuzzing and invariant-testing harness for MCP servers — catch crashes, hangs, schema drift, and state leaks before they ship.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! Redaction of secrets before persistence.
//!
//! Findings and target configuration may contain bearer tokens, cookies, or
//! payload fields named like secrets (`api_key`, `password`, ...). Anything
//! that lands on disk in `.wallfacer/` or in CI artefacts must first be
//! filtered through [`Redact::redacted`] so cleartext secrets do not leak into
//! corpus files, SARIF output, or shared logs.

use std::sync::OnceLock;

use regex::Regex;
use serde_json::{Map, Value};

use crate::{
    finding::{Finding, ReproInfo},
    target::{Target, Transport},
};

/// Placeholder substituted for any value that matched a redaction pattern.
pub const REDACTED_PLACEHOLDER: &str = "<redacted>";

/// Trait implemented by types that can produce a copy with sensitive fields
/// scrubbed. Implementations must be **idempotent** and **non-destructive**:
/// they return a new value rather than mutating in place, so callers can keep
/// the original around for in-process use (e.g. reproducing a call) while
/// persisting only the scrubbed copy.
pub trait Redact {
    /// Returns a deep copy with sensitive fields replaced by
    /// [`REDACTED_PLACEHOLDER`].
    fn redacted(&self) -> Self;
}

/// Returns `true` if a HTTP header name should have its value masked before
/// persistence.
///
/// Matches (case-insensitive):
/// * `Authorization`, `Proxy-Authorization`
/// * `Cookie`, `Set-Cookie`
/// * any name containing `token`, `secret`, `password`, `bearer`, `api-key`,
///   `api_key`, `apikey`
pub fn is_sensitive_header(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    matches!(
        lower.as_str(),
        "authorization" | "proxy-authorization" | "cookie" | "set-cookie"
    ) || contains_secret_marker(&lower)
}

/// Returns `true` if a JSON object key likely identifies a secret value.
///
/// The match is case-insensitive and looks for the same markers as
/// [`is_sensitive_header`], plus standalone `auth` (only as a whole word, to
/// avoid matching unrelated names like `author`).
pub fn is_sensitive_key(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    if contains_secret_marker(&lower) {
        return true;
    }
    // Standalone `auth` word. We split on common separators so `auth_kind` or
    // `kind-auth` match, while `author` and `authentik` do not.
    lower
        .split(|c: char| !c.is_ascii_alphanumeric())
        .any(|segment| segment == "auth")
}

fn contains_secret_marker(lower: &str) -> bool {
    const MARKERS: &[&str] = &[
        "token",
        "secret",
        "password",
        "passwd",
        "bearer",
        "api-key",
        "api_key",
        "apikey",
        "private-key",
        "private_key",
    ];
    MARKERS.iter().any(|marker| lower.contains(marker))
}

/// Returns a copy of `text` with secret-like substrings replaced by
/// [`REDACTED_PLACEHOLDER`]. Patterns matched (case-insensitive):
///
/// * `Authorization: Bearer <token>` / `Bearer <token>` (also `Basic`).
/// * `<sensitive-key> = <value>` and `<sensitive-key>: <value>` where
///   `<sensitive-key>` matches the same keyword set as
///   [`is_sensitive_key`].
///
/// The harness writes server output verbatim into `Finding::details` when
/// a schema violation triggers, so secrets that show up in error
/// messages or echoed payloads would otherwise leak into the corpus.
/// This is a defence-in-depth pass on top of [`redact_json`]; the docs
/// (`docs/security.md`) still describe redaction as best-effort and
/// pattern-based.
pub fn redact_string(text: &str) -> String {
    let mut out = text.to_string();
    for pattern in string_patterns() {
        out = pattern
            .replace_all(&out, |caps: &regex::Captures<'_>| {
                // Capture group 1 holds the prefix to keep, group 2 (if
                // present) the secret to mask. When only one group exists
                // the entire match is masked.
                if let Some(prefix) = caps.get(1) {
                    if caps.get(2).is_some() {
                        return format!("{}{REDACTED_PLACEHOLDER}", prefix.as_str());
                    }
                }
                REDACTED_PLACEHOLDER.to_string()
            })
            .into_owned();
    }
    out
}

fn string_patterns() -> &'static [Regex] {
    static PATTERNS: OnceLock<Vec<Regex>> = OnceLock::new();
    PATTERNS.get_or_init(|| {
        // Each pattern's first capture group is the literal prefix kept
        // verbatim; the second (where present) is the secret value that
        // gets replaced.
        let raw: &[&str] = &[
            // `Bearer <tok>` / `Basic <tok>` (with optional `Authorization:`).
            r"(?i)((?:authorization\s*:\s*)?(?:bearer|basic)\s+)([A-Za-z0-9._\-+/=]{6,})",
            // `key=value` / `key:value` / `"key":"value"` for known sensitive keys.
            // Stops at whitespace or common delimiters so surrounding text is preserved.
            r#"(?i)((?:^|[\s,;{(\["'])(?:authorization|api[-_]?key|apikey|access[-_]?token|refresh[-_]?token|secret|client[-_]?secret|password|passwd|bearer|private[-_]?key|token)["']?\s*[:=]\s*["']?)([^"',;\s\)\]\}]{4,})"#,
        ];
        raw.iter()
            .filter_map(|src| Regex::new(src).ok())
            .collect()
    })
}

/// Recursively redacts a JSON value: any object entry whose key matches
/// [`is_sensitive_key`] has its value replaced by [`REDACTED_PLACEHOLDER`].
/// Arrays and nested objects are walked.
pub fn redact_json(value: &Value) -> Value {
    match value {
        Value::Object(map) => {
            let mut out = Map::with_capacity(map.len());
            for (key, child) in map {
                if is_sensitive_key(key) {
                    out.insert(key.clone(), Value::String(REDACTED_PLACEHOLDER.to_string()));
                } else {
                    out.insert(key.clone(), redact_json(child));
                }
            }
            Value::Object(out)
        }
        Value::Array(items) => Value::Array(items.iter().map(redact_json).collect()),
        other => other.clone(),
    }
}

impl Redact for Target {
    fn redacted(&self) -> Self {
        let transport = match &self.transport {
            Transport::Stdio { command, args, env } => {
                let env = env
                    .iter()
                    .map(|(name, value)| {
                        let masked = if is_sensitive_key(name) {
                            REDACTED_PLACEHOLDER.to_string()
                        } else {
                            value.clone()
                        };
                        (name.clone(), masked)
                    })
                    .collect();
                Transport::Stdio {
                    command: command.clone(),
                    args: args.clone(),
                    env,
                }
            }
            Transport::Http { url, headers } => {
                let headers = headers
                    .iter()
                    .map(|(name, value)| {
                        let masked = if is_sensitive_header(name) {
                            REDACTED_PLACEHOLDER.to_string()
                        } else {
                            value.clone()
                        };
                        (name.clone(), masked)
                    })
                    .collect();
                Transport::Http {
                    url: url.clone(),
                    headers,
                }
            }
        };
        Self {
            transport,
            timeout_ms: self.timeout_ms,
        }
    }
}

impl Redact for ReproInfo {
    fn redacted(&self) -> Self {
        Self {
            seed: self.seed,
            tool_call: redact_json(&self.tool_call),
            transport: self.transport.clone(),
            composition_trail: self.composition_trail.clone(),
        }
    }
}

impl Redact for Finding {
    fn redacted(&self) -> Self {
        Self {
            id: self.id.clone(),
            kind: self.kind.clone(),
            severity: self.severity,
            tool: self.tool.clone(),
            // `message` and `details` carry server-supplied text (error
            // strings, echoed payload fragments). Run them through the
            // string-level redactor so a tool that echoes credentials
            // back doesn't leak them into corpus files. Best-effort:
            // see `docs/security.md`.
            message: redact_string(&self.message),
            details: redact_string(&self.details),
            repro: self.repro.redacted(),
            timestamp: self.timestamp,
        }
    }
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::collections::HashMap;

    #[test]
    fn header_authorization_is_sensitive() {
        assert!(is_sensitive_header("Authorization"));
        assert!(is_sensitive_header("authorization"));
        assert!(is_sensitive_header("AUTHORIZATION"));
    }

    #[test]
    fn header_cookie_variants_are_sensitive() {
        assert!(is_sensitive_header("Cookie"));
        assert!(is_sensitive_header("Set-Cookie"));
        assert!(is_sensitive_header("set-cookie"));
        assert!(is_sensitive_header("Proxy-Authorization"));
    }

    #[test]
    fn header_x_token_pattern_is_sensitive() {
        assert!(is_sensitive_header("X-API-Token"));
        assert!(is_sensitive_header("X-Auth-Token"));
        assert!(is_sensitive_header("x-custom-token"));
        assert!(is_sensitive_header("X-Bearer"));
    }

    #[test]
    fn header_api_key_variants_are_sensitive() {
        assert!(is_sensitive_header("X-API-Key"));
        assert!(is_sensitive_header("Api-Key"));
        assert!(is_sensitive_header("apikey"));
    }

    #[test]
    fn header_benign_is_not_sensitive() {
        assert!(!is_sensitive_header("Content-Type"));
        assert!(!is_sensitive_header("Accept"));
        assert!(!is_sensitive_header("User-Agent"));
        assert!(!is_sensitive_header("X-Request-Id"));
    }

    #[test]
    fn key_password_is_sensitive() {
        assert!(is_sensitive_key("password"));
        assert!(is_sensitive_key("passwd"));
        assert!(is_sensitive_key("user_password"));
    }

    #[test]
    fn key_secret_and_token_variants_are_sensitive() {
        assert!(is_sensitive_key("secret"));
        assert!(is_sensitive_key("clientSecret"));
        assert!(is_sensitive_key("access_token"));
        assert!(is_sensitive_key("private_key"));
    }

    #[test]
    fn key_auth_word_is_sensitive_only_as_whole_word() {
        assert!(is_sensitive_key("auth"));
        assert!(is_sensitive_key("auth_kind"));
        assert!(is_sensitive_key("kind-auth"));
        // "author" and "authentik" must NOT trigger.
        assert!(!is_sensitive_key("author"));
        assert!(!is_sensitive_key("authority"));
    }

    #[test]
    fn key_benign_is_not_sensitive() {
        assert!(!is_sensitive_key("name"));
        assert!(!is_sensitive_key("id"));
        assert!(!is_sensitive_key("value"));
        assert!(!is_sensitive_key("count"));
    }

    #[test]
    fn redact_json_walks_nested_objects() {
        let input = json!({
            "user": "alice",
            "credentials": {
                "password": "p@ss",
                "api_key": "secret-123"
            },
            "items": [
                { "value": 1, "token": "t-1" },
                { "value": 2, "token": "t-2" }
            ]
        });
        let output = redact_json(&input);
        assert_eq!(output["user"], json!("alice"));
        assert_eq!(
            output["credentials"]["password"],
            json!(REDACTED_PLACEHOLDER)
        );
        assert_eq!(
            output["credentials"]["api_key"],
            json!(REDACTED_PLACEHOLDER)
        );
        assert_eq!(output["items"][0]["value"], json!(1));
        assert_eq!(output["items"][0]["token"], json!(REDACTED_PLACEHOLDER));
        assert_eq!(output["items"][1]["token"], json!(REDACTED_PLACEHOLDER));
    }

    #[test]
    fn redact_is_idempotent() {
        let input = json!({"password": "x", "api_key": "y"});
        let once = redact_json(&input);
        let twice = redact_json(&once);
        assert_eq!(once, twice);
    }

    #[test]
    fn redact_target_http_masks_authorization() {
        let mut headers = HashMap::new();
        headers.insert("Authorization".to_string(), "Bearer abc123".to_string());
        headers.insert("Content-Type".to_string(), "application/json".to_string());
        let target = Target {
            transport: Transport::Http {
                url: "http://localhost".to_string(),
                headers,
            },
            timeout_ms: 1000,
        };
        let redacted = target.redacted();
        let Transport::Http { headers, .. } = &redacted.transport else {
            panic!("expected http transport");
        };
        assert_eq!(
            headers.get("Authorization").map(String::as_str),
            Some(REDACTED_PLACEHOLDER)
        );
        assert_eq!(
            headers.get("Content-Type").map(String::as_str),
            Some("application/json")
        );
    }

    #[test]
    fn redact_target_stdio_masks_secret_env() {
        let mut env = HashMap::new();
        env.insert("API_TOKEN".to_string(), "tok-1".to_string());
        env.insert("PATH".to_string(), "/usr/bin".to_string());
        let target = Target {
            transport: Transport::Stdio {
                command: "python3".to_string(),
                args: vec!["server.py".to_string()],
                env,
            },
            timeout_ms: 1000,
        };
        let redacted = target.redacted();
        let Transport::Stdio { env, .. } = &redacted.transport else {
            panic!("expected stdio transport");
        };
        assert_eq!(
            env.get("API_TOKEN").map(String::as_str),
            Some(REDACTED_PLACEHOLDER)
        );
        assert_eq!(env.get("PATH").map(String::as_str), Some("/usr/bin"));
    }

    #[test]
    fn redact_string_masks_bearer_tokens() {
        let input = "got Authorization: Bearer abcDEF123456 from server";
        let output = redact_string(input);
        assert!(
            output.contains(REDACTED_PLACEHOLDER),
            "expected redaction in {output:?}"
        );
        assert!(!output.contains("abcDEF123456"));
    }

    #[test]
    fn redact_string_masks_kv_secrets() {
        let cases = [
            "error: api_key=sk-abcdef12345 not found",
            "params: password: hunter22 expired",
            r#"{"access_token": "tok-1234"}"#,
        ];
        for input in cases {
            let output = redact_string(input);
            assert!(
                output.contains(REDACTED_PLACEHOLDER),
                "expected redaction in {output:?}"
            );
        }
    }

    #[test]
    fn redact_string_passes_through_benign_text() {
        let benign = "tool returned 5 items in 12ms";
        assert_eq!(redact_string(benign), benign);
    }

    #[test]
    fn redact_finding_masks_message_and_details() {
        use crate::finding::{Finding, FindingKind};
        let finding = Finding::new(
            FindingKind::SchemaViolation,
            "tool",
            "auth failed: api_key=sk-leaked-abc123",
            "server response: Authorization: Bearer leak-token-xyz",
            ReproInfo {
                seed: 1,
                tool_call: json!({}),
                transport: "stdio".to_string(),
                composition_trail: Vec::new(),
            },
        );
        let redacted = finding.redacted();
        assert!(redacted.message.contains(REDACTED_PLACEHOLDER));
        assert!(!redacted.message.contains("sk-leaked-abc123"));
        assert!(redacted.details.contains(REDACTED_PLACEHOLDER));
        assert!(!redacted.details.contains("leak-token-xyz"));
    }

    #[test]
    fn redact_finding_masks_repro_payload() {
        use crate::finding::{Finding, FindingKind};
        let finding = Finding::new(
            FindingKind::Crash,
            "tool",
            "msg",
            "details",
            ReproInfo {
                seed: 1,
                tool_call: json!({"password": "p", "name": "alice"}),
                transport: "stdio".to_string(),
                composition_trail: Vec::new(),
            },
        );
        let original_id = finding.id.clone();
        let redacted = finding.redacted();
        // ID is preserved (computed from the original payload).
        assert_eq!(redacted.id, original_id);
        assert_eq!(
            redacted.repro.tool_call["password"],
            json!(REDACTED_PLACEHOLDER)
        );
        assert_eq!(redacted.repro.tool_call["name"], json!("alice"));
    }
}