Repository navigation
Expand file tree
/
Copy pathlogin.integration.test.ts
More file actions
539 lines (500 loc) · 21.4 KB
/
Copy pathlogin.integration.test.ts
File metadata and controls
539 lines (500 loc) · 21.4 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
import { BunServices } from "@effect/platform-bun";
import { describe, expect, it } from "@effect/vitest";
import { Cause, Effect, Exit, FileSystem, Layer, Option, Path, Redacted } from "effect";
import * as HttpClient from "effect/http/HttpClient";
import { TestClock } from "effect/testing";
import {
mockAnalytics,
mockBrowser,
mockOutput,
mockRuntimeInfo,
mockStdin,
mockTty,
} from "../../../tests/helpers/mocks.ts";
import { CliArgs } from "../../shared/cli/cli-args.service.ts";
import { ProfileFlag } from "../../command-internal/global-flags.ts";
import { loginApiLayer } from "../../command-internal/login-api.layer.ts";
import { loginCryptoLayer } from "../../command-internal/login-crypto.layer.ts";
import { assertPermissionDrift } from "../../../tests/helpers/permission-drift.ts";
import {
VALID_TOKEN,
buildTestRuntime,
jsonResponse,
mockCommandPlatformApi,
mockCommandSettings,
mockCommandCredentialsTracked,
mockLoginApi,
mockLoginCrypto,
mockCommandPlatformApiService,
mockTelemetryStateTracked,
useTempWorkdir,
withEnvVar,
} from "../../../tests/helpers/command-mocks.ts";
import { EventLoginCompleted } from "../../shared/telemetry/event-catalog.ts";
import { LoginCrypto } from "./login-crypto.service.ts";
import { login } from "./login.handler.ts";
import type { LoginFlags } from "./login.command.ts";
const tempRoot = useTempWorkdir("supabase-login-int-");
const noopHttpClient = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected HttpClient.execute in login test")),
);
interface SetupOpts {
readonly format?: "text" | "json" | "stream-json";
readonly isTTY?: boolean;
readonly stdoutIsTty?: boolean;
readonly accessTokenEnv?: string;
readonly pipedStdin?: string;
readonly gotrueId?: string;
readonly profileFails?: boolean;
/** Runs the real login API layer against this recorded HTTP mock instead of the service-level mock. */
readonly httpApi?: Parameters<typeof mockCommandPlatformApi>[0];
readonly failTimes?: number;
readonly decryptFails?: boolean;
readonly keygenFails?: boolean;
readonly tokenName?: string;
readonly saveFails?: boolean;
readonly promptTextFail?: boolean;
readonly profileFlag?: string;
readonly profileEnvValue?: Option.Option<string>;
readonly homeDir?: string;
/** Raw argv for explicit `--profile` detection. */
readonly argv?: ReadonlyArray<string>;
}
function flags(overrides: Partial<LoginFlags> = {}): LoginFlags {
return {
token: Option.none(),
name: Option.none(),
noBrowser: false,
...overrides,
};
}
function setupLogin(opts: SetupOpts = {}) {
const isTTY = opts.isTTY ?? false;
const out = mockOutput({ format: opts.format ?? "text", promptTextFail: opts.promptTextFail });
const telemetry = mockTelemetryStateTracked();
const credentials = mockCommandCredentialsTracked({ saveFails: opts.saveFails });
const crypto = mockLoginCrypto({
decryptFails: opts.decryptFails,
keygenFails: opts.keygenFails,
tokenName: opts.tokenName,
});
const loginApi = mockLoginApi({
failTimes: opts.failTimes,
gotrueId: opts.gotrueId,
profileFails: opts.profileFails,
});
const analytics = mockAnalytics();
const httpApi = opts.httpApi === undefined ? undefined : mockCommandPlatformApi(opts.httpApi);
const cliSettings = mockCommandSettings({
workdir: tempRoot.current,
profileEnvValue: opts.profileEnvValue,
accessToken:
opts.accessTokenEnv !== undefined
? Option.some(Redacted.make(opts.accessTokenEnv))
: Option.none(),
});
const tty = mockTty({ stdinIsTty: isTTY, stdoutIsTty: opts.stdoutIsTty ?? false });
const layer = Layer.mergeAll(
buildTestRuntime({
out,
api: {
layer: mockCommandPlatformApiService({ v1: {} }).layer,
httpClientLayer: noopHttpClient,
},
cliSettings,
analytics,
telemetry: telemetry.layer,
tty,
...(opts.homeDir !== undefined
? { runtimeInfo: mockRuntimeInfo({ homeDir: opts.homeDir }) }
: {}),
}),
credentials.layer,
crypto.layer,
httpApi === undefined
? loginApi.layer
: loginApiLayer.pipe(Layer.provide(httpApi.httpClientLayer), Layer.provide(cliSettings)),
mockStdin(isTTY, opts.pipedStdin),
mockBrowser,
Layer.succeed(ProfileFlag, opts.profileFlag ?? "supabase"),
...(opts.argv !== undefined ? [Layer.succeed(CliArgs, { args: opts.argv })] : []),
);
return { layer, out, credentials, crypto, loginApi, telemetry, analytics, httpApi };
}
describe("login integration", () => {
it.effect("saves the token from --token and reports logged in", () => {
const { layer, out, credentials, analytics } = setupLogin();
return Effect.gen(function* () {
yield* login(flags({ token: Option.some(VALID_TOKEN) }));
expect(credentials.savedToken).toBe(VALID_TOKEN);
expect(out.stdoutText).toContain("You are now logged in. Happy coding!");
expect(analytics.captured.map((c) => c.event)).toContain(EventLoginCompleted);
}).pipe(Effect.provide(layer));
});
it.effect("saves the token from SUPABASE_ACCESS_TOKEN env when no flag is given", () => {
const { layer, credentials } = setupLogin({ accessTokenEnv: VALID_TOKEN });
return Effect.gen(function* () {
yield* login(flags());
expect(credentials.savedToken).toBe(VALID_TOKEN);
}).pipe(Effect.provide(layer));
});
it.effect("saves the token piped via stdin in non-TTY", () => {
const { layer, credentials } = setupLogin({
isTTY: false,
pipedStdin: VALID_TOKEN,
});
return Effect.gen(function* () {
yield* login(flags());
expect(credentials.savedToken).toBe(VALID_TOKEN);
}).pipe(Effect.provide(layer));
});
it.effect("rejects an invalid --token with 'cannot save provided token:'", () => {
const { layer } = setupLogin({ saveFails: true });
return Effect.gen(function* () {
const exit = yield* Effect.exit(login(flags({ token: Option.some("not-a-token") })));
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
const causeText = Cause.pretty(exit.cause);
expect(causeText).toContain("LoginSaveTokenError");
expect(causeText).toContain("cannot save provided token:");
}
}).pipe(Effect.provide(layer));
});
it.effect("fails in non-TTY with no token", () => {
const { layer } = setupLogin({ isTTY: false });
return Effect.gen(function* () {
const exit = yield* Effect.exit(login(flags()));
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
const causeText = Cause.pretty(exit.cause);
expect(causeText).toContain("LoginMissingTokenError");
expect(causeText).toContain("Cannot use automatic login flow inside non-TTY environments");
}
}).pipe(Effect.provide(layer));
});
it.effect("browser flow: generates link, opens browser, decrypts, saves, prints created", () => {
const { layer, out, credentials } = setupLogin({ isTTY: true, tokenName: "my-machine" });
return Effect.gen(function* () {
yield* login(flags());
expect(out.stdoutText).toContain(
"Hello from Supabase! Press Enter to open browser and login automatically.",
);
expect(out.stdoutText).toContain("/cli/login?session_id=test-session-id");
expect(out.stdoutText).toContain("Token my-machine created successfully.");
expect(out.stdoutText).toContain("You are now logged in. Happy coding!");
expect(credentials.savedToken).toBe(VALID_TOKEN);
}).pipe(Effect.provide(layer));
});
it.effect(
"browser flow with --no-browser prints the link without the open-browser banner",
() => {
const { layer, out } = setupLogin({ isTTY: true });
return Effect.gen(function* () {
yield* login(flags({ noBrowser: true }));
expect(out.stdoutText).toContain("Here is your login link, open it in the browser");
expect(out.stdoutText).not.toContain("Press Enter to open browser");
}).pipe(Effect.provide(layer));
},
);
it.effect("browser flow uses the default token name when --name is absent", () => {
const { layer, out } = setupLogin({ isTTY: true });
return Effect.gen(function* () {
yield* login(flags());
expect(out.stdoutText).toContain("Token cli_test@host_123 created successfully.");
}).pipe(Effect.provide(layer));
});
it.effect("the default token name ends in unix seconds from the clock", () =>
Effect.gen(function* () {
yield* TestClock.setTime(1_700_000_000_500);
const crypto = yield* LoginCrypto;
expect(yield* crypto.defaultTokenName).toMatch(/^cli_(.+@.+_)?1700000000$/);
}).pipe(Effect.provide(loginCryptoLayer)),
);
it.effect("retries verification on poll failure then succeeds", () => {
const { layer, out, loginApi } = setupLogin({ isTTY: true, failTimes: 2 });
return Effect.gen(function* () {
yield* login(flags());
expect(out.stderrText).toContain("Retry (1/2): ");
expect(out.stderrText).toContain("Retry (2/2): ");
expect(loginApi.loginCallCount).toBe(3);
expect(out.stdoutText).toContain("You are now logged in. Happy coding!");
}).pipe(Effect.provide(layer));
});
it.effect("fails after 2 retries are exhausted", () => {
const { layer, out } = setupLogin({ isTTY: true, failTimes: 3 });
return Effect.gen(function* () {
const exit = yield* Effect.exit(login(flags()));
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.pretty(exit.cause)).toContain("LoginFailedError");
}
expect(out.stderrText).toContain("Retry (2/2): ");
expect(out.stderrText).not.toContain("Retry (3/2): ");
}).pipe(Effect.provide(layer));
});
it.effect("decrypt failure surfaces 'cannot decrypt access token'", () => {
const { layer } = setupLogin({ isTTY: true, decryptFails: true });
return Effect.gen(function* () {
const exit = yield* Effect.exit(login(flags()));
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
const causeText = Cause.pretty(exit.cause);
expect(causeText).toContain("LoginDecryptError");
expect(causeText).toContain("cannot decrypt access token");
}
}).pipe(Effect.provide(layer));
});
it.effect("telemetry: successful profile fetch stitches the gotrue_id", () => {
const { layer, telemetry, analytics } = setupLogin({ gotrueId: "gotrue-abc" });
return Effect.gen(function* () {
yield* login(flags({ token: Option.some(VALID_TOKEN) }));
expect(telemetry.stitchedDistinctId).toBe("gotrue-abc");
expect(telemetry.clearedDistinctId).toBe(false);
expect(analytics.captured.map((c) => c.event)).toContain(EventLoginCompleted);
}).pipe(Effect.provide(layer));
});
it.effect(
"telemetry: profile fetch failure clears distinct_id but login still succeeds + still captures",
() => {
const { layer, out, telemetry, analytics } = setupLogin({ profileFails: true });
return Effect.gen(function* () {
yield* login(flags({ token: Option.some(VALID_TOKEN) }));
expect(telemetry.clearedDistinctId).toBe(true);
expect(telemetry.stitchedDistinctId).toBeUndefined();
expect(analytics.captured.map((c) => c.event)).toContain(EventLoginCompleted);
expect(out.stdoutText).toContain("You are now logged in. Happy coding!");
}).pipe(Effect.provide(layer));
},
);
describe("profile lookup over the real login API", () => {
const PROFILE = { gotrue_id: "gotrue-abc", primary_email: "a@b.co", username: "ab" };
const SESSION = {
access_token: "656e6372797074656420746f6b656e",
public_key: "04abcd",
nonce: "0102030405060708090a0b0c",
};
it.effect("looks up the profile once with the new token after a --token login", () => {
const { layer, out, credentials, telemetry, httpApi } = setupLogin({
httpApi: { response: { status: 200, body: PROFILE } },
});
return Effect.gen(function* () {
yield* login(flags({ token: Option.some(VALID_TOKEN) }));
const requests = httpApi?.requests ?? [];
expect(credentials.savedToken).toBe(VALID_TOKEN);
expect(out.stdoutText).toContain("You are now logged in. Happy coding!");
expect(requests.map(({ method, url }) => `${method} ${url}`)).toEqual([
"GET https://api.supabase.com/v1/profile",
]);
expect(requests[0]?.headers["authorization"]).toBe(`Bearer ${VALID_TOKEN}`);
expect(telemetry.stitchedDistinctId).toBe("gotrue-abc");
assertPermissionDrift({ command: "login", activeFlags: { token: true }, requests });
}).pipe(Effect.provide(layer));
});
it.effect(
"still logs in and clears the distinct id when the profile lookup is forbidden",
() => {
const { layer, out, credentials, telemetry, analytics, httpApi } = setupLogin({
httpApi: { response: { status: 403, body: { message: "Forbidden" } } },
});
return Effect.gen(function* () {
yield* login(flags({ token: Option.some(VALID_TOKEN) }));
const requests = httpApi?.requests ?? [];
expect(requests.map(({ method, url }) => `${method} ${url}`)).toEqual([
"GET https://api.supabase.com/v1/profile",
]);
expect(credentials.savedToken).toBe(VALID_TOKEN);
expect(out.stdoutText).toContain("You are now logged in. Happy coding!");
expect(telemetry.clearedDistinctId).toBe(true);
expect(telemetry.stitchedDistinctId).toBeUndefined();
expect(analytics.captured.map((c) => c.event)).toContain(EventLoginCompleted);
assertPermissionDrift({ command: "login", activeFlags: { token: true }, requests });
}).pipe(Effect.provide(layer));
},
);
it.effect("polls the login session, then looks up the profile in the browser flow", () => {
const { layer, credentials, httpApi } = setupLogin({
isTTY: true,
httpApi: {
handler: (request) =>
Effect.succeed(
request.url.includes("/platform/cli/login/")
? jsonResponse(request, 200, SESSION)
: jsonResponse(request, 200, PROFILE),
),
},
});
return Effect.gen(function* () {
yield* login(flags());
const requests = httpApi?.requests ?? [];
expect(credentials.savedToken).toBe(VALID_TOKEN);
expect(requests.map(({ method, url }) => `${method} ${url}`)).toEqual([
"GET https://api.supabase.com/platform/cli/login/test-session-id?device_code=123456",
"GET https://api.supabase.com/v1/profile",
]);
expect(requests[1]?.headers["authorization"]).toBe(`Bearer ${VALID_TOKEN}`);
assertPermissionDrift({ command: "login", requests });
}).pipe(Effect.provide(layer));
});
});
it.effect("flushes telemetry state via ensuring", () => {
const { layer, telemetry } = setupLogin();
return Effect.gen(function* () {
yield* login(flags({ token: Option.some(VALID_TOKEN) }));
expect(telemetry.flushed).toBe(true);
}).pipe(Effect.provide(layer));
});
for (const format of ["json", "stream-json"] as const) {
it.effect(`${format}: --token emits a single success result with no human banner`, () => {
const { layer, out } = setupLogin({ format });
return Effect.gen(function* () {
yield* login(flags({ token: Option.some(VALID_TOKEN) }));
const success = out.messages.find((m) => m.type === "success");
expect(success?.message).toBe("You are now logged in.");
expect(out.stdoutText).not.toContain("Happy coding!");
}).pipe(Effect.provide(layer));
});
}
it.effect("browser flow: keygen failure exits with LoginCryptoError", () => {
const { layer } = setupLogin({ isTTY: true, keygenFails: true });
return Effect.gen(function* () {
const exit = yield* Effect.exit(login(flags()));
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.pretty(exit.cause)).toContain("LoginCryptoError");
}
}).pipe(Effect.provide(layer));
});
for (const format of ["json", "stream-json"] as const) {
it.effect(`${format}: browser flow emits a success result with token_name`, () => {
const { layer, out } = setupLogin({ format, isTTY: true, tokenName: "my-machine" });
return Effect.gen(function* () {
yield* login(flags());
const success = out.messages.find((m) => m.type === "success");
expect(success?.message).toBe("You are now logged in.");
expect(success?.data).toMatchObject({ token_name: "my-machine" });
expect(out.stdoutText).not.toContain("Happy coding!");
}).pipe(Effect.provide(layer));
});
}
it.effect(
"prints the Claude Code plugin hint to stderr when in Claude Code with a TTY stdout",
() => {
const { layer, out } = setupLogin({ stdoutIsTty: true });
return withEnvVar(
"CLAUDECODE",
"1",
Effect.gen(function* () {
yield* login(flags({ token: Option.some(VALID_TOKEN) }));
expect(out.stderrText).toContain("claude-code-hint");
}).pipe(Effect.provide(layer)),
);
},
);
it.effect("persists ~/.supabase/profile on success when --profile is set", () => {
const { layer } = setupLogin({
profileFlag: "supabase-staging",
homeDir: tempRoot.current,
});
// An ambient SUPABASE_HOME would win over the mocked homeDir and write the real
// profile file, so the persistence tests unset it for their duration.
return withEnvVar(
"SUPABASE_HOME",
undefined,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* login(flags({ token: Option.some(VALID_TOKEN) }));
const profilePath = path.join(tempRoot.current, ".supabase", "profile");
const exists = yield* fs.exists(profilePath);
expect(exists).toBe(true);
const persisted = yield* fs.readFileString(profilePath);
expect(persisted).toBe("supabase-staging");
}).pipe(Effect.provide(layer)),
);
});
it.effect("persists SUPABASE_PROFILE verbatim when neither --profile nor argv names one", () => {
const { layer } = setupLogin({
argv: ["login", "--token", VALID_TOKEN],
homeDir: tempRoot.current,
profileEnvValue: Option.some("supabase-staging"),
});
return withEnvVar(
"SUPABASE_HOME",
undefined,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* login(flags({ token: Option.some(VALID_TOKEN) }));
const persisted = yield* fs.readFileString(
path.join(tempRoot.current, ".supabase", "profile"),
);
expect(persisted).toBe("supabase-staging");
}).pipe(Effect.provide(layer)),
);
});
it.effect("explicit --profile supabase persists 'supabase', shadowing SUPABASE_PROFILE", () => {
const { layer } = setupLogin({
argv: ["login", "--profile", "supabase", "--token", VALID_TOKEN],
homeDir: tempRoot.current,
profileEnvValue: Option.some("rogue-profile"),
});
return withEnvVar(
"SUPABASE_HOME",
undefined,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* login(flags({ token: Option.some(VALID_TOKEN) }));
const profilePath = path.join(tempRoot.current, ".supabase", "profile");
const persisted = yield* fs.readFileString(profilePath);
expect(persisted).toBe("supabase");
}).pipe(Effect.provide(layer)),
);
});
it.effect("persists the raw YAML path selected by SUPABASE_PROFILE", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const profilePath = path.join(tempRoot.current, "profile.yaml");
const { layer } = setupLogin({
homeDir: tempRoot.current,
profileEnvValue: Option.some(profilePath),
});
yield* login(flags({ token: Option.some(VALID_TOKEN) })).pipe(Effect.provide(layer));
expect(yield* fs.readFileString(path.join(tempRoot.current, ".supabase", "profile"))).toBe(
profilePath,
);
}).pipe(Effect.provide(BunServices.layer)),
);
it.effect("explicit --profile supabase heals a stale persisted profile file", () => {
const { layer } = setupLogin({
argv: ["login", "--profile=supabase"],
homeDir: tempRoot.current,
});
return withEnvVar(
"SUPABASE_HOME",
undefined,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const profilePath = path.join(tempRoot.current, ".supabase", "profile");
yield* fs.makeDirectory(path.join(tempRoot.current, ".supabase"), { recursive: true });
yield* fs.writeFileString(profilePath, "resms");
yield* login(flags({ token: Option.some(VALID_TOKEN) }));
const healed = yield* fs.readFileString(profilePath);
expect(healed).toBe("supabase");
}).pipe(Effect.provide(layer)),
);
});
it.effect("browser flow in json mode fails cleanly at the prompt", () => {
const { layer } = setupLogin({ format: "json", isTTY: true, promptTextFail: true });
return Effect.gen(function* () {
const exit = yield* Effect.exit(login(flags()));
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.pretty(exit.cause)).toContain("NonInteractiveError");
}
}).pipe(Effect.provide(layer));
});
});