Files
calendar/packages/trpc/server/routers/viewer/oAuth/generateAuthCode.handler.test.ts
T
Lauris SkraucisGitHubunknown <>Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
c321a6c07a feat: owner can test non accepted OAuth client (#27525)
* refactor: combine exchange and refresh into token endpoint

* refactor: controller error handling

* refactor: use snake_case

* refactor: use snake_case

* refactor: use snake case

* refactor: token endpoint accepts application/x-www-form-urlencoded

* refactor: token endpoint accepts application/x-www-form-urlencoded

* refactor: flat token response data

* refactor: error structure

* refactor: client_id in the body

* fix: address Cubic AI review feedback on OAuth2 endpoints

- Fix getClient endpoint to use proper REST API error format instead of OAuth token error format (confidence 9/10)
- Add missing space after comma in error format string in token.input.pipe.ts (confidence 9/10)
- Support both camelCase and snake_case inputs in authorize endpoint for backward compatibility (confidence 10/10)
- Restore legacy /exchange and /refresh endpoints alongside new /token endpoint for backward compatibility (confidence 10/10)
- Add OAuth2TokensResponseDto for legacy endpoint wrapped responses
- Add OAuth2LegacyExchangeInput and OAuth2LegacyRefreshInput for legacy endpoints

Co-Authored-By: unknown <>

* fix: address additional Cubic AI feedback on OAuth2 endpoints

- Log errors when status code >= 500 in handleClientError (confidence 9/10)
- Add Cache-Control: no-store and Pragma: no-cache headers to legacy /exchange and /refresh endpoints (confidence 9/10)

Co-Authored-By: unknown <>

* docs

* Revert "fix: address additional Cubic AI feedback on OAuth2 endpoints"

This reverts commit 39cc4aa3ebb9e59a171541d7010398425995ed89.

* Revert "fix: address Cubic AI review feedback on OAuth2 endpoints"

This reverts commit 97bf593186db04c0859f9ca30950c9e3e524019d.

* docs

* fix: address Cubic AI review feedback on OAuth2 endpoints

- Fix getClient to use handleClientError instead of handleTokenError (confidence 10)
- Restore legacy /exchange and /refresh endpoints for backward compatibility (confidence 9)
- Fix RFC 6749 error format: use human-readable messages in error_description (confidence 9)
- Fix errorDescription in OAuthService to use OAUTH_ERROR_REASONS mapping (confidence 9)

Co-Authored-By: unknown <>

* fix: address additional Cubic AI feedback on OAuth2 endpoints

- Fix security issue: Replace 'CALENDSO_ENCRYPTION_KEY is not set' with generic 'Internal server configuration error' message (confidence 10/10)
- Fix backward compatibility: Create OAuth2LegacyTokensDto with camelCase properties for legacy /exchange and /refresh endpoints (confidence 9/10)
- Skipped: RFC 6749 error field issue (confidence 8/10, below threshold)

Co-Authored-By: unknown <>

* e2e

* Revert "fix: address additional Cubic AI feedback on OAuth2 endpoints"

This reverts commit a080e93f07aaf5a7dcf81fe605012cb7ebcdc192.

* Revert "fix: address Cubic AI review feedback on OAuth2 endpoints"

This reverts commit 04986a16c981521ca97069152457bf521a9ee45f.

* fix: re-apply Cubic AI review feedback on OAuth2 endpoints

- Restore OAuth2LegacyExchangeInput and OAuth2LegacyRefreshInput classes
- Restore legacy /exchange and /refresh endpoints in OAuth2Controller
- Restore OAuth2LegacyTokensDto and OAuth2TokensResponseDto classes
- Restore OAUTH_ERROR_DESCRIPTIONS mapping in oauth2-error.service.ts
- Restore OAUTH_ERROR_REASONS lookup in OAuthService.ts mapErrorToOAuthError
- Fix encryption_key_missing error to not expose internal env var name

Addresses Cubic AI feedback with confidence >= 9/10:
- Comment 32 (9/10): Legacy endpoints and input classes
- Comment 34 (9/10): Error description mapping in OAuthService
- Comment 35 (10/10): OAUTH_ERROR_DESCRIPTIONS in error service

Skipped (confidence < 9/10):
- Comment 33 (8/10): getClient handleTokenError vs handleClientError

Co-Authored-By: unknown <>

* Revert "fix: re-apply Cubic AI review feedback on OAuth2 endpoints"

This reverts commit 416bef9c931d9a7ed78c65a70a3425550d61b151.

* delete unused file

* fix: e2e tests

* address cubic review

* fix: address Cubic AI review feedback on OAuth2 exception filter

- Fix header case sensitivity: use lowercase 'x-request-id' instead of 'X-Request-Id' since Express lowercases all request headers
- Redact request body in error logs to prevent exposing sensitive OAuth2 credentials like client_secret, password, and refresh_token

Co-Authored-By: unknown <>

* docs: api v2 oauth controller docs

* chore: remove authorize endpoint

* feat: owner can test non accepted OAuth client

* fix: remove sensitive data from OAuth2 exception logs

Remove Authorization header and userEmail from error logs in
OAuth2HttpExceptionFilter to avoid logging sensitive information.

Addresses Cubic AI review feedback (confidence 9/10).

Co-Authored-By: unknown <>

* fix: e2e

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-19 08:11:46 -03:00

543 lines
17 KiB
TypeScript

import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock";
import { describe, expect, it, vi, beforeEach } from "vitest";
import { OAUTH_ERROR_REASONS } from "@calcom/features/oauth/services/OAuthService";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { TRPCError } from "@trpc/server";
import { generateAuthCodeHandler } from "./generateAuthCode.handler";
const mockUser = { id: 1 } as unknown as NonNullable<TrpcSessionUser>;
const mockCtx: { user: NonNullable<TrpcSessionUser> } = {
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,
status: "APPROVED" as const,
};
it("should generate authorization code for PUBLIC client with valid PKCE", async () => {
prismaMock.oAuthClient.findFirst.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: [],
redirectUri: "https://app.example.com/callback",
};
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.findFirst.mockResolvedValue(mockPublicClient);
const input = {
clientId: "public_client_123",
scopes: [],
teamSlug: undefined,
codeChallenge: undefined,
codeChallengeMethod: "S256" as const,
redirectUri: "https://app.example.com/callback",
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input })).rejects.toThrow(
new TRPCError({
code: "BAD_REQUEST",
message: OAUTH_ERROR_REASONS.pkce_required,
})
);
expect(prismaMock.accessCode.create).not.toHaveBeenCalled();
});
it("should reject PUBLIC client without code_challenge_method", async () => {
prismaMock.oAuthClient.findFirst.mockResolvedValue(mockPublicClient);
const input = {
clientId: "public_client_123",
scopes: [],
teamSlug: undefined,
codeChallenge: "test_challenge",
codeChallengeMethod: undefined,
redirectUri: "https://app.example.com/callback",
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input })).rejects.toThrow(
new TRPCError({
code: "BAD_REQUEST",
message: OAUTH_ERROR_REASONS.invalid_code_challenge_method,
})
);
expect(prismaMock.accessCode.create).not.toHaveBeenCalled();
});
it("should reject PUBLIC client with invalid code_challenge_method", async () => {
prismaMock.oAuthClient.findFirst.mockResolvedValue(mockPublicClient);
// Test with MD5 (invalid method)
const inputMD5 = {
clientId: "public_client_123",
scopes: [],
teamSlug: undefined,
codeChallenge: "test_challenge",
codeChallengeMethod: "MD5",
redirectUri: "https://app.example.com/callback",
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input: inputMD5 })).rejects.toThrow(
new TRPCError({
code: "BAD_REQUEST",
message: OAUTH_ERROR_REASONS.invalid_code_challenge_method,
})
);
// Test with plain (should be rejected)
const inputPlain = {
clientId: "public_client_123",
scopes: [],
teamSlug: undefined,
codeChallenge: "test_challenge",
codeChallengeMethod: "plain",
redirectUri: "https://app.example.com/callback",
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input: inputPlain })).rejects.toThrow(
new TRPCError({
code: "BAD_REQUEST",
message: OAUTH_ERROR_REASONS.invalid_code_challenge_method,
})
);
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,
isTrusted: undefined,
logo: undefined,
status: "APPROVED" as const,
};
it("should generate authorization code for CONFIDENTIAL client without PKCE", async () => {
prismaMock.oAuthClient.findFirst.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,
redirectUri: "https://app.example.com/callback",
};
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.findFirst.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,
redirectUri: "https://app.example.com/callback",
state: "1234",
};
const result = await generateAuthCodeHandler({ ctx: mockCtx, input });
expect(result.authorizationCode).toBeDefined();
expect(result.redirectUrl).toEqual(
`https://app.example.com/callback?code=${result.authorizationCode}&state=1234`
);
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.findFirst.mockResolvedValue(mockConfidentialClient);
const input = {
clientId: "confidential_client_456",
scopes: [],
teamSlug: undefined,
codeChallenge: "test_challenge",
codeChallengeMethod: undefined,
redirectUri: "https://app.example.com/callback",
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input })).rejects.toThrow(
new TRPCError({
code: "BAD_REQUEST",
message: OAUTH_ERROR_REASONS.invalid_code_challenge_method,
})
);
expect(prismaMock.accessCode.create).not.toHaveBeenCalled();
});
});
describe("Client validation", () => {
it("should reject invalid client ID", async () => {
prismaMock.oAuthClient.findFirst.mockResolvedValue(null);
const input = {
clientId: "invalid_client",
scopes: [],
teamSlug: undefined,
codeChallenge: undefined,
codeChallengeMethod: undefined,
redirectUri: "https://app.example.com/callback",
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input })).rejects.toThrow(
new TRPCError({
code: "UNAUTHORIZED",
message: OAUTH_ERROR_REASONS.client_not_found,
})
);
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,
status: "APPROVED" as const,
};
prismaMock.oAuthClient.findFirst.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",
redirectUri: "https://app.example.com/callback",
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.findFirst.mockResolvedValue(mockPublicClient);
// Test invalid method
const inputInvalid = {
clientId: "public_client_123",
redirectUri: "https://app.example.com/callback",
scopes: [],
teamSlug: undefined,
codeChallenge: "test_challenge",
codeChallengeMethod: "SHA1",
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input: inputInvalid })).rejects.toThrow(
new TRPCError({
code: "BAD_REQUEST",
message: OAUTH_ERROR_REASONS.invalid_code_challenge_method,
})
);
// Test plain method (should be rejected)
const inputPlain = {
clientId: "public_client_123",
scopes: [],
teamSlug: undefined,
codeChallenge: "test_challenge",
codeChallengeMethod: "plain",
redirectUri: "https://app.example.com/callback",
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input: inputPlain })).rejects.toThrow(
new TRPCError({
code: "BAD_REQUEST",
message: OAUTH_ERROR_REASONS.invalid_code_challenge_method,
})
);
});
it("should reject PENDING client", async () => {
const mockPendingClient = {
clientId: "pending_client_123",
redirectUri: "https://app.example.com/callback",
name: "Test Pending Client",
clientType: "CONFIDENTIAL" as const,
status: "PENDING" as const,
};
prismaMock.oAuthClient.findFirst.mockResolvedValue(mockPendingClient);
const input = {
clientId: "pending_client_123",
scopes: [],
teamSlug: undefined,
codeChallenge: undefined,
codeChallengeMethod: undefined,
redirectUri: "https://app.example.com/callback",
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input })).rejects.toThrow(
new TRPCError({
code: "UNAUTHORIZED",
message: OAUTH_ERROR_REASONS.client_not_approved,
})
);
expect(prismaMock.accessCode.create).not.toHaveBeenCalled();
});
it("should reject REJECTED client", async () => {
const mockRejectedClient = {
clientId: "rejected_client_123",
redirectUri: "https://app.example.com/callback",
name: "Test Rejected Client",
clientType: "CONFIDENTIAL" as const,
status: "REJECTED" as const,
};
prismaMock.oAuthClient.findFirst.mockResolvedValue(mockRejectedClient);
const input = {
clientId: "rejected_client_123",
scopes: [],
teamSlug: undefined,
codeChallenge: undefined,
codeChallengeMethod: undefined,
redirectUri: "https://app.example.com/callback",
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input })).rejects.toThrow(
new TRPCError({
code: "UNAUTHORIZED",
message: OAUTH_ERROR_REASONS.client_rejected,
})
);
expect(prismaMock.accessCode.create).not.toHaveBeenCalled();
});
it("should reject REJECTED client even when user is the owner", async () => {
const mockRejectedClientOwnedByUser = {
clientId: "rejected_client_owned",
redirectUri: "https://app.example.com/callback",
name: "Test Rejected Client Owned",
clientType: "CONFIDENTIAL" as const,
status: "REJECTED" as const,
userId: 1,
};
prismaMock.oAuthClient.findFirst.mockResolvedValue(mockRejectedClientOwnedByUser);
const input = {
clientId: "rejected_client_owned",
scopes: [],
teamSlug: undefined,
codeChallenge: undefined,
codeChallengeMethod: undefined,
redirectUri: "https://app.example.com/callback",
};
await expect(generateAuthCodeHandler({ ctx: mockCtx, input })).rejects.toThrow(
new TRPCError({
code: "UNAUTHORIZED",
message: OAUTH_ERROR_REASONS.client_rejected,
})
);
expect(prismaMock.accessCode.create).not.toHaveBeenCalled();
});
it("should allow PENDING client when user is the owner", async () => {
const mockPendingClientOwnedByUser = {
clientId: "pending_client_owned",
redirectUri: "https://app.example.com/callback",
name: "Test Pending Client Owned",
clientType: "CONFIDENTIAL" as const,
status: "PENDING" as const,
userId: 1,
};
prismaMock.oAuthClient.findFirst.mockResolvedValue(mockPendingClientOwnedByUser);
prismaMock.accessCode.create.mockResolvedValue({
id: 1,
code: "test_auth_code",
clientId: "pending_client_owned",
userId: 1,
teamId: null,
scopes: [],
codeChallenge: null,
codeChallengeMethod: null,
expiresAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
});
const input = {
clientId: "pending_client_owned",
scopes: [],
teamSlug: undefined,
codeChallenge: undefined,
codeChallengeMethod: undefined,
redirectUri: "https://app.example.com/callback",
};
const result = await generateAuthCodeHandler({ ctx: mockCtx, input });
expect(result.authorizationCode).toBeDefined();
});
it("should allow APPROVED client when user is the owner", async () => {
const mockApprovedClientOwnedByUser = {
clientId: "approved_client_owned",
redirectUri: "https://app.example.com/callback",
name: "Test Approved Client Owned",
clientType: "CONFIDENTIAL" as const,
status: "APPROVED" as const,
userId: 1,
};
prismaMock.oAuthClient.findFirst.mockResolvedValue(mockApprovedClientOwnedByUser);
prismaMock.accessCode.create.mockResolvedValue({
id: 1,
code: "test_auth_code",
clientId: "approved_client_owned",
userId: 1,
teamId: null,
scopes: [],
codeChallenge: null,
codeChallengeMethod: null,
expiresAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
});
const input = {
clientId: "approved_client_owned",
scopes: [],
teamSlug: undefined,
codeChallenge: undefined,
codeChallengeMethod: undefined,
redirectUri: "https://app.example.com/callback",
};
const result = await generateAuthCodeHandler({ ctx: mockCtx, input });
expect(result.authorizationCode).toBeDefined();
});
});
});