Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
fix(core): reject non-JSON-RPC response bodies with ApiError
  • Loading branch information
xyos committed Oct 30, 2026
commit 4b694bb2b52226a35fe74d280436b67a55c0d058
5 changes: 5 additions & 0 deletions .changeset/core-client-non-rpc-error-bodies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@aws-blocks/core": patch
---

The typed API client now rejects with an `ApiError` when a response is not a JSON-RPC envelope, such as a gateway's own `429`, `403`, `502` or `504` reply or an HTML error page, instead of resolving `undefined`. The error carries the HTTP status and the gateway's `message` when present.
2 changes: 1 addition & 1 deletion packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ How `status` reaches the client over JSON-RPC: an uncaught error inside an RPC m
}}
```

The client decodes that back into an `ApiError` with the same `status`, `name` and `retriable`, which is why the same `isBlocksError(e, ...)` check works on both sides. Reserved JSON-RPC codes (`-32600`, `-32700`, …) decode to `status: 500`.
The client decodes that back into an `ApiError` with the same `status`, `name` and `retriable`, which is why the same `isBlocksError(e, ...)` check works on both sides. Reserved JSON-RPC codes (`-32600`, `-32700`, …) decode to `status: 500`. A response that is not a JSON-RPC envelope, such as a gateway's own `429 {"message":"Too Many Requests"}` or an HTML error page, also rejects with an `ApiError`: `status` is the HTTP status (`502` if that status was 2xx) and `message` is the body's `message` when present, else `HTTP <status>`.

#### `hasAuthError(state, name)`

Expand Down
70 changes: 70 additions & 0 deletions packages/core/src/client/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,73 @@ describe('ApiNamespaceClient — per-namespace request path', () => {
}
});
});

describe('ApiNamespaceClient — non-JSON-RPC response bodies', () => {
// A gateway or proxy in front of the handler can answer on its own (throttling,
// auth, timeouts, a crashed integration). Those bodies carry no JSON-RPC
// envelope; the client must reject with the HTTP status rather than resolve
// `undefined`. These stub `fetch` (test plumbing — not customer code).
async function callWith(body: string, status: number, contentType = 'application/json'): Promise<unknown> {
const { ApiNamespaceClient } = await import('./index.js');
const originalFetch = globalThis.fetch;
globalThis.fetch = (async () => new Response(body, {
status,
headers: { 'Content-Type': contentType },
})) as typeof fetch;
try {
const api = ApiNamespaceClient<{ hello(): Promise<unknown> }>('reports', {
url: 'https://d123.cloudfront.net/aws-blocks/api',
});
return await api.hello();
} finally {
globalThis.fetch = originalFetch;
}
}

const gatewayResponses: Array<[number, string]> = [
[502, 'Internal server error'],
[429, 'Too Many Requests'],
[403, 'Forbidden'],
[504, 'Endpoint request timed out'],
];
for (const [status, message] of gatewayResponses) {
it(`rejects with ApiError ${status} for a gateway body {"message":"${message}"}`, async () => {
const { ApiError } = await import('./index.js');
await assert.rejects(callWith(JSON.stringify({ message }), status), (err: unknown) => {
assert.ok(err instanceof ApiError, `expected ApiError, got ${String(err)}`);
assert.strictEqual(err.status, status);
assert.strictEqual(err.message, message);
return true;
});
});
}

it('rejects with ApiError carrying the status for a non-JSON body', async () => {
const { ApiError } = await import('./index.js');
await assert.rejects(callWith('<html><body>502 Bad Gateway</body></html>', 502, 'text/html'), (err: unknown) => {
assert.ok(err instanceof ApiError, `expected ApiError, got ${String(err)}`);
assert.strictEqual(err.status, 502);
assert.strictEqual(err.message, 'HTTP 502');
return true;
});
});

it('rejects with status 502 when a 200 response carries no envelope', async () => {
const { ApiError } = await import('./index.js');
await assert.rejects(callWith(JSON.stringify({ hello: 'world' }), 200), (err: unknown) => {
assert.ok(err instanceof ApiError, `expected ApiError, got ${String(err)}`);
assert.strictEqual(err.status, 502);
assert.strictEqual(err.message, 'HTTP 502');
return true;
});
});

it('resolves a valid void result (no `result` member)', async () => {
assert.strictEqual(await callWith(JSON.stringify({ jsonrpc: '2.0', id: 1 }), 200), undefined);
});

it('resolves a valid result envelope sent with a custom non-200 status', async () => {
assert.deepStrictEqual(await callWith(JSON.stringify({ jsonrpc: '2.0', result: { queued: true }, id: 1 }), 202), { queued: true });
assert.strictEqual(await callWith(JSON.stringify({ jsonrpc: '2.0', result: 'teapot', id: 1 }), 418), 'teapot');
});
});
13 changes: 11 additions & 2 deletions packages/core/src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

export type BlocksContext = any;
export type ApiHandler<T extends Record<string, (...args: any[]) => any>> = any;

Check warning on line 5 in packages/core/src/client/index.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/correctness/noUnusedVariables

This type parameter T is unused.
import { encodeRpcRequest, decodeRpcResponse } from '../rpc.js';
import { fetchWithStaleConnectionRetry } from './stale-connection.js';

Expand Down Expand Up @@ -185,7 +185,7 @@
*/
export interface BlocksMiddleware {
/** Transform the request before it's sent. Modify the request in place or return a new one. Can be async. */
onRequest?: (request: BlocksRequest) => BlocksRequest | void | Promise<BlocksRequest | void>;

Check warning on line 188 in packages/core/src/client/index.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/suspicious/noConfusingVoidType

void is confusing inside a union type.
/** Transform the response data after it's received. Used to hydrate __blocks descriptors. */
onResponse?: (data: unknown) => unknown;
}
Expand Down Expand Up @@ -219,7 +219,7 @@
for (const mw of middlewares) {
if (mw.onRequest) {
const result = await mw.onRequest(request);
if (result) request = result;

Check warning on line 222 in packages/core/src/client/index.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noParameterAssign

Assigning a function parameter is confusing.
}
}
return request;
Expand All @@ -228,7 +228,7 @@
function processResponse(data: unknown): unknown {
for (const mw of middlewares) {
if (mw.onResponse) {
data = mw.onResponse(data);

Check warning on line 231 in packages/core/src/client/index.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noParameterAssign

Assigning a function parameter is confusing.
}
}
return data;
Expand Down Expand Up @@ -334,7 +334,7 @@
const send: (url: string, init: RequestInit) => Promise<Response> =
options?.retryStaleConnection === false ? (url, init) => fetch(url, init) : fetchWithStaleConnectionRetry;
return new Proxy({} as any, {
get(target, method: string | symbol) {

Check warning on line 337 in packages/core/src/client/index.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/correctness/noUnusedFunctionParameters

This parameter target is unused.
if (typeof method === 'symbol') return undefined;
return async (...args: any[]) => {
const baseUrl = urlOverride ?? await getApiUrl();
Expand Down Expand Up @@ -371,11 +371,11 @@
.filter(Boolean)
.filter((c: string) => !existingNames.has(c.trim().split('=')[0]))
.join('; ');
request.headers['Cookie'] = newCookies

Check notice on line 374 in packages/core/src/client/index.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/complexity/useLiteralKeys

The computed expression can be simplified without the use of a string literal.
? `${existing}; ${newCookies}`
: existing;
} else {
request.headers['Cookie'] = ssrCookies;

Check notice on line 378 in packages/core/src/client/index.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/complexity/useLiteralKeys

The computed expression can be simplified without the use of a string literal.
}
}

Expand All @@ -389,8 +389,17 @@
body: encodeRpcRequest(request.apiNamespace, request.method, request.args),
});

const rpcBody = await response.json();
const result = decodeRpcResponse(rpcBody); // throws ApiError on RPC error
// A non-JSON body (e.g. a gateway's HTML error page) decodes as no
// envelope, so it surfaces as an ApiError carrying the HTTP status.
const text = await response.text();
let rpcBody: unknown;
try {
rpcBody = JSON.parse(text);
} catch {
rpcBody = undefined;
}
// Throws ApiError on an RPC error or a body that is not a JSON-RPC envelope.
const result = decodeRpcResponse(rpcBody, response.status);
return processResponse(result);
};
}
Expand Down
17 changes: 16 additions & 1 deletion packages/core/src/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,24 @@ export function encodeRpcRequest(apiNamespace: string, method: string, args: unk
* Decode a JSON-RPC 2.0 response body.
*
* Returns the `result` on success, or throws an `ApiError` on error.
*
* A body that is not a JSON-RPC 2.0 envelope (`jsonrpc !== '2.0'`) — e.g. a
* gateway answering on its own with `{"message":"Too Many Requests"}` — also
* throws an `ApiError`. Its status is `httpStatus` when that is not a 2xx,
* else 502 (a success status with no envelope is an upstream fault); its
* message is the body's string `message` when present, else `HTTP <status>`.
* Pass `undefined` as `body` when the response text was not valid JSON.
*
* @param body The parsed response body.
* @param httpStatus The HTTP status of the response, if known.
*/
export function decodeRpcResponse(body: unknown): unknown {
export function decodeRpcResponse(body: unknown, httpStatus?: number): unknown {
const rpc = body as any;
if (rpc === null || typeof rpc !== 'object' || rpc.jsonrpc !== VERSION) {
const status = httpStatus !== undefined && (httpStatus < 200 || httpStatus > 299) ? httpStatus : 502;
const message = typeof rpc?.message === 'string' && rpc.message ? rpc.message : `HTTP ${status}`;
throw new ApiError(message, status);
}
if (rpc.error) {
const { code, message, data } = rpc.error;
// Application error codes use the HTTP status directly (e.g. 409).
Expand Down
Loading