Skip to content

Commit 43227ac

Browse files
authored
fix(responses): close two post-merge review findings (#2500)
Two threads were opened on #2477 and #2476 shortly before each merged, so neither was addressed. Both are real and both are one-line predicates. A selector's namespace is either absent — meaning "unqualified, resolve the bare name" — or a string naming the group. rewriteNamedSelector treated every non-string value as absent, so {type:"function", namespace:1, name:"safe"} took the unqualified path, resolved to a namespace wire name, and authorized an alias the caller never qualified. A wrong-but-valid namespace already failed closed; only malformed ones slipped through. Present-and-invalid now returns the selector untouched. The snapshot fast path compared content but not permissions. This file holds persisted request and response bodies and is written owner-only, and the unconditional rewrite used to restore that on every mutation. Skipping on content alone let a broadened mode persist for the life of the process — a durable privacy regression rather than a slow one. A widened file is now treated as not matching, so the caller rewrites it through the hardening path. POSIX-only check; Windows ACLs are re-applied by that same write path. The docs claim that any byte-identical flush is skipped is also corrected: the skip needs this process to have written the same bytes to the same target, and the file to still match. Tests: five malformed namespace shapes plus an allowed_tools entry, with positive controls proving neither the qualified nor the unqualified path regressed; and a mode-broadening regression. Both mutation-proven — reverting either predicate fails exactly its own cases.
1 parent 02c302a commit 43227ac

5 files changed

Lines changed: 100 additions & 6 deletions

File tree

‎docs-site/src/content/docs/troubleshooting/disk-usage-temp-files.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,10 @@ snapshot actually written**: while that file is small the next write is schedule
5757
about two seconds after a change, and once it is near the 24 MB bound the wait
5858
stretches to at most thirty seconds. A cache that has only just grown therefore
5959
still takes the short wait once — the longer cadence applies from the write after
60-
it. A flush that would reproduce the existing file byte-for-byte is skipped
61-
entirely.
60+
it. A flush is skipped only when this process already wrote the same bytes to the
61+
same file and that file still matches on disk, so a fresh process rewrites an
62+
identical snapshot once, and a file changed underneath the proxy is repaired rather
63+
than left alone.
6264

6365
Together these keep the write rate roughly flat as the cache grows, instead of
6466
re-serializing and replacing the whole file every two seconds.

‎src/responses/namespace-tool-compat.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -223,12 +223,19 @@ function rewriteNamedSelector(
223223
bareFallback: boolean,
224224
): unknown {
225225
if (!isPlainObject(value) || typeof value.name !== "string") return value;
226-
if (typeof value.namespace !== "string") {
226+
// An ABSENT namespace is an unqualified selector and may fall back to the bare
227+
// name. A PRESENT but non-string one is malformed, and must not take that path:
228+
// treating it as absent lets `{type:"function", namespace:1, name:"safe"}` resolve
229+
// to a namespace wire name, which then authorizes an alias the caller never named
230+
// in any well-formed way. Fail closed and hand the selector back untouched.
231+
if ("namespace" in value && typeof value.namespace !== "string") return value;
232+
const namespace = value.namespace;
233+
if (typeof namespace !== "string") {
227234
if (!bareFallback) return value;
228235
const wireName = plan.selectors.get(value.name) ?? undefined;
229236
return wireName === undefined || wireName === value.name ? value : { ...value, name: wireName };
230237
}
231-
const { namespace, ...rest } = value;
238+
const { namespace: _dropped, ...rest } = value;
232239
const wireName = plan.identities.get(loweredIdentity(namespace, value.name))
233240
?? loweredWireName(namespace, value.name);
234241
return { ...rest, name: wireName };

‎src/responses/state.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,18 @@ async function snapshotOnDiskMatches(path: string, payload: string, payloadBytes
117117
try {
118118
const file = Bun.file(path);
119119
if (file.size !== payloadBytes) return false;
120-
return await file.text() === payload;
120+
if (await file.text() !== payload) return false;
121+
// Content matching is not the whole invariant. This file holds persisted request
122+
// and response bodies, and `atomicWriteFileAsync` writes it owner-only; the
123+
// unconditional rewrite used to restore that on every mutation. Skipping without
124+
// checking would let a broadened mode persist indefinitely, so treat a widened
125+
// file as "does not match" and let the caller rewrite it through the hardening
126+
// path. POSIX only — Windows ACLs are re-applied by that same write path.
127+
if (process.platform !== "win32") {
128+
const mode = statSync(path).mode & 0o777;
129+
if (mode !== 0o600) return false;
130+
}
131+
return true;
121132
} catch {
122133
return false;
123134
}

‎tests/namespace-tool-compat.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,61 @@ describe("Responses namespace tool compatibility", () => {
263263
}).aliases.size).toBe(0);
264264
});
265265

266+
// A selector's `namespace` is either absent — meaning "unqualified, resolve the bare
267+
// name" — or a string naming the group. A present-but-malformed value is neither, and
268+
// treating it as absent let it resolve to a namespace wire name and authorize an alias
269+
// the caller never qualified. Fail closed instead: an unqualified selector is a
270+
// deliberate shape, a malformed one is not.
271+
describe("a malformed namespace field authorizes nothing", () => {
272+
const namespaceTools = [{
273+
type: "namespace",
274+
name: "collaboration",
275+
tools: [{ type: "function", name: "safe" }],
276+
}];
277+
const wireName = "collaboration__safe";
278+
279+
test.each([
280+
["a number", 1],
281+
["null", null],
282+
["an object", {}],
283+
["an array", ["collaboration"]],
284+
["a boolean", true],
285+
])("a forced selector whose namespace is %s", (_label, namespace) => {
286+
const { aliases } = rewriteRoutedNamespaceToolsForUpstream({
287+
tools: namespaceTools,
288+
tool_choice: { type: "function", namespace, name: "safe" },
289+
});
290+
expect(aliases.size).toBe(0);
291+
expect(restoreRoutedNamespaceCalls({ type: "function_call", name: wireName }, aliases).changed).toBe(false);
292+
});
293+
294+
test("an allowed_tools entry whose namespace is malformed", () => {
295+
const { aliases } = rewriteRoutedNamespaceToolsForUpstream({
296+
tools: namespaceTools,
297+
tool_choice: { type: "allowed_tools", mode: "required", tools: [{ type: "function", namespace: 1, name: "safe" }] },
298+
});
299+
expect(aliases.size).toBe(0);
300+
});
301+
302+
test("a correctly qualified selector still authorizes, so this is not deny-all", () => {
303+
const { aliases } = rewriteRoutedNamespaceToolsForUpstream({
304+
tools: namespaceTools,
305+
tool_choice: { type: "function", namespace: "collaboration", name: "safe" },
306+
});
307+
expect(aliases.get(wireName)).toEqual({ namespace: "collaboration", name: "safe", kind: "function" });
308+
});
309+
310+
test("an unqualified selector keeps resolving by bare name", () => {
311+
// The absent case is the one legitimate reason the fallback exists; narrowing
312+
// malformed values must not take it away.
313+
const { aliases } = rewriteRoutedNamespaceToolsForUpstream({
314+
tools: namespaceTools,
315+
tool_choice: { type: "function", name: "safe" },
316+
});
317+
expect(aliases.get(wireName)).toBeDefined();
318+
});
319+
});
320+
266321
test("fails closed when flattening would collide with a declared wire name", () => {
267322
expect(() => rewriteRoutedNamespaceToolsForUpstream({
268323
tools: [

‎tests/responses-state-write-amplification.test.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
* of the snapshot actually being written.
99
*/
1010
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
11-
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
11+
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
1212
import { tmpdir } from "node:os";
1313
import { join } from "node:path";
1414
import {
@@ -133,6 +133,25 @@ describe("responses-state snapshot write amplification (#2460)", () => {
133133
expect(readFileSync(snapshot, "utf-8")).toBe(original);
134134
});
135135

136+
// Content is not the whole invariant. This file holds persisted request and response
137+
// bodies and is written owner-only; the unconditional rewrite used to restore that on
138+
// every mutation. Skipping on content alone would let a widened mode persist for the
139+
// life of the process, which is a durable privacy regression rather than a slow one.
140+
test.skipIf(process.platform === "win32")("a snapshot whose mode was broadened is rewritten and re-hardened", async () => {
141+
remember("resp_amp_perm", "sensitive");
142+
await flushResponseState();
143+
expect(statSync(snapshot).mode & 0o777).toBe(0o600);
144+
145+
chmodSync(snapshot, 0o644);
146+
147+
// Same trick as above: the oversized entry is dropped by the per-entry bound, so
148+
// the bounded payload is byte-identical and only the mode differs.
149+
remember("resp_amp_perm_oversized", "y".repeat(3 * 1024 * 1024));
150+
await flushResponseState();
151+
152+
expect(statSync(snapshot).mode & 0o777).toBe(0o600);
153+
});
154+
136155
test("the scheduled debounce stays at its base value for a small snapshot", async () => {
137156
remember("resp_amp_tiny", "tiny");
138157
await flushResponseState();

0 commit comments

Comments
 (0)