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