Skip to content

fix: correctly handle expired JWE's in cookies #2082

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
30 changes: 15 additions & 15 deletions src/server/auth-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
const { payload: updatedSessionCookieValue } = await decrypt(
updatedSessionCookie!.value,
secret
);
) as jose.JWTDecryptResult;
expect(updatedSessionCookieValue).toEqual(expect.objectContaining({
user: {
sub: DEFAULT.sub
Expand Down Expand Up @@ -869,7 +869,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
`__txn_${authorizationUrl.searchParams.get("state")}`
);
expect(transactionCookie).toBeDefined();
expect((await decrypt(transactionCookie!.value, secret)).payload).toEqual(
expect((await decrypt(transactionCookie!.value, secret) as jose.JWTDecryptResult).payload).toEqual(
expect.objectContaining({
nonce: authorizationUrl.searchParams.get("nonce"),
codeVerifier: expect.any(String),
Expand Down Expand Up @@ -1024,7 +1024,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
);
expect(transactionCookie).toBeDefined();
expect(
(await decrypt(transactionCookie!.value, secret)).payload
(await decrypt(transactionCookie!.value, secret) as jose.JWTDecryptResult).payload
).toEqual(expect.objectContaining({
nonce: authorizationUrl.searchParams.get("nonce"),
codeVerifier: expect.any(String),
Expand Down Expand Up @@ -1357,7 +1357,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
`__txn_${authorizationUrl.searchParams.get("state")}`
);
expect(transactionCookie).toBeDefined();
expect((await decrypt(transactionCookie!.value, secret)).payload).toEqual(
expect((await decrypt(transactionCookie!.value, secret) as jose.JWTDecryptResult).payload).toEqual(
expect.objectContaining({
nonce: authorizationUrl.searchParams.get("nonce"),
maxAge: 3600,
Expand Down Expand Up @@ -1404,7 +1404,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
`__txn_${authorizationUrl.searchParams.get("state")}`
);
expect(transactionCookie).toBeDefined();
expect((await decrypt(transactionCookie!.value, secret)).payload).toEqual(
expect((await decrypt(transactionCookie!.value, secret) as jose.JWTDecryptResult).payload).toEqual(
expect.objectContaining({
nonce: authorizationUrl.searchParams.get("nonce"),
codeVerifier: expect.any(String),
Expand Down Expand Up @@ -1450,7 +1450,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
`__txn_${authorizationUrl.searchParams.get("state")}`
);
expect(transactionCookie).toBeDefined();
expect((await decrypt(transactionCookie!.value, secret)).payload).toEqual(
expect((await decrypt(transactionCookie!.value, secret) as jose.JWTDecryptResult).payload).toEqual(
expect.objectContaining({
nonce: authorizationUrl.searchParams.get("nonce"),
codeVerifier: expect.any(String),
Expand Down Expand Up @@ -1584,7 +1584,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
const state = transactionCookie.name.replace("__txn_", "");
expect(transactionCookie).toBeDefined();
expect(
(await decrypt(transactionCookie!.value, secret)).payload
(await decrypt(transactionCookie.value, secret) as jose.JWTDecryptResult).payload
).toEqual(expect.objectContaining({
nonce: expect.any(String),
codeVerifier: expect.any(String),
Expand Down Expand Up @@ -1663,7 +1663,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
const state = transactionCookie.name.replace("__txn_", "");
expect(transactionCookie).toBeDefined();
expect(
(await decrypt(transactionCookie!.value, secret)).payload
(await decrypt(transactionCookie.value, secret) as jose.JWTDecryptResult).payload
).toEqual(expect.objectContaining({
nonce: expect.any(String),
codeVerifier: expect.any(String),
Expand Down Expand Up @@ -1743,7 +1743,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
const state = transactionCookie.name.replace("__txn_", "");
expect(transactionCookie).toBeDefined();
expect(
(await decrypt(transactionCookie!.value, secret)).payload
(await decrypt(transactionCookie.value, secret) as jose.JWTDecryptResult).payload
).toEqual(expect.objectContaining({
nonce: expect.any(String),
codeVerifier: expect.any(String),
Expand Down Expand Up @@ -2297,7 +2297,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
// validate the session cookie
const sessionCookie = response.cookies.get("__session");
expect(sessionCookie).toBeDefined();
const { payload: session } = await decrypt(sessionCookie!.value, secret);
const { payload: session } = await decrypt(sessionCookie!.value, secret) as jose.JWTDecryptResult;
expect(session).toEqual(expect.objectContaining({
user: {
sub: DEFAULT.sub
Expand Down Expand Up @@ -2408,7 +2408,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
// validate the session cookie
const sessionCookie = response.cookies.get("__session");
expect(sessionCookie).toBeDefined();
const { payload: session } = await decrypt(sessionCookie!.value, secret);
const { payload: session } = await decrypt(sessionCookie!.value, secret) as jose.JWTDecryptResult;
expect(session).toEqual(expect.objectContaining({
user: {
sub: DEFAULT.sub
Expand Down Expand Up @@ -2795,7 +2795,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
const { payload: session } = await decrypt(
sessionCookie!.value,
secret
);
) as jose.JWTDecryptResult;
expect(session).toEqual(expect.objectContaining(expectedSession));
});

Expand Down Expand Up @@ -3259,7 +3259,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
const { payload: session } = await decrypt(
sessionCookie!.value,
secret
);
) as jose.JWTDecryptResult;
expect(session).toEqual(expect.objectContaining({
user: {
sub: DEFAULT.sub,
Expand Down Expand Up @@ -3391,7 +3391,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
const { payload: session } = await decrypt(
sessionCookie!.value,
secret
);
) as jose.JWTDecryptResult;
expect(session).toEqual(expect.objectContaining({
user: {
sub: DEFAULT.sub,
Expand Down Expand Up @@ -3493,7 +3493,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
const { payload: updatedSession } = await decrypt<SessionData>(
updatedSessionCookie!.value,
secret
);
) as jose.JWTDecryptResult<SessionData>;
expect(updatedSession.tokenSet.accessToken).toEqual(newAccessToken);
});

Expand Down
8 changes: 4 additions & 4 deletions src/server/cookies.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as jose from "jose";
import { describe, expect, it } from "vitest";

import { generateSecret } from "../test/utils";
Expand All @@ -12,7 +13,7 @@ describe("encrypt/decrypt", async () => {
const maxAge = 60 * 60; // 1 hour in seconds
const expiration = Math.floor(Date.now() / 1000 + maxAge);
const encrypted = await encrypt(payload, secret, expiration);
const decrypted = await decrypt(encrypted, secret);
const decrypted = await decrypt(encrypted, secret) as jose.JWTDecryptResult;

expect(decrypted.payload).toEqual(expect.objectContaining(payload));
});
Expand All @@ -31,9 +32,8 @@ describe("encrypt/decrypt", async () => {
const payload = { key: "value" };
const expiration = Math.floor(Date.now() / 1000 - 60); // 60 seconds in the past
const encrypted = await encrypt(payload, secret, expiration);
await expect(() =>
decrypt(encrypted, secret)
).rejects.toThrowError(`"exp" claim timestamp check failed`);
const decrypted = await decrypt(encrypted, secret);
expect(decrypted).toBeNull();
});

it("should fail to encrypt if a secret is not provided", async () => {
Expand Down
25 changes: 16 additions & 9 deletions src/server/cookies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,24 @@ export async function encrypt(
}

export async function decrypt<T>(cookieValue: string, secret: string) {
const encryptionSecret = await hkdf(
DIGEST,
secret,
"",
ENCRYPTION_INFO,
BYTE_LENGTH
);
try {
const encryptionSecret = await hkdf(
DIGEST,
secret,
"",
ENCRYPTION_INFO,
BYTE_LENGTH
);

const cookie = await jose.jwtDecrypt<T>(cookieValue, encryptionSecret, {});
const cookie = await jose.jwtDecrypt<T>(cookieValue, encryptionSecret, {});

return cookie;
return cookie;
} catch (e: any) {
if (e.code === "ERR_JWT_EXPIRED") {
return null;
}
throw e;
}
}

/**
Expand Down
15 changes: 8 additions & 7 deletions src/server/session/stateful-session-store.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as jose from "jose";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { generateSecret } from "../../test/utils";
Expand Down Expand Up @@ -332,7 +333,7 @@ describe("Stateful Session Store", async () => {
await sessionStore.set(requestCookies, responseCookies, session);

const cookie = responseCookies.get("__session");
const { payload: cookieValue } = await decrypt(cookie!.value, secret);
const { payload: cookieValue } = await decrypt(cookie!.value, secret) as jose.JWTDecryptResult;

expect(cookie).toBeDefined();
expect(cookieValue).toHaveProperty("id");
Expand Down Expand Up @@ -386,7 +387,7 @@ describe("Stateful Session Store", async () => {
await sessionStore.set(requestCookies, responseCookies, session);

const cookie = responseCookies.get("__session");
const { payload: cookieValue } = await decrypt(cookie!.value, secret);
const { payload: cookieValue } = await decrypt(cookie!.value, secret) as jose.JWTDecryptResult;

expect(cookie).toBeDefined();
expect(cookieValue).toHaveProperty("id");
Expand Down Expand Up @@ -434,7 +435,7 @@ describe("Stateful Session Store", async () => {
await sessionStore.set(requestCookies, responseCookies, session);

const cookie = responseCookies.get("__session");
const { payload: cookieValue } = await decrypt(cookie!.value, secret);
const { payload: cookieValue } = await decrypt(cookie!.value, secret) as jose.JWTDecryptResult;

expect(cookie).toBeDefined();
expect(cookieValue).toHaveProperty("id");
Expand Down Expand Up @@ -493,7 +494,7 @@ describe("Stateful Session Store", async () => {
await sessionStore.set(requestCookies, responseCookies, session, true);

const cookie = responseCookies.get("__session");
const { payload: cookieValue } = await decrypt(cookie!.value, secret);
const { payload: cookieValue } = await decrypt(cookie!.value, secret) as jose.JWTDecryptResult;

expect(cookie).toBeDefined();
expect(store.delete).toHaveBeenCalledWith(sessionId); // the old session should be deleted
Expand Down Expand Up @@ -542,7 +543,7 @@ describe("Stateful Session Store", async () => {
await sessionStore.set(requestCookies, responseCookies, session);

const cookie = responseCookies.get("__session");
const { payload: cookieValue } = await decrypt(cookie!.value, secret);
const { payload: cookieValue } = await decrypt(cookie!.value, secret) as jose.JWTDecryptResult;

expect(cookie).toBeDefined();
expect(cookieValue).toHaveProperty("id");
Expand Down Expand Up @@ -592,7 +593,7 @@ describe("Stateful Session Store", async () => {
await sessionStore.set(requestCookies, responseCookies, session);

const cookie = responseCookies.get("__session");
const { payload: cookieValue } = await decrypt(cookie!.value, secret);
const { payload: cookieValue } = await decrypt(cookie!.value, secret) as jose.JWTDecryptResult;

expect(cookie).toBeDefined();
expect(cookieValue).toHaveProperty("id");
Expand Down Expand Up @@ -686,7 +687,7 @@ describe("Stateful Session Store", async () => {
await sessionStore.set(requestCookies, responseCookies, session);

const cookie = responseCookies.get("my-session");
const { payload: cookieValue } = await decrypt(cookie!.value, secret);
const { payload: cookieValue } = await decrypt(cookie!.value, secret) as jose.JWTDecryptResult;

expect(cookie).toBeDefined();
expect(cookieValue).toHaveProperty("id");
Expand Down
32 changes: 22 additions & 10 deletions src/server/session/stateful-session-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,16 @@ export class StatefulSessionStore extends AbstractSessionStore {
// this ensures that v3 sessions are respected and can be transparently rolled over to v4+ sessions
let sessionId: string | null = null;
try {
const { payload: sessionCookie } =
await cookies.decrypt<SessionCookieValue>(cookie.value, this.secret);
sessionId = sessionCookie.id;
const sessionCookie = await cookies.decrypt<SessionCookieValue>(
cookie.value,
this.secret
);

if (sessionCookie === null) {
return null;
}

sessionId = sessionCookie.payload.id;
} catch (e: any) {
// the session cookie could not be decrypted, try to verify if it's a legacy session
if (e.code === "ERR_JWE_INVALID") {
Expand Down Expand Up @@ -115,9 +122,12 @@ export class StatefulSessionStore extends AbstractSessionStore {
let sessionId = null;
const cookieValue = reqCookies.get(this.sessionCookieName)?.value;
if (cookieValue) {
const { payload: sessionCookie } =
const sessionCookie =
await cookies.decrypt<SessionCookieValue>(cookieValue, this.secret);
sessionId = sessionCookie.id;

if (sessionCookie) {
sessionId = sessionCookie.payload.id;
}
}

// if this is a new session created by a new login we need to remove the old session
Expand All @@ -130,17 +140,17 @@ export class StatefulSessionStore extends AbstractSessionStore {
if (!sessionId) {
sessionId = generateId();
}

const maxAge = this.calculateMaxAge(session.internal.createdAt);
const expiration = Date.now() / 1000 + maxAge;
const jwe = await cookies.encrypt(
{
id: sessionId
},
this.secret,
expiration,
expiration
);

resCookies.set(this.sessionCookieName, jwe.toString(), {
...this.cookieConfig,
maxAge
Expand Down Expand Up @@ -168,11 +178,13 @@ export class StatefulSessionStore extends AbstractSessionStore {
return;
}

const { payload: session } = await cookies.decrypt<SessionCookieValue>(
const session = await cookies.decrypt<SessionCookieValue>(
cookieValue,
this.secret
);

await this.store.delete(session.id);
if (session) {
await this.store.delete(session.payload.id);
}
}
}
Loading