Skip to content

Commit e291918

Browse files
authored
fix(gateway): keep cold transcript reads inside the sessions root (#391)
## Requirement or Bug Keep cold transcript file reads inside the sessions root, and pin that the config route rejects prototype-poisoning bodies. Both are open code-scanning alerts on `main`. ## Bug Reproduction Steps 1. Give the session index an entry whose `workspaceId` is `../outside`, and put a `state.json` with an agent at `<home>/outside/<session>/state.json`. 2. Call `readColdRoster(<session>)`. It returns the agent from the file outside `<home>/sessions`. The new test `cold reads stay inside the sessions root when the index names an escaping workspace` does this. It fails before the fix and passes after. ## Root Cause `TranscriptService.readColdRoster` and `readColdSnapshot` built their paths with `join(homeDir, 'sessions', workspaceId, sessionId, ...)`. Only the agent id was checked. The session id and workspace id come from the session index, so the path is safe only while the index is. The gateway already has `resolveStoragePath`, which rejects segments that leave the root, and `readWireRecords` already uses it. This is a fix at the root. ## Code Changes ```diff readColdRoster(sessionId) - readFile(join(homeDir, 'sessions', workspaceId, sessionId, 'state.json')) + readFile(resolveStoragePath(homeDir, 'sessions', workspaceId, sessionId, 'state.json')) escape -> caught like any unreadable state file -> [] readColdSnapshot(sessionId, agentId) - wirePath = join(homeDir, 'sessions', workspaceId, sessionId, 'agents', agentId, 'wire.jsonl') + wirePath = resolveStoragePath(homeDir, 'sessions', workspaceId, sessionId, 'agents', agentId, 'wire.jsonl') escape -> throws "Storage path escapes its root" ``` Config route: Fastify's default JSON parser already rejects `__proto__` and `constructor.prototype` keys, so `convertKeysSnakeToCamel` never sees them. A plain `constructor` key only becomes an own property. No code change; a new test pins the rejection. ## Behavior Changes and Affected Users | Behavior | Before | After | Who relies on the old behavior | Escape hatch | |---|---|---|---|---| | Cold roster with a session-index entry whose ids leave the sessions root | Reads the file outside the root | Returns an empty roster | Nobody; the index only holds ids the engine created | n/a | | Cold snapshot with such an entry | Reads the wire file outside the root | Throws "Storage path escapes its root" | Nobody | n/a | | Config POST with `__proto__` or `constructor.prototype` keys | Rejected by the JSON parser | Unchanged (now covered by a test) | n/a | n/a | Affected module: `packages/agent-gateway` transcript service. Tests: `test/services/transcript.test.ts` (new escape test, red before the fix), `test/config.test.ts` (new parser pin). Gateway suite 75 files / 1437 passed; gateway typecheck, `pnpm run lint` (0 errors) and `check-no-comments` pass. [skip changeset] Users cannot see this change: the session index only holds ids the engine created. ## Checklist - [x] I have read the [CONTRIBUTING](https://github.com/PyModel/pythinker-code/blob/main/CONTRIBUTING.md) document. - [ ] I have linked a related issue (external PRs: issue must have a maintainer's `/approve`). - [x] I have added tests that prove my feature works. - [x] The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR. - [x] Ran `gen-changesets` skill, or this PR needs no changeset. - [x] Ran `gen-docs` skill, or this PR needs no doc update.
1 parent 21388e4 commit e291918

3 files changed

Lines changed: 58 additions & 2 deletions

File tree

‎packages/agent-gateway/src/services/transcript/transcriptService.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ import {
4747
} from '@pymodel/transcript';
4848

4949
import { WireRecordCache, type ContextRecord } from './wireCache';
50+
import { resolveStoragePath } from '../../lib/storagePath';
5051
import { toWireQuestion } from '../../protocol/question-wire';
5152
import { projectPromptContentParts } from '../messages/messageProjection';
5253
import {
@@ -528,7 +529,7 @@ export class TranscriptService {
528529
let meta: SessionMeta;
529530
try {
530531
const raw = await readFile(
531-
join(this.deps.homeDir, SESSIONS_ROOT, summary.workspaceId, sessionId, STATE_FILE),
532+
resolveStoragePath(this.deps.homeDir, SESSIONS_ROOT, summary.workspaceId, sessionId, STATE_FILE),
532533
'utf-8',
533534
);
534535
meta = JSON.parse(raw) as SessionMeta;
@@ -549,7 +550,7 @@ export class TranscriptService {
549550
if (!isPlainAgentId(agentId)) {
550551
return groupMessagesIntoSnapshot([]);
551552
}
552-
const wirePath = join(
553+
const wirePath = resolveStoragePath(
553554
this.deps.homeDir,
554555
SESSIONS_ROOT,
555556
summary.workspaceId,

‎packages/agent-gateway/test/config.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,24 @@ describe('server-v2 /api/v1/config', () => {
8787
expect(cfg.yolo).toBe(false);
8888
});
8989

90+
it('POST rejects bodies with prototype-poisoning keys before they reach the config', async () => {
91+
await boot();
92+
for (const body of [
93+
'{"providers":{"__proto__":{"type":"openai","base_url":"https://api.example.com/v1"}}}',
94+
'{"__proto__":{"default_model":"x"}}',
95+
'{"thinking":{"constructor":{"prototype":{"enabled":true}}}}',
96+
]) {
97+
const res = await authedFetch(server as RunningServer, base, '/api/v1/config', {
98+
method: 'POST',
99+
headers: { 'content-type': 'application/json' },
100+
body,
101+
});
102+
const envelope = (await res.json()) as Envelope<unknown>;
103+
expect(envelope.code).not.toBe(0);
104+
expect(envelope.msg).toContain('not valid JSON');
105+
}
106+
});
107+
90108
it('POST { yolo: true } sets default_permission_mode = yolo and echoes yolo = true', async () => {
91109
await boot();
92110
const cfg = await patchConfig({ yolo: true });

‎packages/agent-gateway/test/services/transcript.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2793,6 +2793,43 @@ describe('AgentTranscriptProjector', () => {
27932793
}
27942794
});
27952795

2796+
it('cold reads stay inside the sessions root when the index names an escaping workspace', async () => {
2797+
const home = await mkdtemp(join(tmpdir(), 'transcript-cold-escape-'));
2798+
try {
2799+
const outside = join(home, 'outside', 's1');
2800+
await mkdir(join(outside, 'agents', 'main'), { recursive: true });
2801+
await writeFile(
2802+
join(outside, 'state.json'),
2803+
JSON.stringify({ agents: { main: { type: 'main' } } }),
2804+
);
2805+
await writeFile(
2806+
join(outside, 'agents', 'main', 'wire.jsonl'),
2807+
`${JSON.stringify({ type: 'metadata', protocol_version: 1 })}\n`,
2808+
);
2809+
const service = new TranscriptService({
2810+
homeDir: home,
2811+
core: {
2812+
accessor: {
2813+
get: (token: unknown) => {
2814+
if (token === ISessionManager) {
2815+
return { get: () => undefined, list: () => [] };
2816+
}
2817+
if (token === IWorkspaceInstanceManager) {
2818+
return { list: () => [], onDidChange: () => ({ dispose: () => undefined }) };
2819+
}
2820+
if (token === ISessionIndex) return { get: async () => ({ workspaceId: '../outside' }) };
2821+
return undefined;
2822+
},
2823+
},
2824+
} as unknown as Scope,
2825+
});
2826+
expect(await service.readColdRoster('s1')).toEqual([]);
2827+
await expect(service.readColdSnapshot('s1', 'main')).rejects.toThrow('Storage path escapes its root');
2828+
} finally {
2829+
await rm(home, { recursive: true, force: true });
2830+
}
2831+
});
2832+
27962833
it('readColdSnapshot folds task/todo/goal/plan/interaction records into the cold snapshot', async () => {
27972834
const home = await mkdtemp(join(tmpdir(), 'transcript-cold-facts-'));
27982835
try {

0 commit comments

Comments
 (0)