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

fix: read and migrate v3 session format to v4 #1923

Merged
merged 3 commits into from
Feb 18, 2025
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
105 changes: 65 additions & 40 deletions src/server/auth-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
// assert session has been updated
const updatedSessionCookie = response.cookies.get("__session");
expect(updatedSessionCookie).toBeDefined();
const updatedSessionCookieValue = await decrypt(
const { payload: updatedSessionCookieValue } = await decrypt(
updatedSessionCookie!.value,
secret
);
Expand Down Expand Up @@ -795,13 +795,15 @@ ca/T0LLtgmbMmxSv/MmzIg==
`__txn_${authorizationUrl.searchParams.get("state")}`
);
expect(transactionCookie).toBeDefined();
expect(await decrypt(transactionCookie!.value, secret)).toEqual({
nonce: authorizationUrl.searchParams.get("nonce"),
codeVerifier: expect.any(String),
responseType: "code",
state: authorizationUrl.searchParams.get("state"),
returnTo: "/"
});
expect((await decrypt(transactionCookie!.value, secret)).payload).toEqual(
{
nonce: authorizationUrl.searchParams.get("nonce"),
codeVerifier: expect.any(String),
responseType: "code",
state: authorizationUrl.searchParams.get("state"),
returnTo: "/"
}
);
});

it("should return an error if the discovery endpoint could not be fetched", async () => {
Expand Down Expand Up @@ -911,7 +913,9 @@ ca/T0LLtgmbMmxSv/MmzIg==
`__txn_${authorizationUrl.searchParams.get("state")}`
);
expect(transactionCookie).toBeDefined();
expect(await decrypt(transactionCookie!.value, secret)).toEqual({
expect(
(await decrypt(transactionCookie!.value, secret)).payload
).toEqual({
nonce: authorizationUrl.searchParams.get("nonce"),
codeVerifier: expect.any(String),
responseType: "code",
Expand Down Expand Up @@ -1243,14 +1247,16 @@ ca/T0LLtgmbMmxSv/MmzIg==
`__txn_${authorizationUrl.searchParams.get("state")}`
);
expect(transactionCookie).toBeDefined();
expect(await decrypt(transactionCookie!.value, secret)).toEqual({
nonce: authorizationUrl.searchParams.get("nonce"),
maxAge: 3600,
codeVerifier: expect.any(String),
responseType: "code",
state: authorizationUrl.searchParams.get("state"),
returnTo: "/"
});
expect((await decrypt(transactionCookie!.value, secret)).payload).toEqual(
{
nonce: authorizationUrl.searchParams.get("nonce"),
maxAge: 3600,
codeVerifier: expect.any(String),
responseType: "code",
state: authorizationUrl.searchParams.get("state"),
returnTo: "/"
}
);
});

it("should store the returnTo path in the transaction state", async () => {
Expand Down Expand Up @@ -1288,13 +1294,15 @@ ca/T0LLtgmbMmxSv/MmzIg==
`__txn_${authorizationUrl.searchParams.get("state")}`
);
expect(transactionCookie).toBeDefined();
expect(await decrypt(transactionCookie!.value, secret)).toEqual({
nonce: authorizationUrl.searchParams.get("nonce"),
codeVerifier: expect.any(String),
responseType: "code",
state: authorizationUrl.searchParams.get("state"),
returnTo: "https://example.com/dashboard"
});
expect((await decrypt(transactionCookie!.value, secret)).payload).toEqual(
{
nonce: authorizationUrl.searchParams.get("nonce"),
codeVerifier: expect.any(String),
responseType: "code",
state: authorizationUrl.searchParams.get("state"),
returnTo: "https://example.com/dashboard"
}
);
});

it("should prevent open redirects originating from the returnTo parameter", async () => {
Expand Down Expand Up @@ -1332,13 +1340,15 @@ ca/T0LLtgmbMmxSv/MmzIg==
`__txn_${authorizationUrl.searchParams.get("state")}`
);
expect(transactionCookie).toBeDefined();
expect(await decrypt(transactionCookie!.value, secret)).toEqual({
nonce: authorizationUrl.searchParams.get("nonce"),
codeVerifier: expect.any(String),
responseType: "code",
state: authorizationUrl.searchParams.get("state"),
returnTo: "/"
});
expect((await decrypt(transactionCookie!.value, secret)).payload).toEqual(
{
nonce: authorizationUrl.searchParams.get("nonce"),
codeVerifier: expect.any(String),
responseType: "code",
state: authorizationUrl.searchParams.get("state"),
returnTo: "/"
}
);
});

