Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

At error cause to AT error when it's from a failed grant #878

Merged
merged 2 commits into from
Oct 21, 2022
Merged
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
3 changes: 2 additions & 1 deletion src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { NextMiddleware, NextRequest, NextResponse } from 'next/server';
import { default as CookieStore } from './auth0-session/cookie-store';
import MiddlewareCookies from './utils/middleware-cookies';
import { SessionCache, Session } from './session/';
import Session from './session/session';
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MW was importing get-access-token.ts in it's binary, which it doesn't need

import SessionCache from './session/cache';
import {
WithMiddlewareAuthRequired,
default as withMiddlewareAuthRequiredFactory
Expand Down
18 changes: 14 additions & 4 deletions src/session/get-access-token.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { IncomingMessage, ServerResponse } from 'http';
import { NextApiRequest, NextApiResponse } from 'next';
import { ClientFactory } from '../auth0-session';
import type { errors } from 'openid-client';
import { ClientFactory, IdentityProviderError } from '../auth0-session';
import { AccessTokenError, AccessTokenErrorCode } from '../utils/errors';
import { intersect, match } from '../utils/array';
import { Session, SessionCache, fromTokenSet } from '../session';
Expand Down Expand Up @@ -161,9 +162,18 @@ export default function accessTokenFactory(
(session.refreshToken && accessTokenRequest && accessTokenRequest.refresh)
) {
const client = await getClient();
const tokenSet = await client.refresh(session.refreshToken, {
exchangeBody: accessTokenRequest?.authorizationParams
});
let tokenSet;
try {
tokenSet = await client.refresh(session.refreshToken, {
exchangeBody: accessTokenRequest?.authorizationParams
});
} catch (e) {
throw new AccessTokenError(
AccessTokenErrorCode.FAILED_REFRESH_GRANT,
'The request to refresh the access token failed.',
new IdentityProviderError(e as errors.OPError)
);
}

// Update the session.
const newSession = fromTokenSet(tokenSet, config);
Expand Down
7 changes: 4 additions & 3 deletions src/utils/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ export enum AccessTokenErrorCode {
MISSING_ACCESS_TOKEN = 'ERR_MISSING_ACCESS_TOKEN',
MISSING_REFRESH_TOKEN = 'ERR_MISSING_REFRESH_TOKEN',
EXPIRED_ACCESS_TOKEN = 'ERR_EXPIRED_ACCESS_TOKEN',
INSUFFICIENT_SCOPE = 'ERR_INSUFFICIENT_SCOPE'
INSUFFICIENT_SCOPE = 'ERR_INSUFFICIENT_SCOPE',
FAILED_REFRESH_GRANT = 'ERR_FAILED_REFRESH_GRANT'
}

/**
Expand All @@ -96,9 +97,9 @@ export enum AccessTokenErrorCode {
* @category Server
*/
export class AccessTokenError extends AuthError {
constructor(code: AccessTokenErrorCode, message: string) {
constructor(code: AccessTokenErrorCode, message: string, cause?: Error) {
/* c8 ignore next */
super({ code: code, message: message, name: 'AccessTokenError' });
super({ code: code, message: message, name: 'AccessTokenError', cause });

// Capturing stack trace, excluding constructor call from it.
Error.captureStackTrace(this, this.constructor);
Expand Down
11 changes: 11 additions & 0 deletions tests/fixtures/oidc-nocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,17 @@ export async function refreshTokenExchange(
});
}

export async function failedRefreshTokenExchange(
params: ConfigParameters,
refreshToken: string,
payload: Record<string, unknown>,
status = 401
): Promise<nock.Scope> {
return nock(`${params.issuerBaseURL}`)
.post('/oauth/token', `grant_type=refresh_token&refresh_token=${refreshToken}`)
.reply(status, payload);
}

export async function refreshTokenRotationExchange(
params: ConfigParameters,
refreshToken: string,
Expand Down
39 changes: 38 additions & 1 deletion tests/session/get-access-token.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { login, setup, teardown } from '../fixtures/setup';
import { withApi } from '../fixtures/default-settings';
import { get } from '../auth0-session/fixtures/helpers';
import { Session } from '../../src';
import { refreshTokenExchange, refreshTokenRotationExchange } from '../fixtures/oidc-nocks';
import { failedRefreshTokenExchange, refreshTokenExchange, refreshTokenRotationExchange } from '../fixtures/oidc-nocks';
import { makeIdToken } from '../auth0-session/fixtures/cert';
import nock from 'nock';

Expand Down Expand Up @@ -166,6 +166,43 @@ describe('get access token', () => {
expect(refreshToken).toEqual('GEbRxBN...edjnXbL');
});

test('should fail when refresh grant fails', async () => {
await failedRefreshTokenExchange(withApi, 'GEbRxBN...edjnXbL', {}, 500);
const baseUrl = await setup(withApi, { getAccessTokenOptions: { refresh: true } });
const cookieJar = await login(baseUrl);
await expect(get(baseUrl, '/api/access-token', { cookieJar })).rejects.toThrow(
'The request to refresh the access token failed. CAUSE: expected 200 OK, got: 500 Internal Server Error'
);
});

test('should fail when refresh grant fails with oauth error', async () => {
await failedRefreshTokenExchange(
withApi,
'GEbRxBN...edjnXbL',
{ error: 'invalid_grant', error_description: 'Unknown or invalid refresh token.' },
401
);
const baseUrl = await setup(withApi, { getAccessTokenOptions: { refresh: true } });
const cookieJar = await login(baseUrl);
await expect(get(baseUrl, '/api/access-token', { cookieJar })).rejects.toThrow(
'The request to refresh the access token failed. CAUSE: invalid_grant (Unknown or invalid refresh token.)'
);
});

test('should escape oauth error', async () => {
await failedRefreshTokenExchange(
withApi,
'GEbRxBN...edjnXbL',
{ error: '<script>alert(1)</script>', error_description: '<script>alert(2)</script>' },
401
);
const baseUrl = await setup(withApi, { getAccessTokenOptions: { refresh: true } });
const cookieJar = await login(baseUrl);
await expect(get(baseUrl, '/api/access-token', { cookieJar })).rejects.toThrow(
'The request to refresh the access token failed. CAUSE: &lt;script&gt;alert(1)&lt;/script&gt; (&lt;script&gt;alert(2)&lt;/script&gt;)'
);
});

test('should retrieve a new access token and rotate the refresh token', async () => {
await refreshTokenRotationExchange(
withApi,
Expand Down