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

AntigravityAuth.test.ts

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