Skip to content

Commit 88aa583

Browse files
cliffhallclaude
andcommitted
feat(network): address #1387 review — form-encoded masking, cleaner flag, a11y (#1386)
Code-review feedback on the auth-response-body masking PR: - Extended masking to form-urlencoded bodies (finding #1): the token *request* is `application/x-www-form-urlencoded` and carries `code` / `code_verifier` / `client_secret` / `refresh_token`. `maskSecretsInBody` now masks those in form bodies too (preserving formatting; placeholder not percent-encoded). `code`/`code_verifier`/`client_assertion` are form-only sensitive keys — deliberately NOT masked in JSON, where `code` is usually an error/status code. - Replaced the double-stringify `hasSecrets` heuristic with an explicit masked-flag propagated out of `maskNode` (finding #2) — robust if the transform ever grows non-identity behavior, and one fewer serialization. - Reset reveal state on body change via `key={body}` remount instead of a setState-in-effect (finding #3; avoids the cascading-render lint rule). - a11y (finding #4): `aria-label` on the Reveal/Hide button and `aria-live` on the hidden/revealed status text. - Security tripwire comment near the `saveSession` listener (finding #6): captured auth bodies are unmasked at source (masking is UI-only), so any new post-token-exchange persistence path must redact first. Tests: form-encoded masking (token + refresh requests), JSON `code` NOT masked, non-object JSON pass-through, default-fetch wrapper. Story play + NetworkEntry tests updated for the new aria-labels and the now-masked form request body. Finding #5 (pretty-print asymmetry) is already handled by ContentViewer's JSON formatting; #4-aria and #6 are the doc/a11y bits. Also merges the squash-merged #1385 base from v2/main. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
1 parent 5274a8d commit 88aa583

6 files changed

Lines changed: 184 additions & 54 deletions

File tree

‎clients/web/src/components/groups/NetworkEntry/NetworkEntry.stories.tsx‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -108,16 +108,26 @@ export const AuthSuccess: Story = {
108108
args: { entry: authEntry, isListExpanded: true },
109109
play: async ({ canvasElement }) => {
110110
const canvas = within(canvasElement);
111-
// Token-response secrets are masked by default — the raw token must not be
112-
// visible until the user explicitly reveals it.
113-
await expect(canvas.getByText("Secrets hidden")).toBeInTheDocument();
111+
// Both bodies carry secrets: the form request (`code=…`) and the JSON
112+
// response (`access_token`). Both are masked by default — the raw values
113+
// must not be visible until explicitly revealed.
114+
const hidden = canvas.getAllByText("Secrets hidden");
115+
await expect(hidden.length).toBeGreaterThanOrEqual(2);
114116
await expect(canvasElement.textContent).not.toContain("eyJhbGciOiJSUzI1");
115117
await expect(canvasElement.textContent).toContain("••••••••");
116118
// Non-secret fields stay visible.
117119
await expect(canvasElement.textContent).toContain("Bearer");
118120

119-
await userEvent.click(canvas.getByRole("button", { name: "Reveal" }));
120-
await expect(canvas.getByText("Secrets revealed")).toBeInTheDocument();
121+
// Reveal every masked body and confirm the raw response token appears.
122+
const revealButtons = canvas.getAllByRole("button", {
123+
name: "Reveal secrets in body",
124+
});
125+
for (const button of revealButtons) {
126+
await userEvent.click(button);
127+
}
128+
await expect(canvas.getAllByText("Secrets revealed").length).toBe(
129+
revealButtons.length,
130+
);
121131
await expect(canvasElement.textContent).toContain("eyJhbGciOiJSUzI1");
122132
},
123133
};

‎clients/web/src/components/groups/NetworkEntry/NetworkEntry.test.tsx‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -219,21 +219,25 @@ describe("NetworkEntry", () => {
219219
expect(container.textContent).toContain("••••••••");
220220
expect(container.textContent).toContain("Bearer");
221221

222-
await user.click(screen.getByRole("button", { name: "Reveal" }));
222+
await user.click(
223+
screen.getByRole("button", { name: "Reveal secrets in body" }),
224+
);
223225

224226
expect(screen.getByText("Secrets revealed")).toBeInTheDocument();
225227
expect(container.textContent).toContain("super-secret-token");
226228

227229
// Toggling back re-masks.
228-
await user.click(screen.getByRole("button", { name: "Hide" }));
230+
await user.click(
231+
screen.getByRole("button", { name: "Hide secrets in body" }),
232+
);
229233
expect(container.textContent).not.toContain("super-secret-token");
230234
});
231235

232236
it("does not add a reveal toggle for non-secret bodies", () => {
233237
renderWithMantine(<NetworkEntry entry={baseEntry} isListExpanded={true} />);
234238
expect(screen.queryByText("Secrets hidden")).not.toBeInTheDocument();
235239
expect(
236-
screen.queryByRole("button", { name: "Reveal" }),
240+
screen.queryByRole("button", { name: "Reveal secrets in body" }),
237241
).not.toBeInTheDocument();
238242
});
239243
});

