|
| 1 | +import { db } from '@sim/db' |
| 2 | +import { account, user } from '@sim/db/schema' |
| 3 | +import { emailMailerMock } from '@sim/testing/mocks/email-mailer.mock' |
| 4 | +import { emailTemplatesMock } from '@sim/testing/mocks/email-templates.mock' |
| 5 | +import { posthogServerMock } from '@sim/testing/mocks/posthog-server.mock' |
| 6 | +import { generateId } from '@sim/utils/id' |
| 7 | +import { eq } from 'drizzle-orm' |
| 8 | +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' |
| 9 | + |
| 10 | +vi.hoisted(() => { |
| 11 | + process.env.MICROSOFT_CLIENT_ID = 'microsoft-sign-in-fixture-client' |
| 12 | + process.env.MICROSOFT_CLIENT_SECRET = 'microsoft-sign-in-fixture-secret' |
| 13 | +}) |
| 14 | + |
| 15 | +vi.mock('@/lib/messaging/email/mailer', () => emailMailerMock) |
| 16 | +vi.mock('@/components/emails', () => emailTemplatesMock) |
| 17 | +vi.mock('@/lib/posthog/server', () => posthogServerMock) |
| 18 | + |
| 19 | +const MICROSOFT_TOKEN_ENDPOINT = 'https://login.microsoftonline.com/common/oauth2/v2.0/token' |
| 20 | +const APP_ORIGIN = 'http://localhost:3000' |
| 21 | + |
| 22 | +function unsignedJwt(claims: Record<string, unknown>) { |
| 23 | + const encode = (value: object) => Buffer.from(JSON.stringify(value)).toString('base64url') |
| 24 | + return `${encode({ alg: 'none', typ: 'JWT' })}.${encode(claims)}.` |
| 25 | +} |
| 26 | + |
| 27 | +describe('Microsoft sign-in for an existing account', () => { |
| 28 | + let auth: typeof import('@/lib/auth/auth').auth |
| 29 | + let userId: string |
| 30 | + let email: string |
| 31 | + let subject: string |
| 32 | + let objectId: string |
| 33 | + |
| 34 | + beforeAll(async () => { |
| 35 | + ;({ auth } = await import('@/lib/auth/auth')) |
| 36 | + }, 90_000) |
| 37 | + |
| 38 | + beforeEach(async () => { |
| 39 | + userId = generateId() |
| 40 | + email = `${userId}@microsoft-sign-in.test` |
| 41 | + subject = `sub-${generateId()}` |
| 42 | + objectId = generateId() |
| 43 | + const now = new Date() |
| 44 | + await db.insert(user).values({ |
| 45 | + id: userId, |
| 46 | + name: 'Microsoft sign-in fixture', |
| 47 | + email, |
| 48 | + emailVerified: true, |
| 49 | + createdAt: now, |
| 50 | + updatedAt: now, |
| 51 | + }) |
| 52 | + await db.insert(account).values({ |
| 53 | + id: generateId(), |
| 54 | + accountId: subject, |
| 55 | + providerId: 'microsoft', |
| 56 | + userId, |
| 57 | + createdAt: now, |
| 58 | + updatedAt: now, |
| 59 | + }) |
| 60 | + |
| 61 | + const realFetch = globalThis.fetch |
| 62 | + vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { |
| 63 | + const url = input instanceof Request ? input.url : String(input) |
| 64 | + if (url === MICROSOFT_TOKEN_ENDPOINT) { |
| 65 | + return Response.json({ |
| 66 | + access_token: 'microsoft-fixture-access-token', |
| 67 | + token_type: 'Bearer', |
| 68 | + expires_in: 3600, |
| 69 | + scope: 'openid profile email', |
| 70 | + id_token: unsignedJwt({ |
| 71 | + iss: 'https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0', |
| 72 | + aud: process.env.MICROSOFT_CLIENT_ID, |
| 73 | + tid: '9188040d-6c67-4c5b-b112-36a304b66dad', |
| 74 | + sub: subject, |
| 75 | + oid: objectId, |
| 76 | + email, |
| 77 | + name: 'Microsoft sign-in fixture', |
| 78 | + }), |
| 79 | + }) |
| 80 | + } |
| 81 | + if (url.startsWith('https://graph.microsoft.com/')) return new Response(null, { status: 404 }) |
| 82 | + return realFetch(input, init) |
| 83 | + }) |
| 84 | + }) |
| 85 | + |
| 86 | + afterEach(async () => { |
| 87 | + vi.restoreAllMocks() |
| 88 | + await db.delete(user).where(eq(user.id, userId)) |
| 89 | + }) |
| 90 | + |
| 91 | + it('signs in through the account stored under the ID token subject without a duplicate link', async () => { |
| 92 | + const start = await auth.handler( |
| 93 | + new Request(`${APP_ORIGIN}/api/auth/sign-in/social`, { |
| 94 | + method: 'POST', |
| 95 | + headers: { 'content-type': 'application/json', origin: APP_ORIGIN }, |
| 96 | + body: JSON.stringify({ provider: 'microsoft', callbackURL: '/workspace' }), |
| 97 | + }) |
| 98 | + ) |
| 99 | + expect(start.status).toBe(200) |
| 100 | + const { url } = (await start.json()) as { url: string } |
| 101 | + const state = new URL(url).searchParams.get('state') |
| 102 | + const stateCookies = start.headers |
| 103 | + .getSetCookie() |
| 104 | + .map((value) => value.split(';')[0]) |
| 105 | + .join('; ') |
| 106 | + |
| 107 | + const callback = await auth.handler( |
| 108 | + new Request( |
| 109 | + `${APP_ORIGIN}/api/auth/callback/microsoft?code=microsoft-fixture-code&state=${state}`, |
| 110 | + { headers: { cookie: stateCookies } } |
| 111 | + ) |
| 112 | + ) |
| 113 | + |
| 114 | + expect(callback.status).toBe(302) |
| 115 | + expect(callback.headers.get('location')).toMatch(/\/workspace$/) |
| 116 | + expect(callback.headers.getSetCookie().some((value) => value.includes('session_token='))).toBe( |
| 117 | + true |
| 118 | + ) |
| 119 | + const accounts = await db |
| 120 | + .select({ accountId: account.accountId }) |
| 121 | + .from(account) |
| 122 | + .where(eq(account.userId, userId)) |
| 123 | + expect(accounts).toEqual([{ accountId: subject }]) |
| 124 | + }) |
| 125 | +}) |
0 commit comments