@strixgov/mcp-proxy 0.2.5 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/types.d.ts CHANGED
@@ -2,12 +2,60 @@
2
2
  * TypeScript surface for @strixgov/mcp-proxy.
3
3
  */
4
4
 
5
- export interface UpstreamConfig {
5
+ /** A child-process (stdio) upstream. */
6
+ export interface StdioUpstreamConfig {
6
7
  command: string;
7
8
  args?: string[];
8
9
  env?: Record<string, string>;
9
10
  }
10
11
 
12
+ /** A hosted MCP server reached over Streamable HTTP. Credentials come from the environment. */
13
+ export interface HttpUpstreamConfig {
14
+ url: string;
15
+ headers?: Record<string, string | { fromEnv: string; prefix?: string }>;
16
+ allowedOrigins?: string[];
17
+ allowPrivateNetwork?: boolean;
18
+ timeoutMs?: number;
19
+ }
20
+
21
+ export type UpstreamConfig = StdioUpstreamConfig | HttpUpstreamConfig;
22
+
23
+ export interface SecretScanningOptions {
24
+ /** Credential-shaped strings in a call's arguments. Default "block". */
25
+ arguments?: "block" | "warn" | "off";
26
+ /** Credential-shaped strings in a tool's result. Default "warn". */
27
+ results?: "redact" | "warn" | "off";
28
+ }
29
+
30
+ /** One constraint on a call's arguments; exactly one of the check fields besides `path`. */
31
+ export interface ArgumentRule {
32
+ path: string;
33
+ required?: true;
34
+ max?: number;
35
+ min?: number;
36
+ maxLength?: number;
37
+ in?: unknown[];
38
+ pattern?: string;
39
+ notPattern?: string;
40
+ withinPath?: string;
41
+ }
42
+
43
+ export interface ConfigDescription {
44
+ serverId: string;
45
+ upstream: object;
46
+ capabilityCount: number;
47
+ policyDefault: string;
48
+ approval: string;
49
+ storagePath: string;
50
+ toolPinning: string;
51
+ hideDeniedTools: boolean;
52
+ secretScanning: { arguments: string; results: string };
53
+ argumentRuleTools: string[];
54
+ auditLog: "off" | "file" | "storagePath";
55
+ rateLimitedTools: string[];
56
+ warnings: string[];
57
+ }
58
+
11
59
  export interface ProxyOptions {
12
60
  upstream: UpstreamConfig;
13
61
  serverId?: string;
@@ -31,6 +79,15 @@ export interface ProxyOptions {
31
79
  pollIntervalMs?: number;
32
80
  };
33
81
  storagePath?: string;
82
+ keyPath?: string;
83
+ toolPinning?: "block" | "warn" | "off";
84
+ repinTools?: boolean;
85
+ hideDeniedTools?: boolean;
86
+ rateLimits?: Record<string, { windowMs: number; max: number; perActor?: boolean }>;
87
+ secretScanning?: false | SecretScanningOptions;
88
+ argumentRules?: Record<string, ArgumentRule[]>;
89
+ /** Append every audit event as one JSON line: true = <storagePath>/audit.jsonl, or a file path. */
90
+ auditLog?: boolean | string;
34
91
  signingKey?: object;
35
92
  connectedMode?: { kernelUrl: string; apiKey: string; tenantId: string };
36
93
  onReceipt?: (receipt: object) => void;
@@ -51,6 +108,14 @@ export interface ProxyConfigFile {
51
108
  policy?: ProxyOptions["policy"];
52
109
  approval?: ProxyOptions["approval"];
53
110
  storagePath?: string;
111
+ keyPath?: string;
112
+ toolPinning?: ProxyOptions["toolPinning"];
113
+ hideDeniedTools?: boolean;
114
+ repinTools?: boolean;
115
+ rateLimits?: ProxyOptions["rateLimits"];
116
+ secretScanning?: ProxyOptions["secretScanning"];
117
+ argumentRules?: ProxyOptions["argumentRules"];
118
+ auditLog?: ProxyOptions["auditLog"];
54
119
  }
55
120
 
56
121
  export declare function startProxy(opts: ProxyOptions): Promise<ProxyHandle>;
@@ -58,3 +123,20 @@ export declare function loadConfig(filePath: string): Promise<ProxyConfigFile>;
58
123
  export declare function resolveCapabilities(
59
124
  capabilities: string | Array<object> | undefined,
60
125
  ): Promise<Array<object> | undefined>;
126
+
127
+ export declare function describeConfig(cfg: ProxyConfigFile, capabilities?: Array<object>): ConfigDescription;
128
+ export declare function unknownConfigKeys(cfg: object): string[];
129
+
130
+ export declare const SECRET_IN_ARGUMENTS: "SECRET_IN_ARGUMENTS";
131
+ export declare const ARGUMENT_RULE_VIOLATION: "ARGUMENT_RULE_VIOLATION";
132
+ export declare const SECRET_PATTERNS: ReadonlyArray<{ name: string; re: RegExp }>;
133
+ export declare function scanValue(value: unknown): {
134
+ findings: Array<{ pattern: string; path: string }>;
135
+ complete: boolean;
136
+ };
137
+ export declare function redactText(text: string): { text: string; patterns: string[]; count: number };
138
+ export declare function redactValue(value: unknown): { value: unknown; patterns: string[]; count: number; complete: boolean };
139
+ export declare function createContentGuard(opts?: {
140
+ secretScanning?: false | SecretScanningOptions;
141
+ argumentRules?: Record<string, ArgumentRule[]>;
142
+ }): object;
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Regression tests for the findings of the 360 review of the content guard.
3
+ * Credential-shaped values are fabricated, format-only strings.
4
+ */
5
+ import test from "node:test";
6
+ import assert from "node:assert/strict";
7
+ import { spawnSync } from "node:child_process";
8
+ import fs from "node:fs";
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+ import url from "node:url";
12
+
13
+ import { scanValue, redactText, redactValue, compileArgumentRules, createContentGuard } from "../src/content-guard.mjs";
14
+
15
+ const AWS = "AKIA" + "IOSFODNN7EXAMPLE";
16
+ const GH = "ghp_" + "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8";
17
+ const BIN = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), "..", "bin", "strix-mcp-proxy.mjs");
18
+
19
+ test("jwt pattern is linear: a long run of near-tokens does not stall the scan", () => {
20
+ const hostile = "eyJAAAAAAAA-".repeat(20_000); // 240k characters, no dot
21
+ const t0 = process.hrtime.bigint();
22
+ scanValue({ a: hostile });
23
+ const ms = Number(process.hrtime.bigint() - t0) / 1e6;
24
+ assert.ok(ms < 500, `scan took ${ms.toFixed(0)} ms`);
25
+ });
26
+
27
+ test("private key: the whole block is redacted, not only the BEGIN line", () => {
28
+ const BEGIN = "-----BEGIN " + "RSA PRIVATE KEY-----";
29
+ const END = "-----END " + "RSA PRIVATE KEY-----";
30
+ const pem = `${BEGIN}\nMIIEowIBAAKCAQEAfakefakefake\nbase64bodyline\n${END}`;
31
+ const r = redactText(`before ${pem} after`);
32
+ assert.equal(r.text, "before [REDACTED:private_key_block] after");
33
+ const open = redactText("-----BEGIN " + "PRIVATE KEY-----\nbody with no end marker");
34
+ assert.ok(!open.text.includes("body with"), "an unterminated block is redacted to the end");
35
+ });
36
+
37
+ test("redact never returns an unscanned subtree", () => {
38
+ const items = Array.from({ length: 10_010 }, (_, i) => (i === 10_005 ? GH : "x"));
39
+ const r = redactValue(items);
40
+ assert.equal(r.complete, false);
41
+ assert.ok(!JSON.stringify(r.value).includes(GH));
42
+ let deep = GH;
43
+ for (let i = 0; i < 40; i += 1) deep = { n: deep };
44
+ assert.ok(!JSON.stringify(redactValue(deep).value).includes(GH));
45
+ });
46
+
47
+ test("boundaries: adjacent underscores and delimiters do not hide a key; adjacent letters do not make a false match", () => {
48
+ for (const text of [`secret_${AWS}`, `${AWS}_x`, `TOKEN_${GH}`, `x=${AWS}`, `a-${GH}`]) {
49
+ assert.ok(scanValue(text).findings.length >= 1, text);
50
+ }
51
+ assert.equal(scanValue(`x${AWS}`).findings.length, 0, "an adjacent letter means it is part of a longer word");
52
+ });
53
+
54
+ test("more formats are recognised, without the matched text", () => {
55
+ const samples = {
56
+ gitlab_token: "glpat-" + "a".repeat(20),
57
+ stripe_webhook_secret: "whsec_" + "a".repeat(24),
58
+ huggingface_token: "hf_" + "a".repeat(34),
59
+ sendgrid_key: "SG." + "a".repeat(16) + "." + "b".repeat(16),
60
+ google_oauth_token: "ya29." + "a".repeat(20),
61
+ openai_api_key: "sk-" + "a".repeat(48),
62
+ url_with_password: "postgres://app:hunter2pw@db.internal:5432/x",
63
+ jwt: "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.",
64
+ };
65
+ for (const [name, text] of Object.entries(samples)) {
66
+ const found = scanValue({ v: text }).findings.map((f) => f.pattern);
67
+ assert.ok(found.includes(name), `${name}: found ${found.join(",") || "nothing"}`);
68
+ }
69
+ assert.equal(scanValue("https://example.com/path?x=1").findings.length, 0);
70
+ assert.equal(scanValue("see https://user@example.com/docs").findings.length, 0, "a user name alone is not a password");
71
+ });
72
+
73
+ test("redaction keeps shape: __proto__ stays an own key and colliding keys do not overwrite", () => {
74
+ const input = JSON.parse('{"__proto__":{"a":1},"ok":2}');
75
+ const out = redactValue(input).value;
76
+ assert.ok(Object.prototype.hasOwnProperty.call(out, "__proto__"));
77
+ assert.equal(JSON.parse(JSON.stringify(out)).ok, 2);
78
+ const k1 = "ghp_" + "A".repeat(36);
79
+ const k2 = "ghp_" + "B".repeat(36);
80
+ const two = redactValue({ [k1]: 1, [k2]: 2 }).value;
81
+ assert.equal(Object.keys(two).length, 2);
82
+ });
83
+
84
+ test("rules: a pattern that can take exponential time is refused at load, and long ones too", () => {
85
+ assert.throws(() => compileArgumentRules({ t: [{ path: "a", notPattern: "(a+)+b" }] }), /exponential/);
86
+ assert.throws(() => compileArgumentRules({ t: [{ path: "a", pattern: "^(\\w+\\s?)*$" }] }), /exponential/);
87
+ assert.throws(() => compileArgumentRules({ t: [{ path: "a", pattern: "a".repeat(1_001) }] }), /longer than/);
88
+ assert.doesNotThrow(() => compileArgumentRules({ t: [{ path: "a", pattern: "^[a-z]{1,8}-\\d+$" }] }));
89
+ });
90
+
91
+ test("error text is scrubbed in redact mode", () => {
92
+ const msg = `auth failed for key ${AWS}`;
93
+ const g = createContentGuard({ secretScanning: { results: "redact" } });
94
+ const s = g.scrubError(msg);
95
+ assert.equal(s.changed, true);
96
+ assert.ok(!s.message.includes(AWS));
97
+ });
98
+
99
+ test("binary content is reported as not scanned", () => {
100
+ const g = createContentGuard({ secretScanning: { results: "warn" } });
101
+ const { report } = g.checkResult("t", { content: [{ type: "image", data: "AAAA", mimeType: "image/png" }, { type: "text", text: "hi" }] });
102
+ const note = report.find((e) => e.kind === "result.unscanned_content");
103
+ assert.ok(note);
104
+ assert.equal(note.detail.items, 1);
105
+ });
106
+
107
+ test("CLI: --secret-scanning flags apply together with --config", () => {
108
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "strix-flag-"));
109
+ try {
110
+ const file = path.join(dir, "c.json");
111
+ fs.writeFileSync(file, JSON.stringify({ upstream: { command: "node", args: ["-e", "0"] }, capabilities: [] }));
112
+ const out = spawnSync(process.execPath, [BIN, "--config", file, "--secret-scanning-args", "bogus"], { encoding: "utf8", timeout: 15_000 });
113
+ assert.notEqual(out.status, 0, "a bad flag value must be rejected, not ignored");
114
+ assert.match(out.stderr, /secretScanning.arguments/);
115
+ } finally {
116
+ fs.rmSync(dir, { recursive: true, force: true });
117
+ }
118
+ });
119
+
120
+ test("--validate output survives a pipe at large size", () => {
121
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "strix-big-"));
122
+ try {
123
+ const rules = {};
124
+ for (let i = 0; i < 6_000; i += 1) rules[`tool_${i}`] = [{ path: "a", max: 1 }];
125
+ const file = path.join(dir, "c.json");
126
+ fs.writeFileSync(file, JSON.stringify({ upstream: { command: "node", args: [] }, capabilities: [], argumentRules: rules }));
127
+ const out = spawnSync(process.execPath, [BIN, "--validate", "--config", file], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 30_000 });
128
+ assert.doesNotThrow(() => JSON.parse(out.stdout));
129
+ } finally {
130
+ fs.rmSync(dir, { recursive: true, force: true });
131
+ }
132
+ });
133
+
134
+ test("rules: repeated groups with overlapping alternation are refused at load", () => {
135
+ for (const pat of ["^(a|a)*$", "^(a|aa)+$", "^(\\w|\\d)+$", "^(?:a|a)+$", "^(.|.)*$"]) {
136
+ assert.throws(() => compileArgumentRules({ t: [{ path: "a", pattern: pat }] }), /exponential/, pat);
137
+ }
138
+ assert.doesNotThrow(() => compileArgumentRules({ t: [{ path: "a", pattern: "^(?:get|list)_[a-z]+$" }] }), "an alternation that is not repeated is fine");
139
+ });
140
+
141
+ test("error text is scrubbed for the audit log even when result scanning is off", () => {
142
+ const g = createContentGuard({ secretScanning: { results: "off" } });
143
+ assert.equal(g.scrubError(`bad key ${AWS}`).message.includes(AWS), false);
144
+ });
145
+
146
+ test("a credential used as a root-level key gives the path <key>, with no leading dot", () => {
147
+ const { findings } = scanValue({ [AWS]: 1 });
148
+ assert.ok(findings.every((f) => !f.path.startsWith(".")));
149
+ });
150
+
151
+ test("--validate: auditLog true with a null storagePath, and a relative auditLog path, are warned about", async () => {
152
+ const { describeConfig } = await import("../src/config.mjs");
153
+ const base = { upstream: { command: "node", args: [] } };
154
+ const a = describeConfig({ ...base, storagePath: null, auditLog: true }, []);
155
+ assert.ok(a.warnings.some((w) => /storagePath is null/.test(w)));
156
+ assert.match(a.storagePath, /ephemeral/);
157
+ assert.ok(describeConfig({ ...base, auditLog: "logs/a.jsonl" }, []).warnings.some((w) => /relative path/.test(w)));
158
+ assert.ok(!describeConfig({ ...base, auditLog: "~/a.jsonl" }, []).warnings.some((w) => /relative path/.test(w)));
159
+ });
@@ -0,0 +1,387 @@
1
+ /**
2
+ * Content guard: credential scanning of arguments and results, and argument
3
+ * rules. Test credentials are assembled at run time from fragments so that no
4
+ * credential-shaped string is committed to the repository.
5
+ */
6
+
7
+ import test from "node:test";
8
+ import assert from "node:assert/strict";
9
+
10
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
11
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
12
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
13
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
14
+ import { verifyReceipt, computeInvocationHash } from "@strixgov/tool-gateway";
15
+
16
+ import { startProxy } from "../src/index.mjs";
17
+ import {
18
+ scanValue,
19
+ redactText,
20
+ redactValue,
21
+ compileArgumentRules,
22
+ evaluateArgumentRules,
23
+ createContentGuard,
24
+ SECRET_PATTERNS,
25
+ } from "../src/content-guard.mjs";
26
+
27
+ // Fabricated, format-only values. None is a real credential.
28
+ const AWS = "AKIA" + "IOSFODNN7EXAMPLE";
29
+ const GH = "ghp_" + "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8";
30
+ const STRIPE = "sk_live_" + "abcdefghijklmnop1234";
31
+ const PEM = "-----BEGIN " + "RSA PRIVATE KEY-----";
32
+ const JWT = "eyJhbGciOiJIUzI1NiJ9" + "." + "eyJzdWIiOiIxMjM0NTY3ODkwIn0" + "." + "dBjftJeZ4CVPmB92K27uhbUJU1p1r";
33
+
34
+ // ─── unit: scanning ─────────────────────────────────────────────────────────
35
+
36
+ test("scan: finds each listed credential format and reports the path, never the text", () => {
37
+ const cases = [
38
+ ["aws_access_key_id", AWS],
39
+ ["github_token", GH],
40
+ ["stripe_key", STRIPE],
41
+ ["private_key_block", PEM],
42
+ ["jwt", JWT],
43
+ ];
44
+ for (const [pattern, secret] of cases) {
45
+ const { findings, complete } = scanValue({ note: { body: `use ${secret} now` } });
46
+ assert.equal(complete, true);
47
+ assert.deepEqual(findings, [{ pattern, path: "note.body" }], pattern);
48
+ assert.ok(!JSON.stringify(findings).includes(secret), "the matched text must not be in the findings");
49
+ }
50
+ });
51
+
52
+ test("scan: array positions, object keys and nested values are all covered", () => {
53
+ const { findings } = scanValue({ list: ["ok", `x ${AWS}`], [GH]: "value" });
54
+ assert.deepEqual(
55
+ findings.map((f) => `${f.pattern}@${f.path}`).sort(),
56
+ ["aws_access_key_id@list[1]", "github_token@<key>"],
57
+ );
58
+ });
59
+
60
+ test("scan: ordinary text and near-misses are not flagged", () => {
61
+ const clean = {
62
+ prose: "the password is stored in the vault",
63
+ short: "AKIA123",
64
+ other: "sk_live_short",
65
+ hash: "d41d8cd98f00b204e9800998ecf8427e",
66
+ uuid: "123e4567-e89b-12d3-a456-426614174000",
67
+ email: "person@example.com",
68
+ };
69
+ assert.deepEqual(scanValue(clean).findings, []);
70
+ });
71
+
72
+ test("scan: a value too deep to scan is reported as incomplete, not clean", () => {
73
+ let deep = "end";
74
+ for (let i = 0; i < 40; i++) deep = { child: deep };
75
+ assert.equal(scanValue(deep).complete, false);
76
+ });
77
+
78
+ test("scan: a pattern list sanity check (every pattern compiles and is global)", () => {
79
+ for (const p of SECRET_PATTERNS) {
80
+ assert.ok(p.re.global, `${p.name} must be global so redaction replaces every match`);
81
+ assert.ok(p.name.length > 0);
82
+ }
83
+ });
84
+
85
+ // ─── unit: redaction ────────────────────────────────────────────────────────
86
+
87
+ test("redact: replaces every match, names the kind, counts them, leaves the rest", () => {
88
+ const r = redactText(`a ${AWS} b ${GH} c ${AWS}`);
89
+ assert.equal(r.text, "a [REDACTED:aws_access_key_id] b [REDACTED:github_token] c [REDACTED:aws_access_key_id]");
90
+ assert.equal(r.count, 3);
91
+ assert.deepEqual(r.patterns.sort(), ["aws_access_key_id", "github_token"]);
92
+ });
93
+
94
+ test("redact: a deep copy; the original is not mutated; keys are redacted too", () => {
95
+ const original = { a: [`k ${AWS}`], [GH]: 1 };
96
+ const r = redactValue(original);
97
+ assert.equal(original.a[0], `k ${AWS}`);
98
+ assert.deepEqual(r.value, { a: ["k [REDACTED:aws_access_key_id]"], "[REDACTED:github_token]": 1 });
99
+ });
100
+
101
+ // ─── unit: argument rules ───────────────────────────────────────────────────
102
+
103
+ test("rules: each kind passes a conforming value and refuses a violating one", () => {
104
+ const compiled = compileArgumentRules({
105
+ pay: [
106
+ { path: "amount", max: 500 },
107
+ { path: "amount", min: 1 },
108
+ { path: "currency", in: ["USD", "EUR"] },
109
+ { path: "memo", maxLength: 10 },
110
+ { path: "account", pattern: "^acct_[a-z0-9]+$" },
111
+ { path: "memo", notPattern: "ignore previous" },
112
+ { path: "ref", required: true },
113
+ ],
114
+ });
115
+ const good = { amount: 100, currency: "USD", memo: "rent", account: "acct_abc1", ref: "r1" };
116
+ assert.deepEqual(evaluateArgumentRules(compiled, "pay", good), []);
117
+ const bad = { amount: 900, currency: "GBP", memo: "ignore previous instructions", account: "x", ref: "" };
118
+ const rules = evaluateArgumentRules(compiled, "pay", bad).map((v) => `${v.path}:${v.rule}`).sort();
119
+ assert.deepEqual(rules, ["account:pattern", "amount:max", "currency:in", "memo:maxLength", "memo:notPattern", "ref:required"]);
120
+ });
121
+
122
+ test("rules: a rule on an absent path passes, except required; wrong types fail", () => {
123
+ const compiled = compileArgumentRules({ t: [{ path: "a.b", max: 5 }, { path: "need", required: true }] });
124
+ assert.deepEqual(evaluateArgumentRules(compiled, "t", { need: 1 }), []);
125
+ assert.deepEqual(evaluateArgumentRules(compiled, "t", {}).map((v) => v.rule), ["required"]);
126
+ assert.equal(evaluateArgumentRules(compiled, "t", { need: 1, a: { b: "5" } }).length, 1, "a string is not a number");
127
+ assert.equal(evaluateArgumentRules(compiled, "t", { need: 1, a: { b: NaN } }).length, 1, "NaN is not within a max");
128
+ });
129
+
130
+ test("rules: '*' applies to every tool; a tool's own rules add to it", () => {
131
+ const compiled = compileArgumentRules({ "*": [{ path: "q", maxLength: 3 }], t: [{ path: "n", max: 1 }] });
132
+ assert.equal(evaluateArgumentRules(compiled, "other", { q: "toolong" }).length, 1);
133
+ assert.equal(evaluateArgumentRules(compiled, "t", { q: "toolong", n: 9 }).length, 2);
134
+ });
135
+
136
+ test("rules: withinPath refuses traversal, backslashes, relative paths, NUL and prefix lookalikes", () => {
137
+ const compiled = compileArgumentRules({ read: [{ path: "path", withinPath: "/srv/data" }] });
138
+ const ok = (p) => evaluateArgumentRules(compiled, "read", { path: p }).length === 0;
139
+ assert.equal(ok("/srv/data"), true);
140
+ assert.equal(ok("/srv/data/a/b.txt"), true);
141
+ assert.equal(ok("/srv/data/../etc/passwd"), false);
142
+ assert.equal(ok("/srv/data/a/../../x"), false);
143
+ assert.equal(ok("/srv/data\\..\\..\\etc"), false);
144
+ assert.equal(ok("/srv/database/x"), false, "a sibling that shares the prefix is outside");
145
+ assert.equal(ok("relative/path"), false);
146
+ assert.equal(ok("/srv/data/x\0.txt"), false);
147
+ assert.equal(ok(42), false);
148
+ });
149
+
150
+ test("rules: a violation never carries the offending value", () => {
151
+ const compiled = compileArgumentRules({ t: [{ path: "token", notPattern: "secretvalue" }] });
152
+ const v = evaluateArgumentRules(compiled, "t", { token: "secretvalue-123" });
153
+ assert.equal(v.length, 1);
154
+ assert.ok(!JSON.stringify(v).includes("secretvalue"));
155
+ });
156
+
157
+ test("rules: bad specs are startup errors naming the location", () => {
158
+ assert.throws(() => compileArgumentRules({ t: [] }), /non-empty array/);
159
+ assert.throws(() => compileArgumentRules({ t: [{ path: "a" }] }), /exactly one of/);
160
+ assert.throws(() => compileArgumentRules({ t: [{ path: "a", max: 1, min: 0 }] }), /exactly one of/);
161
+ assert.throws(() => compileArgumentRules({ t: [{ path: "a", pattern: "(" }] }), /not a valid regular expression/);
162
+ assert.throws(() => compileArgumentRules({ t: [{ path: "a", withinPath: "relative" }] }), /absolute POSIX/);
163
+ assert.throws(() => compileArgumentRules({ t: [{ max: 1 }] }), /path must be/);
164
+ assert.throws(() => compileArgumentRules([]), /must be an object/);
165
+ });
166
+
167
+ test("guard: bad modes are startup errors", () => {
168
+ assert.throws(() => createContentGuard({ secretScanning: { arguments: "strict" } }), /arguments must be one of/);
169
+ assert.throws(() => createContentGuard({ secretScanning: { results: "block" } }), /results must be one of/);
170
+ });
171
+
172
+ // ─── e2e ────────────────────────────────────────────────────────────────────
173
+
174
+ const CAPS = [
175
+ { id: "mcp.demo.read_note", name: "read_note", risk: "LOW", mode: "READ" },
176
+ { id: "mcp.demo.write_note", name: "write_note", risk: "MEDIUM", mode: "WRITE" },
177
+ { id: "mcp.demo.pay", name: "pay", risk: "MEDIUM", mode: "WRITE" },
178
+ ];
179
+
180
+ async function startUpstream(resultText = "ok") {
181
+ const calls = [];
182
+ const server = new Server({ name: "demo", version: "0.0.1" }, { capabilities: { tools: {} } });
183
+ const defs = ["read_note", "write_note", "pay"].map((name) => ({ name, description: name, inputSchema: { type: "object" } }));
184
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: defs }));
185
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
186
+ calls.push({ name: req.params.name, args: req.params.arguments });
187
+ return { content: [{ type: "text", text: resultText }] };
188
+ });
189
+ const [c, s] = InMemoryTransport.createLinkedPair();
190
+ await server.connect(s);
191
+ const upstreamClient = new Client({ name: "u", version: "0.0.1" }, { capabilities: {} });
192
+ await upstreamClient.connect(c);
193
+ return { calls, upstreamClient };
194
+ }
195
+
196
+ async function startGuarded({ resultText, ...extra } = {}) {
197
+ const upstream = await startUpstream(resultText);
198
+ const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
199
+ const receipts = [];
200
+ const audits = [];
201
+ const proxy = await startProxy({
202
+ serverId: "demo",
203
+ capabilities: CAPS,
204
+ policy: { riskOverrides: { LOW: "ALLOW", MEDIUM: "ALLOW" }, default: "DENY" },
205
+ storagePath: null,
206
+ shadowDiscovery: false,
207
+ onReceipt: (r) => receipts.push(r),
208
+ onAudit: (e) => audits.push(e),
209
+ transport: { kind: "test", upstreamClient: upstream.upstreamClient, serverTransport: serverSide },
210
+ ...extra,
211
+ });
212
+ const client = new Client({ name: "consumer", version: "0.0.1" }, { capabilities: {} });
213
+ await client.connect(clientSide);
214
+ return { upstream, proxy, client, receipts, audits };
215
+ }
216
+
217
+ test("e2e: a credential in the arguments is refused by default, never reaches the upstream, and is not in the receipt", async () => {
218
+ const ctx = await startGuarded();
219
+ try {
220
+ await assert.rejects(
221
+ ctx.client.callTool({ name: "write_note", arguments: { body: `deploy key ${AWS}` } }),
222
+ /SECRET_IN_ARGUMENTS/,
223
+ );
224
+ assert.deepEqual(ctx.upstream.calls, [], "the call must not be sent");
225
+ const denial = ctx.receipts.at(-1);
226
+ assert.equal(denial.decision, "DENY");
227
+ assert.equal(denial.denialReason, "SECRET_IN_ARGUMENTS");
228
+ assert.equal(verifyReceipt(denial, ctx.proxy.signingKey.publicKey).signatureValid, true);
229
+ const everything = JSON.stringify({ receipts: ctx.receipts, audits: ctx.audits });
230
+ assert.ok(!everything.includes(AWS), "the credential must not appear in any receipt or audit event");
231
+ assert.ok(ctx.audits.some((a) => a.kind === "call.secret_detected" && a.detail.findings[0].pattern === "aws_access_key_id"));
232
+ // The receipt binds the arguments with the credential REDACTED: a hash of the
233
+ // real arguments would let anyone holding a guess of a low-entropy secret confirm it.
234
+ const redactedHash = computeInvocationHash({
235
+ capabilityId: denial.capabilityId,
236
+ action: "mcp.callTool:write_note",
237
+ args: { body: "deploy key [REDACTED:aws_access_key_id]" },
238
+ actorId: denial.actorId ?? "",
239
+ actorRole: denial.actorRole ?? "",
240
+ });
241
+ assert.equal(denial.invocationHash, redactedHash);
242
+ } finally {
243
+ await ctx.proxy.stop();
244
+ }
245
+ });
246
+
247
+ test("e2e: a clean call to the same tool still runs", async () => {
248
+ const ctx = await startGuarded();
249
+ try {
250
+ await ctx.client.callTool({ name: "write_note", arguments: { body: "nothing secret" } });
251
+ assert.equal(ctx.upstream.calls.length, 1);
252
+ } finally {
253
+ await ctx.proxy.stop();
254
+ }
255
+ });
256
+
257
+ test("e2e: arguments 'warn' reports and allows; 'off' and secretScanning:false do nothing", async () => {
258
+ for (const [label, opt] of [
259
+ ["warn", { arguments: "warn" }],
260
+ ["off", { arguments: "off" }],
261
+ ["false", false],
262
+ ]) {
263
+ const ctx = await startGuarded({ secretScanning: opt });
264
+ try {
265
+ await ctx.client.callTool({ name: "write_note", arguments: { body: AWS } });
266
+ assert.equal(ctx.upstream.calls.length, 1, `${label}: call goes through`);
267
+ const reported = ctx.audits.some((a) => a.kind === "call.secret_detected");
268
+ assert.equal(reported, label === "warn", `${label}: reported only in warn`);
269
+ } finally {
270
+ await ctx.proxy.stop();
271
+ }
272
+ }
273
+ });
274
+
275
+ test("e2e: results are reported by default and unchanged; redact mode rewrites what the client sees", async () => {
276
+ const text = `the key is ${GH}`;
277
+ const warn = await startGuarded({ resultText: text });
278
+ try {
279
+ const out = await warn.client.callTool({ name: "read_note", arguments: {} });
280
+ assert.equal(out.content[0].text, text, "default: the client gets the result as returned");
281
+ assert.ok(warn.audits.some((a) => a.kind === "result.secret_detected" && a.detail.mode === "warn"));
282
+ } finally {
283
+ await warn.proxy.stop();
284
+ }
285
+ const redact = await startGuarded({ resultText: text, secretScanning: { results: "redact" } });
286
+ try {
287
+ const out = await redact.client.callTool({ name: "read_note", arguments: {} });
288
+ assert.equal(out.content[0].text, "the key is [REDACTED:github_token]");
289
+ assert.ok(!JSON.stringify(redact.audits).includes(GH));
290
+ } finally {
291
+ await redact.proxy.stop();
292
+ }
293
+ });
294
+
295
+ test("e2e: argument rules refuse before the upstream, with a signed DENY that names the path and not the value", async () => {
296
+ const ctx = await startGuarded({
297
+ argumentRules: { pay: [{ path: "amount", max: 500 }, { path: "to", in: ["acct_known"] }] },
298
+ });
299
+ try {
300
+ await ctx.client.callTool({ name: "pay", arguments: { amount: 100, to: "acct_known" } });
301
+ assert.equal(ctx.upstream.calls.length, 1, "a conforming call runs");
302
+
303
+ await assert.rejects(
304
+ ctx.client.callTool({ name: "pay", arguments: { amount: 9000, to: "acct_other" } }),
305
+ /ARGUMENT_RULE_VIOLATION.*amount \(max\).*to \(in\)/,
306
+ );
307
+ assert.equal(ctx.upstream.calls.length, 1, "the violating call was not sent");
308
+ const denial = ctx.receipts.at(-1);
309
+ assert.equal(denial.denialReason, "ARGUMENT_RULE_VIOLATION");
310
+ assert.equal(verifyReceipt(denial, ctx.proxy.signingKey.publicKey).signatureValid, true);
311
+ assert.ok(!JSON.stringify(ctx.audits).includes("acct_other"));
312
+ } finally {
313
+ await ctx.proxy.stop();
314
+ }
315
+ });
316
+
317
+ test("e2e: rules cannot relax policy; a call policy denies stays denied", async () => {
318
+ const ctx = await startGuarded({
319
+ policy: { default: "DENY" },
320
+ argumentRules: { pay: [{ path: "amount", max: 500 }] },
321
+ });
322
+ try {
323
+ await assert.rejects(ctx.client.callTool({ name: "pay", arguments: { amount: 1 } }));
324
+ assert.equal(ctx.upstream.calls.length, 0);
325
+ } finally {
326
+ await ctx.proxy.stop();
327
+ }
328
+ });
329
+
330
+ test("scan: a credential used as an object key is masked in the path of what sits beneath it", () => {
331
+ const { findings } = scanValue({ [AWS]: { inner: GH } });
332
+ assert.ok(findings.length >= 2);
333
+ for (const f of findings) {
334
+ assert.ok(!f.path.includes(AWS), `path leaked the key: ${f.path}`);
335
+ assert.ok(!f.path.includes(GH));
336
+ }
337
+ assert.ok(findings.some((f) => f.path === "<key>.inner"));
338
+ });
339
+
340
+ test("e2e: auditLog writes one JSON line per audit event, with no credential in the file", async () => {
341
+ const fsm = await import("node:fs");
342
+ const osm = await import("node:os");
343
+ const pathm = await import("node:path");
344
+ const dir = fsm.mkdtempSync(pathm.join(osm.tmpdir(), "strix-auditlog-"));
345
+ const file = pathm.join(dir, "audit.jsonl");
346
+ const ctx = await startGuarded({ auditLog: file });
347
+ try {
348
+ await assert.rejects(ctx.client.callTool({ name: "write_note", arguments: { body: `k ${AWS}` } }), /SECRET_IN_ARGUMENTS/);
349
+ const text = fsm.readFileSync(file, "utf8");
350
+ const lines = text.trim().split("\n").map((l) => JSON.parse(l));
351
+ assert.ok(lines.length >= 1);
352
+ assert.ok(lines.every((l) => typeof l.ts === "string" && typeof l.kind === "string"));
353
+ assert.ok(lines.some((l) => l.kind === "call.secret_detected"));
354
+ assert.ok(!text.includes(AWS), "the credential must not be in the audit file");
355
+ assert.equal(fsm.statSync(file).mode & 0o077, 0, "file is owner-only");
356
+ } finally {
357
+ await ctx.proxy.stop();
358
+ fsm.rmSync(dir, { recursive: true, force: true });
359
+ }
360
+ });
361
+
362
+ test("startProxy: auditLog true without a storagePath is a startup error", async () => {
363
+ const upstream = await startUpstream();
364
+ const [, serverSide] = InMemoryTransport.createLinkedPair();
365
+ await assert.rejects(
366
+ startProxy({
367
+ serverId: "demo", capabilities: CAPS, storagePath: null, auditLog: true, shadowDiscovery: false,
368
+ transport: { kind: "test", upstreamClient: upstream.upstreamClient, serverTransport: serverSide },
369
+ }),
370
+ /auditLog: true needs a storagePath/,
371
+ );
372
+ });
373
+
374
+ test("startProxy: auditLog rejects a relative path, a bare ~, and ~user", async () => {
375
+ const upstream = await startUpstream();
376
+ for (const bad of ["logs/a.jsonl", "~", "~bob/a.jsonl"]) {
377
+ const [, serverSide] = InMemoryTransport.createLinkedPair();
378
+ await assert.rejects(
379
+ startProxy({
380
+ serverId: "demo", capabilities: CAPS, storagePath: null, auditLog: bad, shadowDiscovery: false,
381
+ transport: { kind: "test", upstreamClient: upstream.upstreamClient, serverTransport: serverSide },
382
+ }),
383
+ /auditLog must be/,
384
+ bad,
385
+ );
386
+ }
387
+ });