Skip to content

Commit 1c70b92

Browse files
committed
Merge main before the #9955 squash into mike/expo-native-sync-bridge
2 parents 245af6a + b396050 commit 1c70b92

47 files changed

Lines changed: 1520 additions & 157 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.changeset/localization-modifier-quoted-params.md‎

Lines changed: 0 additions & 5 deletions
This file was deleted.

‎.changeset/mosaic-invite-members-dialog.md‎

Lines changed: 0 additions & 2 deletions
This file was deleted.
File renamed without changes.

‎integration/testUtils/machineAuthHelpers.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ export type FakeMachineNetwork = {
2424
cleanup: () => Promise<void>;
2525
};
2626

27-
async function createFakeMachineNetwork(clerkClient: ClerkClient): Promise<FakeMachineNetwork> {
28-
const fakeCompanyName = faker.company.name();
27+
export async function createFakeMachineNetwork(clerkClient: ClerkClient): Promise<FakeMachineNetwork> {
28+
const fakeCompanyName = `${faker.company.name()} ${Date.now()}`;
2929

3030
const primaryServer = await clerkClient.machines.create({
3131
name: `${fakeCompanyName} Primary API Server`,
@@ -68,7 +68,7 @@ async function createFakeMachineNetwork(clerkClient: ClerkClient): Promise<FakeM
6868
};
6969
}
7070

71-
async function createJwtM2MToken(clerkClient: ClerkClient, senderSecretKey: string): Promise<M2MToken> {
71+
export async function createJwtM2MToken(clerkClient: ClerkClient, senderSecretKey: string): Promise<M2MToken> {
7272
return clerkClient.m2m.createToken({
7373
machineSecretKey: senderSecretKey,
7474
secondsUntilExpiration: 60 * 30,
@@ -181,7 +181,7 @@ export type MachineAuthTestAdapter = {
181181

182182
const createApiKeysEnv = (): EnvironmentConfig => appConfigs.envs.withAPIKeys.clone();
183183

184-
const createMachineClient = () =>
184+
export const createMachineClient = () =>
185185
createClerkClient({
186186
secretKey: instanceKeys.get('with-api-keys').sk,
187187
});

‎integration/tests/next-machine.test.ts‎

Lines changed: 208 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,20 @@
1-
import { test } from '@playwright/test';
1+
import type { User } from '@clerk/backend';
2+
import { TokenType } from '@clerk/backend/internal';
3+
import { expect, test } from '@playwright/test';
24

5+
import type { Application } from '../models/application';
36
import { appConfigs } from '../presets';
4-
import type { MachineAuthTestAdapter } from '../testUtils/machineAuthHelpers';
5-
import { registerApiKeyAuthTests, registerM2MAuthTests, registerOAuthAuthTests } from '../testUtils/machineAuthHelpers';
7+
import { createTestUtils } from '../testUtils';
8+
import type { FakeMachineNetwork, MachineAuthTestAdapter } from '../testUtils/machineAuthHelpers';
9+
import {
10+
createFakeMachineNetwork,
11+
createJwtM2MToken,
12+
createMachineClient,
13+
registerApiKeyAuthTests,
14+
registerM2MAuthTests,
15+
registerOAuthAuthTests,
16+
} from '../testUtils/machineAuthHelpers';
17+
import type { FakeAPIKey, FakeUser } from '../testUtils/usersService';
618

719
const adapter: MachineAuthTestAdapter = {
820
baseConfig: appConfigs.next.appRouter,
@@ -94,4 +106,197 @@ test.describe('Next.js machine authentication @machine', () => {
94106
registerApiKeyAuthTests(adapter);
95107
registerM2MAuthTests(adapter);
96108
registerOAuthAuthTests(adapter);
109+
110+
test.describe('auth.protect() authorization with API keys', () => {
111+
test.describe.configure({ mode: 'parallel' });
112+
let app: Application;
113+
let fakeUser: FakeUser;
114+
let fakeBapiUser: User;
115+
let fakeAPIKey: FakeAPIKey;
116+
117+
test.beforeAll(async () => {
118+
test.setTimeout(120_000);
119+
120+
app = await appConfigs.next.appRouter
121+
.clone()
122+
.addFile(
123+
'src/app/api/protect/route.ts',
124+
() => `
125+
import { auth } from '@clerk/nextjs/server';
126+
127+
export async function GET() {
128+
const { userId, tokenType } = await auth.protect({ token: 'api_key' });
129+
130+
return Response.json({ userId, tokenType });
131+
}
132+
133+
export async function POST() {
134+
const { userId } = await auth.protect({ role: 'org:admin' }, { token: ['session_token', 'api_key'] });
135+
136+
return Response.json({ userId });
137+
}
138+
139+
export async function PUT() {
140+
await auth.protect(() => false, { token: 'api_key' });
141+
142+
return Response.json({ protected: true });
143+
}
144+
145+
export async function PATCH() {
146+
const { userId, tokenType } = await auth.protect(() => true, { token: 'api_key' });
147+
148+
return Response.json({ userId, tokenType });
149+
}
150+
`,
151+
)
152+
.commit();
153+
await app.setup();
154+
await app.withEnv(appConfigs.envs.withAPIKeys.clone());
155+
await app.dev();
156+
157+
const u = createTestUtils({ app });
158+
fakeUser = u.services.users.createFakeUser(test);
159+
fakeBapiUser = await u.services.users.createBapiUser(fakeUser);
160+
fakeAPIKey = await u.services.users.createFakeAPIKey(fakeBapiUser.id);
161+
});
162+
163+
test.afterAll(async () => {
164+
await fakeAPIKey?.revoke();
165+
await fakeUser?.deleteIfExists();
166+
await app?.teardown();
167+
});
168+
169+
test('should return 200 if API key is valid and no authorization params are passed', async ({ request }) => {
170+
const res = await request.get(new URL('/api/protect', app.serverUrl).toString(), {
171+
headers: { Authorization: `Bearer ${fakeAPIKey.secret}` },
172+
});
173+
expect(res.status()).toBe(200);
174+
expect(await res.json()).toEqual({ userId: fakeBapiUser.id, tokenType: TokenType.ApiKey });
175+
});
176+
177+
test('should return 401 if API key is valid but a role is required', async ({ request }) => {
178+
const res = await request.post(new URL('/api/protect', app.serverUrl).toString(), {
179+
headers: { Authorization: `Bearer ${fakeAPIKey.secret}` },
180+
});
181+
expect(res.status()).toBe(401);
182+
});
183+
184+
test('should return 401 if API key is valid but the predicate returns false', async ({ request }) => {
185+
const res = await request.put(new URL('/api/protect', app.serverUrl).toString(), {
186+
headers: { Authorization: `Bearer ${fakeAPIKey.secret}` },
187+
});
188+
expect(res.status()).toBe(401);
189+
});
190+
191+
test('should return 200 if API key is valid and the predicate returns true', async ({ request }) => {
192+
const res = await request.patch(new URL('/api/protect', app.serverUrl).toString(), {
193+
headers: { Authorization: `Bearer ${fakeAPIKey.secret}` },
194+
});
195+
expect(res.status()).toBe(200);
196+
expect(await res.json()).toEqual({ userId: fakeBapiUser.id, tokenType: TokenType.ApiKey });
197+
});
198+
});
199+
200+
test.describe('session helpers with machine tokens', () => {
201+
test.describe.configure({ mode: 'parallel' });
202+
let app: Application;
203+
let network: FakeMachineNetwork;
204+
let jwtToken: string;
205+
206+
test.beforeAll(async () => {
207+
test.setTimeout(120_000);
208+
209+
network = await createFakeMachineNetwork(createMachineClient());
210+
jwtToken = (await createJwtM2MToken(createMachineClient(), network.scopedSender.secretKey)).token;
211+
212+
app = await appConfigs.next.appRouter
213+
.clone()
214+
.addFile(
215+
'src/pages/api/pages-session.ts',
216+
() => `
217+
import { getAuth } from '@clerk/nextjs/server';
218+
import type { NextApiRequest, NextApiResponse } from 'next';
219+
220+
export default function handler(req: NextApiRequest, res: NextApiResponse) {
221+
const { userId, tokenType } = getAuth(req);
222+
223+
if (!userId) {
224+
return res.status(401).json({ error: 'Unauthorized' });
225+
}
226+
227+
return res.status(200).json({ userId, tokenType });
228+
}
229+
`,
230+
)
231+
.addFile(
232+
'src/app/api/app-session/route.ts',
233+
() => `
234+
import { auth } from '@clerk/nextjs/server';
235+
236+
export async function GET() {
237+
const { userId, tokenType } = await auth();
238+
239+
if (!userId) {
240+
return Response.json({ error: 'Unauthorized' }, { status: 401 });
241+
}
242+
243+
return Response.json({ userId, tokenType });
244+
}
245+
`,
246+
)
247+
.addFile(
248+
'src/app/api/app-machine/route.ts',
249+
() => `
250+
import { auth } from '@clerk/nextjs/server';
251+
252+
export async function GET() {
253+
const { subject, tokenType, isAuthenticated } = await auth({ acceptsToken: 'm2m_token' });
254+
255+
if (!isAuthenticated) {
256+
return Response.json({ error: 'Unauthorized' }, { status: 401 });
257+
}
258+
259+
return Response.json({ subject, tokenType });
260+
}
261+
`,
262+
)
263+
.commit();
264+
await app.setup();
265+
await app.withEnv(
266+
appConfigs.envs.withAPIKeys
267+
.clone()
268+
.setEnvVariable('private', 'CLERK_MACHINE_SECRET_KEY', network.primaryServer.secretKey),
269+
);
270+
await app.dev();
271+
});
272+
273+
test.afterAll(async () => {
274+
await network?.cleanup();
275+
await app?.teardown();
276+
});
277+
278+
test('should return 200 from auth() if the route accepts M2M tokens', async ({ request }) => {
279+
const res = await request.get(new URL('/api/app-machine', app.serverUrl).toString(), {
280+
headers: { Authorization: `Bearer ${jwtToken}` },
281+
});
282+
expect(res.status()).toBe(200);
283+
expect(await res.json()).toEqual({ subject: network.scopedSender.id, tokenType: TokenType.M2MToken });
284+
});
285+
286+
test('should return 401 from getAuth() if a JWT-format M2M token is sent', async ({ request }) => {
287+
const res = await request.get(new URL('/api/pages-session', app.serverUrl).toString(), {
288+
headers: { Authorization: `Bearer ${jwtToken}` },
289+
});
290+
expect(res.status()).toBe(401);
291+
});
292+
293+
test('should return 401 from auth() if a JWT-format M2M token is sent with a padded Authorization header', async ({
294+
request,
295+
}) => {
296+
const res = await request.get(new URL('/api/app-session', app.serverUrl).toString(), {
297+
headers: { Authorization: `Bearer ${jwtToken} x` },
298+
});
299+
expect(res.status()).toBe(401);
300+
});
301+
});
97302
});

‎packages/chrome-extension/CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
# Change Log
22

3+
## 3.1.94
4+
5+
### Patch Changes
6+
7+
- Updated dependencies [[`3b4ceb6`](https://github.com/clerk/javascript/commit/3b4ceb677056fb20dc1f44b7657edc5aeeb5e1cb)]:
8+
- @clerk/ui@1.40.1
9+
310
## 3.1.93
411

512
### Patch Changes

‎packages/chrome-extension/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@clerk/chrome-extension",
3-
"version": "3.1.93",
3+
"version": "3.1.94",
44
"description": "Clerk SDK for Chrome extensions",
55
"keywords": [
66
"auth",

0 commit comments

Comments
 (0)