Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AntigravityAuth.test.ts

527 lines20.6 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import { ProviderInstanceId, ProviderSetupError, type ProviderAuthState } from "@t3tools/contracts";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as Fiber from "effect/Fiber";
8import * as Option from "effect/Option";
9import * as Scope from "effect/Scope";
10import * as Stream from "effect/Stream";
11import * as TestClock from "effect/testing/TestClock";
12import * as AcpErrors from "effect-acp/errors";
13import type * as AcpSchema from "effect-acp/schema";
14​
15import {
16 makeAntigravityAuth,
17 type AntigravityAuth,
18 type AntigravityAuthRuntime,
19} from "./AntigravityAuth.ts";
20import type { AcpSessionRuntimeStartResult } from "./acp/AcpSessionRuntime.ts";
21​
22const instanceId = ProviderInstanceId.make("antigravity-auth-test");
23const owner = "t3-auth-session-owner";
24const otherOwner = "t3-auth-session-other";
25const authorizationUrl =
26 "https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A51234%2F&state=test-state";
27const callbackUrl = "http://127.0.0.1:51234/?state=test-state&code=test-code";
28​
29const initialized = {
30 protocolVersion: 1,
31 authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],
32 agentCapabilities: { auth: { logout: {} } },
33} satisfies AcpSchema.InitializeResponse;
34const started: AcpSessionRuntimeStartResult = {
35 sessionId: "native-session",
36 initializeResult: initialized,
37 sessionSetupResult: {
38 sessionId: "native-session",
39 models: {
40 currentModelId: "gemini-test",
41 availableModels: [{ modelId: "gemini-test", name: "Gemini test" }],
42 },
43 },
44 modelConfigId: "model",
45};
46​
47const phase = (auth: AntigravityAuth, value: ProviderAuthState["phase"], sessionId = owner) =>
48 auth.controller.subscribe(sessionId).pipe(
49 Stream.filter((state) => state.phase === value),
50 Stream.runHead,
51 Effect.map(Option.getOrThrow),
52 );
53​
54const makeHarness = Effect.fn("makeAuthTestHarness")(function* (
55 options: {
56 readonly interactive?: boolean;
57 readonly authorizationUrls?: ReadonlyArray<string>;
58 readonly supportsLogout?: boolean;
59 readonly beforeInitialize?: Effect.Effect<void>;
60 readonly forwardCallback?: Effect.Effect<void, ProviderSetupError>;
61 } = {},
62) {
63 const authenticated = yield* Deferred.make<void, AcpErrors.AcpError>();
64 const discovered = yield* Deferred.make<void>();
65 const closed = yield* Deferred.make<void>();
66 const events: string[] = [];
67 let receiveAuthorizationUrl:
68 | ((url: string) => Effect.Effect<void, AcpErrors.AcpError>)
69 | undefined;
70 let forwarded = 0;
71 let catalog = ["previous-account-model"];
72 const auth = yield* makeAntigravityAuth({
73 instanceId,
74 makeRuntime: (input) =>
75 Effect.gen(function* () {
76 receiveAuthorizationUrl = input.onAuthorizationUrl;
77 events.push("process-open");
78 yield* Effect.addFinalizer(() =>
79 Effect.gen(function* () {
80 events.push("process-close");
81 yield* Deferred.succeed(closed, undefined);
82 }),
83 );
84 return {
85 initialize: () =>
86 Effect.gen(function* () {
87 events.push("initialize");
88 yield* options.beforeInitialize ?? Effect.void;
89 return options.supportsLogout === false
90 ? { ...initialized, agentCapabilities: {} }
91 : initialized;
92 }),
93 start: () =>
94 Effect.gen(function* () {
95 events.push("authenticate");
96 if (options.interactive !== false && input.onAuthorizationUrl) {
97 for (const url of options.authorizationUrls ?? [authorizationUrl]) {
98 yield* input.onAuthorizationUrl(url);
99 }
100 }
101 yield* Deferred.await(authenticated);
102 events.push("session-new");
103 yield* Deferred.await(discovered);
104 return started;
105 }),
106 request: (method) =>
107 Effect.sync(() => {
108 events.push(method);
109 return {};
110 }),
111 } satisfies AntigravityAuthRuntime;
112 }),
113 onAuthenticated: () =>
114 Effect.sync(() => {
115 catalog = ["gemini-test"];
116 events.push("catalog-published");
117 }),
118 onSignedOut: Effect.sync(() => {
119 catalog = [];
120 events.push("catalog-cleared");
121 }),
122 forwardCallback: () =>
123 options.forwardCallback ??
124 Effect.sync(() => {
125 forwarded += 1;
126 }),
127 });
128 return {
129 auth,
130 authenticated,
131 discovered,
132 closed,
133 events,
134 catalog: () => catalog,
135 forwarded: () => forwarded,
136 receiveAuthorizationUrl: (url: string) =>
137 Effect.suspend(() =>
138 receiveAuthorizationUrl
139 ? receiveAuthorizationUrl(url)
140 : Effect.die("Authorization URL receiver is not ready."),
141 ),
142 };
143});
144​
145it.layer(NodeServices.layer)("AntigravityAuth", (it) => {
146 it.effect("accepts the same authorization URL from stderr and stdout", () =>
147 Effect.gen(function* () {
148 const harness = yield* makeHarness({
149 authorizationUrls: [authorizationUrl, authorizationUrl],
150 });
151 yield* harness.auth.controller.start(owner);
152 const waiting = yield* phase(harness.auth, "waiting");
153 assert.equal(waiting.authorizationUrl, authorizationUrl);
154​
155 yield* Deferred.succeed(harness.authenticated, undefined);
156 yield* Deferred.succeed(harness.discovered, undefined);
157 yield* phase(harness.auth, "succeeded");
158 }),
159 );
160​
161 it.effect("accepts a delayed duplicate after callback completion starts", () =>
162 Effect.gen(function* () {
163 const harness = yield* makeHarness();
164 const state = yield* harness.auth.controller.start(owner);
165 yield* phase(harness.auth, "waiting");
166 yield* harness.auth.controller.complete(owner, {
167 flowId: state.flowId!,
168 callbackUrl,
169 });
170​
171 yield* harness.receiveAuthorizationUrl(authorizationUrl);
172​
173 yield* Deferred.succeed(harness.authenticated, undefined);
174 yield* Deferred.succeed(harness.discovered, undefined);
175 yield* phase(harness.auth, "succeeded");
176 }),
177 );
178​
179 it.effect("rejects a different second authorization URL", () =>
180 Effect.gen(function* () {
181 const harness = yield* makeHarness({
182 authorizationUrls: [authorizationUrl, `${authorizationUrl}&scope=another-request`],
183 });
184 yield* harness.auth.controller.start(owner);
185​
186 const failed = yield* phase(harness.auth, "failed");
187 assert.isNull(failed.authorizationUrl);
188 assert.deepEqual(harness.catalog(), ["previous-account-model"]);
189 }),
190 );
191​
192 it.effect("keeps a remote flow private and waits for native auth and catalog discovery", () =>
193 Effect.gen(function* () {
194 const harness = yield* makeHarness();
195 const state = yield* harness.auth.controller.start(owner);
196 assert.isNotNull(state.flowId);
197 const waiting = yield* phase(harness.auth, "waiting");
198 assert.equal(waiting.authorizationUrl, authorizationUrl);
199​
200 const other = yield* phase(harness.auth, "waiting", otherOwner);
201 assert.isNull(other.authorizationUrl);
202 assert.isNull(other.flowId);
203 const stolen = yield* harness.auth.controller
204 .complete(otherOwner, { flowId: state.flowId!, callbackUrl })
205 .pipe(Effect.exit);
206 assert.isTrue(Exit.isFailure(stolen));
207 assert.equal(harness.forwarded(), 0);
208​
209 const verifying = yield* harness.auth.controller.complete(owner, {
210 flowId: state.flowId!,
211 callbackUrl,
212 });
213 assert.equal(verifying.phase, "verifying");
214 assert.equal(harness.forwarded(), 1);
215 assert.deepEqual(harness.catalog(), ["previous-account-model"]);
216​
217 yield* Deferred.succeed(harness.authenticated, undefined);
218 yield* Deferred.succeed(harness.discovered, undefined);
219 const succeeded = yield* phase(harness.auth, "succeeded");
220 assert.deepEqual(harness.catalog(), ["gemini-test"]);
221 assert.isNull(succeeded.authorizationUrl);
222 assert.isNull(succeeded.expiresAt);
223 assert.equal(harness.events.at(-1), "process-close");
224 }),
225 );
226​
227 it.effect("does not call callback HTTP success a successful Google sign-in", () =>
228 Effect.gen(function* () {
229 const harness = yield* makeHarness();
230 const state = yield* harness.auth.controller.start(owner);
231 yield* phase(harness.auth, "waiting");
232 yield* harness.auth.controller.complete(owner, { flowId: state.flowId!, callbackUrl });
233 yield* Deferred.fail(
234 harness.authenticated,
235 AcpErrors.AcpRequestError.internalError(`access_denied ${callbackUrl}`),
236 );
237 const failed = yield* phase(harness.auth, "failed");
238 assert.include(failed.message ?? "", "not approved");
239 assert.notInclude(failed.message ?? "", "test-code");
240 assert.isNull(failed.authorizationUrl);
241 assert.deepEqual(harness.catalog(), ["previous-account-model"]);
242 yield* Deferred.await(harness.closed);
243 }),
244 );
245​
246 it.effect("accepts direct local or cached completion without a callback RPC", () =>
247 Effect.gen(function* () {
248 const harness = yield* makeHarness({ interactive: false });
249 yield* harness.auth.controller.start(owner);
250 yield* Deferred.succeed(harness.authenticated, undefined);
251 yield* Deferred.succeed(harness.discovered, undefined);
252 yield* phase(harness.auth, "succeeded");
253 assert.equal(harness.forwarded(), 0);
254 assert.deepEqual(harness.catalog(), ["gemini-test"]);
255 }),
256 );
257​
258 it.effect("rejects mismatched callbacks without sending any HTTP request", () =>
259 Effect.gen(function* () {
260 const harness = yield* makeHarness();
261 const state = yield* harness.auth.controller.start(owner);
262 yield* phase(harness.auth, "waiting");
263 for (const invalidUrl of [
264 callbackUrl.replace("51234", "51235"),
265 callbackUrl.replace("test-state", "wrong-state"),
266 callbackUrl.replace("/?", "/other?"),
267 `${callbackUrl}&state=test-state`,
268 ]) {
269 const result = yield* harness.auth.controller
270 .complete(owner, { flowId: state.flowId!, callbackUrl: invalidUrl })
271 .pipe(Effect.exit);
272 assert.isTrue(Exit.isFailure(result));
273 }
274 assert.equal(harness.forwarded(), 0);
275 assert.equal((yield* phase(harness.auth, "waiting")).authorizationUrl, authorizationUrl);
276 yield* harness.auth.controller.cancel(owner, state.flowId!);
277 }),
278 );
279​
280 it.effect("fails the flow when delivery fails after the requesting client disconnects", () =>
281 Effect.gen(function* () {
282 const deliveryGate = yield* Deferred.make<void>();
283 const harness = yield* makeHarness({
284 forwardCallback: Deferred.await(deliveryGate).pipe(
285 Effect.andThen(
286 Effect.fail(
287 new ProviderSetupError({
288 instanceId,
289 operation: "complete",
290 detail: "loopback refused",
291 }),
292 ),
293 ),
294 ),
295 });
296 const state = yield* harness.auth.controller.start(owner);
297 yield* phase(harness.auth, "waiting");
298 // The client sends the callback, then its socket drops before Google answers.
299 const request = yield* harness.auth.controller
300 .complete(owner, { flowId: state.flowId!, callbackUrl })
301 .pipe(Effect.forkScoped);
302 yield* phase(harness.auth, "verifying");
303 yield* Fiber.interrupt(request);
304 yield* Deferred.succeed(deliveryGate, undefined);
305 const failed = yield* phase(harness.auth, "failed");
306 assert.include(failed.message ?? "", "Could not deliver");
307 assert.isTrue(harness.events.includes("process-close"));
308 }),
309 );
310​
311 it.effect("cancel closes the owned process without forwarding a denial", () =>
312 Effect.gen(function* () {
313 const harness = yield* makeHarness();
314 const state = yield* harness.auth.controller.start(owner);
315 yield* phase(harness.auth, "waiting");
316 const wrongOwner = yield* harness.auth.controller
317 .cancel(otherOwner, state.flowId!)
318 .pipe(Effect.exit);
319 assert.isTrue(Exit.isFailure(wrongOwner));
320 const cancelled = yield* harness.auth.controller.cancel(owner, state.flowId!);
321 assert.equal(cancelled.phase, "cancelled");
322 assert.isNull(cancelled.authorizationUrl);
323 assert.equal(harness.forwarded(), 0);
324 yield* Deferred.await(harness.closed);
325 assert.deepEqual(harness.catalog(), ["previous-account-model"]);
326 }),
327 );
328​
329 it.effect("expires the flow at the official deadline and removes its URL", () =>
330 Effect.gen(function* () {
331 const harness = yield* makeHarness();
332 const state = yield* harness.auth.controller.start(owner);
333 yield* phase(harness.auth, "waiting");
334 yield* TestClock.adjust("300 seconds");
335 const failed = yield* phase(harness.auth, "failed");
336 assert.include(failed.message ?? "", "expired");
337 assert.isNull(failed.authorizationUrl);
338 yield* Deferred.await(harness.closed);
339 const late = yield* harness.auth.controller
340 .complete(owner, { flowId: state.flowId!, callbackUrl })
341 .pipe(Effect.exit);
342 assert.isTrue(Exit.isFailure(late));
343 assert.equal(harness.forwarded(), 0);
344 }),
345 );
346​
347 it.effect("survives subscriber disconnect and does not replace a competing client's flow", () =>
348 Effect.gen(function* () {
349 const harness = yield* makeHarness();
350 const first = yield* harness.auth.controller.start(owner);
351 yield* phase(harness.auth, "waiting");
352 const second = yield* harness.auth.controller.start(owner);
353 assert.equal(first.flowId, second.flowId);
354 const competing = yield* harness.auth.controller.start(otherOwner).pipe(Effect.exit);
355 assert.isTrue(Exit.isFailure(competing));
356 const resumed = yield* phase(harness.auth, "waiting");
357 assert.equal(resumed.flowId, first.flowId);
358 assert.deepEqual(harness.events, ["process-open", "authenticate"]);
359 yield* harness.auth.controller.cancel(owner, first.flowId!);
360 }),
361 );
362​
363 it.effect("sign-out closes admission and every process before fresh native logout", () =>
364 Effect.gen(function* () {
365 const harness = yield* makeHarness();
366 const processScope = yield* Scope.make();
367 yield* Effect.addFinalizer(() => Scope.close(processScope, Exit.void));
368 const stop = Effect.gen(function* () {
369 harness.events.push("chat-close");
370 yield* Scope.close(processScope, Exit.void);
371 });
372 yield* harness.auth.withProcess(stop, Effect.void).pipe(Scope.provide(processScope));
373 const stopSessions = Effect.gen(function* () {
374 harness.events.push("sessions-stop");
375 const denied = yield* harness.auth
376 .withProcess(
377 Effect.void,
378 Effect.sync(() => harness.events.push("late-process")),
379 )
380 .pipe(Effect.scoped, Effect.exit);
381 assert.isTrue(Exit.isFailure(denied));
382 });
383 const result = yield* harness.auth.controller.logout(stopSessions);
384 assert.equal(result.phase, "idle");
385 assert.deepEqual(harness.events, [
386 "sessions-stop",
387 "chat-close",
388 "process-open",
389 "initialize",
390 "logout",
391 "catalog-cleared",
392 "process-close",
393 ]);
394 assert.deepEqual(harness.catalog(), []);
395 yield* harness.auth.withProcess(Effect.void, Effect.void).pipe(Effect.scoped);
396 }),
397 );
398​
399 it.effect("signs out after a slow packaged runtime starts", () =>
400 Effect.gen(function* () {
401 const entered = yield* Deferred.make<void>();
402 const initialized = yield* Deferred.make<void>();
403 const harness = yield* makeHarness({
404 beforeInitialize: Deferred.succeed(entered, undefined).pipe(
405 Effect.andThen(Deferred.await(initialized)),
406 ),
407 });
408 const logout = yield* harness.auth.controller.logout(Effect.void).pipe(Effect.forkScoped);
409 yield* Deferred.await(entered);
410 yield* TestClock.adjust("47 seconds");
411 yield* Deferred.succeed(initialized, undefined);
412 assert.equal((yield* Fiber.join(logout)).phase, "idle");
413 assert.include(harness.events, "logout");
414 assert.deepEqual(harness.catalog(), []);
415 yield* Deferred.await(harness.closed);
416 }),
417 );
418​
419 it.effect("closes a stalled sign-out process without clearing its account catalog", () =>
420 Effect.gen(function* () {
421 const entered = yield* Deferred.make<void>();
422 const harness = yield* makeHarness({
423 beforeInitialize: Deferred.succeed(entered, undefined).pipe(Effect.andThen(Effect.never)),
424 });
425 const logout = yield* harness.auth.controller
426 .logout(Effect.void)
427 .pipe(Effect.exit, Effect.forkScoped);
428 yield* Deferred.await(entered);
429 yield* TestClock.adjust("90 seconds");
430 assert.isTrue(Exit.isFailure(yield* Fiber.join(logout)));
431 yield* Deferred.await(harness.closed);
432 assert.notInclude(harness.events, "logout");
433 assert.deepEqual(harness.catalog(), ["previous-account-model"]);
434 yield* harness.auth.withProcess(Effect.void, Effect.void).pipe(Effect.scoped);
435 }),
436 );
437​
438 it.effect(
439 "sign-out interrupts startup without interrupting its caller after startup returns",
440 () =>
441 Effect.gen(function* () {
442 const harness = yield* makeHarness();
443 const entering = yield* Deferred.make<void>();
444 const continueStartup = yield* Deferred.make<void>();
445 const processScope = yield* Scope.make();
446 yield* Effect.addFinalizer(() => Scope.close(processScope, Exit.void));
447 const task = Effect.gen(function* () {
448 yield* Deferred.succeed(entering, undefined);
449 yield* Deferred.await(continueStartup);
450 harness.events.push("late-spawn");
451 });
452 const startup = yield* harness.auth
453 .withProcess(Scope.close(processScope, Exit.void), task)
454 .pipe(Scope.provide(processScope), Effect.forkScoped);
455 yield* Deferred.await(entering);
456 yield* harness.auth.controller.logout(Effect.void);
457 yield* Deferred.succeed(continueStartup, undefined);
458 assert.isTrue(Exit.isFailure(yield* Fiber.await(startup)));
459 assert.notInclude(harness.events, "late-spawn");
460 assert.include(harness.events, "logout");
461 }),
462 );
463​
464 it.effect("failed session stopping still closes owned processes and skips native logout", () =>
465 Effect.gen(function* () {
466 const harness = yield* makeHarness();
467 const processScope = yield* Scope.make();
468 yield* Effect.addFinalizer(() => Scope.close(processScope, Exit.void));
469 const stop = Effect.gen(function* () {
470 harness.events.push("chat-close");
471 yield* Scope.close(processScope, Exit.void);
472 });
473 yield* harness.auth.withProcess(stop, Effect.void).pipe(Scope.provide(processScope));
474 const result = yield* harness.auth.controller
475 .logout(
476 Effect.fail(
477 new ProviderSetupError({
478 instanceId,
479 operation: "stopSessions",
480 detail: "Stop failed.",
481 }),
482 ),
483 )
484 .pipe(Effect.exit);
485 assert.isTrue(Exit.isFailure(result));
486 assert.deepEqual(harness.events, ["chat-close"]);
487 assert.deepEqual(harness.catalog(), ["previous-account-model"]);
488 }),
489 );
490​
491 it.effect("finishes sign-out when the requesting client disconnects", () =>
492 Effect.gen(function* () {
493 const harness = yield* makeHarness();
494 const stopping = yield* Deferred.make<void>();
495 const continueStop = yield* Deferred.make<void>();
496 const request = yield* harness.auth.controller
497 .logout(
498 Effect.gen(function* () {
499 yield* Deferred.succeed(stopping, undefined);
500 yield* Deferred.await(continueStop);
501 }),
502 )
503 .pipe(Effect.forkScoped);
504 yield* Deferred.await(stopping);
505 yield* Fiber.interrupt(request);
506 yield* Deferred.succeed(continueStop, undefined);
507 const result = yield* harness.auth.controller.subscribe(owner).pipe(
508 Stream.filter((state) => state.message === "Signed out of Google."),
509 Stream.runHead,
510 Effect.map(Option.getOrThrow),
511 );
512 assert.equal(result.phase, "idle");
513 assert.deepEqual(harness.catalog(), []);
514 assert.include(harness.events, "logout");
515 }),
516 );
517​
518 it.effect("does not call logout unless the official process advertises it", () =>
519 Effect.gen(function* () {
520 const harness = yield* makeHarness({ supportsLogout: false });
521 const result = yield* harness.auth.controller.logout(Effect.void).pipe(Effect.exit);
522 assert.isTrue(Exit.isFailure(result));
523 assert.deepEqual(harness.events, ["process-open", "initialize", "process-close"]);
524 assert.deepEqual(harness.catalog(), ["previous-account-model"]);
525 }),
526 );
527});