Files
calendar/packages/trpc/server/routers/viewer/oAuth/generateAuthCode.handler.test.ts
T
Carina WollendorferGitHubcubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>CarinaWollicubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
4e0798577a 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 <wollencarina@gmail.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-11-26 17:02:42 +01:00

355 lines
11 KiB
TypeScript

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: "test@example.com",
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",
})
);
});
});
});