fix(api): handle expected Auth0 errors (#60499)

This commit is contained in:
Oliver Eyton-Williams
2025-05-27 06:21:03 +02:00
committed by GitHub
parent 6299f545ed
commit 0b1db2b9c6
4 changed files with 100 additions and 56 deletions

View File

@@ -137,6 +137,33 @@ describe('auth0 plugin', () => {
expect(res.statusCode).toBe(302);
});
it('should log expected Auth0 errors', async () => {
jest.spyOn(fastify.log, 'error');
const auth0Error = Error('Response Error: 403 Forbidden');
// @ts-expect-error - mocking a hapi/boom error
auth0Error.data = {
payload: {
error: 'invalid_grant'
}
};
getAccessTokenFromAuthorizationCodeFlowSpy.mockRejectedValueOnce(
auth0Error
);
const res = await fastify.inject({
method: 'GET',
url: '/auth/auth0/callback?state=invalid'
});
expect(fastify.log.error).toHaveBeenCalledWith(
auth0Error,
'Auth failed: invalid_grant'
);
expect(res.statusCode).toBe(302);
});
it('should not create a user if the state is invalid', async () => {
await fastify.inject({
method: 'GET',

View File

@@ -1,5 +1,7 @@
import fastifyOauth2, { type OAuth2Namespace } from '@fastify/oauth2';
import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox';
import { Type } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';
import fp from 'fastify-plugin';
import {
@@ -23,6 +25,14 @@ declare module 'fastify' {
}
}
const Auth0ErrorSchema = Type.Object({
data: Type.Object({
payload: Type.Object({
error: Type.String()
})
})
});
/**
* Fastify plugin for Auth0 authentication. This uses fastify-plugin to expose
* the auth0OAuth decorator (for easier testing), but to maintain encapsulation
@@ -111,6 +121,9 @@ export const auth0Client: FastifyPluginCallbackTypebox = fp(
// functions.
if (error instanceof Error && error.message === 'Invalid state') {
logger.error('Auth failed: invalid state');
} else if (Value.Check(Auth0ErrorSchema, error)) {
const errorType = error.data.payload.error;
logger.error(error, 'Auth failed: ' + errorType);
} else {
logger.error(error, 'Failed to get access token from Auth0');
fastify.Sentry.captureException(error);