-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathgoogle-auth-callback.spec.ts
More file actions
359 lines (311 loc) · 9.68 KB
/
google-auth-callback.spec.ts
File metadata and controls
359 lines (311 loc) · 9.68 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
import { expect, type Page, test } from "@playwright/test";
const CALLBACK_PATH = "/auth/google/callback";
const INTENT_STORAGE_PREFIX = "compass.googleAuthorizationIntent";
const REQUIRED_SCOPES = [
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/calendar.readonly",
"https://www.googleapis.com/auth/calendar.events",
];
type CapturedAuthRequest = {
body: unknown;
headers: Record<string, string>;
};
type ApiMocks = {
connectGoogle: CapturedAuthRequest[];
loginOrSignup: CapturedAuthRequest[];
};
type ApiMockOptions = {
beforeConnectGoogleResponse?: Promise<void>;
beforeLoginOrSignupResponse?: Promise<void>;
connectGoogleResponse?: {
body?: unknown;
status: number;
};
};
const createDeferred = () => {
let resolve!: () => void;
const promise = new Promise<void>((done) => {
resolve = done;
});
return { promise, resolve };
};
const getIntentStorageKey = (state: string) =>
`${INTENT_STORAGE_PREFIX}.${state}`;
const getCallbackUrl = (state: string, scope = REQUIRED_SCOPES.join(" ")) =>
`${CALLBACK_PATH}?state=${encodeURIComponent(
state,
)}&code=auth-code&scope=${encodeURIComponent(scope)}`;
const expectGoogleAuthRequestBody = (
request: CapturedAuthRequest | undefined,
state: string,
) => {
expect(request?.body).toMatchObject({
thirdPartyId: "google",
clientType: "web",
redirectURIInfo: {
redirectURIOnProviderDashboard: expect.stringContaining(CALLBACK_PATH),
redirectURIQueryParams: {
code: "auth-code",
state,
},
},
});
};
const writeGoogleAuthorizationIntent = async ({
intent,
page,
returnPath,
state,
}: {
intent: "signIn" | "connectCalendar";
page: Page;
returnPath: string;
state: string;
}) => {
await page.goto("/week");
await page.evaluate(
({ key, value }) => {
sessionStorage.setItem(key, JSON.stringify(value));
},
{
key: getIntentStorageKey(state),
value: {
intent,
returnPath,
createdAt: Date.now(),
},
},
);
};
const setActiveCompassSession = async (page: Page) => {
const now = Date.now();
const pageOrigin = new URL(page.url()).origin;
const expires = Math.floor(now / 1000) + 60 * 60;
const frontToken = Buffer.from(
JSON.stringify({
ate: now + 60 * 60 * 1000,
uid: "test-user-id",
up: {},
}),
).toString("base64");
await page.context().addCookies([
{
expires,
name: "st-last-access-token-update",
url: pageOrigin,
value: now.toString(),
},
{
expires,
name: "sFrontToken",
url: pageOrigin,
value: frontToken,
},
]);
};
const prepareGoogleAuthCallbackPage = async (
page: Page,
options: ApiMockOptions = {},
): Promise<ApiMocks> => {
const apiMocks: ApiMocks = {
connectGoogle: [],
loginOrSignup: [],
};
page.on("dialog", async (dialog) => {
await dialog.dismiss().catch(() => undefined);
});
await page.addInitScript(() => {
window.__COMPASS_E2E_TEST__ = true;
window.alert = () => undefined;
window.confirm = () => true;
window.prompt = () => null;
});
await page.route("**/api/**", async (route) => {
const request = route.request();
const url = new URL(request.url());
if (url.pathname.endsWith("/api/signinup")) {
apiMocks.loginOrSignup.push({
body: request.postDataJSON(),
headers: request.headers(),
});
await options.beforeLoginOrSignupResponse;
return route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
user: { emails: ["user@example.com"] },
}),
});
}
if (url.pathname.endsWith("/api/auth/google/connect")) {
apiMocks.connectGoogle.push({
body: request.postDataJSON(),
headers: request.headers(),
});
await options.beforeConnectGoogleResponse;
return route.fulfill({
status: options.connectGoogleResponse?.status ?? 200,
contentType: "application/json",
body: JSON.stringify(options.connectGoogleResponse?.body ?? {}),
});
}
if (url.pathname.includes("/api/session")) {
return route.fulfill({
status: 401,
contentType: "application/json",
body: JSON.stringify({ message: "unauthorized" }),
});
}
if (url.pathname.endsWith("/api/user/metadata")) {
return route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ google: { connectionState: "HEALTHY" } }),
});
}
if (url.pathname.endsWith("/api/config")) {
return route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ google: { isConfigured: true } }),
});
}
return route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({}),
});
});
return apiMocks;
};
test.describe("Google auth callback", () => {
test("shows completion status while finishing a saved Google sign-in intent", async ({
page,
}) => {
const state = "sign-in-state";
const delayedSignIn = createDeferred();
const apiMocks = await prepareGoogleAuthCallbackPage(page, {
beforeLoginOrSignupResponse: delayedSignIn.promise,
});
await writeGoogleAuthorizationIntent({
intent: "signIn",
page,
returnPath: "/week",
state,
});
await page.goto(getCallbackUrl(state));
await expect(
page.locator('[role="status"][aria-busy="true"][aria-live="polite"]'),
).toBeVisible();
await expect(
page.getByText("Completing Google authorization..."),
).toBeVisible();
await expect(page.getByText("Returning you to Compass.")).toBeVisible();
delayedSignIn.resolve();
await expect(page).toHaveURL(/\/week$/);
expect(apiMocks.loginOrSignup).toHaveLength(1);
expect(apiMocks.connectGoogle).toHaveLength(0);
expect(apiMocks.loginOrSignup[0]?.headers.rid).toBe("thirdparty");
expectGoogleAuthRequestBody(apiMocks.loginOrSignup[0], state);
expect(
await page.evaluate(
(key) => sessionStorage.getItem(key),
getIntentStorageKey(state),
),
).toBeNull();
});
test("finishes a saved Google Calendar connect intent when the Compass session is active", async ({
page,
}) => {
const state = "connect-calendar-state";
const apiMocks = await prepareGoogleAuthCallbackPage(page);
await writeGoogleAuthorizationIntent({
intent: "connectCalendar",
page,
returnPath: "/week",
state,
});
await setActiveCompassSession(page);
await page.goto(getCallbackUrl(state));
await expect(page).toHaveURL(/\/week$/);
expect(apiMocks.loginOrSignup).toHaveLength(0);
expect(apiMocks.connectGoogle).toHaveLength(1);
expectGoogleAuthRequestBody(apiMocks.connectGoogle[0], state);
});
test("recovers a saved Google Calendar connect intent through Google sign-in when the Compass session is missing", async ({
page,
}) => {
const state = "connect-calendar-session-missing-state";
const apiMocks = await prepareGoogleAuthCallbackPage(page);
await writeGoogleAuthorizationIntent({
intent: "connectCalendar",
page,
returnPath: "/week",
state,
});
await page.goto(getCallbackUrl(state));
await expect(page).toHaveURL(/\/week$/);
expect(apiMocks.connectGoogle).toHaveLength(0);
expect(apiMocks.loginOrSignup).toHaveLength(1);
expect(apiMocks.loginOrSignup[0]?.headers.rid).toBe("thirdparty");
expectGoogleAuthRequestBody(apiMocks.loginOrSignup[0], state);
});
test("recovers through Google sign-in when Google connect rejects an expired Compass session", async ({
page,
}) => {
const state = "connect-calendar-session-expired-state";
const apiMocks = await prepareGoogleAuthCallbackPage(page, {
connectGoogleResponse: {
status: 401,
body: { message: "unauthorized" },
},
});
await writeGoogleAuthorizationIntent({
intent: "connectCalendar",
page,
returnPath: "/week",
state,
});
await setActiveCompassSession(page);
await page.goto(getCallbackUrl(state));
await expect(page).toHaveURL(/\/week$/);
expect(apiMocks.connectGoogle).toHaveLength(1);
expect(apiMocks.loginOrSignup).toHaveLength(1);
expect(apiMocks.loginOrSignup[0]?.headers.rid).toBe("thirdparty");
expectGoogleAuthRequestBody(apiMocks.connectGoogle[0], state);
expectGoogleAuthRequestBody(apiMocks.loginOrSignup[0], state);
});
test("rejects callbacks that are missing required Google Calendar scopes", async ({
page,
}) => {
const state = "missing-scopes-state";
const apiMocks = await prepareGoogleAuthCallbackPage(page);
await writeGoogleAuthorizationIntent({
intent: "signIn",
page,
returnPath: "/week",
state,
});
await page.goto(getCallbackUrl(state, REQUIRED_SCOPES[0] ?? ""));
await expect(page).toHaveURL(/\/week$/);
await expect(
page.getByText(
"Missing Google Calendar permissions. Please grant all requested permissions.",
),
).toBeVisible();
expect(apiMocks.loginOrSignup).toHaveLength(0);
expect(apiMocks.connectGoogle).toHaveLength(0);
});
test("rejects callbacks without a saved intent", async ({ page }) => {
const apiMocks = await prepareGoogleAuthCallbackPage(page);
await page.goto(getCallbackUrl("unknown-state"));
await expect(page).toHaveURL(/\/day(\/|$)/);
await expect(
page.getByText(
"Google authorization could not be completed. Please try again.",
),
).toBeVisible();
expect(apiMocks.loginOrSignup).toHaveLength(0);
expect(apiMocks.connectGoogle).toHaveLength(0);
});
});