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

AntigravityAuth.test.ts

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