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>
This commit is contained in:
authored and GitHub committed 2026-02-19 08:11:46 -03:00
1 parent 0eb2c15b39
commit c321a6c07a
12 files changed
+532 -67

No files matched your search

@@ -37,6 +37,7 @@ export class OAuthClientRepository {
clientSecret: true,
clientType: true,
status: true,
userId: true,
},
});
}
@@ -1,15 +1,15 @@
import { randomBytes } from "node:crypto";
import jwt from "jsonwebtoken";
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import { AccessCodeRepository } from "@calcom/features/oauth/repositories/AccessCodeRepository";
import { OAuthClientRepository } from "@calcom/features/oauth/repositories/OAuthClientRepository";
import process from "node:process";
import type { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import type { AccessCodeRepository } from "@calcom/features/oauth/repositories/AccessCodeRepository";
import type { OAuthClientRepository } from "@calcom/features/oauth/repositories/OAuthClientRepository";
import { generateSecret } from "@calcom/features/oauth/utils/generateSecret";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { ErrorWithCode } from "@calcom/lib/errors";
import { verifyCodeChallenge } from "@calcom/lib/pkce";
import { OAuthClientStatus } from "@calcom/prisma/enums";
import type { AccessScope, OAuthClientType } from "@calcom/prisma/enums";
import { OAuthClientStatus } from "@calcom/prisma/enums";
import jwt from "jsonwebtoken";
export interface OAuth2Client {
clientId: string;
@@ -82,7 +82,11 @@ export class OAuthService {
};
}
async getClientForAuthorization(clientId: string, redirectUri: string): Promise<OAuth2Client> {
async getClientForAuthorization(
clientId: string,
redirectUri: string,
loggedInUserId?: number
): Promise<OAuth2Client> {
const client = await this.oAuthClientRepository.findByClientId(clientId);
if (!client) {
@@ -91,7 +95,7 @@ export class OAuthService {
this.validateRedirectUri(client.redirectUri, redirectUri);
this.ensureClientIsApproved(client);
this.ensureClientAccessAllowed(client, loggedInUserId);
return {
clientId: client.clientId,
@@ -105,7 +109,7 @@ export class OAuthService {
async generateAuthorizationCode(
clientId: string,
userId: number,
loggedInUserId: number,
redirectUri: string,
scopes: AccessScope[],
state?: string,
@@ -119,7 +123,7 @@ export class OAuthService {
throw new ErrorWithCode(ErrorCode.Unauthorized, "unauthorized_client", { reason: "client_not_found" });
}
this.ensureClientIsApproved(client);
this.ensureClientAccessAllowed(client, loggedInUserId);
// RFC 6749 4.1.2.1: Redirect URI mismatch on Auth step is 'invalid_request'
this.validateRedirectUri(client.redirectUri, redirectUri);
@@ -143,7 +147,7 @@ export class OAuthService {
let teamId: number | undefined;
if (teamSlug) {
const team = await this.teamsRepository.findTeamBySlugWithAdminRole(teamSlug, userId);
const team = await this.teamsRepository.findTeamBySlugWithAdminRole(teamSlug, loggedInUserId);
if (!team) {
// Specific OAuth error for user denying or failing permission
throw new ErrorWithCode(ErrorCode.Unauthorized, "access_denied", {
@@ -158,7 +162,7 @@ export class OAuthService {
await this.accessCodeRepository.create({
code: authorizationCode,
clientId,
userId: teamSlug ? undefined : userId,
userId: teamSlug ? undefined : loggedInUserId,
teamId,
scopes,
codeChallenge,
@@ -173,6 +177,22 @@ export class OAuthService {
return { redirectUrl, authorizationCode, client };
}
private ensureClientAccessAllowed(
client: { status: OAuthClientStatus; userId: number | null },
loggedInUserId?: number | null
): void {
if (client.status === OAuthClientStatus.REJECTED) {
throw new ErrorWithCode(ErrorCode.Unauthorized, "unauthorized_client", {
reason: "client_rejected",
});
}
const isOwner = loggedInUserId != null && loggedInUserId === client.userId;
if (!isOwner) {
this.ensureClientIsApproved(client);
}
}
private ensureClientIsApproved(client: { status: OAuthClientStatus }): void {
if (client.status !== OAuthClientStatus.APPROVED) {
throw new ErrorWithCode(ErrorCode.Unauthorized, "unauthorized_client", {
@@ -283,6 +303,8 @@ export class OAuthService {
throw new ErrorWithCode(ErrorCode.BadRequest, "invalid_grant", { reason: "code_invalid_or_expired" });
}
this.ensureClientAccessAllowed(client, accessCode.userId);
const pkceError = this.verifyPKCE(client, accessCode, codeVerifier);
if (pkceError) {
// RFC 7636 4.4.1: If verification fails, return 'invalid_grant'
@@ -318,8 +340,6 @@ export class OAuthService {
});
}
this.ensureClientIsApproved(client);
const decodedToken = this.verifyRefreshToken(refreshToken);
if (!decodedToken || decodedToken.token_type !== "Refresh Token") {
@@ -330,6 +350,8 @@ export class OAuthService {
throw new ErrorWithCode(ErrorCode.BadRequest, "invalid_grant", { reason: "client_id_mismatch" });
}
this.ensureClientAccessAllowed(client, decodedToken.userId);
const tokens = this.createTokens({
clientId,
userId: decodedToken.userId,
@@ -459,6 +481,7 @@ export class OAuthService {
export type OAuthErrorReason =
| "client_not_found"
| "client_not_approved"
| "client_rejected"
| "redirect_uri_mismatch"
| "pkce_required"
| "invalid_code_challenge_method"
@@ -476,6 +499,7 @@ export type OAuthErrorReason =
export const OAUTH_ERROR_REASONS: Record<OAuthErrorReason, string> = {
client_not_found: "OAuth client with ID not found",
client_not_approved: "OAuth client is not approved",
client_rejected: "OAuth client has been rejected",
redirect_uri_mismatch: "redirect_uri does not match OAuth client's redirect URI",
pkce_required: "code_challenge required for public clients",
invalid_code_challenge_method: "code_challenge_method must be S256",