describe("with pushed authorization requests", async () => {
Expand Down Expand Up @@ -1463,7 +1473,9 @@ ca/T0LLtgmbMmxSv/MmzIg==
const transactionCookie = transactionCookies[0];
const state = transactionCookie.name.replace("__txn_", "");
expect(transactionCookie).toBeDefined();
expect(await decrypt(transactionCookie!.value, secret)).toEqual({
expect(
(await decrypt(transactionCookie!.value, secret)).payload
).toEqual({
nonce: expect.any(String),
codeVerifier: expect.any(String),
responseType: "code",
Expand Down Expand Up @@ -1540,7 +1552,9 @@ ca/T0LLtgmbMmxSv/MmzIg==
const transactionCookie = transactionCookies[0];
const state = transactionCookie.name.replace("__txn_", "");
expect(transactionCookie).toBeDefined();
expect(await decrypt(transactionCookie!.value, secret)).toEqual({
expect(
(await decrypt(transactionCookie!.value, secret)).payload
).toEqual({
nonce: expect.any(String),
codeVerifier: expect.any(String),
responseType: "code",
Expand Down Expand Up @@ -1618,7 +1632,9 @@ ca/T0LLtgmbMmxSv/MmzIg==
const transactionCookie = transactionCookies[0];
const state = transactionCookie.name.replace("__txn_", "");
expect(transactionCookie).toBeDefined();
expect(await decrypt(transactionCookie!.value, secret)).toEqual({
expect(
(await decrypt(transactionCookie!.value, secret)).payload
).toEqual({
nonce: expect.any(String),
codeVerifier: expect.any(String),
responseType: "code",
Expand Down Expand Up @@ -2122,7 +2138,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
// validate the session cookie
const sessionCookie = response.cookies.get("__session");
expect(sessionCookie).toBeDefined();
const session = await decrypt(sessionCookie!.value, secret);
const { payload: session } = await decrypt(sessionCookie!.value, secret);
expect(session).toEqual({
user: {
sub: DEFAULT.sub
Expand Down Expand Up @@ -2230,7 +2246,7 @@ ca/T0LLtgmbMmxSv/MmzIg==
// validate the session cookie
const sessionCookie = response.cookies.get("__session");
expect(sessionCookie).toBeDefined();
const session = await decrypt(sessionCookie!.value, secret);
const { payload: session } = await decrypt(sessionCookie!.value, secret);
expect(session).toEqual({
user: {
sub: DEFAULT.sub
Expand Down Expand Up @@ -2601,7 +2617,10 @@ ca/T0LLtgmbMmxSv/MmzIg==
// validate the session cookie
const sessionCookie = response.cookies.get("__session");
expect(sessionCookie).toBeDefined();
const session = await decrypt(sessionCookie!.value, secret);
const { payload: session } = await decrypt(
sessionCookie!.value,
secret
);
expect(session).toEqual(expectedSession);
});

Expand Down Expand Up @@ -3051,7 +3070,10 @@ ca/T0LLtgmbMmxSv/MmzIg==
// validate the session cookie
const sessionCookie = response.cookies.get("__session");
expect(sessionCookie).toBeDefined();
const session = await decrypt(sessionCookie!.value, secret);
const { payload: session } = await decrypt(
sessionCookie!.value,
secret
);
expect(session).toEqual({
user: {
sub: DEFAULT.sub,
Expand Down Expand Up @@ -3177,7 +3199,10 @@ ca/T0LLtgmbMmxSv/MmzIg==
// validate the session cookie
const sessionCookie = response.cookies.get("__session");
expect(sessionCookie).toBeDefined();
const session = await decrypt(sessionCookie!.value, secret);
const { payload: session } = await decrypt(
sessionCookie!.value,
secret
);
expect(session).toEqual({
user: {
sub: DEFAULT.sub,
Expand Down Expand Up @@ -3273,7 +3298,7 @@ ca/T0LLtgmbMmxSv/MmzIg==

// validate that the session cookie has been updated
const updatedSessionCookie = response.cookies.get("__session");
const updatedSession = await decrypt<SessionData>(
const { payload: updatedSession } = await decrypt<SessionData>(
updatedSessionCookie!.value,
secret
);
Expand Down
5 changes: 3 additions & 2 deletions src/server/auth-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -390,14 +390,15 @@ export class AuthClient {
return this.onCallback(new MissingStateError(), {}, null);
}

const transactionState = await this.transactionStore.get(
const transactionStateCookie = await this.transactionStore.get(
req.cookies,
state
);
if (!transactionState) {
if (!transactionStateCookie) {
return this.onCallback(new InvalidStateError(), {}, null);
}

const transactionState = transactionStateCookie.payload;
const onCallbackCtx: OnCallbackContext = {
returnTo: transactionState.returnTo
};
Expand Down
2 changes: 1 addition & 1 deletion src/server/cookies.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ describe("encrypt/decrypt", async () => {
const encrypted = await encrypt(payload, secret);
const decrypted = await decrypt(encrypted, secret);

expect(decrypted).toEqual(payload);
expect(decrypted.payload).toEqual(payload);
});

it("should fail to decrypt a payload with the incorrect secret", async () => {
Expand Down
71 changes: 68 additions & 3 deletions src/server/cookies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,15 @@ const DIGEST = "sha256";
const BYTE_LENGTH = 32;
const ENCRYPTION_INFO = "JWE CEK";

export async function encrypt(payload: jose.JWTPayload, secret: string) {
export async function encrypt(
payload: jose.JWTPayload,
secret: string,
additionalHeaders?: {
iat: number;
uat: number;
exp: number;
}
) {
const encryptionSecret = await hkdf(
DIGEST,
secret,
Expand All @@ -18,7 +26,7 @@ export async function encrypt(payload: jose.JWTPayload, secret: string) {
);

const encryptedCookie = await new jose.EncryptJWT(payload)
.setProtectedHeader({ enc: ENC, alg: ALG })
.setProtectedHeader({ enc: ENC, alg: ALG, ...additionalHeaders })
.encrypt(encryptionSecret);

return encryptedCookie.toString();
Expand All @@ -35,7 +43,64 @@ export async function decrypt<T>(cookieValue: string, secret: string) {

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

return cookie.payload;
return cookie;
}

/**
* Derive a signing key from a given secret.
* This method is used solely to migrate signed, legacy cookies to the new encrypted cookie format (v4+).
*/
const signingSecret = (secret: string): Promise<Uint8Array> =>
hkdf("sha256", secret, "", "JWS Cookie Signing", BYTE_LENGTH);

/**
* Verify a signed cookie. If the cookie is valid, the value is returned. Otherwise, undefined is returned.
* This method is used solely to migrate signed, legacy cookies to the new encrypted cookie format (v4+).
*/
export async function verifySigned(
k: string,
v: string,
secret: string
): Promise<string | undefined> {
if (!v) {
return undefined;
}
const [value, signature] = v.split(".");
const flattenedJWS = {
protected: jose.base64url.encode(
JSON.stringify({ alg: "HS256", b64: false, crit: ["b64"] })
),
payload: `${k}=${value}`,
signature
};
const key = await signingSecret(secret);

try {
await jose.flattenedVerify(flattenedJWS, key, {
algorithms: ["HS256"]
});
return value;
} catch (e) {
return undefined;
}
}

/**
* Sign a cookie value using a secret.
* This method is used solely to migrate signed, legacy cookies to the new encrypted cookie format (v4+).
*/
export async function sign(
name: string,
value: string,
secret: string
): Promise<string> {
const key = await signingSecret(secret);
const { signature } = await new jose.FlattenedSign(
new TextEncoder().encode(`${name}=${value}`)
)
.setProtectedHeader({ alg: "HS256", b64: false, crit: ["b64"] })
.sign(key);
return `${value}.${signature}`;
}

export interface CookieOptions {
Expand Down
Loading