Skip to content
Open
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
7 changes: 6 additions & 1 deletion server/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@ export async function readJson(
request: Request,
maxBytes = 48000,
): Promise<unknown> {
if (!request.headers.get('content-type')?.startsWith('application/json'))
const mediaType = request.headers
.get('content-type')
?.split(';', 1)[0]
.trim()
.toLowerCase();
if (mediaType !== 'application/json')
throw new StoreError(415, 'Send JSON content.');
if (Number(request.headers.get('content-length')) > maxBytes)
throw new StoreError(413, 'Request is too large.');
Expand Down
39 changes: 39 additions & 0 deletions tests/workspace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,3 +216,42 @@ void test('bounded JSON reader validates content type, actual bytes and malforme
);
}
});

void test('JSON media types are case-insensitive and accept parameters', async () => {
for (const contentType of [
'Application/JSON',
'APPLICATION/JSON; CHARSET=UTF-8',
'application/json;charset=utf-8',
'application/json ; charset="utf-8"',
]) {
const request = new Request('https://test', {
method: 'POST',
headers: { 'Content-Type': contentType },
body: '{"ok":true}',
});
assert.deepEqual(await readJson(request), { ok: true }, contentType);
}
});

void test('unsupported JSON lookalikes fail before consuming the request body', async () => {
for (const contentType of [
undefined,
'text/plain',
'application/jsonp',
'application/json-seq',
'application/json+custom',
'application/json, text/plain',
]) {
const request = new Request('https://test', {
method: 'POST',
headers: contentType ? { 'Content-Type': contentType } : {},
body: new TextEncoder().encode('{"ok":true}'),
});
await assert.rejects(
() => readJson(request),
(error: unknown) => error instanceof StoreError && error.status === 415,
String(contentType),
);
assert.equal(request.bodyUsed, false, String(contentType));
}
});
Loading