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

AntigravityAuth.test.ts

558 lines21.6 KB

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