-
Notifications
You must be signed in to change notification settings - Fork 452
Expand file tree
/
Copy pathmachineAuthHelpers.ts
More file actions
543 lines (466 loc) · 18 KB
/
machineAuthHelpers.ts
File metadata and controls
543 lines (466 loc) · 18 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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
import { randomBytes } from 'node:crypto';
import type { ClerkClient, M2MToken, Machine, OAuthApplication, User } from '@clerk/backend';
import { createClerkClient } from '@clerk/backend';
import { TokenType } from '@clerk/backend/internal';
import { faker } from '@faker-js/faker';
import type { Page } from '@playwright/test';
import { expect, test } from '@playwright/test';
import type { Application } from '../models/application';
import type { ApplicationConfig } from '../models/applicationConfig';
import type { EnvironmentConfig } from '../models/environment';
import { appConfigs } from '../presets';
import { instanceKeys } from '../presets/envs';
import { createTestUtils } from './index';
import type { FakeAPIKey, FakeUser } from './usersService';
export type FakeMachineNetwork = {
primaryServer: Machine;
scopedSender: Machine;
unscopedSender: Machine;
scopedSenderToken: M2MToken;
unscopedSenderToken: M2MToken;
cleanup: () => Promise<void>;
};
async function createFakeMachineNetwork(clerkClient: ClerkClient): Promise<FakeMachineNetwork> {
const fakeCompanyName = faker.company.name();
const primaryServer = await clerkClient.machines.create({
name: `${fakeCompanyName} Primary API Server`,
});
const scopedSender = await clerkClient.machines.create({
name: `${fakeCompanyName} Scoped Sender`,
scopedMachines: [primaryServer.id],
});
const scopedSenderToken = await clerkClient.m2m.createToken({
machineSecretKey: scopedSender.secretKey,
secondsUntilExpiration: 60 * 30,
});
const unscopedSender = await clerkClient.machines.create({
name: `${fakeCompanyName} Unscoped Sender`,
});
const unscopedSenderToken = await clerkClient.m2m.createToken({
machineSecretKey: unscopedSender.secretKey,
secondsUntilExpiration: 60 * 30,
});
return {
primaryServer,
scopedSender,
unscopedSender,
scopedSenderToken,
unscopedSenderToken,
cleanup: async () => {
await Promise.all([
clerkClient.m2m.revokeToken({ m2mTokenId: scopedSenderToken.id }),
clerkClient.m2m.revokeToken({ m2mTokenId: unscopedSenderToken.id }),
]);
await Promise.all([
clerkClient.machines.delete(scopedSender.id),
clerkClient.machines.delete(unscopedSender.id),
clerkClient.machines.delete(primaryServer.id),
]);
},
};
}
async function createJwtM2MToken(clerkClient: ClerkClient, senderSecretKey: string): Promise<M2MToken> {
return clerkClient.m2m.createToken({
machineSecretKey: senderSecretKey,
secondsUntilExpiration: 60 * 30,
tokenFormat: 'jwt',
});
}
export type FakeOAuthApp = {
oAuthApp: OAuthApplication;
cleanup: () => Promise<void>;
};
async function createFakeOAuthApp(clerkClient: ClerkClient, callbackUrl: string): Promise<FakeOAuthApp> {
const oAuthApp = await clerkClient.oauthApplications.create({
name: `Integration Test OAuth App - ${Date.now()}`,
redirectUris: [callbackUrl],
scopes: 'profile email',
});
return {
oAuthApp,
cleanup: async () => {
await clerkClient.oauthApplications.delete(oAuthApp.id);
},
};
}
export type ObtainOAuthAccessTokenParams = {
page: Page;
oAuthApp: OAuthApplication;
redirectUri: string;
fakeUser: { email?: string; password: string };
signIn: {
waitForMounted: (...args: any[]) => Promise<any>;
signInWithEmailAndInstantPassword: (params: { email: string; password: string }) => Promise<any>;
};
};
async function obtainOAuthAccessToken({
page,
oAuthApp,
redirectUri,
fakeUser,
signIn,
}: ObtainOAuthAccessTokenParams): Promise<string> {
const state = randomBytes(16).toString('hex');
const authorizeUrl = new URL(oAuthApp.authorizeUrl);
authorizeUrl.searchParams.set('client_id', oAuthApp.clientId);
authorizeUrl.searchParams.set('redirect_uri', redirectUri);
authorizeUrl.searchParams.set('response_type', 'code');
authorizeUrl.searchParams.set('scope', 'profile email');
authorizeUrl.searchParams.set('state', state);
await page.goto(authorizeUrl.toString());
await signIn.waitForMounted();
await signIn.signInWithEmailAndInstantPassword({
email: fakeUser.email,
password: fakeUser.password,
});
const consentButton = page.getByRole('button', { name: 'Allow' });
await consentButton.waitFor({ timeout: 10000 });
await consentButton.click();
await page.waitForURL(/oauth\/callback/, { timeout: 10000 });
const callbackUrl = new URL(page.url());
const authCode = callbackUrl.searchParams.get('code');
expect(authCode).toBeTruthy();
expect(oAuthApp.clientSecret).toBeTruthy();
const tokenResponse = await page.request.post(oAuthApp.tokenFetchUrl, {
data: new URLSearchParams({
grant_type: 'authorization_code',
code: authCode,
redirect_uri: redirectUri,
client_id: oAuthApp.clientId,
client_secret: oAuthApp.clientSecret,
}).toString(),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
expect(tokenResponse.status()).toBe(200);
const tokenData = (await tokenResponse.json()) as { access_token?: string };
expect(tokenData.access_token).toBeTruthy();
return tokenData.access_token;
}
type RouteBuilder = (config: ApplicationConfig) => ApplicationConfig;
export type MachineAuthTestAdapter = {
baseConfig: ApplicationConfig;
apiKey: {
path: string;
addRoutes: RouteBuilder;
};
m2m: {
path: string;
addRoutes: RouteBuilder;
};
oauth: {
verifyPath: string;
callbackPath: string;
addRoutes: RouteBuilder;
};
rateLimit?: {
path: string;
addRoutes: RouteBuilder;
};
};
const createApiKeysEnv = (): EnvironmentConfig => appConfigs.envs.withAPIKeys.clone();
const createMachineClient = () =>
createClerkClient({
secretKey: instanceKeys.get('with-api-keys').sk,
});
const buildApp = async (adapter: MachineAuthTestAdapter, addRoutes: RouteBuilder): Promise<Application> => {
const config = addRoutes(adapter.baseConfig.clone());
return config.commit();
};
const createOAuthClient = (app: Application) =>
createClerkClient({
secretKey: app.env.privateVariables.get('CLERK_SECRET_KEY'),
publishableKey: app.env.publicVariables.get('CLERK_PUBLISHABLE_KEY'),
});
export const registerApiKeyAuthTests = (adapter: MachineAuthTestAdapter): void => {
test.describe('API key auth', () => {
test.describe.configure({ mode: 'parallel' });
let app: Application;
let fakeUser: FakeUser;
let fakeBapiUser: User;
let fakeAPIKey: FakeAPIKey;
test.beforeAll(async () => {
test.setTimeout(120_000);
app = await buildApp(adapter, adapter.apiKey.addRoutes);
await app.setup();
await app.withEnv(createApiKeysEnv());
await app.dev();
const u = createTestUtils({ app });
fakeUser = u.services.users.createFakeUser();
fakeBapiUser = await u.services.users.createBapiUser(fakeUser);
fakeAPIKey = await u.services.users.createFakeAPIKey(fakeBapiUser.id);
});
test.afterAll(async () => {
await fakeAPIKey?.revoke();
await fakeUser?.deleteIfExists();
await app?.teardown();
});
test('should return 401 if no API key is provided', async ({ request }) => {
const res = await request.get(new URL(adapter.apiKey.path, app.serverUrl).toString());
expect(res.status()).toBe(401);
});
test('should return 401 if API key is invalid', async ({ request }) => {
const res = await request.get(new URL(adapter.apiKey.path, app.serverUrl).toString(), {
headers: { Authorization: 'Bearer invalid_key' },
});
expect(res.status()).toBe(401);
});
test('should return 200 with auth object if API key is valid', async ({ request }) => {
const res = await request.get(new URL(adapter.apiKey.path, app.serverUrl).toString(), {
headers: { Authorization: `Bearer ${fakeAPIKey.secret}` },
});
const apiKeyData = await res.json();
expect(res.status()).toBe(200);
expect(apiKeyData.userId).toBe(fakeBapiUser.id);
expect(apiKeyData.tokenType).toBe(TokenType.ApiKey);
});
for (const [tokenType, token] of [
['M2M', 'mt_test_mismatch'],
['OAuth', 'oat_test_mismatch'],
] as const) {
test(`rejects ${tokenType} token on API key route (token type mismatch)`, async ({ request }) => {
const res = await request.get(new URL(adapter.apiKey.path, app.serverUrl).toString(), {
headers: { Authorization: `Bearer ${token}` },
});
expect(res.status()).toBe(401);
});
}
test('should handle multiple token types', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
const url = new URL(adapter.apiKey.path, app.serverUrl).toString();
await u.po.signIn.goTo();
await u.po.signIn.waitForMounted();
await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password });
await u.po.expect.toBeSignedIn();
const getRes = await u.page.request.get(url);
expect(getRes.status()).toBe(401);
const postWithSessionRes = await u.page.request.post(url);
const sessionData = await postWithSessionRes.json();
expect(postWithSessionRes.status()).toBe(200);
expect(sessionData.userId).toBe(fakeBapiUser.id);
expect(sessionData.tokenType).toBe(TokenType.SessionToken);
const postWithApiKeyRes = await u.page.request.post(url, {
headers: { Authorization: `Bearer ${fakeAPIKey.secret}` },
});
const apiKeyData = await postWithApiKeyRes.json();
expect(postWithApiKeyRes.status()).toBe(200);
expect(apiKeyData.userId).toBe(fakeBapiUser.id);
expect(apiKeyData.tokenType).toBe(TokenType.ApiKey);
});
});
};
export const registerM2MAuthTests = (adapter: MachineAuthTestAdapter): void => {
test.describe('M2M auth', () => {
test.describe.configure({ mode: 'parallel' });
let app: Application;
let network: FakeMachineNetwork;
test.beforeAll(async () => {
test.setTimeout(120_000);
network = await createFakeMachineNetwork(createMachineClient());
app = await buildApp(adapter, adapter.m2m.addRoutes);
await app.setup();
const env = createApiKeysEnv().setEnvVariable(
'private',
'CLERK_MACHINE_SECRET_KEY',
network.primaryServer.secretKey,
);
await app.withEnv(env);
await app.dev();
});
test.afterAll(async () => {
await network?.cleanup();
await app?.teardown();
});
test('rejects requests with invalid M2M tokens', async ({ request }) => {
const url = new URL(adapter.m2m.path, app.serverUrl).toString();
const res = await request.get(url);
expect(res.status()).toBe(401);
const res2 = await request.get(url, {
headers: { Authorization: 'Bearer mt_xxx' },
});
expect(res2.status()).toBe(401);
});
test('rejects M2M requests when sender machine lacks access to receiver machine', async ({ request }) => {
const res = await request.get(new URL(adapter.m2m.path, app.serverUrl).toString(), {
headers: { Authorization: `Bearer ${network.unscopedSenderToken.token}` },
});
expect(res.status()).toBe(401);
});
test('authorizes M2M requests when sender machine has proper access', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
const res = await u.page.request.get(new URL(adapter.m2m.path, app.serverUrl).toString(), {
headers: { Authorization: `Bearer ${network.scopedSenderToken.token}` },
});
expect(res.status()).toBe(200);
const body = await res.json();
expect(body.subject).toBe(network.scopedSender.id);
expect(body.tokenType).toBe(TokenType.M2MToken);
});
test('verifies JWT format M2M token via local verification', async ({ request }) => {
const jwtToken = await createJwtM2MToken(createMachineClient(), network.scopedSender.secretKey);
const res = await request.get(new URL(adapter.m2m.path, app.serverUrl).toString(), {
headers: { Authorization: `Bearer ${jwtToken.token}` },
});
expect(res.status()).toBe(200);
const body = await res.json();
expect(body.subject).toBe(network.scopedSender.id);
expect(body.tokenType).toBe(TokenType.M2MToken);
});
for (const [tokenType, token] of [
['API key', 'ak_test_mismatch'],
['OAuth', 'oat_test_mismatch'],
] as const) {
test(`rejects ${tokenType} token on M2M route (token type mismatch)`, async ({ request }) => {
const res = await request.get(new URL(adapter.m2m.path, app.serverUrl).toString(), {
headers: { Authorization: `Bearer ${token}` },
});
expect(res.status()).toBe(401);
});
}
});
};
export const registerOAuthAuthTests = (adapter: MachineAuthTestAdapter): void => {
test.describe('OAuth auth', () => {
test.describe.configure({ mode: 'parallel' });
let app: Application;
let fakeUser: FakeUser;
let fakeOAuth: FakeOAuthApp;
test.beforeAll(async () => {
test.setTimeout(120_000);
app = await buildApp(adapter, adapter.oauth.addRoutes);
await app.setup();
await app.withEnv(createApiKeysEnv());
await app.dev();
const u = createTestUtils({ app });
fakeUser = u.services.users.createFakeUser();
await u.services.users.createBapiUser(fakeUser);
fakeOAuth = await createFakeOAuthApp(
createOAuthClient(app),
new URL(adapter.oauth.callbackPath, app.serverUrl).toString(),
);
});
test.afterAll(async () => {
await fakeOAuth?.cleanup();
await fakeUser?.deleteIfExists();
await app?.teardown();
});
test('verifies valid OAuth access token obtained through authorization flow', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
const accessToken = await obtainOAuthAccessToken({
page: u.page,
oAuthApp: fakeOAuth.oAuthApp,
redirectUri: new URL(adapter.oauth.callbackPath, app.serverUrl).toString(),
fakeUser,
signIn: u.po.signIn,
});
const res = await u.page.request.get(new URL(adapter.oauth.verifyPath, app.serverUrl).toString(), {
headers: { Authorization: `Bearer ${accessToken}` },
});
expect(res.status()).toBe(200);
const authData = await res.json();
expect(authData.userId).toBeDefined();
expect(authData.tokenType).toBe(TokenType.OAuthToken);
});
test('rejects request without OAuth token', async ({ request }) => {
const res = await request.get(new URL(adapter.oauth.verifyPath, app.serverUrl).toString());
expect(res.status()).toBe(401);
});
test('rejects request with invalid OAuth token', async ({ request }) => {
const res = await request.get(new URL(adapter.oauth.verifyPath, app.serverUrl).toString(), {
headers: { Authorization: 'Bearer invalid_oauth_token' },
});
expect(res.status()).toBe(401);
});
for (const [tokenType, token] of [
['API key', 'ak_test_mismatch'],
['M2M', 'mt_test_mismatch'],
] as const) {
test(`rejects ${tokenType} token on OAuth route (token type mismatch)`, async ({ request }) => {
const res = await request.get(new URL(adapter.oauth.verifyPath, app.serverUrl).toString(), {
headers: { Authorization: `Bearer ${token}` },
});
expect(res.status()).toBe(401);
});
}
});
};
export const registerRateLimitTests = (adapter: MachineAuthTestAdapter): void => {
if (!adapter.rateLimit) {
return;
}
test.describe('Machine token rate limiting', () => {
test.describe.configure({ mode: 'serial' });
let app: Application;
let fakeUser: FakeUser;
let fakeBapiUser: User;
let fakeAPIKey: FakeAPIKey;
test.beforeAll(async () => {
test.setTimeout(120_000);
app = await buildApp(adapter, adapter.rateLimit!.addRoutes);
await app.setup();
await app.withEnv(createApiKeysEnv());
await app.dev();
const u = createTestUtils({ app });
fakeUser = u.services.users.createFakeUser();
fakeBapiUser = await u.services.users.createBapiUser(fakeUser);
fakeAPIKey = await u.services.users.createFakeAPIKey(fakeBapiUser.id);
});
test.afterAll(async () => {
await fakeAPIKey?.revoke();
await fakeUser?.deleteIfExists();
await app?.teardown();
});
test('rate-limits opaque machine tokens after burst exhaustion', async ({ request }) => {
const url = new URL(adapter.rateLimit!.path, app.serverUrl).toString();
// Use a dedicated test IP so this test's bucket is isolated from others
const testIp = '203.0.113.42';
for (let i = 0; i < 20; i++) {
await request.get(url, {
headers: {
Authorization: `Bearer ${fakeAPIKey.secret}`,
'x-forwarded-for': testIp,
},
});
}
const res = await request.get(url, {
headers: {
Authorization: `Bearer ${fakeAPIKey.secret}`,
'x-forwarded-for': testIp,
},
});
expect(res.status()).toBe(401);
const body = await res.json();
expect(body.reason).toBe('machine-token-rate-limit');
});
test('tracks different source IPs independently', async ({ request }) => {
const url = new URL(adapter.rateLimit!.path, app.serverUrl).toString();
const ipA = '203.0.113.1';
const ipB = '203.0.113.2';
for (let i = 0; i < 20; i++) {
await request.get(url, {
headers: {
Authorization: `Bearer ${fakeAPIKey.secret}`,
'x-forwarded-for': ipA,
},
});
}
const resA = await request.get(url, {
headers: {
Authorization: `Bearer ${fakeAPIKey.secret}`,
'x-forwarded-for': ipA,
},
});
expect(resA.status()).toBe(401);
const bodyA = await resA.json();
expect(bodyA.reason).toBe('machine-token-rate-limit');
const resB = await request.get(url, {
headers: {
Authorization: `Bearer ${fakeAPIKey.secret}`,
'x-forwarded-for': ipB,
},
});
expect(resB.status()).toBe(200);
});
});
};