feat: OAuth2 controller api v2 + refactor oAuth Trpc handlers (#25989)

* feat(api-v2): add OAuth2 controller skeleton for auth module

- Add new OAuth2 module under /auth with controller, service, repository, and DTOs
- Implement skeleton endpoints:
  - GET /v2/auth/oauth2/clients/:clientId - Get OAuth client info
  - POST /v2/auth/oauth2/clients/:clientId/authorize - Generate authorization code
  - POST /v2/auth/oauth2/clients/:clientId/exchange - Exchange code for tokens
  - POST /v2/auth/oauth2/clients/:clientId/refresh - Refresh access token
- Create input DTOs for authorize, exchange, and refresh operations
- Create output DTOs for client info, authorization code, and tokens
- Register OAuth2Module in endpoints.module.ts

Co-Authored-By: [email protected] <[email protected]>

* chore: add missing functions to platform libraries

* feat(api-v2): integrate OAuthService from platform-libraries into OAuth2 controller

- Add OAuthService export to platform-libraries
- Refactor OAuth2Service to use OAuthService.validateClient() and OAuthService.verifyPKCE()
- Remove duplicate local implementations of validateClient and verifyPKCE methods

Co-Authored-By: [email protected] <[email protected]>

* feat(api-v2): use local validateClient and verifyPKCE implementations

- Remove OAuthService export from platform-libraries (will be deprecated)
- Reimplement validateClient and verifyPKCE methods locally in OAuth2Service
- Use verifyCodeChallenge and generateSecret from platform-libraries directly

Co-Authored-By: [email protected] <[email protected]>

* refactor(api-v2): separate repositories for OAuth2, access codes, and teams

- Create AccessCodeRepository for access code Prisma operations
- Add findTeamBySlugWithAdminRole method to TeamsRepository
- Move generateAuthorizationCode, createTokens, verifyRefreshToken to OAuth2Service
- Update OAuth2Repository to only contain OAuth client operations
- Update OAuth2Module to import TeamsModule and provide AccessCodeRepository

Addresses PR review comments to properly separate concerns

Co-Authored-By: [email protected] <[email protected]>

* feat(api-v2): implement JWT token creation and verification for OAuth2

- Implement createTokens method using jsonwebtoken to sign access and refresh tokens
- Implement verifyRefreshToken method to verify JWT refresh tokens
- Add ConfigService injection for CALENDSO_ENCRYPTION_KEY access
- Import ConfigModule in OAuth2Module for dependency injection

Based on logic from apps/web/app/api/auth/oauth/token/route.ts and
apps/web/app/api/auth/oauth/refreshToken/route.ts

Co-Authored-By: [email protected] <[email protected]>

* fix: refactor and dayjs import fix

* feat(api-v2): add ApiAuthGuard to getClient endpoint and e2e tests for OAuth2

- Add @UseGuards(ApiAuthGuard) to getClient endpoint for authentication
- Add comprehensive e2e tests for all OAuth2 endpoints:
  - GET /v2/auth/oauth2/clients/:clientId
  - POST /v2/auth/oauth2/clients/:clientId/authorize
  - POST /v2/auth/oauth2/clients/:clientId/exchange
  - POST /v2/auth/oauth2/clients/:clientId/refresh
- Tests cover happy paths and error cases (invalid client, invalid code, etc.)

Co-Authored-By: [email protected] <[email protected]>

* chore(api-v2): hide OAuth2 endpoints from Swagger documentation

Co-Authored-By: [email protected] <[email protected]>

* hide endpoints from doc

* fix(api-v2): address PR feedback for OAuth2 controller

- Fix P0 critical bug: token_type field name mismatch in DecodedRefreshToken interface
- Add @Equals('authorization_code') validation to exchange.input.ts grantType
- Add @Equals('refresh_token') validation to refresh.input.ts grantType
- Add @IsNotEmpty() validation to get-client.input.ts clientId
- Add @Expose() decorators to all output DTOs for proper serialization
- Add security test assertion to verify clientSecret is not returned in response

Co-Authored-By: [email protected] <[email protected]>

* feat(api-v2): implement redirect behavior for OAuth2 authorize endpoint

- Update authorize endpoint to return HTTP 303 redirect with authorization code
- Add exact match validation for redirect URI (security requirement)
- Implement error handling with redirect to redirect URI and error query params
- Add state parameter support for CSRF protection
- Update e2e tests to verify redirect behavior (303 status, Location header, error redirects)

Co-Authored-By: [email protected] <[email protected]>

* refactor(api-v2): address PR feedback for OAuth2 authorize endpoint

- Make redirectUri a required input parameter (remove optional fallback)
- Move buildRedirectUrl and mapErrorToOAuthError to oauth2Service
- Add return statements to res.redirect() calls
- Simplify controller by delegating redirect URL building to service

Co-Authored-By: [email protected] <[email protected]>

* wip move code outside of api v2

* feat(oauth): wire up dependency injection for OAuthService and repositories

Co-Authored-By: [email protected] <[email protected]>

* refactor: oAuthService used in routes

* fix imports

* fix(api-v2): return 404 for invalid client ID instead of redirect in authorize endpoint

Co-Authored-By: [email protected] <[email protected]>

* fix(api-v2): fix E2E test URL paths and remove bootstrap() in authenticated section

- Remove bootstrap() call in authenticated section to match working test pattern
- Change URL paths from /api/v2/... to /v2/... in authenticated section
- Keep bootstrap() and /api/v2/... paths in unauthenticated section

Co-Authored-By: [email protected] <[email protected]>

* fix(api-v2): mock getToken from next-auth/jwt for E2E tests

- Add jest.mock for next-auth/jwt getToken function
- Mock returns null for unauthenticated tests
- Mock returns { email: userEmail } for authenticated tests
- Remove withNextAuth helper since ApiAuthGuard uses ApiAuthStrategy
  which calls getToken directly, not NextAuthStrategy

Co-Authored-By: [email protected] <[email protected]>

* fix tests and code review

* cleanup generate secrets

* cleanup controller

* chore: remove console.log from OAuthService.validateClient

Co-Authored-By: [email protected] <[email protected]>

* Update apps/web/app/api/auth/oauth/refreshToken/route.ts

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

* fix(api-v2): add bootstrap() to authenticated E2E tests and update URL paths to /api/v2/

Co-Authored-By: [email protected] <[email protected]>

* Merge remote-tracking branch 'origin/devin/oauth2-controller-skeleton-1765988792' and remove console.log from token route

Co-Authored-By: [email protected] <[email protected]>

* chore: remove dead code

* refactor

* refactor: generateAuthCode trpc handler and getClient trpc handler

* remove pkce check for refreshToken endpoint

* Update packages/trpc/server/routers/viewer/oAuth/getClient.handler.ts

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

* refactor: error handling

* refactor: error handling

* refactor: error handling

* remove console log

* provide redirectUri in generateAuthCodeHandler

* provide redirectUri in authorize view

* refactor: replace HttpError with ErrorWithCode in OAuth files

- Update OAuthService to use ErrorWithCode instead of HttpError
- Update mapErrorToOAuthError to check ErrorCode instead of status codes
- Update token/route.ts and refreshToken/route.ts to use ErrorWithCode
- Add ErrorWithCode export to platform-libraries
- Use getHttpStatusCode to map ErrorCode to HTTP status codes

Co-Authored-By: [email protected] <[email protected]>

* fix: update generateAuthCode handler to use ErrorWithCode instead of HttpError

The handler was still checking for HttpError in its catch block, but OAuthService
now throws ErrorWithCode. This caused the error messages to be lost and replaced
with 'server_error' instead of the specific error messages.

Co-Authored-By: [email protected] <[email protected]>

* fix: update OAuth2 controller to use ErrorWithCode instead of HttpError

The controller was still checking for HttpError in its catch blocks, but OAuthService
now throws ErrorWithCode. This caused all errors to return 500 Internal Server Error
instead of the correct HTTP status codes (400, 401, 404).

Also added getHttpStatusCode export to platform-libraries.

Co-Authored-By: [email protected] <[email protected]>

* fix: add explicit unknown type annotation to catch blocks in OAuth2 controller

Co-Authored-By: [email protected] <[email protected]>

* fix: change NotFoundException to HttpException in authorize endpoint

Co-Authored-By: [email protected] <[email protected]>

* fix: handle err with ErrorWithCode in authorize endpoint catch block

Co-Authored-By: [email protected] <[email protected]>

* fix: move errorWithCode

* fix: error code rfc

* fix: no need to handle errors there is a middleware

* refactor errors

* refactor errors

* refactor redirecturi and state from api

* refactor: address PR comments for OAuth2 controller

- Remove unused GetOAuth2ClientInput class
- Change API tag from 'Auth / OAuth2' to 'OAuth2'
- Move OAuthClientFixture to separate fixture file (oauth2-client.repository.fixture.ts)
- Add 'type' property to OAuth2ClientDto for confidential/public client type
- Rename 'clientId' to 'id' in OAuth2ClientDto (using @Expose mapping)
- Clean up duplicate provider declarations in oauth2.module.ts
- Update e2e tests to use new fixture and verify type property

Co-Authored-By: Volnei Munhoz <[email protected]>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Volnei Munhoz <[email protected]>
Co-authored-by: Volnei Munhoz <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-01-07 08:05:21 -03:00
1 parent ca32f04cc1
commit 61a932f8f5
44 files changed
+1683 -366

No files matched your search

@@ -58,16 +58,15 @@ import { X_CAL_CLIENT_ID, X_CAL_PLATFORM_EMBED } from "@calcom/platform-constant
import { BOOKING_READ, SUCCESS_STATUS, BOOKING_WRITE } from "@calcom/platform-constants";
import {
BookingResponse,
HttpError,
handleMarkNoShow,
getAllUserBookings,
getBookingInfo,
handleCancelBooking,
getBookingForReschedule,
ErrorCode,
} from "@calcom/platform-libraries";
import { CreationSource } from "@calcom/platform-libraries";
import { type InstantBookingCreateResult } from "@calcom/platform-libraries/bookings";
import { HttpError, ErrorCode } from "@calcom/platform-libraries/errors";
import {
GetBookingsInput_2024_04_15,
CancelBookingInput_2024_04_15,
@@ -125,7 +124,7 @@ export class BookingsController_2024_04_15 {
private readonly instantBookingCreateService: InstantBookingCreateService,
private readonly eventTypeRepository: PrismaEventTypeRepository,
private readonly teamRepository: PrismaTeamRepository
) { }
) {}
@Get("/")
@UseGuards(ApiAuthGuard)
@@ -0,0 +1,13 @@
import { PrismaAccessCodeRepository } from "@/lib/repositories/prisma-access-code.repository";
import { PrismaOAuthClientRepository } from "@/lib/repositories/prisma-oauth-client.repository";
import { PrismaTeamRepository } from "@/lib/repositories/prisma-team.repository";
import { OAuthService } from "@/lib/services/oauth.service";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { Module } from "@nestjs/common";
@Module({
imports: [PrismaModule],
providers: [PrismaAccessCodeRepository, PrismaOAuthClientRepository, PrismaTeamRepository, OAuthService],
exports: [OAuthService],
})
export class oAuthServiceModule {}
@@ -0,0 +1,12 @@
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { PrismaAccessCodeRepository as PrismaAccessCodeRepositoryLib } from "@calcom/platform-libraries/repositories";
import type { PrismaClient } from "@calcom/prisma";
@Injectable()
export class PrismaAccessCodeRepository extends PrismaAccessCodeRepositoryLib {
constructor(private readonly dbWrite: PrismaWriteService) {
super(dbWrite.prisma as unknown as PrismaClient);
}
}
@@ -0,0 +1,12 @@
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { PrismaOAuthClientRepository as PrismaOAuthClientRepositoryLib } from "@calcom/platform-libraries/repositories";
import type { PrismaClient } from "@calcom/prisma";
@Injectable()
export class PrismaOAuthClientRepository extends PrismaOAuthClientRepositoryLib {
constructor(private readonly dbWrite: PrismaWriteService) {
super(dbWrite.prisma as unknown as PrismaClient);
}
}
@@ -0,0 +1,21 @@
import { PrismaAccessCodeRepository } from "@/lib/repositories/prisma-access-code.repository";
import { PrismaOAuthClientRepository } from "@/lib/repositories/prisma-oauth-client.repository";
import { PrismaTeamRepository } from "@/lib/repositories/prisma-team.repository";
import { Injectable } from "@nestjs/common";
import { OAuthService as BaseOAuthService } from "@calcom/platform-libraries";
@Injectable()
export class OAuthService extends BaseOAuthService {
constructor(
accessCodeRepository: PrismaAccessCodeRepository,
oAuthClientRepository: PrismaOAuthClientRepository,
teamsRepository: PrismaTeamRepository
) {
super({
accessCodeRepository: accessCodeRepository,
oAuthClientRepository: oAuthClientRepository,
teamsRepository: teamsRepository,
});
}
}
@@ -0,0 +1,319 @@
import { bootstrap } from "@/app";
import { AppModule } from "@/app.module";
import { HttpExceptionFilter } from "@/filters/http-exception.filter";
import { PrismaExceptionFilter } from "@/filters/prisma-exception.filter";
import { ZodExceptionFilter } from "@/filters/zod-exception.filter";
import { AuthModule } from "@/modules/auth/auth.module";
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { UsersModule } from "@/modules/users/users.module";
import { INestApplication } from "@nestjs/common";
import { NestExpressApplication } from "@nestjs/platform-express";
import { Test, TestingModule } from "@nestjs/testing";
import * as nextAuthJwt from "next-auth/jwt";
import * as request from "supertest";
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
import { OAuth2ClientRepositoryFixture } from "test/fixtures/repository/oauth2-client.repository.fixture";
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
import { randomString } from "test/utils/randomString";
import { generateSecret } from "@calcom/platform-libraries";
import type { Membership, Team, User } from "@calcom/prisma/client";
import { AccessScope, OAuthClientType } from "@calcom/prisma/enums";
// Mock next-auth/jwt getToken for ApiAuthStrategy NEXT_AUTH authentication
jest.mock("next-auth/jwt", () => ({
getToken: jest.fn(),
}));
const mockGetToken = nextAuthJwt.getToken as jest.MockedFunction<typeof nextAuthJwt.getToken>;
describe("OAuth2 Controller Endpoints", () => {
describe("User Not Authenticated", () => {
let appWithoutAuth: INestApplication;
beforeAll(async () => {
// Mock getToken to return null for unauthenticated tests
mockGetToken.mockResolvedValue(null);
const moduleRef = await Test.createTestingModule({
providers: [PrismaExceptionFilter, HttpExceptionFilter, ZodExceptionFilter],
imports: [AppModule, UsersModule, AuthModule, PrismaModule],
}).compile();
appWithoutAuth = moduleRef.createNestApplication();
bootstrap(appWithoutAuth as NestExpressApplication);
await appWithoutAuth.init();
});
it("GET /v2/auth/oauth2/clients/:clientId should return 401 without auth", () => {
return request(appWithoutAuth.getHttpServer())
.get("/api/v2/auth/oauth2/clients/test-client-id")
.expect(401);
});
it("POST /v2/auth/oauth2/clients/:clientId/authorize should return 401 without auth", () => {
return request(appWithoutAuth.getHttpServer())
.post("/api/v2/auth/oauth2/clients/test-client-id/authorize")
.send({
redirectUri: "https://example.com/callback",
scopes: ["READ_BOOKING"],
})
.expect(401);
});
afterAll(async () => {
await appWithoutAuth.close();
});
});
describe("User Authenticated", () => {
let app: INestApplication;
let moduleRef: TestingModule;
let userRepositoryFixture: UserRepositoryFixture;
let teamRepositoryFixture: TeamRepositoryFixture;
let membershipRepositoryFixture: MembershipRepositoryFixture;
let oAuthClientFixture: OAuth2ClientRepositoryFixture;
let user: User;
let team: Team;
let membership: Membership;
let oAuthClient: { clientId: string };
let authorizationCode: string;
let refreshToken: string;
const testClientId = `test-oauth-client-${randomString()}`;
const testClientSecret = "test-secret-123";
const testRedirectUri = "https://example.com/callback";
beforeAll(async () => {
const userEmail = `oauth2-e2e-user-${randomString()}@api.com`;
// Mock getToken to return the user email for authenticated tests
// This is needed because ApiAuthGuard uses ApiAuthStrategy which calls getToken from next-auth/jwt
mockGetToken.mockResolvedValue({ email: userEmail });
moduleRef = await Test.createTestingModule({
providers: [PrismaExceptionFilter, HttpExceptionFilter, ZodExceptionFilter],
imports: [AppModule, UsersModule, AuthModule, PrismaModule],
}).compile();
app = moduleRef.createNestApplication();
bootstrap(app as NestExpressApplication);
await app.init();
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
teamRepositoryFixture = new TeamRepositoryFixture(moduleRef);
membershipRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
oAuthClientFixture = new OAuth2ClientRepositoryFixture(moduleRef);
user = await userRepositoryFixture.create({
email: userEmail,
});
team = await teamRepositoryFixture.create({
name: `oauth2-e2e-team-${randomString()}`,
slug: `oauth2-e2e-team-${randomString()}`,
});
membership = await membershipRepositoryFixture.create({
user: { connect: { id: user.id } },
team: { connect: { id: team.id } },
role: "OWNER",
accepted: true,
});
const [hashedSecret] = generateSecret(testClientSecret);
oAuthClient = await oAuthClientFixture.create({
clientId: testClientId,
name: "Test OAuth Client",
redirectUri: testRedirectUri,
clientSecret: hashedSecret,
clientType: OAuthClientType.CONFIDENTIAL,
});
});
describe("GET /api/v2/auth/oauth2/clients/:clientId", () => {
it("should return OAuth client info for valid client ID", async () => {
const response = await request(app.getHttpServer())
.get(`/api/v2/auth/oauth2/clients/${testClientId}`)
.expect(200);
expect(response.body.status).toBe("success");
expect(response.body.data.id).toBe(testClientId);
expect(response.body.data.name).toBe("Test OAuth Client");
expect(response.body.data.redirectUri).toBe(testRedirectUri);
expect(response.body.data.type).toBe(OAuthClientType.CONFIDENTIAL);
expect(response.body.data.clientSecret).toBeUndefined();
});
it("should return 404 for non-existent client ID", async () => {
await request(app.getHttpServer())
.get("/api/v2/auth/oauth2/clients/non-existent-client-id")
.expect(404);
});
});
describe("POST /api/v2/auth/oauth2/clients/:clientId/authorize", () => {
it("should redirect with authorization code for valid request", async () => {
const response = await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/authorize`)
.send({
redirectUri: testRedirectUri,
scopes: [AccessScope.READ_BOOKING, AccessScope.READ_PROFILE],
teamSlug: team.slug,
state: "test-state-123",
})
.expect(303);
expect(response.headers.location).toBeDefined();
const redirectUrl = new URL(response.headers.location);
expect(redirectUrl.origin + redirectUrl.pathname).toBe(testRedirectUri);
expect(redirectUrl.searchParams.get("code")).toBeDefined();
expect(redirectUrl.searchParams.get("state")).toBe("test-state-123");
authorizationCode = redirectUrl.searchParams.get("code") as string;
});
it("should redirect with error for invalid client ID", async () => {
await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/clients/invalid-client-id/authorize")
.send({
redirectUri: testRedirectUri,
scopes: [AccessScope.READ_BOOKING],
})
.expect(404);
});
it("should redirect with error for invalid team slug", async () => {
const response = await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/authorize`)
.send({
redirectUri: testRedirectUri,
scopes: [AccessScope.READ_BOOKING],
teamSlug: "non-existent-team-slug",
state: "test-state-456",
})
.expect(303);
expect(response.headers.location).toBeDefined();
const redirectUrl = new URL(response.headers.location);
expect(redirectUrl.searchParams.get("error")).toBe("access_denied");
expect(redirectUrl.searchParams.get("state")).toBe("test-state-456");
});
it("should throw error 400 for mismatched redirect URI", async () => {
await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/authorize`)
.send({
redirectUri: "https://wrong-domain.com/callback",
scopes: [AccessScope.READ_BOOKING],
state: "test-state-789",
})
.expect(400);
});
});
describe("POST /api/v2/auth/oauth2/clients/:clientId/exchange", () => {
it("should exchange authorization code for tokens", async () => {
const response = await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/exchange`)
.send({
code: authorizationCode,
clientSecret: testClientSecret,
redirectUri: testRedirectUri,
})
.expect(200);
expect(response.body.status).toBe("success");
expect(response.body.data.access_token).toBeDefined();
expect(response.body.data.refresh_token).toBeDefined();
expect(response.body.data.token_type).toBe("bearer");
expect(response.body.data.expires_in).toBe(1800);
refreshToken = response.body.data.refresh_token;
});
it("should return 400 for invalid/used authorization code", async () => {
await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/exchange`)
.send({
code: authorizationCode,
clientSecret: testClientSecret,
redirectUri: testRedirectUri,
})
.expect(400);
});
it("should return 401 for invalid client secret", async () => {
const newAuthResponse = await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/authorize`)
.send({
redirectUri: testRedirectUri,
scopes: [AccessScope.READ_BOOKING],
teamSlug: team.slug,
})
.expect(303);
const newRedirectUrl = new URL(newAuthResponse.headers.location);
const newAuthCode = newRedirectUrl.searchParams.get("code") as string;
await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/exchange`)
.send({
code: newAuthCode,
clientSecret: "wrong-secret",
redirectUri: testRedirectUri,
})
.expect(401);
});
});
describe("POST /api/v2/auth/oauth2/clients/:clientId/refresh", () => {
it("should refresh access token with valid refresh token", async () => {
const response = await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/refresh`)
.send({
refreshToken: refreshToken,
clientSecret: testClientSecret,
})
.expect(200);
expect(response.body.status).toBe("success");
expect(response.body.data.access_token).toBeDefined();
expect(response.body.data.refresh_token).toBeDefined();
expect(response.body.data.token_type).toBe("bearer");
expect(response.body.data.expires_in).toBe(1800);
});
it("should return 400 for invalid refresh token", async () => {
await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/refresh`)
.send({
refreshToken: "invalid-refresh-token",
clientSecret: testClientSecret,
})
.expect(400);
});
it("should return 401 for wrong client ID with valid refresh token", async () => {
await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/clients/wrong-client-id/refresh")
.send({
refreshToken: refreshToken,
clientSecret: testClientSecret,
})
.expect(401);
});
});
afterAll(async () => {
await oAuthClientFixture.delete(oAuthClient.clientId);
await membershipRepositoryFixture.delete(membership.id);
await teamRepositoryFixture.delete(team.id);
await userRepositoryFixture.delete(user.id);
await app.close();
});
});
});
@@ -0,0 +1,168 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { OAuthService } from "@/lib/services/oauth.service";
import { ApiAuthGuardOnlyAllow } from "@/modules/auth/decorators/api-auth-guard-only-allow.decorator";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { OAuth2AuthorizeInput } from "@/modules/auth/oauth2/inputs/authorize.input";
import { OAuth2ExchangeInput } from "@/modules/auth/oauth2/inputs/exchange.input";
import { OAuth2RefreshInput } from "@/modules/auth/oauth2/inputs/refresh.input";
import { OAuth2ClientDto, OAuth2ClientResponseDto } from "@/modules/auth/oauth2/outputs/oauth2-client.output";
import { OAuth2TokensDto, OAuth2TokensResponseDto } from "@/modules/auth/oauth2/outputs/oauth2-tokens.output";
import {
Body,
Controller,
Get,
HttpCode,
HttpException,
HttpStatus,
InternalServerErrorException,
Logger,
Param,
Post,
Res,
UseGuards,
} from "@nestjs/common";
import { ApiExcludeController, ApiOperation, ApiTags } from "@nestjs/swagger";
import { plainToInstance } from "class-transformer";
import type { Response } from "express";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { ErrorWithCode, getHttpStatusCode } from "@calcom/platform-libraries/errors";
@Controller({
path: "/v2/auth/oauth2/clients/:clientId",
version: API_VERSIONS_VALUES,
})
@ApiExcludeController(true)
@ApiTags("OAuth2")
export class OAuth2Controller {
private readonly logger = new Logger("OAuth2Controller");
constructor(private readonly oAuthService: OAuthService) {}
@Get("/")
@HttpCode(HttpStatus.OK)
@UseGuards(ApiAuthGuard)
@ApiOperation({
summary: "Get OAuth2 client",
description: "Returns the OAuth2 client information for the given client ID",
})
async getClient(@Param("clientId") clientId: string): Promise<OAuth2ClientResponseDto> {
try {
const client = await this.oAuthService.getClient(clientId);
return {
status: SUCCESS_STATUS,
data: plainToInstance(OAuth2ClientDto, client, { strategy: "excludeAll" }),
};
} catch (err: unknown) {
if (err instanceof ErrorWithCode) {
const statusCode = getHttpStatusCode(err);
throw new HttpException(err.message, statusCode);
}
this.logger.error(err);
throw new InternalServerErrorException("Could not get oAuthClient");
}
}
@Post("/authorize")
@UseGuards(ApiAuthGuard)
@ApiAuthGuardOnlyAllow(["NEXT_AUTH"])
@ApiOperation({
summary: "Generate authorization code",
description:
"Generates an authorization code for the OAuth2 flow and redirects to the redirect URI with the code. Requires user authentication.",
})
async authorize(
@Param("clientId") clientId: string,
@Body() body: OAuth2AuthorizeInput,
@GetUser("id") userId: number,
@Res() res: Response
): Promise<void> {
try {
const client = await this.oAuthService.getClient(clientId);
const result = await this.oAuthService.generateAuthorizationCode(
client.clientId,
userId,
body.redirectUri,
body.scopes,
body.state,
body.teamSlug,
body.codeChallenge,
body.codeChallengeMethod
);
return res.redirect(303, result.redirectUrl);
} catch (err: unknown) {
if (err instanceof ErrorWithCode) {
if (err.message === "unauthorized_client" || err?.data?.["reason"] === "redirect_uri_mismatch") {
const statusCode = getHttpStatusCode(err);
throw new HttpException(err.message, statusCode);
}
}
const errorRedirectUrl = this.oAuthService.buildErrorRedirectUrl(body.redirectUri, err, body.state);
return res.redirect(303, errorRedirectUrl);
}
}
@Post("/exchange")
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary: "Exchange authorization code for tokens",
description: "Exchanges an authorization code for access and refresh tokens",
})
async exchange(
@Param("clientId") clientId: string,
@Body() body: OAuth2ExchangeInput
): Promise<OAuth2TokensResponseDto> {
try {
const tokens = await this.oAuthService.exchangeCodeForTokens(
clientId,
body.code,
body.clientSecret,
body.redirectUri,
body.codeVerifier
);
return {
status: SUCCESS_STATUS,
data: plainToInstance(OAuth2TokensDto, tokens, { strategy: "excludeAll" }),
};
} catch (err: unknown) {
if (err instanceof ErrorWithCode) {
const statusCode = getHttpStatusCode(err);
throw new HttpException(err.message, statusCode);
}
this.logger.error(err);
throw new InternalServerErrorException("Could not exchange code for tokens");
}
}
@Post("/refresh")
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary: "Refresh access token",
description: "Refreshes an access token using a refresh token",
})
async refresh(
@Param("clientId") clientId: string,
@Body() body: OAuth2RefreshInput
): Promise<OAuth2TokensResponseDto> {
try {
const tokens = await this.oAuthService.refreshAccessToken(
clientId,
body.refreshToken,
body.clientSecret
);
return {
status: SUCCESS_STATUS,
data: plainToInstance(OAuth2TokensDto, tokens, { strategy: "excludeAll" }),
};
} catch (err: unknown) {
if (err instanceof ErrorWithCode) {
const statusCode = getHttpStatusCode(err);
throw new HttpException(err.message, statusCode);
}
this.logger.error(err);
throw new InternalServerErrorException("Could not refresh tokens");
}
}
}
@@ -0,0 +1,53 @@
import { ApiHideProperty, ApiProperty } from "@nestjs/swagger";
import { Equals, IsArray, IsEnum, IsOptional, IsString } from "class-validator";
import { AccessScope } from "@calcom/prisma/enums";
export class OAuth2AuthorizeInput {
@ApiProperty({
description:
"The redirect URI to redirect to after authorization. Must exactly match the registered redirect URI.",
example: "https://example.com/callback",
})
@IsString()
redirectUri!: string;
@ApiProperty({
description: "OAuth state parameter for CSRF protection. Will be included in the redirect.",
required: false,
})
@IsOptional()
@IsString()
state?: string;
@ApiProperty({
description: "The scopes to request",
enum: AccessScope,
isArray: true,
example: ["READ_BOOKING", "READ_PROFILE"],
})
@IsArray()
@IsEnum(AccessScope, { each: true })
scopes: AccessScope[] = [];
@ApiProperty({
description: "The team slug to authorize for (optional)",
required: false,
})
@IsOptional()
@IsString()
teamSlug?: string;
@ApiProperty({
description: "PKCE code challenge (required for public clients)",
required: false,
})
@IsOptional()
@IsString()
codeChallenge?: string;
@ApiHideProperty()
@IsString()
@Equals("S256")
codeChallengeMethod: string = "S256";
}
@@ -0,0 +1,39 @@
import { ApiHideProperty, ApiProperty } from "@nestjs/swagger";
import { Equals, IsOptional, IsString } from "class-validator";
export class OAuth2ExchangeInput {
@ApiProperty({
description: "The authorization code received from the authorize endpoint",
example: "abc123",
})
@IsString()
code!: string;
@ApiProperty({
description: "The client secret (required for confidential clients)",
required: false,
})
@IsOptional()
@IsString()
clientSecret?: string;
@ApiProperty({
description: "The redirect URI used in the authorization request",
example: "https://example.com/callback",
})
@IsString()
redirectUri!: string;
@ApiHideProperty()
@IsString()
@Equals("authorization_code")
grantType: string = "authorization_code";
@ApiProperty({
description: "PKCE code verifier (required if code_challenge was used)",
required: false,
})
@IsOptional()
@IsString()
codeVerifier?: string;
}
@@ -0,0 +1,24 @@
import { ApiHideProperty, ApiProperty } from "@nestjs/swagger";
import { Equals, IsOptional, IsString } from "class-validator";
export class OAuth2RefreshInput {
@ApiProperty({
description: "The refresh token",
example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
})
@IsString()
refreshToken!: string;
@ApiProperty({
description: "The client secret (required for confidential clients)",
required: false,
})
@IsOptional()
@IsString()
clientSecret?: string;
@ApiHideProperty()
@IsString()
@Equals("refresh_token")
grantType: string = "refresh_token";
}
@@ -0,0 +1,9 @@
import { oAuthServiceModule } from "@/lib/modules/oauth.module";
import { OAuth2Controller } from "@/modules/auth/oauth2/controllers/oauth2.controller";
import { Module } from "@nestjs/common";
@Module({
imports: [oAuthServiceModule],
controllers: [OAuth2Controller],
})
export class OAuth2Module {}
@@ -0,0 +1,74 @@
import { ApiProperty } from "@nestjs/swagger";
import { Expose, Type } from "class-transformer";
import { IsBoolean, IsEnum, IsNotEmptyObject, IsOptional, IsString, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
import { OAuthClientType } from "@calcom/prisma/enums";
export class OAuth2ClientDto {
@ApiProperty({
description: "The OAuth client ID",
example: "clxxxxxxxxxxxxxxxx",
})
@IsString()
@Expose({ name: "clientId" })
id!: string;
@ApiProperty({
description: "The redirect URI for the OAuth client",
example: "https://example.com/callback",
})
@IsString()
@Expose()
redirectUri!: string;
@ApiProperty({
description: "The name of the OAuth client",
example: "My App",
})
@IsString()
@Expose()
name!: string;
@ApiProperty({
description: "The logo URL of the OAuth client",
required: false,
})
@IsOptional()
@IsString()
@Expose()
logo?: string | null;
@ApiProperty({
description: "Whether the OAuth client is trusted",
example: false,
})
@IsBoolean()
@Expose()
isTrusted!: boolean;
@ApiProperty({
description: "The type of OAuth client (CONFIDENTIAL or PUBLIC)",
example: "CONFIDENTIAL",
enum: OAuthClientType,
})
@IsEnum(OAuthClientType)
@Expose({ name: "clientType" })
type!: OAuthClientType;
}
export class OAuth2ClientResponseDto {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
@Expose()
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@ApiProperty({
type: OAuth2ClientDto,
})
@IsNotEmptyObject()
@ValidateNested()
@Type(() => OAuth2ClientDto)
@Expose()
data!: OAuth2ClientDto;
}
@@ -0,0 +1,55 @@
import { ApiProperty } from "@nestjs/swagger";
import { Expose, Type } from "class-transformer";
import { IsEnum, IsNotEmptyObject, IsNumber, IsString, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
export class OAuth2TokensDto {
@ApiProperty({
description: "The access token",
example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
})
@IsString()
@Expose({ name: "accessToken" })
access_token!: string;
@ApiProperty({
description: "The token type",
example: "bearer",
})
@IsString()
@Expose({ name: "tokenType" })
token_type!: string;
@ApiProperty({
description: "The refresh token",
example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
})
@IsString()
@Expose({ name: "refreshToken" })
refresh_token!: string;
@ApiProperty({
description: "The number of seconds until the access token expires",
example: 1800,
})
@IsNumber()
@Expose({ name: "expiresIn" })
expires_in!: number;
}
export class OAuth2TokensResponseDto {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
@Expose()
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@ApiProperty({
type: OAuth2TokensDto,
})
@IsNotEmptyObject()
@ValidateNested()
@Type(() => OAuth2TokensDto)
@Expose()
data!: OAuth2TokensDto;
}
+3 -1
View File
@@ -1,5 +1,6 @@
import { PlatformEndpointsModule } from "@/ee/platform-endpoints-module";
import { AtomsModule } from "@/modules/atoms/atoms.module";
import { OAuth2Module } from "@/modules/auth/oauth2/oauth2.module";
import { BillingModule } from "@/modules/billing/billing.module";
import { CalUnifiedCalendarsModule } from "@/modules/cal-unified-calendars/cal-unified-calendars.module";
import { ConferencingModule } from "@/modules/conferencing/conferencing.module";
@@ -22,6 +23,7 @@ import { WebhooksModule } from "./webhooks/webhooks.module";
@Module({
imports: [
OAuth2Module,
OAuthClientModule,
BillingModule,
PlatformEndpointsModule,
@@ -43,7 +45,7 @@ import { WebhooksModule } from "./webhooks/webhooks.module";
],
})
export class EndpointsModule implements NestModule {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
configure(_consumer: MiddlewareConsumer) {
// TODO: apply ratelimits
}
@@ -0,0 +1,43 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { TestingModule } from "@nestjs/testing";
import { OAuthClientType } from "@calcom/prisma/enums";
export class OAuth2ClientRepositoryFixture {
private prismaReadClient: PrismaReadService["prisma"];
private prismaWriteClient: PrismaWriteService["prisma"];
constructor(module: TestingModule) {
this.prismaReadClient = module.get(PrismaReadService).prisma;
this.prismaWriteClient = module.get(PrismaWriteService).prisma;
}
async create(data: {
clientId: string;
name: string;
redirectUri: string;
clientSecret?: string;
clientType?: OAuthClientType;
logo?: string;
isTrusted?: boolean;
}) {
return this.prismaWriteClient.oAuthClient.create({
data: {
clientId: data.clientId,
name: data.name,
redirectUri: data.redirectUri,
clientSecret: data.clientSecret,
clientType: data.clientType || OAuthClientType.CONFIDENTIAL,
logo: data.logo,
isTrusted: data.isTrusted || false,
},
});
}
async delete(clientId: string) {
return this.prismaWriteClient.oAuthClient.delete({
where: { clientId },
});
}
}
+2 -1
View File
@@ -30,7 +30,8 @@
"@calcom/platform-libraries/repositories": ["../../../packages/platform/libraries/repositories.ts"],
"@calcom/platform-libraries/bookings": ["../../../packages/platform/libraries/bookings.ts"],
"@calcom/platform-libraries/private-links": ["../../../packages/platform/libraries/private-links.ts"],
"@calcom/platform-libraries/organizations": ["../../../packages/platform/libraries/organizations.ts"]
"@calcom/platform-libraries/organizations": ["../../../packages/platform/libraries/organizations.ts"],
"@calcom/platform-libraries/errors": ["../../../packages/platform/libraries/errors.ts"]
},
"incremental": true,
"skipLibCheck": true,
@@ -1,19 +1,18 @@
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
import { parseUrlFormData } from "app/api/parseRequestData";
import jwt from "jsonwebtoken";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { OAuthClientRepository } from "@calcom/features/oauth/repositories/OAuthClientRepository";
import { OAuthService } from "@calcom/features/oauth/services/OAuthService";
import prisma from "@calcom/prisma";
import type { OAuthTokenPayload } from "@calcom/types/oauth";
import { getOAuthService } from "@calcom/features/oauth/di/OAuthService.container";
import { OAUTH_ERROR_REASONS } from "@calcom/features/oauth/services/OAuthService";
import { ErrorWithCode } from "@calcom/lib/errors";
import { getHttpStatusCode } from "@calcom/lib/server/getServerErrorFromUnknown";
async function handler(req: NextRequest) {
const { client_id, client_secret, grant_type, refresh_token } = await parseUrlFormData(req);
if (!process.env.CALENDSO_ENCRYPTION_KEY) {
return NextResponse.json({ message: "CALENDSO_ENCRYPTION_KEY is not set" }, { status: 500 });
return NextResponse.json({ message: OAUTH_ERROR_REASONS["encryption_key_missing"] }, { status: 500 });
}
if (!client_id) {
@@ -23,87 +22,33 @@ async function handler(req: NextRequest) {
if (grant_type !== "refresh_token") {
return NextResponse.json({ error: "invalid_request" }, { status: 400 });
}
const oAuthClientRepository = new OAuthClientRepository(prisma);
const client = await oAuthClientRepository.findByClientId(client_id);
if (!client) {
return NextResponse.json({ error: "invalid_client" }, { status: 401 });
}
const isValidClient = OAuthService.validateClient(client, client_secret);
if (!isValidClient) {
return NextResponse.json({ error: "invalid_client" }, { status: 401 });
}
const secretKey = process.env.CALENDSO_ENCRYPTION_KEY;
let decodedRefreshToken: OAuthTokenPayload;
try {
const oAuthService = getOAuthService();
const refreshTokenValue = refresh_token || req.headers.get("authorization")?.split(" ")[1] || "";
const tokens = await oAuthService.refreshAccessToken(client_id, refreshTokenValue, client_secret);
if (!refreshTokenValue) {
return NextResponse.json({ error: "invalid_request" }, { status: 400 });
}
decodedRefreshToken = jwt.verify(refreshTokenValue, secretKey) as OAuthTokenPayload;
} catch {
return NextResponse.json({ error: "invalid_grant" }, { status: 400 });
}
if (!decodedRefreshToken || decodedRefreshToken.token_type !== "Refresh Token") {
return NextResponse.json({ error: "invalid_grant" }, { status: 400 });
}
if (decodedRefreshToken.clientId !== client_id) {
return NextResponse.json({ error: "invalid_grant" }, { status: 400 });
}
const accessTokenExpiresIn = 1800; // 30 minutes
const payloadAuthToken: OAuthTokenPayload = {
userId: decodedRefreshToken.userId,
teamId: decodedRefreshToken.teamId,
scope: decodedRefreshToken.scope,
token_type: "Access Token",
clientId: client_id,
};
const payloadRefreshToken: OAuthTokenPayload = {
userId: decodedRefreshToken.userId,
teamId: decodedRefreshToken.teamId,
scope: decodedRefreshToken.scope,
token_type: "Refresh Token",
clientId: client_id,
};
const access_token = jwt.sign(payloadAuthToken, secretKey, {
expiresIn: accessTokenExpiresIn,
});
const refresh_token_new = jwt.sign(payloadRefreshToken, secretKey, {
expiresIn: 30 * 24 * 60 * 60, // 30 days
});
return NextResponse.json(
{
access_token,
token_type: "bearer",
refresh_token: refresh_token_new,
expires_in: accessTokenExpiresIn,
},
{
status: 200,
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Cache-Control": "no-store",
Pragma: "no-cache",
return NextResponse.json(
{
access_token: tokens.accessToken,
token_type: "bearer",
refresh_token: tokens.refreshToken,
expires_in: tokens.expiresIn,
},
{
status: 200,
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Cache-Control": "no-store",
Pragma: "no-cache",
},
}
);
} catch (err) {
if (err instanceof ErrorWithCode) {
return NextResponse.json({ error: err.message }, { status: getHttpStatusCode(err) });
}
);
return NextResponse.json({ error: "server_error" }, { status: 500 });
}
}
export const POST = defaultResponderForAppDir(handler);
@@ -5,8 +5,8 @@ import jwt from "jsonwebtoken";
import { NextRequest } from "next/server";
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import { generateSecret } from "@calcom/features/oauth/utils/generateSecret";
import { verifyCodeChallenge } from "@calcom/lib/pkce";
import { generateSecret } from "@calcom/trpc/server/routers/viewer/oAuth/addClient.handler";
import { POST } from "../route";
@@ -55,7 +55,7 @@ vi.mock("@calcom/lib/pkce", () => ({
verifyCodeChallenge: vi.fn(),
}));
vi.mock("@calcom/trpc/server/routers/viewer/oAuth/addClient.handler", () => ({
vi.mock("@calcom/features/oauth/utils/generateSecret", () => ({
generateSecret: vi.fn(),
}));
@@ -160,8 +160,8 @@ describe("POST /api/auth/oauth/token", () => {
} as const;
it("should exchange authorization code for tokens with valid PKCE", async () => {
prismaMock.oAuthClient.findFirst.mockResolvedValue(
mockPublicClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findFirst>>
prismaMock.oAuthClient.findUnique.mockResolvedValue(
mockPublicClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findUnique>>
);
prismaMock.accessCode.findFirst.mockResolvedValue(
mockAccessCode as unknown as Awaited<ReturnType<typeof prismaMock.accessCode.findFirst>>
@@ -195,8 +195,8 @@ describe("POST /api/auth/oauth/token", () => {
});
it("should reject PUBLIC client without code_verifier", async () => {
prismaMock.oAuthClient.findFirst.mockResolvedValue(
mockPublicClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findFirst>>
prismaMock.oAuthClient.findUnique.mockResolvedValue(
mockPublicClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findUnique>>
);
prismaMock.accessCode.findFirst.mockResolvedValue(
mockAccessCode as unknown as Awaited<ReturnType<typeof prismaMock.accessCode.findFirst>>
@@ -219,8 +219,8 @@ describe("POST /api/auth/oauth/token", () => {
});
it("should reject PUBLIC client with missing code challenge in access code", async () => {
prismaMock.oAuthClient.findFirst.mockResolvedValue(
mockPublicClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findFirst>>
prismaMock.oAuthClient.findUnique.mockResolvedValue(
mockPublicClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findUnique>>
);
prismaMock.accessCode.findFirst.mockResolvedValue({
...mockAccessCode,
@@ -246,8 +246,8 @@ describe("POST /api/auth/oauth/token", () => {
});
it("should reject PUBLIC client with invalid code_verifier", async () => {
prismaMock.oAuthClient.findFirst.mockResolvedValue(
mockPublicClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findFirst>>
prismaMock.oAuthClient.findUnique.mockResolvedValue(
mockPublicClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findUnique>>
);
prismaMock.accessCode.findFirst.mockResolvedValue(
mockAccessCode as unknown as Awaited<ReturnType<typeof prismaMock.accessCode.findFirst>>
@@ -290,8 +290,8 @@ describe("POST /api/auth/oauth/token", () => {
} as const;
it("should exchange authorization code for tokens with valid client secret", async () => {
prismaMock.oAuthClient.findFirst.mockResolvedValue(
mockConfidentialClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findFirst>>
prismaMock.oAuthClient.findUnique.mockResolvedValue(
mockConfidentialClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findUnique>>
);
prismaMock.accessCode.findFirst.mockResolvedValue(
mockAccessCode as unknown as Awaited<ReturnType<typeof prismaMock.accessCode.findFirst>>
@@ -325,8 +325,8 @@ describe("POST /api/auth/oauth/token", () => {
});
it("should reject CONFIDENTIAL client without client_secret", async () => {
prismaMock.oAuthClient.findFirst.mockResolvedValue(
mockConfidentialClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findFirst>>
prismaMock.oAuthClient.findUnique.mockResolvedValue(
mockConfidentialClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findUnique>>
);
const tokenRequest = createTokenRequest({
@@ -346,8 +346,8 @@ describe("POST /api/auth/oauth/token", () => {
});
it("should reject CONFIDENTIAL client with invalid client_secret", async () => {
prismaMock.oAuthClient.findFirst.mockResolvedValue(
mockConfidentialClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findFirst>>
prismaMock.oAuthClient.findUnique.mockResolvedValue(
mockConfidentialClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findUnique>>
);
mockGenerateSecret.mockReturnValue(["different_hashed_secret", "wrong_secret"]);
@@ -377,8 +377,8 @@ describe("POST /api/auth/oauth/token", () => {
codeChallengeMethod: "S256",
} as const;
prismaMock.oAuthClient.findFirst.mockResolvedValue(
mockConfidentialClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findFirst>>
prismaMock.oAuthClient.findUnique.mockResolvedValue(
mockConfidentialClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findUnique>>
);
prismaMock.accessCode.findFirst.mockResolvedValue(
mockAccessCodeWithPKCE as unknown as Awaited<ReturnType<typeof prismaMock.accessCode.findFirst>>
@@ -422,8 +422,8 @@ describe("POST /api/auth/oauth/token", () => {
codeChallengeMethod: "S256",
} as const;
prismaMock.oAuthClient.findFirst.mockResolvedValue(
mockConfidentialClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findFirst>>
prismaMock.oAuthClient.findUnique.mockResolvedValue(
mockConfidentialClient as Awaited<ReturnType<typeof prismaMock.oAuthClient.findUnique>>
);
prismaMock.accessCode.findFirst.mockResolvedValue(
mockAccessCodeWithPKCE as unknown as Awaited<ReturnType<typeof prismaMock.accessCode.findFirst>>
@@ -471,7 +471,7 @@ describe("POST /api/auth/oauth/token", () => {
});
it("should reject invalid client_id", async () => {
prismaMock.oAuthClient.findFirst.mockResolvedValue(null);
prismaMock.oAuthClient.findUnique.mockResolvedValue(null);
const tokenRequest = createTokenRequest({
grant_type: "authorization_code",
@@ -490,11 +490,11 @@ describe("POST /api/auth/oauth/token", () => {
});
it("should reject mismatched redirect_uri", async () => {
prismaMock.oAuthClient.findFirst.mockResolvedValue({
prismaMock.oAuthClient.findUnique.mockResolvedValue({
redirectUri: "https://app.example.com/callback",
clientSecret: null,
clientType: "PUBLIC" as const,
} as Awaited<ReturnType<typeof prismaMock.oAuthClient.findFirst>>);
} as Awaited<ReturnType<typeof prismaMock.oAuthClient.findUnique>>);
const tokenRequest = createTokenRequest({
grant_type: "authorization_code",
@@ -513,11 +513,11 @@ describe("POST /api/auth/oauth/token", () => {
});
it("should reject expired authorization code", async () => {
prismaMock.oAuthClient.findFirst.mockResolvedValue({
prismaMock.oAuthClient.findUnique.mockResolvedValue({
redirectUri: "https://app.example.com/callback",
clientSecret: null,
clientType: "PUBLIC" as const,
} as Awaited<ReturnType<typeof prismaMock.oAuthClient.findFirst>>);
} as Awaited<ReturnType<typeof prismaMock.oAuthClient.findUnique>>);
prismaMock.accessCode.findFirst.mockResolvedValue(null);
const tokenRequest = createTokenRequest({
+34 -81
View File
@@ -1,14 +1,12 @@
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
import { parseUrlFormData } from "app/api/parseRequestData";
import jwt from "jsonwebtoken";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { AccessCodeRepository } from "@calcom/features/oauth/repositories/AccessCodeRepository";
import { OAuthClientRepository } from "@calcom/features/oauth/repositories/OAuthClientRepository";
import { OAuthService } from "@calcom/features/oauth/services/OAuthService";
import prisma from "@calcom/prisma";
import type { OAuthTokenPayload } from "@calcom/types/oauth";
import { getOAuthService } from "@calcom/features/oauth/di/OAuthService.container";
import { OAUTH_ERROR_REASONS } from "@calcom/features/oauth/services/OAuthService";
import { ErrorWithCode } from "@calcom/lib/errors";
import { getHttpStatusCode } from "@calcom/lib/server/getServerErrorFromUnknown";
async function handler(req: NextRequest) {
const { code, client_id, client_secret, grant_type, redirect_uri, code_verifier } = await parseUrlFormData(
@@ -16,7 +14,7 @@ async function handler(req: NextRequest) {
);
if (!process.env.CALENDSO_ENCRYPTION_KEY) {
return NextResponse.json({ message: "CALENDSO_ENCRYPTION_KEY is not set" }, { status: 500 });
return NextResponse.json({ message: OAUTH_ERROR_REASONS["encryption_key_missing"] }, { status: 500 });
}
if (!client_id || !code || !redirect_uri) {
@@ -27,83 +25,38 @@ async function handler(req: NextRequest) {
return NextResponse.json({ error: "invalid_request" }, { status: 400 });
}
const oAuthClientRepository = new OAuthClientRepository(prisma);
const accessCodeRepository = new AccessCodeRepository(prisma);
try {
const oAuthService = getOAuthService();
const tokens = await oAuthService.exchangeCodeForTokens(
client_id,
code,
client_secret,
redirect_uri,
code_verifier
);
const client = await oAuthClientRepository.findByClientId(client_id);
if (!client) {
return NextResponse.json({ error: "invalid_client" }, { status: 401 });
}
if (client.redirectUri !== redirect_uri) {
return NextResponse.json({ error: "invalid_grant" }, { status: 400 });
}
const isValidClient = OAuthService.validateClient(client, client_secret);
if (!isValidClient) {
return NextResponse.json({ error: "invalid_client" }, { status: 401 });
}
const accessCode = await accessCodeRepository.findValidCode(code, client_id);
// Delete all expired accessCodes + the one that is used here
await accessCodeRepository.deleteExpiredAndUsedCodes(code, client_id);
if (!accessCode) {
return NextResponse.json({ error: "invalid_grant" }, { status: 400 });
}
const pkceError = OAuthService.verifyPKCE(client, accessCode, code_verifier);
if (pkceError) {
return NextResponse.json({ error: pkceError.error }, { status: pkceError.status });
}
const secretKey = process.env.CALENDSO_ENCRYPTION_KEY;
const payloadAuthToken: OAuthTokenPayload = {
userId: accessCode.userId,
teamId: accessCode.teamId,
scope: accessCode.scopes,
token_type: "Access Token",
clientId: client_id,
};
const payloadRefreshToken: OAuthTokenPayload = {
userId: accessCode.userId,
teamId: accessCode.teamId,
scope: accessCode.scopes,
token_type: "Refresh Token",
clientId: client_id,
// Include PKCE information for clients that used PKCE (PUBLIC mandatory, CONFIDENTIAL optional)
...(accessCode.codeChallenge && {
codeChallenge: accessCode.codeChallenge,
codeChallengeMethod: accessCode.codeChallengeMethod,
}),
};
const accessTokenExpiresIn = 1800; // 30 minutes
const access_token = jwt.sign(payloadAuthToken, secretKey, {
expiresIn: accessTokenExpiresIn,
});
const refresh_token = jwt.sign(payloadRefreshToken, secretKey, {
expiresIn: 30 * 24 * 60 * 60, // 30 days
});
return NextResponse.json(
{ access_token, token_type: "bearer", refresh_token, expires_in: accessTokenExpiresIn },
{
status: 200,
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Cache-Control": "no-store",
Pragma: "no-cache",
return NextResponse.json(
{
access_token: tokens.accessToken,
token_type: "bearer",
refresh_token: tokens.refreshToken,
expires_in: tokens.expiresIn,
},
{
status: 200,
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Cache-Control": "no-store",
Pragma: "no-cache",
},
}
);
} catch (err) {
if (err instanceof ErrorWithCode) {
return NextResponse.json({ error: err.message }, { status: getHttpStatusCode(err) });
}
);
}
return NextResponse.json({ error: "error_code_exchange" }, { status: 500 });
}
export const POST = defaultResponderForAppDir(handler);
@@ -46,7 +46,8 @@ export default function Authorize() {
const generateAuthCodeMutation = trpc.viewer.oAuth.generateAuthCode.useMutation({
onSuccess: (data) => {
window.location.href = `${client?.redirectUri}?code=${data.authorizationCode}&state=${state}`;
window.location.href =
data.redirectUrl ?? `${client?.redirectUri}?code=${data.authorizationCode}&state=${state}`;
},
onError: (error) => {
let oauthError = "server_error";
@@ -96,9 +97,11 @@ export default function Authorize() {
if (client?.isTrusted && selectedAccount) {
generateAuthCodeMutation.mutate({
clientId: client_id as string,
redirectUri: client.redirectUri,
scopes,
codeChallenge: code_challenge || undefined,
codeChallengeMethod: (code_challenge_method as "S256") || undefined,
state,
});
}
}, [client?.isTrusted, selectedAccount]);
@@ -223,11 +226,13 @@ export default function Authorize() {
generateAuthCodeMutation.mutate({
clientId: client_id as string,
scopes,
redirectUri: client.redirectUri,
teamSlug: selectedAccount?.value.startsWith("team/")
? selectedAccount?.value.substring(5)
: undefined, // team account starts with /team/<slug>
codeChallenge: code_challenge || undefined,
codeChallengeMethod: (code_challenge_method as "S256") || undefined,
state,
});
}}
data-testid="allow-button">
+3 -2
View File
@@ -1,9 +1,10 @@
import { expect } from "@playwright/test";
import { createHash, randomBytes } from "node:crypto";
import { OAUTH_ERROR_REASONS } from "@calcom/features/oauth/services/OAuthService";
import { generateSecret } from "@calcom/features/oauth/utils/generateSecret";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { prisma } from "@calcom/prisma";
import { generateSecret } from "@calcom/trpc/server/routers/viewer/oAuth/addClient.handler";
import { test } from "./lib/fixtures";
@@ -417,7 +418,7 @@ test.describe("OAuth Provider - PKCE (Public Clients)", () => {
const url = new URL(page.url());
expect(url.searchParams.get("error")).toBe("invalid_request");
expect(url.searchParams.get("error_description")).toBe("code_challenge required for public clients");
expect(url.searchParams.get("error_description")).toBe(OAUTH_ERROR_REASONS["pkce_required"]);
expect(url.searchParams.get("state")).toBe("1234");
// Should not contain authorization code
expect(url.searchParams.get("code")).toBeNull();