feat: OAuth PKCE (#25313)

* add public client

* implement PKCE

* pass codeChallenge and codeChallengeMethod to handler

* fixes for secure oauth flow

* fix type error

* clean up refresh token endpoint

* only support S256

* fix type error

* remove comment

* add tests

* fix type errors in route.test.ts

* add missing support for refresh token

* add e2e test for public client refresh tokens

* allow pkce for confidential clients

* fix type error

* fix e2e

* fix option pkce for confidential clients

* e2e test improvements

* fix test

* remove only

* add delay

* fix e2e tests

* remove only

* don't skip pkce if codeChallenge is set

* add service functions for token endpoint

* use service function in refreshToken endpoint

* use repository

* remove return types

* e2e test fixes

* fix e2e test

* remove .only in e2e test

* remove pause

* fix error responses in token endpoints

* adjust tests to new error responses

* fix error responses

* e2e improvements

* redirect on error

* adjust tests

* Update apps/web/modules/auth/oauth2/authorize-view.tsx

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2025-11-26 17:02:42 +01:00
1 parent c95b0833c1
commit 4e0798577a
19 files changed
+2034 -110

No files matched your search

@@ -0,0 +1,42 @@
import type { PrismaClient } from "@calcom/prisma";
export class AccessCodeRepository {
constructor(private readonly prisma: PrismaClient) {}
async findValidCode(code: string, clientId: string) {
return await this.prisma.accessCode.findFirst({
where: {
code: code,
clientId: clientId,
expiresAt: {
gt: new Date(),
},
},
select: {
userId: true,
teamId: true,
scopes: true,
codeChallenge: true,
codeChallengeMethod: true,
},
});
}
async deleteExpiredAndUsedCodes(code: string, clientId: string) {
await this.prisma.accessCode.deleteMany({
where: {
OR: [
{
expiresAt: {
lt: new Date(),
},
},
{
code: code,
clientId: clientId,
},
],
},
});
}
}
@@ -0,0 +1,18 @@
import type { PrismaClient } from "@calcom/prisma";
export class OAuthClientRepository {
constructor(private readonly prisma: PrismaClient) {}
async findByClientId(clientId: string) {
return await this.prisma.oAuthClient.findFirst({
where: {
clientId: clientId,
},
select: {
redirectUri: true,
clientSecret: true,
clientType: true,
},
});
}
}
@@ -0,0 +1,61 @@
import { verifyCodeChallenge } from "@calcom/lib/pkce";
import { generateSecret } from "@calcom/trpc/server/routers/viewer/oAuth/addClient.handler";
interface OAuthClient {
clientType: "CONFIDENTIAL" | "PUBLIC";
clientSecret?: string | null;
}
type OAuthErrorCode = "invalid_request" | "invalid_grant";
interface PKCESource {
codeChallenge?: string | null;
codeChallengeMethod?: string | null;
}
interface OAuthErrorResult {
error: OAuthErrorCode;
status: number;
}
export class OAuthService {
static validateClient(client: OAuthClient, client_secret?: string): boolean {
if (client.clientType === "CONFIDENTIAL") {
if (!client_secret) return false;
const [hashedSecret] = generateSecret(client_secret);
if (client.clientSecret !== hashedSecret) return false;
}
return true; // PUBLIC has no client_secret
}
/**
* PKCE validator for BOTH:
* - exchanging authorization code
* - exchanging refresh token
*/
static verifyPKCE(
client: OAuthClient,
source: PKCESource,
code_verifier?: string
): OAuthErrorResult | null {
// Determine if PKCE should be enforced
const shouldEnforcePKCE =
client.clientType === "PUBLIC" || (client.clientType === "CONFIDENTIAL" && source.codeChallenge);
if (!shouldEnforcePKCE) return null;
const method = source.codeChallengeMethod || "S256";
if (!source.codeChallenge || !code_verifier || method !== "S256") {
return { error: "invalid_request", status: 400 };
}
if (!verifyCodeChallenge(code_verifier, source.codeChallenge, method)) {
return { error: "invalid_grant", status: 400 };
}
return null;
}
}
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import { isValidCodeChallengeMethod, verifyCodeChallenge } from "./pkce";
describe("PKCE Functions", () => {
describe("verifyCodeChallenge", () => {
it("should verify S256 code challenge correctly", () => {
const codeVerifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
const codeChallenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
const result = verifyCodeChallenge(codeVerifier, codeChallenge, "S256");
expect(result).toBe(true);
});
it("should fail verification with wrong S256 code challenge", () => {
const codeVerifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
const wrongCodeChallenge = "wrong_challenge_value";
const result = verifyCodeChallenge(codeVerifier, wrongCodeChallenge, "S256");
expect(result).toBe(false);
});
it("should default to S256 method when none specified", () => {
const codeVerifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
const codeChallenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
const result = verifyCodeChallenge(codeVerifier, codeChallenge);
expect(result).toBe(true);
});
it("should return false for unsupported method", () => {
const codeVerifier = "test_verifier";
const codeChallenge = "test_challenge";
const result = verifyCodeChallenge(codeVerifier, codeChallenge, "MD5");
expect(result).toBe(false);
});
});
describe("isValidCodeChallengeMethod", () => {
it("should accept S256 method", () => {
expect(isValidCodeChallengeMethod("S256")).toBe(true);
});
it("should reject unsupported methods", () => {
expect(isValidCodeChallengeMethod("plain")).toBe(false);
expect(isValidCodeChallengeMethod("MD5")).toBe(false);
expect(isValidCodeChallengeMethod("SHA1")).toBe(false);
expect(isValidCodeChallengeMethod("invalid")).toBe(false);
expect(isValidCodeChallengeMethod("")).toBe(false);
});
});
});
+17
View File
@@ -0,0 +1,17 @@
import { createHash } from "crypto";
export function verifyCodeChallenge(
codeVerifier: string,
codeChallenge: string,
method: string = "S256"
): boolean {
if (method === "S256") {
const expectedChallenge = createHash("sha256").update(codeVerifier).digest("base64url");
return expectedChallenge === codeChallenge;
}
return false;
}
export function isValidCodeChallengeMethod(method: string): boolean {
return method === "S256";
}
@@ -0,0 +1,10 @@
-- CreateEnum
CREATE TYPE "public"."OAuthClientType" AS ENUM ('confidential', 'public');
-- AlterTable
ALTER TABLE "public"."AccessCode" ADD COLUMN "codeChallenge" TEXT,
ADD COLUMN "codeChallengeMethod" TEXT DEFAULT 'S256';
-- AlterTable
ALTER TABLE "public"."OAuthClient" ADD COLUMN "clientType" "public"."OAuthClientType" NOT NULL DEFAULT 'confidential',
ALTER COLUMN "clientSecret" DROP NOT NULL;
+20 -12
View File
@@ -1737,26 +1737,34 @@ model SelectedSlots {
@@unique(fields: [userId, slotUtcStartDate, slotUtcEndDate, uid], name: "selectedSlotUnique")
}
enum OAuthClientType {
CONFIDENTIAL @map("confidential")
PUBLIC @map("public")
}
model OAuthClient {
clientId String @id @unique
clientId String @id @unique
redirectUri String
clientSecret String
clientSecret String?
clientType OAuthClientType @default(CONFIDENTIAL)
name String
logo String?
accessCodes AccessCode[]
}
model AccessCode {
id Int @id @default(autoincrement())
code String
clientId String?
client OAuthClient? @relation(fields: [clientId], references: [clientId], onDelete: Cascade)
expiresAt DateTime
scopes AccessScope[]
userId Int?
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
teamId Int?
team Team? @relation(fields: [teamId], references: [id], onDelete: Cascade)
id Int @id @default(autoincrement())
code String
clientId String?
client OAuthClient? @relation(fields: [clientId], references: [clientId], onDelete: Cascade)
expiresAt DateTime
scopes AccessScope[]
userId Int?
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
teamId Int?
team Team? @relation(fields: [teamId], references: [id], onDelete: Cascade)
codeChallenge String?
codeChallengeMethod String? @default("S256")
}
enum AccessScope {
@@ -1,6 +1,7 @@
import { randomBytes, createHash } from "crypto";
import { prisma } from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import type { TAddClientInputSchema } from "./addClient.schema";
@@ -9,27 +10,39 @@ type AddClientOptions = {
};
export const addClientHandler = async ({ input }: AddClientOptions) => {
const { name, redirectUri, logo } = input;
const { name, redirectUri, logo, enablePkce } = input;
const [hashedSecret, secret] = generateSecret();
const clientId = randomBytes(32).toString("hex");
const clientType = enablePkce ? "PUBLIC" : "CONFIDENTIAL";
const client = await prisma.oAuthClient.create({
data: {
name,
redirectUri,
clientId,
clientSecret: hashedSecret,
logo,
},
});
const clientWithSecret = {
...client,
clientSecret: secret,
// Only generate client secret for confidential clients
const clientData: Prisma.OAuthClientCreateInput = {
name,
redirectUri,
clientId,
clientType,
logo,
};
return clientWithSecret;
let secret: string | undefined;
if (!enablePkce) {
const [hashedSecret, plainSecret] = generateSecret();
clientData.clientSecret = hashedSecret;
secret = plainSecret;
}
const client = await prisma.oAuthClient.create({
data: clientData,
});
return {
clientId: client.clientId,
name: client.name,
redirectUri: client.redirectUri,
logo: client.logo,
clientType: client.clientType,
clientSecret: secret, // Only return plain secret for confidential clients
isPkceEnabled: enablePkce,
};
};
const hashSecretKey = (apiKey: string): string => createHash("sha256").update(apiKey).digest("hex");
@@ -4,6 +4,7 @@ export const ZAddClientInputSchema = z.object({
name: z.string(),
redirectUri: z.string(),
logo: z.string(),
enablePkce: z.boolean().optional().default(false),
});
export type TAddClientInputSchema = z.infer<typeof ZAddClientInputSchema>;
@@ -0,0 +1,354 @@
import prismaMock from "../../../../../../tests/libs/__mocks__/prismaMock";
import { describe, expect, it, vi, beforeEach } from "vitest";
import { TRPCError } from "@trpc/server";
import { generateAuthCodeHandler } from "./generateAuthCode.handler";
const mockUser = {
id: 1,
email: "[email protected]",
name: "Test User",
};
const mockCtx = {
user: mockUser,
};
describe("generateAuthCodeHandler", () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe("PUBLIC clients", () => {
const mockPublicClient = {
clientId: "public_client_123",
redirectUri: "https://app.example.com/callback",
name: "Test Public Client",
clientType: "PUBLIC" as const,
};
it("should generate authorization code for PUBLIC client with valid PKCE", async () => {
prismaMock.oAuthClient.findUnique.mockResolvedValue(mockPublicClient);
prismaMock.accessCode.create.mockResolvedValue({
id: 1,
code: "test_auth_code",
clientId: "public_client_123",
userId: 1,
teamId: null,
codeChallenge: "test_challenge",
codeChallengeMethod: "S256",
expiresAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
});
const input = {
clientId: "public_client_123",
teamSlug: undefined,
codeChallenge: "test_challenge",
codeChallengeMethod: "S256" as const,
scopes: [],
};
const result = await generateAuthCodeHandler({ ctx: mockCtx, input });
expect(result.client).toEqual(mockPublicClient);
expect(result.authorizationCode).toBeDefined();
expect(prismaMock.accessCode.create).toHaveBeenCalledWith({
data: expect.objectContaining({
clientId: "public_client_123",
userId: 1,
teamId: undefined,
scopes: [],
codeChallenge: "test_challenge",
codeChallengeMethod: "S256",
}),
});
});
it("should reject PUBLIC client without code_challenge", async () => {
prismaMock.oAuthClient.findUnique.mockResolvedValue(mockPublicClient);
const input = {
clientId: "public_client_123",
scopes: [],
teamSlug: undefined,
codeChallenge: undefined,
codeChallengeMethod: "S256" as const,
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input })).rejects.toThrow(
new TRPCError({
code: "BAD_REQUEST",
message: "code_challenge required for public clients",
})
);
expect(prismaMock.accessCode.create).not.toHaveBeenCalled();
});
it("should reject PUBLIC client without code_challenge_method", async () => {
prismaMock.oAuthClient.findUnique.mockResolvedValue(mockPublicClient);
const input = {
clientId: "public_client_123",
scopes: [],
teamSlug: undefined,
codeChallenge: "test_challenge",
codeChallengeMethod: undefined,
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input })).rejects.toThrow(
new TRPCError({
code: "BAD_REQUEST",
message: "code_challenge_method must be S256 for public clients",
})
);
expect(prismaMock.accessCode.create).not.toHaveBeenCalled();
});
it("should reject PUBLIC client with invalid code_challenge_method", async () => {
prismaMock.oAuthClient.findUnique.mockResolvedValue(mockPublicClient);
// Test with MD5 (invalid method)
const inputMD5 = {
clientId: "public_client_123",
scopes: [],
teamSlug: undefined,
codeChallenge: "test_challenge",
codeChallengeMethod: "MD5",
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input: inputMD5 })).rejects.toThrow(
new TRPCError({
code: "BAD_REQUEST",
message: "code_challenge_method must be S256 for public clients",
})
);
// Test with plain (should be rejected)
const inputPlain = {
clientId: "public_client_123",
scopes: [],
teamSlug: undefined,
codeChallenge: "test_challenge",
codeChallengeMethod: "plain",
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input: inputPlain })).rejects.toThrow(
new TRPCError({
code: "BAD_REQUEST",
message: "code_challenge_method must be S256 for public clients",
})
);
expect(prismaMock.accessCode.create).not.toHaveBeenCalled();
});
});
describe("CONFIDENTIAL clients", () => {
const mockConfidentialClient = {
clientId: "confidential_client_456",
redirectUri: "https://app.example.com/callback",
name: "Test Confidential Client",
clientType: "CONFIDENTIAL" as const,
};
it("should generate authorization code for CONFIDENTIAL client without PKCE", async () => {
prismaMock.oAuthClient.findUnique.mockResolvedValue(mockConfidentialClient);
prismaMock.accessCode.create.mockResolvedValue({
id: 1,
code: "test_auth_code",
clientId: "confidential_client_456",
userId: 1,
teamId: null,
scopes: [],
codeChallenge: null,
codeChallengeMethod: null,
expiresAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
});
const input = {
clientId: "confidential_client_456",
scopes: [],
teamSlug: undefined,
codeChallenge: undefined,
codeChallengeMethod: undefined,
};
const result = await generateAuthCodeHandler({ ctx: mockCtx, input });
expect(result.client).toEqual(mockConfidentialClient);
expect(result.authorizationCode).toBeDefined();
expect(prismaMock.accessCode.create).toHaveBeenCalledWith({
data: expect.objectContaining({
clientId: "confidential_client_456",
userId: 1,
teamId: undefined,
scopes: [],
codeChallenge: undefined,
codeChallengeMethod: undefined,
}),
});
});
it("should accept CONFIDENTIAL client with valid PKCE for enhanced security", async () => {
prismaMock.oAuthClient.findUnique.mockResolvedValue(mockConfidentialClient);
prismaMock.accessCode.create.mockResolvedValue({
id: 1,
code: "test_auth_code",
clientId: "confidential_client_456",
userId: 1,
teamId: null,
scopes: [],
expiresAt: new Date(),
codeChallenge: "test_challenge",
codeChallengeMethod: "S256",
});
const input = {
clientId: "confidential_client_456",
scopes: [],
teamSlug: undefined,
codeChallenge: "test_challenge",
codeChallengeMethod: "S256" as const,
};
const result = await generateAuthCodeHandler({ ctx: mockCtx, input });
expect(result.authorizationCode).toBeDefined();
expect(prismaMock.accessCode.create).toHaveBeenCalledWith({
data: {
code: expect.any(String),
clientId: "confidential_client_456",
userId: 1,
teamId: undefined,
scopes: [],
expiresAt: expect.any(Date),
codeChallenge: "test_challenge",
codeChallengeMethod: "S256",
},
});
});
it("should reject CONFIDENTIAL client with code_challenge but missing method", async () => {
prismaMock.oAuthClient.findUnique.mockResolvedValue(mockConfidentialClient);
const input = {
clientId: "confidential_client_456",
scopes: [],
teamSlug: undefined,
codeChallenge: "test_challenge",
codeChallengeMethod: undefined,
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input })).rejects.toThrow(
new TRPCError({
code: "BAD_REQUEST",
message: "code_challenge_method must be S256 when PKCE is used",
})
);
expect(prismaMock.accessCode.create).not.toHaveBeenCalled();
});
});
describe("Client validation", () => {
it("should reject invalid client ID", async () => {
prismaMock.oAuthClient.findUnique.mockResolvedValue(null);
const input = {
clientId: "invalid_client",
scopes: [],
teamSlug: undefined,
codeChallenge: undefined,
codeChallengeMethod: undefined,
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input })).rejects.toThrow(
new TRPCError({
code: "UNAUTHORIZED",
message: "Client ID not valid",
})
);
expect(prismaMock.accessCode.create).not.toHaveBeenCalled();
});
it("should accept only supported PKCE methods", async () => {
const mockPublicClient = {
clientId: "public_client_123",
redirectUri: "https://app.example.com/callback",
name: "Test Public Client",
clientType: "PUBLIC" as const,
};
prismaMock.oAuthClient.findUnique.mockResolvedValue(mockPublicClient);
prismaMock.accessCode.create.mockResolvedValue({
id: 1,
code: "test_auth_code",
clientId: "public_client_123",
userId: 1,
teamId: null,
scopes: [],
codeChallenge: "test_challenge",
codeChallengeMethod: "S256",
expiresAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
});
// Test S256
const inputS256 = {
clientId: "public_client_123",
scopes: [],
teamSlug: undefined,
codeChallenge: "test_challenge",
codeChallengeMethod: "S256" as const,
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input: inputS256 })).resolves.toBeDefined();
// Reset mocks for next test
vi.clearAllMocks();
prismaMock.oAuthClient.findUnique.mockResolvedValue(mockPublicClient);
// Test invalid method
const inputInvalid = {
clientId: "public_client_123",
scopes: [],
teamSlug: undefined,
codeChallenge: "test_challenge",
codeChallengeMethod: "SHA1",
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input: inputInvalid })).rejects.toThrow(
new TRPCError({
code: "BAD_REQUEST",
message: "code_challenge_method must be S256 for public clients",
})
);
// Test plain method (should be rejected)
const inputPlain = {
clientId: "public_client_123",
scopes: [],
teamSlug: undefined,
codeChallenge: "test_challenge",
codeChallengeMethod: "plain",
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input: inputPlain })).rejects.toThrow(
new TRPCError({
code: "BAD_REQUEST",
message: "code_challenge_method must be S256 for public clients",
})
);
});
});
});
@@ -17,7 +17,7 @@ type AddClientOptions = {
};
export const generateAuthCodeHandler = async ({ ctx, input }: AddClientOptions) => {
const { clientId, scopes, teamSlug } = input;
const { clientId, scopes, teamSlug, codeChallenge, codeChallengeMethod } = input;
const client = await prisma.oAuthClient.findUnique({
where: {
clientId,
@@ -26,12 +26,37 @@ export const generateAuthCodeHandler = async ({ ctx, input }: AddClientOptions)
clientId: true,
redirectUri: true,
name: true,
clientType: true,
},
});
if (!client) {
throw new TRPCError({ code: "UNAUTHORIZED", message: "Client ID not valid" });
}
if (client.clientType === "PUBLIC") {
if (!codeChallenge) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "code_challenge required for public clients",
});
}
if (!codeChallengeMethod || codeChallengeMethod !== "S256") {
throw new TRPCError({
code: "BAD_REQUEST",
message: "code_challenge_method must be S256 for public clients",
});
}
} else if (client.clientType === "CONFIDENTIAL") {
// Optional PKCE validation for CONFIDENTIAL clients
if (codeChallenge && (!codeChallengeMethod || codeChallengeMethod !== "S256")) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "code_challenge_method must be S256 when PKCE is used",
});
}
}
const authorizationCode = generateAuthorizationCode();
const team = teamSlug
@@ -62,6 +87,8 @@ export const generateAuthCodeHandler = async ({ ctx, input }: AddClientOptions)
teamId: team ? team.id : undefined,
expiresAt: dayjs().add(10, "minutes").toDate(),
scopes: scopes as [AccessScope],
codeChallenge,
codeChallengeMethod,
},
});
return { client, authorizationCode };
@@ -4,6 +4,8 @@ export const ZGenerateAuthCodeInputSchema = z.object({
clientId: z.string(),
scopes: z.array(z.string()),
teamSlug: z.string().optional(),
codeChallenge: z.string().optional(),
codeChallengeMethod: z.enum(["S256"]).optional(),
});
export type TGenerateAuthCodeInputSchema = z.infer<typeof ZGenerateAuthCodeInputSchema>;
+2
View File
@@ -4,4 +4,6 @@ export type OAuthTokenPayload = {
token_type: string;
scope: string[];
clientId: string;
codeChallenge?: string | null;
codeChallengeMethod?: string | null;
};