‎clients/web/src/components/groups/NetworkEntry/NetworkEntry.tsx‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,10 @@ const RevealButton = Button.withProps({
134134

135135
function BodyPreview({ body }: { body: string }) {
136136
// Reveal state for masked secrets. Hooks run before any early return so the
137-
// order stays stable across the too-large / has-secrets branches.
137+
// order stays stable across the too-large / has-secrets branches. The reveal
138+
// state resets when the body content changes because callers key
139+
// `<BodyPreview>` by `body` (remounting on swap), so a previously-revealed
140+
// view never persists across a content change.
138141
const [revealed, setRevealed] = useState(false);
139142

140143
const tooLarge = body.length > MAX_INLINE_BODY_CHARS;
@@ -146,10 +149,10 @@ function BodyPreview({ body }: { body: string }) {
146149
);
147150
}
148151

149-
// OAuth responses (token exchange, DCR) carry bearer-grade secrets. Mask
150-
// them by default and gate the raw values behind an explicit reveal so they
151-
// aren't exposed at a glance during a screen-share. Bodies without secrets
152-
// render as-is with no toggle.
152+
// OAuth responses (token exchange, DCR) and the token request carry
153+
// bearer-grade secrets. Mask them by default and gate the raw values behind
154+
// an explicit reveal so they aren't exposed at a glance during a
155+
// screen-share. Bodies without secrets render as-is with no toggle.
153156
const { masked, hasSecrets } = maskSecretsInBody(body);
154157
if (!hasSecrets) {
155158
return <ContentViewer block={{ type: "text", text: body }} copyable />;
@@ -159,10 +162,15 @@ function BodyPreview({ body }: { body: string }) {
159162
return (
160163
<Stack gap="xs">
161164
<Group gap="xs">
162-
<Text size="xs" c="dimmed">
165+
<Text size="xs" c="dimmed" aria-live="polite">
163166
{revealed ? "Secrets revealed" : "Secrets hidden"}
164167
</Text>
165-
<RevealButton onClick={() => setRevealed((v) => !v)}>
168+
<RevealButton
169+
onClick={() => setRevealed((v) => !v)}
170+
aria-label={
171+
revealed ? "Hide secrets in body" : "Reveal secrets in body"
172+
}
173+
>
166174
{revealed ? "Hide" : "Reveal"}
167175
</RevealButton>
168176
</Group>
@@ -225,7 +233,7 @@ export function NetworkEntry({ entry, isListExpanded }: NetworkEntryProps) {
225233
<Text size="sm" fw={500}>
226234
Request Body
227235
</Text>
228-
<BodyPreview body={entry.requestBody} />
236+
<BodyPreview key={entry.requestBody} body={entry.requestBody} />
229237
</Stack>
230238
)}
231239
{entry.responseHeaders && (
@@ -242,7 +250,10 @@ export function NetworkEntry({ entry, isListExpanded }: NetworkEntryProps) {
242250
Response Body
243251
</Text>
244252
{entry.responseBody ? (
245-
<BodyPreview body={entry.responseBody} />
253+
<BodyPreview
254+
key={entry.responseBody}
255+
body={entry.responseBody}
256+
/>
246257
) : (
247258
<Text size="xs" c="dimmed">
248259
{isLongLivedStream(entry)

‎clients/web/src/utils/maskSecrets.test.ts‎

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,16 +70,57 @@ describe("maskSecretsInBody", () => {
7070
expect(hasSecrets).toBe(false);
7171
});
7272

73-
it("returns non-JSON bodies unchanged with no secrets", () => {
74-
const body = "code=abc&code_verifier=xyz"; // form-encoded, not JSON
73+
it("returns a form body with no sensitive params unchanged", () => {
74+
const body = "grant_type=authorization_code&redirect_uri=http://x/cb";
7575
const { masked, hasSecrets } = maskSecretsInBody(body);
7676
expect(hasSecrets).toBe(false);
7777
expect(masked).toBe(body);
7878
});
7979

80+
it("masks sensitive params in a form-encoded token request, preserving other params", () => {
81+
const body =
82+
"grant_type=authorization_code&code=AUTHCODE&code_verifier=VERIFIER&client_id=public-1&redirect_uri=http://x/cb";
83+
const { masked, hasSecrets } = maskSecretsInBody(body);
84+
expect(hasSecrets).toBe(true);
85+
expect(masked).toContain(`code=${MASK_PLACEHOLDER}`);
86+
expect(masked).toContain(`code_verifier=${MASK_PLACEHOLDER}`);
87+
expect(masked).not.toContain("AUTHCODE");
88+
expect(masked).not.toContain("VERIFIER");
89+
// Non-secret params are untouched (and formatting preserved).
90+
expect(masked).toContain("grant_type=authorization_code");
91+
expect(masked).toContain("client_id=public-1");
92+
expect(masked).toContain("redirect_uri=http://x/cb");
93+
});
94+
95+
it("masks refresh_token and client_secret in a form-encoded refresh request", () => {
96+
const body =
97+
"grant_type=refresh_token&refresh_token=RTVAL&client_secret=CSVAL";
98+
const { masked, hasSecrets } = maskSecretsInBody(body);
99+
expect(hasSecrets).toBe(true);
100+
expect(masked).not.toContain("RTVAL");
101+
expect(masked).not.toContain("CSVAL");
102+
});
103+
104+
it("does NOT mask a JSON `code` field (e.g. a JSON-RPC error code)", () => {
105+
// `code` is form-only sensitive; in JSON it's usually an error/status code.
106+
const { masked, hasSecrets } = maskSecretsInBody(
107+
JSON.stringify({ code: "some-string-code", message: "boom" }),
108+
);
109+
expect(hasSecrets).toBe(false);
110+
expect(JSON.parse(masked).code).toBe("some-string-code");
111+
});
112+
80113
it("does not treat pure reformatting as masking", () => {
81114
// Minified JSON with no secret keys → reserialized but hasSecrets false.
82115
const { hasSecrets } = maskSecretsInBody('{"a":1,"b":[2,3]}');
83116
expect(hasSecrets).toBe(false);
84117
});
118+
119+
it("passes through valid-but-non-object JSON (string / number / null) untouched", () => {
120+
for (const raw of ['"abc"', "42", "null", "true"]) {
121+
const { masked, hasSecrets } = maskSecretsInBody(raw);
122+
expect(hasSecrets).toBe(false);
123+
expect(JSON.parse(masked)).toEqual(JSON.parse(raw));
124+
}
125+
});
85126
});
Lines changed: 90 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,110 @@
11
/**
22
* Masks sensitive OAuth values inside a captured HTTP body for display in the
3-
* Network tab. OAuth token-exchange and registration responses carry
4-
* credentials (`access_token`, `refresh_token`, …); we show the body so it's
5-
* inspectable, but mask those values by default so they aren't exposed at a
6-
* glance during a screen-share. The raw body is preserved by the caller and
7-
* shown only when the user explicitly reveals it.
3+
* Network tab. OAuth token-exchange / registration responses carry credentials
4+
* (`access_token`, `refresh_token`, …) and the token *request* (a
5+
* `application/x-www-form-urlencoded` body) carries `code` / `code_verifier` /
6+
* `client_secret`. We show the body so it's inspectable, but mask those values
7+
* by default so they aren't exposed at a glance during a screen-share. The raw
8+
* body is preserved by the caller and shown only when the user reveals it.
9+
*
10+
* Both JSON and form-encoded bodies are handled; anything else (or a body with
11+
* no sensitive keys) passes through unchanged with `hasSecrets: false`.
812
*/
913

10-
// JSON keys whose values are bearer-grade secrets. Matched case-insensitively.
11-
// `client_secret` covers DCR responses for confidential clients; the token
12-
// fields cover the `/token` exchange and refresh responses.
13-
const SENSITIVE_KEYS = new Set([
14+
// Keys masked in JSON bodies — bearer-grade secrets only. `code` is
15+
// deliberately NOT here: a JSON body's `code` is usually something else (e.g.
16+
// a JSON-RPC error `code`), and we don't want to mask those.
17+
const JSON_SENSITIVE_KEYS = new Set([
1418
"access_token",
1519
"refresh_token",
1620
"id_token",
1721
"client_secret",
1822
]);
1923

24+
// Keys masked in form-encoded bodies — the JSON set plus the single-use OAuth
25+
// request material that only appears as form params (authorization code, PKCE
26+
// verifier, private-key-JWT client assertion).
27+
const FORM_SENSITIVE_KEYS = new Set([
28+
...JSON_SENSITIVE_KEYS,
29+
"code",
30+
"code_verifier",
31+
"client_assertion",
32+
]);
33+
2034
// What a masked value is replaced with. A fixed-width dotted string keeps the
2135
// shape recognizable as "a value was here" without hinting at its length.
2236
export const MASK_PLACEHOLDER = "••••••••";
2337

24-
function isSensitiveKey(key: string): boolean {
25-
return SENSITIVE_KEYS.has(key.toLowerCase());
38+
interface MaskedNode {
39+
node: unknown;
40+
masked: boolean;
2641
}
2742

28-
function maskValue(key: string, value: unknown): unknown {
29-
if (isSensitiveKey(key) && typeof value === "string" && value.length > 0) {
30-
return MASK_PLACEHOLDER;
31-
}
32-
return maskNode(value);
33-
}
34-
35-
function maskNode(node: unknown): unknown {
43+
// Recursively mask sensitive string values in a parsed JSON node, tracking
44+
// whether anything was masked (so the caller never has to infer it by
45+
// comparing serializations — reformatting alone can't trip the flag, and it's
46+
// robust if this function ever grows non-identity transforms).
47+
function maskNode(node: unknown): MaskedNode {
3648
if (Array.isArray(node)) {
37-
return node.map((item) => maskNode(item));
49+
let masked = false;
50+
const out = node.map((item) => {
51+
const r = maskNode(item);
52+
masked = masked || r.masked;
53+
return r.node;
54+
});
55+
return { node: out, masked };
3856
}
3957
if (node !== null && typeof node === "object") {
58+
let masked = false;
4059
const out: Record<string, unknown> = {};
4160
for (const [key, value] of Object.entries(
4261
node as Record<string, unknown>,
4362
)) {
44-
out[key] = maskValue(key, value);
63+
if (
64+
JSON_SENSITIVE_KEYS.has(key.toLowerCase()) &&
65+
typeof value === "string" &&
66+
value.length > 0
67+
) {
68+
out[key] = MASK_PLACEHOLDER;
69+
masked = true;
70+
} else {
71+
const r = maskNode(value);
72+
out[key] = r.node;
73+
masked = masked || r.masked;
74+
}
4575
}
46-
return out;
76+
return { node: out, masked };
4777
}
48-
return node;
78+
return { node, masked: false };
79+
}
80+
81+
// Mask sensitive params in a form-urlencoded body, preserving the original
82+
// formatting (we only swap the value, so the placeholder isn't percent-encoded
83+
// the way `URLSearchParams.toString()` would mangle it). A non-form string
84+
// (no `key=value` pairs with a sensitive key) falls through untouched.
85+
function maskFormBody(body: string): MaskResult {
86+
let hasSecrets = false;
87+
const masked = body
88+
.split("&")
89+
.map((pair) => {
90+
const eq = pair.indexOf("=");
91+
if (eq === -1) return pair;
92+
const rawKey = pair.slice(0, eq);
93+
const value = pair.slice(eq + 1);
94+
let key: string;
95+
try {
96+
key = decodeURIComponent(rawKey);
97+
} catch {
98+
key = rawKey;
99+
}
100+
if (FORM_SENSITIVE_KEYS.has(key.toLowerCase()) && value.length > 0) {
101+
hasSecrets = true;
102+
return `${rawKey}=${MASK_PLACEHOLDER}`;
103+
}
104+
return pair;
105+
})
106+
.join("&");
107+
return { masked: hasSecrets ? masked : body, hasSecrets };
49108
}
50109

51110
export interface MaskResult {
@@ -56,23 +115,19 @@ export interface MaskResult {
56115
}
57116

58117
/**
59-
* Mask sensitive fields in a JSON body. Non-JSON bodies (or JSON without any
60-
* sensitive keys) are returned unchanged with `hasSecrets: false`, so callers
61-
* can skip the reveal affordance entirely. The masked JSON is re-serialized
62-
* pretty-printed; the caller keeps the original string for the revealed view.
118+
* Mask sensitive fields in an HTTP body for display. JSON bodies are masked
119+
* structurally (and re-serialized pretty-printed); non-JSON bodies are treated
120+
* as form-encoded. Bodies with no sensitive keys return unchanged with
121+
* `hasSecrets: false` so callers can skip the reveal affordance. The caller
122+
* keeps the original string for the revealed view.
63123
*/
64124
export function maskSecretsInBody(body: string): MaskResult {
65125
let parsed: unknown;
66126
try {
67127
parsed = JSON.parse(body);
68128
} catch {
69-
return { masked: body, hasSecrets: false };
129+
return maskFormBody(body);
70130
}
71-
const maskedNode = maskNode(parsed);
72-
const masked = JSON.stringify(maskedNode, null, 2);
73-
// The serialized output differs from the input only when something was
74-
// masked (whitespace-only reformatting aside), but compare the structures
75-
// directly so reformatting alone never trips the "has secrets" flag.
76-
const hasSecrets = JSON.stringify(maskedNode) !== JSON.stringify(parsed);
77-
return { masked, hasSecrets };
131+
const { node, masked } = maskNode(parsed);
132+
return { masked: JSON.stringify(node, null, 2), hasSecrets: masked };
78133
}

‎core/mcp/state/fetchRequestLogState.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,15 @@ export class FetchRequestLogState extends TypedEventTarget<FetchRequestLogStateE
112112
// non-redirect `saveSession` caller (e.g. a future token-refresh save
113113
// point) and is harmless when it duplicates the primary flush —
114114
// last-writer-wins on an identical payload under the same id.
115+
//
116+
// SECURITY TRIPWIRE: captured `auth`-category response bodies in this log
117+
// are stored UNMASKED (masking is a Network-UI display concern only).
118+
// Today the only `saveSession` trigger is the pre-redirect flush, which
119+
// runs before the `/token` exchange — so no bearer token is ever
120+
// persisted. Any NEW `saveSession` trigger added after token exchange
121+
// (e.g. a periodic snapshot) would write `access_token` /
122+
// `refresh_token` to disk. Redact response bodies here before persisting
123+
// if that ever changes.
115124
const onSaveSession = (
116125
event: TypedEventGeneric<InspectorClientEventMap, "saveSession">,
117126
): void => {

0 commit comments

Comments
 (0)