-
Notifications
You must be signed in to change notification settings - Fork 515
Expand file tree
/
Copy pathmodel.tsx
More file actions
396 lines (345 loc) · 12.6 KB
/
model.tsx
File metadata and controls
396 lines (345 loc) · 12.6 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import { createMfaRequiredError } from "@/app/api/latest/auth/mfa/sign-in/verification-code-handler";
import { usersCrudHandlers } from "@/app/api/latest/users/crud";
import { Prisma } from "@/generated/prisma/client";
import { checkApiKeySet } from "@/lib/internal-api-keys";
import { isAcceptedNativeAppUrl, validateRedirectUrl } from "@/lib/redirect-urls";
import { getSoleTenancyFromProjectBranch, getTenancy } from "@/lib/tenancies";
import { createRefreshTokenObj, decodeAccessToken, generateAccessTokenFromRefreshTokenIfValid, isRefreshTokenValid } from "@/lib/tokens";
import { getPrismaClientForTenancy, globalPrismaClient } from "@/prisma-client";
import { AuthorizationCode, AuthorizationCodeModel, Client, Falsey, RefreshToken, Token, User } from "@node-oauth/oauth2-server";
import { KnownErrors } from "@stackframe/stack-shared";
import { captureError, throwErr } from "@stackframe/stack-shared/dist/utils/errors";
import { getProjectBranchFromClientId } from ".";
const PrismaClientKnownRequestError = Prisma.PrismaClientKnownRequestError;
declare module "@node-oauth/oauth2-server" {
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
interface Client {}
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
interface User {}
}
const enabledScopes = ["legacy"];
function assertScopeIsValid(scope: string[]) {
for (const s of scope) {
if (!checkScope(s)) {
throw new KnownErrors.InvalidScope(s);
}
}
}
function checkScope(scope: string | string[] | undefined) {
if (typeof scope === "string") {
return enabledScopes.includes(scope);
} else if (Array.isArray(scope)){
return scope.every((s) => enabledScopes.includes(s));
} else {
return false;
}
}
export class OAuthModel implements AuthorizationCodeModel {
async getClient(clientId: string, clientSecret: string): Promise<Client | Falsey> {
const tenancy = await getSoleTenancyFromProjectBranch(...getProjectBranchFromClientId(clientId), true);
if (!tenancy) {
return false;
}
// If client_secret is provided, validate it
// Note: The specific error handling (sentinel vs invalid key) is done in the route handlers
// that call this method, as they have more context about the request
if (clientSecret) {
const keySet = await checkApiKeySet(tenancy.project.id, { publishableClientKey: clientSecret });
if (keySet.status === "error") {
return false;
}
}
let redirectUris: string[] = [];
try {
redirectUris = Object.entries(tenancy.config.domains.trustedDomains)
// note that this may include wildcard domains, which is fine because we correctly account for them in
// model.validateRedirectUri(...)
.filter(([_, domain]) => {
return domain.baseUrl;
})
.map(([_, domain]) => new URL(domain.handlerPath, domain.baseUrl).toString());
} catch (e) {
captureError("get-oauth-redirect-urls", {
error: e,
projectId: tenancy.project.id,
domains: tenancy.config.domains,
});
throw e;
}
if (redirectUris.length === 0 && tenancy.config.domains.allowLocalhost) {
redirectUris.push("http://localhost");
}
return {
id: tenancy.project.id,
grants: ["authorization_code", "refresh_token"],
redirectUris: redirectUris,
};
}
async validateScope(user: User | null, client: Client | null, scope?: string[]): Promise<string[] | Falsey> {
if (!user) {
return false;
}
if (!client) {
return false;
}
return checkScope(scope) ? scope : false;
}
async generateAccessToken(client: Client, user: User, scope: string[]): Promise<string> {
assertScopeIsValid(scope);
const tenancy = await getSoleTenancyFromProjectBranch(...getProjectBranchFromClientId(client.id));
const refreshTokenObj = await this._getOrCreateRefreshTokenObj(client, user, scope);
return await generateAccessTokenFromRefreshTokenIfValid({
tenancy,
refreshTokenObj,
}) ?? throwErr("Get or create refresh token failed; returned refreshTokenObj that's invalid (or maybe it's an ultra-rare race condition and it became invalid in since the function call?)", { refreshTokenObj }); // TODO fix the ultra-rare race condition — although unless we're at gigascale this should basically never happen
}
async _getOrCreateRefreshTokenObj(client: Client, user: User, scope: string[]) {
const tenancy = await getSoleTenancyFromProjectBranch(...getProjectBranchFromClientId(client.id));
// if refresh token already exists and is valid, return it
if (user.refreshTokenId) {
const refreshTokenObj = await globalPrismaClient.projectUserRefreshToken.findUnique({
where: {
tenancyId_id: {
tenancyId: tenancy.id,
id: user.refreshTokenId,
},
},
});
if (refreshTokenObj && await isRefreshTokenValid({ tenancy, refreshTokenObj })) {
return refreshTokenObj;
}
}
// otherwise, create a new refresh token and set its ID on the user
const refreshTokenObj = await createRefreshTokenObj({
tenancy,
projectUserId: user.id,
});
user.refreshTokenId = refreshTokenObj.id;
return refreshTokenObj;
}
async generateRefreshToken(client: Client, user: User, scope: string[]): Promise<string> {
assertScopeIsValid(scope);
const tokenObj = await this._getOrCreateRefreshTokenObj(client, user, scope);
return tokenObj.refreshToken;
}
async saveToken(token: Token, client: Client, user: User): Promise<Token | Falsey> {
if (token.refreshToken) {
const tenancy = await getSoleTenancyFromProjectBranch(...getProjectBranchFromClientId(client.id));
const prisma = await getPrismaClientForTenancy(tenancy);
const projectUser = await prisma.projectUser.findUniqueOrThrow({
where: {
tenancyId_projectUserId: {
tenancyId: tenancy.id,
projectUserId: user.id,
},
},
});
if (projectUser.requiresTotpMfa) {
throw await createMfaRequiredError({
project: tenancy.project,
branchId: tenancy.branchId,
userId: projectUser.projectUserId,
isNewUser: false,
});
}
await globalPrismaClient.projectUserRefreshToken.upsert({
where: {
tenancyId_id: {
tenancyId: tenancy.id,
id: user.refreshTokenId,
},
},
update: {
refreshToken: token.refreshToken,
expiresAt: token.refreshTokenExpiresAt,
},
create: {
refreshToken: token.refreshToken,
tenancyId: tenancy.id,
projectUserId: user.id,
},
});
}
token.client = client;
token.user = user;
return {
accessToken: token.accessToken,
accessTokenExpiresAt: token.accessTokenExpiresAt,
refreshToken: token.refreshToken,
refreshTokenExpiresAt: token.refreshTokenExpiresAt,
scope: token.scope,
client: token.client,
user: token.user,
// TODO remove deprecated camelCase properties
newUser: user.newUser,
is_new_user: user.newUser,
afterCallbackRedirectUrl: user.afterCallbackRedirectUrl,
after_callback_redirect_url: user.afterCallbackRedirectUrl,
};
}
async getAccessToken(accessToken: string): Promise<Token | Falsey> {
const result = await decodeAccessToken(accessToken, { allowAnonymous: true, allowRestricted: true });
if (result.status === "error") {
captureError("getAccessToken", result.error);
return false;
}
const decoded = result.data;
return {
accessToken,
accessTokenExpiresAt: new Date(decoded.exp * 1000),
user: {
id: decoded.userId,
},
client: {
id: decoded.projectId,
grants: ["authorization_code", "refresh_token"],
},
scope: enabledScopes,
};
}
async getRefreshToken(refreshToken: string): Promise<RefreshToken | Falsey> {
const token = await globalPrismaClient.projectUserRefreshToken.findUnique({
where: {
refreshToken,
},
});
if (!token) {
return false;
}
const tenancy = await getTenancy(token.tenancyId);
if (!tenancy) {
// this may trigger when the tenancy was deleted after the token was created
return false;
}
if (!(await isRefreshTokenValid({ tenancy, refreshTokenObj: token }))) {
return false;
}
return {
refreshToken,
refreshTokenExpiresAt: token.expiresAt === null ? undefined : token.expiresAt,
user: {
id: token.projectUserId,
refreshTokenId: token.id,
},
client: {
id: tenancy.project.id,
grants: ["authorization_code", "refresh_token"],
},
scope: enabledScopes,
};
}
async revokeToken(token: RefreshToken): Promise<boolean> {
// No refreshToken rotation for now (see Git history for old code)
return true;
}
async verifyScope(token: Token, scope: string[]): Promise<boolean> {
return checkScope(scope);
}
async saveAuthorizationCode(
code: Pick<AuthorizationCode, 'authorizationCode' | 'expiresAt' | 'redirectUri' | 'scope' | 'codeChallenge' | 'codeChallengeMethod'>,
client: Client,
user: User
): Promise<AuthorizationCode | Falsey> {
if (!code.scope) {
throw new KnownErrors.InvalidScope("<empty string>");
}
assertScopeIsValid(code.scope);
const tenancy = await getSoleTenancyFromProjectBranch(...getProjectBranchFromClientId(client.id));
if (!validateRedirectUrl(code.redirectUri, tenancy) && !isAcceptedNativeAppUrl(code.redirectUri)) {
throw new KnownErrors.RedirectUrlNotWhitelisted();
}
await globalPrismaClient.projectUserAuthorizationCode.create({
data: {
authorizationCode: code.authorizationCode,
codeChallenge: code.codeChallenge || "",
codeChallengeMethod: code.codeChallengeMethod || "",
redirectUri: code.redirectUri,
expiresAt: code.expiresAt,
projectUserId: user.id,
newUser: user.newUser,
afterCallbackRedirectUrl: user.afterCallbackRedirectUrl,
tenancyId: tenancy.id,
},
});
return {
authorizationCode: code.authorizationCode,
expiresAt: code.expiresAt,
redirectUri: code.redirectUri,
scope: enabledScopes,
client: {
id: client.id,
grants: ["authorization_code", "refresh_token"],
},
user,
};
}
async getAuthorizationCode(authorizationCode: string): Promise<AuthorizationCode | Falsey> {
const code = await globalPrismaClient.projectUserAuthorizationCode.findUnique({
where: {
authorizationCode,
},
});
if (!code) {
return false;
}
const tenancy = await getTenancy(code.tenancyId);
if (!tenancy) {
// this may trigger when the tenancy was deleted after the code was created
return false;
}
try {
await usersCrudHandlers.adminRead({
tenancy,
user_id: code.projectUserId,
allowedErrorTypes: [KnownErrors.UserNotFound],
});
} catch (error) {
if (error instanceof KnownErrors.UserNotFound) {
// this may trigger when the user was deleted after the code was created
return false;
}
throw error;
}
return {
authorizationCode: code.authorizationCode,
expiresAt: code.expiresAt,
redirectUri: code.redirectUri,
scope: enabledScopes,
codeChallenge: code.codeChallenge,
codeChallengeMethod: code.codeChallengeMethod,
client: {
// TODO once we support branches, the branch ID should be included here
id: tenancy.project.id,
grants: ["authorization_code", "refresh_token"],
},
user: {
id: code.projectUserId,
newUser: code.newUser,
afterCallbackRedirectUrl: code.afterCallbackRedirectUrl,
},
};
}
async revokeAuthorizationCode(code: AuthorizationCode): Promise<boolean> {
try {
const deletedCode = await globalPrismaClient.projectUserAuthorizationCode.delete({
where: {
authorizationCode: code.authorizationCode,
},
});
return !!deletedCode;
} catch (error) {
if (!(error instanceof PrismaClientKnownRequestError)) {
throw error;
}
return false;
}
}
async validateRedirectUri(redirect_uri: string, client: Client): Promise<boolean> {
// Accept native app OAuth URLs without trusted domain configuration
if (isAcceptedNativeAppUrl(redirect_uri)) {
return true;
}
const tenancy = await getSoleTenancyFromProjectBranch(...getProjectBranchFromClientId(client.id));
return validateRedirectUrl(redirect_uri, tenancy);
}
}