mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-04-13 22:00:19 -04:00
fix(api): handle expected Auth0 errors (#60499)
This commit is contained in:
committed by
GitHub
parent
6299f545ed
commit
0b1db2b9c6
@@ -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',
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user