|
| 1 | +/** |
| 2 | + * Tests for the Gmail API mail provider |
| 3 | + * |
| 4 | + * @vitest-environment node |
| 5 | + */ |
| 6 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' |
| 7 | + |
| 8 | +const { mockJwtConstructor, mockGetAccessToken, mockEnv } = vi.hoisted(() => { |
| 9 | + const mockGetAccessToken = vi.fn() |
| 10 | + const jwtInstance = { getAccessToken: mockGetAccessToken } |
| 11 | + const mockEnv: Record<string, string | undefined> = {} |
| 12 | + return { |
| 13 | + mockJwtConstructor: vi.fn().mockImplementation( |
| 14 | + class { |
| 15 | + constructor() { |
| 16 | + // biome-ignore lint/correctness/noConstructorReturn: vitest constructs mocks via Reflect.construct; returning the object overrides the instance so `new JWT()` yields the shared mock the tests assert on |
| 17 | + return jwtInstance |
| 18 | + } |
| 19 | + } |
| 20 | + ), |
| 21 | + mockGetAccessToken, |
| 22 | + mockEnv, |
| 23 | + } |
| 24 | +}) |
| 25 | + |
| 26 | +vi.mock('google-auth-library', () => ({ |
| 27 | + JWT: mockJwtConstructor, |
| 28 | +})) |
| 29 | + |
| 30 | +vi.mock('@/lib/core/config/env', () => ({ |
| 31 | + env: mockEnv, |
| 32 | + getEnv: (key: string) => mockEnv[key], |
| 33 | +})) |
| 34 | + |
| 35 | +import { createGmailProvider } from '@/lib/messaging/email/providers/gmail' |
| 36 | +import type { ProcessedEmailData } from '@/lib/messaging/email/types' |
| 37 | + |
| 38 | +const VALID_CREDENTIALS = JSON.stringify({ |
| 39 | + client_email: 'mailer@my-project.iam.gserviceaccount.com', |
| 40 | + private_key: '-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----\n', |
| 41 | +}) |
| 42 | + |
| 43 | +const BASE_DATA: ProcessedEmailData = { |
| 44 | + to: 'user@example.com', |
| 45 | + subject: 'Welcome to Sim', |
| 46 | + html: '<p>Hello</p>', |
| 47 | + senderEmail: 'Sim <noreply@sim.example>', |
| 48 | + headers: {}, |
| 49 | +} |
| 50 | + |
| 51 | +const mockFetch = vi.fn() |
| 52 | + |
| 53 | +describe('Gmail mail provider', () => { |
| 54 | + beforeEach(() => { |
| 55 | + vi.clearAllMocks() |
| 56 | + vi.stubGlobal('fetch', mockFetch) |
| 57 | + mockEnv.GMAIL_SENDER = 'noreply@sim.example' |
| 58 | + mockEnv.GMAIL_CREDENTIALS_JSON = VALID_CREDENTIALS |
| 59 | + mockGetAccessToken.mockResolvedValue({ token: 'test-token' }) |
| 60 | + }) |
| 61 | + |
| 62 | + afterEach(() => { |
| 63 | + vi.unstubAllGlobals() |
| 64 | + vi.restoreAllMocks() |
| 65 | + }) |
| 66 | + |
| 67 | + describe('createGmailProvider', () => { |
| 68 | + it('returns null when neither GMAIL_SENDER nor GMAIL_CREDENTIALS_JSON is set', () => { |
| 69 | + mockEnv.GMAIL_SENDER = undefined |
| 70 | + mockEnv.GMAIL_CREDENTIALS_JSON = undefined |
| 71 | + |
| 72 | + expect(createGmailProvider()).toBeNull() |
| 73 | + }) |
| 74 | + |
| 75 | + it('returns null when only one of the two variables is set', () => { |
| 76 | + mockEnv.GMAIL_CREDENTIALS_JSON = undefined |
| 77 | + expect(createGmailProvider()).toBeNull() |
| 78 | + |
| 79 | + mockEnv.GMAIL_CREDENTIALS_JSON = VALID_CREDENTIALS |
| 80 | + mockEnv.GMAIL_SENDER = undefined |
| 81 | + expect(createGmailProvider()).toBeNull() |
| 82 | + }) |
| 83 | + |
| 84 | + it('returns null for invalid or incomplete credentials JSON', () => { |
| 85 | + mockEnv.GMAIL_CREDENTIALS_JSON = 'not-json' |
| 86 | + expect(createGmailProvider()).toBeNull() |
| 87 | + |
| 88 | + mockEnv.GMAIL_CREDENTIALS_JSON = JSON.stringify({ client_email: 'x@y.iam' }) |
| 89 | + expect(createGmailProvider()).toBeNull() |
| 90 | + }) |
| 91 | + |
| 92 | + it('creates a JWT client impersonating the configured sender with the gmail.send scope', () => { |
| 93 | + const provider = createGmailProvider() |
| 94 | + |
| 95 | + expect(provider?.name).toBe('gmail') |
| 96 | + expect(mockJwtConstructor).toHaveBeenCalledWith({ |
| 97 | + email: 'mailer@my-project.iam.gserviceaccount.com', |
| 98 | + key: '-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----\n', |
| 99 | + scopes: ['https://www.googleapis.com/auth/gmail.send'], |
| 100 | + subject: 'noreply@sim.example', |
| 101 | + }) |
| 102 | + }) |
| 103 | + }) |
| 104 | + |
| 105 | + describe('send', () => { |
| 106 | + it('posts the raw RFC 822 message to the Gmail media-upload endpoint', async () => { |
| 107 | + mockFetch.mockResolvedValueOnce( |
| 108 | + new Response(JSON.stringify({ id: 'msg-1', threadId: 'thr-1' }), { status: 200 }) |
| 109 | + ) |
| 110 | + |
| 111 | + const provider = createGmailProvider() |
| 112 | + const result = await provider!.send({ |
| 113 | + ...BASE_DATA, |
| 114 | + headers: { 'List-Unsubscribe': '<https://sim.example/unsub>' }, |
| 115 | + replyTo: 'help@sim.example', |
| 116 | + }) |
| 117 | + |
| 118 | + expect(result).toEqual({ |
| 119 | + success: true, |
| 120 | + message: 'Email sent successfully via Gmail', |
| 121 | + data: { id: 'msg-1' }, |
| 122 | + }) |
| 123 | + |
| 124 | + const [url, init] = mockFetch.mock.calls[0] |
| 125 | + expect(url).toBe( |
| 126 | + 'https://gmail.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=media' |
| 127 | + ) |
| 128 | + expect(init.method).toBe('POST') |
| 129 | + expect(init.headers).toEqual({ |
| 130 | + Authorization: 'Bearer test-token', |
| 131 | + 'Content-Type': 'message/rfc822', |
| 132 | + }) |
| 133 | + |
| 134 | + const raw = (init.body as Buffer).toString() |
| 135 | + expect(raw).toContain('To: user@example.com') |
| 136 | + expect(raw).toContain('Subject: Welcome to Sim') |
| 137 | + expect(raw).toContain('From: Sim <noreply@sim.example>') |
| 138 | + expect(raw).toContain('Reply-To: help@sim.example') |
| 139 | + expect(raw).toContain('List-Unsubscribe: <https://sim.example/unsub>') |
| 140 | + expect(raw).toContain('<p>Hello</p>') |
| 141 | + }) |
| 142 | + |
| 143 | + it('encodes attachments into the MIME payload', async () => { |
| 144 | + mockFetch.mockResolvedValueOnce( |
| 145 | + new Response(JSON.stringify({ id: 'msg-2' }), { status: 200 }) |
| 146 | + ) |
| 147 | + |
| 148 | + const provider = createGmailProvider() |
| 149 | + await provider!.send({ |
| 150 | + ...BASE_DATA, |
| 151 | + attachments: [ |
| 152 | + { |
| 153 | + filename: 'report.txt', |
| 154 | + content: Buffer.from('report body'), |
| 155 | + contentType: 'text/plain', |
| 156 | + }, |
| 157 | + ], |
| 158 | + }) |
| 159 | + |
| 160 | + const [, init] = mockFetch.mock.calls[0] |
| 161 | + const raw = (init.body as Buffer).toString() |
| 162 | + expect(raw).toContain('Content-Type: text/plain; name=report.txt') |
| 163 | + expect(raw).toContain('Content-Disposition: attachment; filename=report.txt') |
| 164 | + expect(raw).toContain(Buffer.from('report body').toString('base64')) |
| 165 | + }) |
| 166 | + |
| 167 | + it('throws when no access token can be obtained', async () => { |
| 168 | + mockGetAccessToken.mockResolvedValueOnce({ token: null }) |
| 169 | + |
| 170 | + const provider = createGmailProvider() |
| 171 | + await expect(provider!.send(BASE_DATA)).rejects.toThrow( |
| 172 | + 'Failed to obtain a Gmail API access token' |
| 173 | + ) |
| 174 | + expect(mockFetch).not.toHaveBeenCalled() |
| 175 | + }) |
| 176 | + |
| 177 | + it('throws with status details when the Gmail API rejects the send', async () => { |
| 178 | + mockFetch.mockResolvedValueOnce( |
| 179 | + new Response(JSON.stringify({ error: { message: 'Delegation denied' } }), { |
| 180 | + status: 403, |
| 181 | + statusText: 'Forbidden', |
| 182 | + }) |
| 183 | + ) |
| 184 | + |
| 185 | + const provider = createGmailProvider() |
| 186 | + await expect(provider!.send(BASE_DATA)).rejects.toThrow( |
| 187 | + 'Gmail API send failed: 403 Forbidden' |
| 188 | + ) |
| 189 | + }) |
| 190 | + }) |
| 191 | +}) |
0 commit comments