Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 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
80 changes: 46 additions & 34 deletions src/server/auth-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
audience?: string;
issuer?: string;
alg?: string;
privateKey?: CryptoKey;
privateKey?: jose.CryptoKey;
}): Promise<string> {
return await new jose.SignJWT({
events: {
Expand Down Expand Up @@ -5039,14 +5039,17 @@ ca/T0LLtgmbMmxSv/MmzIg==

// Mock the transactionStore.save method to verify the saved state
const originalSave = authClient["transactionStore"].save;
authClient["transactionStore"].save = vi.fn(async (cookies, state) => {
expect(state.returnTo).toBe(defaultReturnTo);
return originalSave.call(
authClient["transactionStore"],
cookies,
state
);
});
authClient["transactionStore"].save = vi.fn(
async (cookies, state, reqCookies) => {
expect(state.returnTo).toBe(defaultReturnTo);
return originalSave.call(
authClient["transactionStore"],
cookies,
state,
reqCookies
);
}
);

await authClient.startInteractiveLogin();

Expand All @@ -5059,14 +5062,17 @@ ca/T0LLtgmbMmxSv/MmzIg==

// Mock the transactionStore.save method to verify the saved state
const originalSave = authClient["transactionStore"].save;
authClient["transactionStore"].save = vi.fn(async (cookies, state) => {
expect(state.returnTo).toBe("/custom-return-path");
return originalSave.call(
authClient["transactionStore"],
cookies,
state
);
});
authClient["transactionStore"].save = vi.fn(
async (cookies, state, reqCookies) => {
expect(state.returnTo).toBe("/custom-return-path");
return originalSave.call(
authClient["transactionStore"],
cookies,
state,
reqCookies
);
}
);

await authClient.startInteractiveLogin({ returnTo });

Expand All @@ -5079,14 +5085,17 @@ ca/T0LLtgmbMmxSv/MmzIg==
DEFAULT.appBaseUrl + "/custom-return-path?query=param#hash";

const originalSave = authClient["transactionStore"].save;
authClient["transactionStore"].save = vi.fn(async (cookies, state) => {
expect(state.returnTo).toBe("/custom-return-path?query=param#hash");
return originalSave.call(
authClient["transactionStore"],
cookies,
state
);
});
authClient["transactionStore"].save = vi.fn(
async (cookies, state, reqCookies) => {
expect(state.returnTo).toBe("/custom-return-path?query=param#hash");
return originalSave.call(
authClient["transactionStore"],
cookies,
state,
reqCookies
);
}
);

await authClient.startInteractiveLogin({ returnTo });

Expand All @@ -5101,15 +5110,18 @@ ca/T0LLtgmbMmxSv/MmzIg==

// Mock the transactionStore.save method to verify the saved state
const originalSave = authClient["transactionStore"].save;
authClient["transactionStore"].save = vi.fn(async (cookies, state) => {
// Should use the default safe path instead of the malicious one
expect(state.returnTo).toBe("/safe-path");
return originalSave.call(
authClient["transactionStore"],
cookies,
state
);
});
authClient["transactionStore"].save = vi.fn(
async (cookies, state, reqCookies) => {
// Should use the default safe path instead of the malicious one
expect(state.returnTo).toBe("/safe-path");
return originalSave.call(
authClient["transactionStore"],
cookies,
state,
reqCookies
);
}
);

await authClient.startInteractiveLogin({ returnTo: unsafeReturnTo });

Expand Down
60 changes: 45 additions & 15 deletions src/server/auth-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ export interface AuthClientOptions {
domain: string;
clientId: string;
clientSecret?: string;
clientAssertionSigningKey?: string | CryptoKey;
clientAssertionSigningKey?: string | jose.CryptoKey;
clientAssertionSigningAlg?: string;
authorizationParameters?: AuthorizationParameters;
pushedAuthorizationRequests?: boolean;
Expand Down Expand Up @@ -156,7 +156,7 @@ export class AuthClient {

private clientMetadata: oauth.Client;
private clientSecret?: string;
private clientAssertionSigningKey?: string | CryptoKey;
private clientAssertionSigningKey?: string | jose.CryptoKey;
private clientAssertionSigningAlg: string;
private domain: string;
private authorizationParameters: AuthorizationParameters;
Expand Down Expand Up @@ -395,6 +395,8 @@ export class AuthClient {

// Set response and save transaction
const res = NextResponse.redirect(authorizationUrl.toString());

// Save transaction state
await this.transactionStore.save(res.cookies, transactionState);

return res;
Expand Down Expand Up @@ -505,7 +507,7 @@ export class AuthClient {
async handleCallback(req: NextRequest): Promise<NextResponse> {
const state = req.nextUrl.searchParams.get("state");
if (!state) {
return this.onCallback(new MissingStateError(), {}, null);
return this.handleCallbackError(new MissingStateError(), {}, req);
}

const transactionStateCookie = await this.transactionStore.get(
Expand All @@ -525,7 +527,12 @@ export class AuthClient {
await this.discoverAuthorizationServerMetadata();

if (discoveryError) {
return this.onCallback(discoveryError, onCallbackCtx, null);
return this.handleCallbackError(
discoveryError,
onCallbackCtx,
req,
state
);
}

let codeGrantParams: URLSearchParams;
Expand All @@ -537,15 +544,16 @@ export class AuthClient {
transactionState.state
);
} catch (e: any) {
return this.onCallback(
return this.handleCallbackError(
new AuthorizationError({
cause: new OAuth2Error({
code: e.error,
message: e.error_description
})
}),
onCallbackCtx,
null
req,
state
);
}

Expand All @@ -566,10 +574,11 @@ export class AuthClient {
}
);
} catch (e: any) {
return this.onCallback(
return this.handleCallbackError(
new AuthorizationCodeGrantRequestError(e.message),
onCallbackCtx,
null
req,
state
);
}

Expand All @@ -586,15 +595,16 @@ export class AuthClient {
}
);
} catch (e: any) {
return this.onCallback(
return this.handleCallbackError(
new AuthorizationCodeGrantError({
cause: new OAuth2Error({
code: e.error,
message: e.error_description
})
}),
onCallbackCtx,
null
req,
state
);
}

Expand Down Expand Up @@ -622,6 +632,8 @@ export class AuthClient {

await this.sessionStore.set(req.cookies, res.cookies, session, true);
addCacheControlHeadersForSession(res);

// Clean up the current transaction cookie after successful authentication
await this.transactionStore.delete(res.cookies, state);

return res;
Expand Down Expand Up @@ -903,6 +915,25 @@ export class AuthClient {
return res;
}

/**
* Handle callback errors with transaction cleanup
*/
private async handleCallbackError(
error: SdkError,
ctx: OnCallbackContext,
req: NextRequest,
state?: string
): Promise<NextResponse> {
const response = await this.onCallback(error, ctx, null);

// Clean up the transaction cookie on error to prevent accumulation
if (state) {
await this.transactionStore.delete(response.cookies, state);
}

return response;
}

private async verifyLogoutToken(
logoutToken: string
): Promise<[null, LogoutToken] | [SdkError, null]> {
Expand Down Expand Up @@ -1079,19 +1110,18 @@ export class AuthClient {
);
}

let clientPrivateKey = this.clientAssertionSigningKey as
| CryptoKey
| undefined;
let clientPrivateKey: jose.CryptoKey | undefined = this
.clientAssertionSigningKey as jose.CryptoKey | undefined;

if (clientPrivateKey && !(clientPrivateKey instanceof CryptoKey)) {
if (clientPrivateKey && typeof clientPrivateKey === "string") {
clientPrivateKey = await jose.importPKCS8(
clientPrivateKey,
this.clientAssertionSigningAlg
);
}

return clientPrivateKey
? oauth.PrivateKeyJwt(clientPrivateKey)
? oauth.PrivateKeyJwt(clientPrivateKey as CryptoKey)
: oauth.ClientSecretPost(this.clientSecret!);
}

Expand Down
5 changes: 4 additions & 1 deletion src/server/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,8 @@ export interface Auth0ClientOptions {
* Defaults to `false`.
*/
noContentProfileResponseWhenUnauthenticated?: boolean;

enableParallelTransactions?: boolean;
}

export type PagesRouterRequest = IncomingMessage | NextApiRequest;
Expand Down Expand Up @@ -272,7 +274,8 @@ export class Auth0Client {
this.transactionStore = new TransactionStore({
...options.session,
secret,
cookieOptions: transactionCookieOptions
cookieOptions: transactionCookieOptions,
enableParallelTransactions: options.enableParallelTransactions || true
});

this.sessionStore = options.sessionStore
Expand Down
Loading