From 5cce98d7bf03c7be244649e8f7503b1a38ded855 Mon Sep 17 00:00:00 2001 From: max-kammerer Date: Tue, 22 Oct 2024 11:50:08 +0200 Subject: [PATCH] fix: return client customized error, if present, on auth fail in playground (#8842) fixes #CORE-1134 --- packages/cubejs-api-gateway/src/gateway.ts | 9 ++++- packages/cubejs-api-gateway/test/auth.test.ts | 39 +++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/packages/cubejs-api-gateway/src/gateway.ts b/packages/cubejs-api-gateway/src/gateway.ts index e96465c7c0f16..bd95541085fd0 100644 --- a/packages/cubejs-api-gateway/src/gateway.ts +++ b/packages/cubejs-api-gateway/src/gateway.ts @@ -2225,10 +2225,15 @@ class ApiGateway { if (this.playgroundAuthSecret) { const systemCheckAuthFn = this.createCheckAuthSystemFn(); return async (ctx, authorization) => { + // TODO: separate two auth workflows try { await mainCheckAuthFn(ctx, authorization); - } catch (error) { - await systemCheckAuthFn(ctx, authorization); + } catch (mainAuthError) { + try { + await systemCheckAuthFn(ctx, authorization); + } catch (playgroundAuthError) { + throw mainAuthError; + } } }; } diff --git a/packages/cubejs-api-gateway/test/auth.test.ts b/packages/cubejs-api-gateway/test/auth.test.ts index 007b28fa4d481..cbb728f60c248 100644 --- a/packages/cubejs-api-gateway/test/auth.test.ts +++ b/packages/cubejs-api-gateway/test/auth.test.ts @@ -299,6 +299,45 @@ describe('test authorization', () => { expectSecurityContext(handlerMock.mock.calls[0][0].context.authInfo); }); + test('custom checkAuth with CubejsHandlerError fail in playground', async () => { + const loggerMock = jest.fn(() => { + // + }); + + const expectSecurityContext = (securityContext) => { + expect(securityContext.uid).toEqual(5); + expect(securityContext.iat).toBeDefined(); + expect(securityContext.exp).toBeDefined(); + }; + + const handlerMock = jest.fn((req, res) => { + expectSecurityContext(req.context.securityContext); + expectSecurityContext(req.context.authInfo); + + res.status(200).end(); + }); + + const playgroundAuthSecret = 'playgroundSecret'; + + const token = generateAuthToken({ uid: 5, }, {}); + + const { app } = createApiGateway(handlerMock, loggerMock, { + playgroundAuthSecret, + checkAuth: async (req: Request, auth?: string) => { + throw new CubejsHandlerError(409, 'Error', 'Custom error'); + } + }); + + const res = await request(app) + .get('/test-auth-fake') + .set('Authorization', `Authorization: ${token}`) + .expect(409); + + expect(res.body).toMatchObject({ + error: 'Custom error' + }); + }); + test('custom checkAuth with deprecated authInfo', async () => { const loggerMock = jest.fn(() => { //