Skip to content

Commit c632727

Browse files
authored
fix(api-gateway): Handle invalid query (invalid JSON) as 400 Bad Request (#7455)
1 parent 567d2ca commit c632727

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

packages/cubejs-api-gateway/src/gateway.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1901,11 +1901,17 @@ class ApiGateway {
19011901

19021902
protected parseQueryParam(query): Query | Query[] {
19031903
if (!query || query === 'undefined') {
1904-
throw new UserError('query param is required');
1904+
throw new UserError('Query param is required');
19051905
}
1906+
19061907
if (typeof query === 'string') {
1907-
query = JSON.parse(query);
1908+
try {
1909+
return JSON.parse(query) as Query | Query[];
1910+
} catch (e: any) {
1911+
throw new UserError(`Unable to decode query param as JSON, error: ${e.message}`);
1912+
}
19081913
}
1914+
19091915
return query as Query | Query[];
19101916
}
19111917

packages/cubejs-api-gateway/test/index.test.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,32 @@ describe('API Gateway', () => {
9191
expect(res.body && res.body.error).toStrictEqual('Invalid token');
9292
});
9393

94+
test('query field is empty', async () => {
95+
const { app } = await createApiGateway();
96+
97+
const res = await request(app)
98+
.get('/cubejs-api/v1/load?query=')
99+
.set('Authorization', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M')
100+
.expect(400);
101+
102+
expect(res.body && res.body.error).toStrictEqual(
103+
'Query param is required'
104+
);
105+
});
106+
107+
test('incorrect json for query field', async () => {
108+
const { app } = await createApiGateway();
109+
110+
const res = await request(app)
111+
.get('/cubejs-api/v1/load?query=NOT_A_JSON')
112+
.set('Authorization', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M')
113+
.expect(400);
114+
115+
expect(res.body && res.body.error).toStrictEqual(
116+
'Unable to decode query param as JSON, error: Unexpected token N in JSON at position 0'
117+
);
118+
});
119+
94120
test('requires auth', async () => {
95121
const { app } = await createApiGateway();
96122

0 commit comments

Comments
 (0)