-
Notifications
You must be signed in to change notification settings - Fork 12.2k
Expand file tree
/
Copy pathpermissions.guard.ts
More file actions
172 lines (148 loc) · 6.47 KB
/
permissions.guard.ts
File metadata and controls
172 lines (148 loc) · 6.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import {
BOOKING_READ,
BOOKING_WRITE,
EVENT_TYPE_READ,
EVENT_TYPE_WRITE,
PROFILE_READ,
SCHEDULE_READ,
SCHEDULE_WRITE,
X_CAL_CLIENT_ID,
} from "@calcom/platform-constants";
import { hasPermissions } from "@calcom/platform-utils";
import type { PlatformOAuthClient } from "@calcom/prisma/client";
import type { AccessScope } from "@calcom/prisma/enums";
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Reflector } from "@nestjs/core";
import { getToken } from "next-auth/jwt";
import { isApiKey } from "@/lib/api-key";
import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
import { OAuthClientsOutputService } from "@/modules/oauth-clients/services/oauth-clients/oauth-clients-output.service";
import { TokensRepository } from "@/modules/tokens/tokens.repository";
import { TokensService } from "@/modules/tokens/tokens.service";
// note(Lauris): exclude legacy scopes
type NewAccessScope = Exclude<AccessScope, "READ_BOOKING" | "READ_PROFILE">;
// scope name -> permission number (for checking if token has required permissions)
const SCOPE_TO_PERMISSION: Record<NewAccessScope, number> = {
EVENT_TYPE_READ: EVENT_TYPE_READ,
EVENT_TYPE_WRITE: EVENT_TYPE_WRITE,
BOOKING_READ: BOOKING_READ,
BOOKING_WRITE: BOOKING_WRITE,
SCHEDULE_READ: SCHEDULE_READ,
SCHEDULE_WRITE: SCHEDULE_WRITE,
PROFILE_READ: PROFILE_READ,
};
const PERMISSION_TO_SCOPE: Record<number, NewAccessScope> = {
[EVENT_TYPE_READ]: "EVENT_TYPE_READ",
[EVENT_TYPE_WRITE]: "EVENT_TYPE_WRITE",
[BOOKING_READ]: "BOOKING_READ",
[BOOKING_WRITE]: "BOOKING_WRITE",
[SCHEDULE_READ]: "SCHEDULE_READ",
[SCHEDULE_WRITE]: "SCHEDULE_WRITE",
[PROFILE_READ]: "PROFILE_READ",
};
@Injectable()
export class PermissionsGuard implements CanActivate {
constructor(
private reflector: Reflector,
private tokensRepository: TokensRepository,
private tokensService: TokensService,
private readonly config: ConfigService,
private readonly oAuthClientRepository: OAuthClientRepository,
private readonly oAuthClientsOutputService: OAuthClientsOutputService
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const requiredPermissions = this.reflector.get(Permissions, context.getHandler());
if (!requiredPermissions?.length || !Object.keys(requiredPermissions)?.length) {
return true;
}
const request = context.switchToHttp().getRequest();
const bearerToken = request.get("Authorization")?.replace("Bearer ", "");
const nextAuthSecret = this.config.get("next.authSecret", { infer: true });
const nextAuthToken = await getToken({ req: request, secret: nextAuthSecret });
const oAuthClientId = request.params?.clientId || request.get(X_CAL_CLIENT_ID);
const apiKey = bearerToken && isApiKey(bearerToken, this.config.get("api.apiKeyPrefix") ?? "cal_");
const decodedThirdPartyToken = bearerToken ? this.getDecodedThirdPartyAccessToken(bearerToken) : null;
if (nextAuthToken || apiKey) {
return true;
}
if (decodedThirdPartyToken) {
return this.checkThirdPartyTokenPermissions(decodedThirdPartyToken, requiredPermissions);
}
if (!bearerToken && !oAuthClientId) {
throw new ForbiddenException(
"PermissionsGuard - no authentication provided. Provide either authorization bearer token containing managed user access token or oAuth client id in 'x-cal-client-id' header."
);
}
const oAuthClient = bearerToken
? await this.getOAuthClientByAccessToken(bearerToken)
: await this.getOAuthClientById(oAuthClientId);
const hasRequiredPermissions = hasPermissions(oAuthClient.permissions, [...requiredPermissions]);
if (!hasRequiredPermissions) {
throw new ForbiddenException(
`PermissionsGuard - oAuth client with id=${
oAuthClient.id
} does not have the required permissions=${requiredPermissions
.map((permission) => this.oAuthClientsOutputService.transformOAuthClientPermission(permission))
.join(
", "
)}. Go to platform dashboard settings and add the required permissions to the oAuth client.`
);
}
return true;
}
async getOAuthClientByAccessToken(
accessToken: string
): Promise<Pick<PlatformOAuthClient, "id" | "permissions">> {
const oAuthClient = await this.tokensRepository.getAccessTokenClient(accessToken);
if (!oAuthClient) {
throw new ForbiddenException(
`PermissionsGuard - no oAuth client found for access token=${accessToken}`
);
}
return oAuthClient;
}
async getOAuthClientById(id: string): Promise<Pick<PlatformOAuthClient, "id" | "permissions">> {
const oAuthClient = await this.oAuthClientRepository.getOAuthClient(id);
if (!oAuthClient) {
throw new ForbiddenException(`PermissionsGuard - no oAuth client found for client id=${id}`);
}
return oAuthClient;
}
checkThirdPartyTokenPermissions(
decodedToken: { scope?: string[] },
requiredPermissions: number[]
): boolean {
const tokenScopes: string[] = decodedToken.scope ?? [];
if (tokenScopes.length === 0) {
return true;
}
const tokenPermissions = this.resolveTokenPermissions(tokenScopes);
// note(Lauris): legacy access tokens either did not have scopes defined or had legacy scopes defined,
// if so give full access just like we have been doing up until now.
if (tokenPermissions.size === 0) {
return true;
}
const missingPermissions = requiredPermissions.filter((permission) => !tokenPermissions.has(permission));
if (missingPermissions.length > 0) {
const missingScopeNames = missingPermissions.map((permission) => PERMISSION_TO_SCOPE[permission]).filter(Boolean);
throw new ForbiddenException(
`insufficient_scope: token does not have the required scopes. Required: ${missingScopeNames.join(", ")}. Token has: ${tokenScopes.join(", ")}`
);
}
return true;
}
private resolveTokenPermissions(scopes: string[]): Set<number> {
const permissions = new Set<number>();
for (const scope of scopes) {
if (scope in SCOPE_TO_PERMISSION) {
permissions.add(SCOPE_TO_PERMISSION[scope as NewAccessScope]);
}
}
return permissions;
}
getDecodedThirdPartyAccessToken(bearerToken: string) {
return this.tokensService.getDecodedThirdPartyAccessToken(bearerToken);
}
}