Skip to content

Commit 9f634f8

Browse files
committed
fix(cli): classify cloud HTTP errors before JSON parsing
1 parent e9c353f commit 9f634f8

4 files changed

Lines changed: 40 additions & 54 deletions

File tree

‎src/__tests__/cloud-connect-profile.test.ts‎

Lines changed: 11 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -366,40 +366,12 @@ test('connect without remote config rejects legacy remoteConfig string profile r
366366
}
367367
});
368368

369-
test('connect without remote config reports cloud profile authorization failures', async () => {
370-
const tempRoot = mkdtempForTestSync('agent-device-connect-cloud-denied-');
371-
const stateDir = path.join(tempRoot, '.state');
372-
mockedResolveCloudAccessForConnect.mockResolvedValue({
373-
accessToken: 'adc_agent_cloud',
374-
cloudBaseUrl: 'https://cloud.example',
375-
});
376-
vi.stubGlobal(
377-
'fetch',
378-
vi.fn(
379-
async () =>
380-
new Response(JSON.stringify({ error: 'forbidden' }), {
381-
status: 403,
382-
headers: { 'content-type': 'application/json' },
383-
}),
384-
),
385-
);
386-
387-
try {
388-
await assert.rejects(connectWithGeneratedCloudProfile(stateDir), (error: unknown) => {
389-
assert.equal((error as { code?: string }).code, 'UNAUTHORIZED');
390-
assert.match(
391-
(error as Error).message,
392-
/Cloud connection profile endpoint rejected the request/,
393-
);
394-
return true;
395-
});
396-
} finally {
397-
fs.rmSync(tempRoot, { recursive: true, force: true });
398-
}
399-
});
400-
401-
for (const status of [429, 503]) {
402-
test(`connect without remote config propagates cloud profile ${status} failures`, async () => {
369+
for (const [status, code] of [
370+
[403, 'UNAUTHORIZED'],
371+
[429, 'COMMAND_FAILED'],
372+
[503, 'COMMAND_FAILED'],
373+
] as const) {
374+
test(`connect without remote config preserves cloud profile ${status} failures`, async () => {
403375
const tempRoot = mkdtempForTestSync(`agent-device-connect-cloud-${status}-`);
404376
const stateDir = path.join(tempRoot, '.state');
405377
mockedResolveCloudAccessForConnect.mockResolvedValue({
@@ -408,14 +380,16 @@ for (const status of [429, 503]) {
408380
});
409381
vi.stubGlobal(
410382
'fetch',
411-
vi.fn(async () => new Response('{"error":"secret"}', { status })),
383+
vi.fn(async () => new Response('<html>private-body-secret</html>', { status })),
412384
);
413385
try {
414386
await assert.rejects(connectWithGeneratedCloudProfile(stateDir), (error: unknown) => {
415387
const normalized = normalizeError(error);
416-
assert.equal(normalized.code, 'COMMAND_FAILED');
388+
assert.equal(normalized.code, code);
417389
assert.equal(normalized.details?.status, status);
418-
assert.equal(normalized.retriable, true);
390+
if (code === 'COMMAND_FAILED') assert.equal(normalized.retriable, true);
391+
assert.match(normalized.message, /Cloud connection profile endpoint rejected the request/);
392+
assert.doesNotMatch(JSON.stringify(normalized), /private-body-secret/);
419393
return true;
420394
});
421395
assert.equal(readActiveConnectionState({ stateDir }), null);

‎src/cli/__tests__/auth-session.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ test('remote auth does not fall back to login when session refresh gets 503', as
197197
},
198198
fetch: async () => {
199199
fetchCalls += 1;
200-
return new Response('{"error":"secret"}', { status: 503 });
200+
return new Response('<html>private-body-secret</html>', { status: 503 });
201201
},
202202
},
203203
}),

‎src/cli/__tests__/cloud-response.test.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,19 @@ for (const status of [401, 403]) {
2020
});
2121
}
2222

23-
for (const status of [404, 429, 503]) {
23+
for (const [status, retriable] of [
24+
[404, undefined],
25+
[429, true],
26+
[503, true],
27+
] as const) {
2428
test(`cloud response ${status} preserves status without requesting login`, async () => {
2529
await assert.rejects(
26-
readCloudJsonResponse(new Response('{"accessToken":"secret"}', { status }), options),
30+
readCloudJsonResponse(new Response('<html>secret</html>', { status }), options),
2731
(error: unknown) => {
2832
const normalized = normalizeError(error);
2933
assert.equal(normalized.code, 'COMMAND_FAILED');
3034
assert.equal(normalized.details?.status, status);
31-
assert.equal(normalized.retriable, status === 429 || status >= 500 ? true : undefined);
35+
assert.equal(normalized.retriable, retriable);
3236
assert.doesNotMatch(JSON.stringify(normalized), /secret|accessToken/);
3337
return true;
3438
},
@@ -44,3 +48,16 @@ test('cloud response keeps successful JSON and invalid JSON behavior', async ()
4448
return true;
4549
});
4650
});
51+
52+
test('malformed successful JSON never exposes response text through its cause', async () => {
53+
await assert.rejects(
54+
readCloudJsonResponse(new Response('private-body-secret'), options),
55+
(error: unknown) => {
56+
const normalized = normalizeError(error);
57+
assert.equal(normalized.code, 'COMMAND_FAILED');
58+
assert.equal(normalized.details?.status, 200);
59+
assert.doesNotMatch(JSON.stringify(normalized), /private-body-secret/);
60+
return true;
61+
},
62+
);
63+
});

‎src/cli/cloud-response.ts‎

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,6 @@ export async function readCloudJsonResponse<T>(
88
},
99
): Promise<T> {
1010
const text = await response.text();
11-
let parsed: unknown = {};
12-
if (text.trim().length > 0) {
13-
try {
14-
parsed = JSON.parse(text);
15-
} catch (error) {
16-
throw new AppError(
17-
'COMMAND_FAILED',
18-
options.invalidJsonMessage,
19-
{ status: response.status },
20-
error instanceof Error ? error : undefined,
21-
);
22-
}
23-
}
2411
if (!response.ok) {
2512
const status = response.status;
2613
const code = status === 401 || status === 403 ? 'UNAUTHORIZED' : 'COMMAND_FAILED';
@@ -31,5 +18,13 @@ export async function readCloudJsonResponse<T>(
3118
: {}),
3219
});
3320
}
21+
let parsed: unknown = {};
22+
if (text.trim().length > 0) {
23+
try {
24+
parsed = JSON.parse(text);
25+
} catch {
26+
throw new AppError('COMMAND_FAILED', options.invalidJsonMessage, { status: response.status });
27+
}
28+
}
3429
return parsed as T;
3530
}

0 commit comments

Comments
 (0)