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

auth.test.ts

483 lines17.2 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, type ProviderAuthState } from "@t3tools/contracts";
6import { AcpRegistrySettings } from "../settings.ts";
7import * as Deferred from "effect/Deferred";
8import * as Cause from "effect/Cause";
9import * as Effect from "effect/Effect";
10import * as Option from "effect/Option";
11import * as Schema from "effect/Schema";
12import * as Stream from "effect/Stream";
13import type * as AcpSchema from "effect-acp/compat";
14import { AcpRequestError } from "effect-acp/errors";
15​
16import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
17import { formatFailureDetail, makeAcpRegistryAuth } from "./auth.ts";
18import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
19import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
20​
21const decodeSettings = Schema.decodeSync(AcpRegistrySettings);
22const instanceId = ProviderInstanceId.make("acp-auth-test");
23const browserMethod = { id: "browser", name: "Browser", type: "agent" as const };
24const terminalMethod = {
25 id: "terminal",
26 name: "Terminal",
27 type: "terminal" as const,
28 args: ["login"],
29 env: { LOGIN: "yes", OVERRIDE: "method" },
30};
31const resolved: AcpRegistrySupport.ResolvedAcpRegistryAgent = {
32 agent: {
33 id: "test-agent",
34 name: "Test",
35 version: "1.0.0",
36 description: "Test",
37 distribution: {},
38 },
39 distribution: "binary",
40 spawn: {
41 command: "/managed/agent",
42 args: ["--acp"],
43 env: { OVERRIDE: "spawn", AGENT_HOME: "/custom/home" },
44 },
45};
46const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = {
47 inspect: () =>
48 Effect.succeed({
49 status: "ready",
50 agentId: "test-agent",
51 version: "1.0.0",
52 distribution: "binary",
53 }),
54 resolve: () => Effect.succeed(resolved),
55 search: () => Effect.die("unused"),
56 prepare: () => Effect.die("unused"),
57 uninstallManagedBinary: () => Effect.die("unused"),
58};
59​
60const makeHarness = (
61 method: AcpSchema.AuthMethod,
62 failVerification = false,
63 settings = decodeSettings({ agentId: "test-agent" }),
64 providerInstanceId = instanceId,
65 authenticateError?: AcpRequestError,
66) =>
67 Effect.gen(function* () {
68 const verify = yield* Deferred.make<void>();
69 const changed: boolean[] = [];
70 const closed: number[] = [];
71 const authenticated: string[] = [];
72 const started: number[] = [];
73 let runtimes = 0;
74 let version = "1.0.0";
75 let terminalSpawn: PtyAdapter.PtySpawnInput | undefined;
76 let data: ((data: string) => void) | undefined;
77 let exit: ((event: PtyAdapter.PtyExitEvent) => void) | undefined;
78 let killed = false;
79 let closedBeforeTerminal = false;
80 const written: string[] = [];
81 const sizes: number[][] = [];
82 const controller = yield* makeAcpRegistryAuth({
83 instanceId: providerInstanceId,
84 settings,
85 cwd: "/workspace",
86 environment: { PATH: "/tools", OVERRIDE: "base" },
87 onChanged: (value) =>
88 Effect.sync(() => {
89 changed.push(value);
90 }),
91 makeRuntime: () =>
92 Effect.gen(function* () {
93 const id = ++runtimes;
94 yield* Effect.addFinalizer(() =>
95 Effect.sync(() => {
96 closed.push(id);
97 }),
98 );
99 const initialized: AcpSchema.InitializeResponse = {
100 protocolVersion: 2,
101 agentCapabilities: {},
102 authMethods: [{ ...method, name: `${method.name} ${version}` }],
103 };
104 let elicitation:
105 | Parameters<AcpSessionRuntime.AcpSessionRuntime["Service"]["handleElicitation"]>[0]
106 | undefined;
107 return {
108 initialize: () => Effect.succeed(initialized),
109 handleElicitation: (handler) =>
110 Effect.sync(() => {
111 elicitation = handler;
112 }),
113 authenticate: (methodId) =>
114 Effect.gen(function* () {
115 authenticated.push(methodId);
116 if (authenticateError !== undefined) {
117 return yield* authenticateError;
118 }
119 if (elicitation)
120 yield* elicitation(
121 {
122 mode: "url",
123 url: "https://example.com/login",
124 elicitationId: "consent",
125 requestId: "login",
126 message: "Sign in",
127 },
128 { requestId: "login", method: "elicitation/create" },
129 );
130 }),
131 start: () =>
132 Effect.gen(function* () {
133 started.push(id);
134 yield* Deferred.await(verify);
135 if (failVerification)
136 return yield* new AcpRequestError({
137 method: "session/new",
138 code: -32000,
139 errorMessage: "Authentication required",
140 });
141 return {
142 sessionId: "verified",
143 initializeResult: initialized,
144 sessionSetupResult: { sessionId: "verified" },
145 modelConfigId: undefined,
146 };
147 }),
148 logout: Effect.succeed({}),
149 };
150 }),
151 }).pipe(
152 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, {
153 ...catalog,
154 inspect: () =>
155 Effect.sync(() => ({
156 status: "ready" as const,
157 agentId: "test-agent",
158 version,
159 distribution: "binary" as const,
160 })),
161 }),
162 Effect.provideService(PtyAdapter.PtyAdapter, {
163 spawn: (input) =>
164 Effect.sync(() => {
165 terminalSpawn = input;
166 closedBeforeTerminal = closed.includes(runtimes);
167 return {
168 pid: 123,
169 write: (input) => {
170 written.push(input);
171 },
172 resize: (cols, rows) => {
173 sizes.push([cols, rows]);
174 },
175 kill: () => {
176 killed = true;
177 },
178 onData: (callback) => {
179 data = callback;
180 return () => {
181 data = undefined;
182 };
183 },
184 onExit: (callback) => {
185 exit = callback;
186 return () => {
187 exit = undefined;
188 };
189 },
190 };
191 }),
192 }),
193 );
194 const state = (predicate: (state: ProviderAuthState) => boolean) =>
195 controller
196 .subscribe("owner")
197 .pipe(Stream.filter(predicate), Stream.runHead, Effect.map(Option.getOrThrow));
198 const phase = (phase: ProviderAuthState["phase"]) => state((value) => value.phase === phase);
199 yield* state((value) => (value.methods?.length ?? 0) > 0);
200 return {
201 controller,
202 verify,
203 changed,
204 closed,
205 authenticated,
206 started,
207 phase,
208 state,
209 terminalSpawn: () => terminalSpawn,
210 closedBeforeTerminal: () => closedBeforeTerminal,
211 data: (value: string) => data?.(value),
212 exit: (exitCode: number) => exit?.({ exitCode, signal: null }),
213 killed: () => killed,
214 written,
215 sizes,
216 runtimes: () => runtimes,
217 setVersion: (value: string) => {
218 version = value;
219 },
220 };
221 }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog));
222​
223it.effect("keeps local credentials separate from a matching registry agent ID", () =>
224 Effect.gen(function* () {
225 const registry = yield* makeHarness(browserMethod);
226 const local = yield* makeHarness(
227 browserMethod,
228 false,
229 decodeSettings({ source: "local", commandPath: "/different/agent" }),
230 ProviderInstanceId.make("test-agent"),
231 );
232 assert.deepEqual(registry.controller.credentialBinding, {
233 owner: "provider",
234 key: "acp:test-agent",
235 });
236 assert.deepEqual(local.controller.credentialBinding, {
237 owner: "provider",
238 key: "acp:local:test-agent",
239 });
240 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
241);
242​
243it.effect(
244 "discovers methods without signing in, then waits for browser consent and session verification",
245 () =>
246 Effect.gen(function* () {
247 const h = yield* makeHarness(browserMethod);
248 assert.deepEqual(h.authenticated, []);
249 assert.deepEqual(h.started, []);
250 assert.deepEqual(h.closed, [1]);
251 const flow = yield* h.controller.start("owner", Effect.void, "browser");
252 const waiting = yield* h.phase("waiting");
253 assert.deepEqual(waiting.interaction, {
254 type: "browser",
255 id: "consent",
256 url: "https://example.com/login",
257 requiresConsent: true,
258 });
259 yield* h.controller.respond!("owner", {
260 instanceId,
261 flowId: flow.flowId!,
262 interactionId: "consent",
263 response: { type: "browser", action: "accept" },
264 });
265 yield* h.phase("verifying");
266 assert.deepEqual(h.changed, []);
267 yield* Deferred.succeed(h.verify, undefined);
268 yield* h.phase("succeeded");
269 assert.deepEqual(h.authenticated, ["browser"]);
270 assert.deepEqual(h.changed, [true]);
271 assert.deepEqual(h.closed, [1, 2]);
272 yield* h.controller.logout(Effect.void);
273 assert.deepEqual(h.changed, [true, false]);
274 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
275);
276​
277it.effect(
278 "runs terminal auth directly with the resolved environment and reconnects to verify",
279 () =>
280 Effect.gen(function* () {
281 const h = yield* makeHarness(terminalMethod);
282 const flow = yield* h.controller.start("owner", Effect.void, "terminal");
283 yield* h.phase("waiting");
284 assert.isTrue(h.closedBeforeTerminal());
285 assert.deepEqual(h.terminalSpawn(), {
286 shell: "/managed/agent",
287 args: ["--acp", "login"],
288 cwd: "/workspace",
289 cols: 80,
290 rows: 24,
291 env: { PATH: "/tools", OVERRIDE: "method", AGENT_HOME: "/custom/home", LOGIN: "yes" },
292 });
293 h.data("Enter code: ");
294 const output = yield* h.state(
295 (value) =>
296 value.interaction?.type === "terminal" && value.interaction.output === "Enter code: ",
297 );
298 assert.strictEqual(
299 output.interaction?.type === "terminal" && output.interaction.outputOffset,
300 12,
301 );
302 yield* h.controller.respond!("owner", {
303 instanceId,
304 flowId: flow.flowId!,
305 interactionId: "terminal",
306 response: { type: "terminal", data: "123\r", size: { cols: 100, rows: 30 } },
307 });
308 assert.deepEqual(h.written, ["123\r"]);
309 assert.deepEqual(h.sizes, [[100, 30]]);
310 h.exit(0);
311 yield* h.phase("verifying");
312 assert.isTrue(h.killed());
313 assert.deepEqual(h.authenticated, []);
314 yield* Deferred.succeed(h.verify, undefined);
315 yield* h.phase("succeeded");
316 assert.deepEqual(h.started, [3]);
317 assert.deepEqual(h.changed, [true]);
318 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
319);
320​
321it.effect("cancels the login PTY and rejects further terminal input", () =>
322 Effect.gen(function* () {
323 const h = yield* makeHarness(terminalMethod);
324 const flow = yield* h.controller.start("owner");
325 yield* h.phase("waiting");
326 yield* h.controller.cancel("owner", flow.flowId!);
327 assert.isTrue(h.killed());
328 assert.deepEqual(h.started, []);
329 assert.deepEqual(h.changed, []);
330 assert.strictEqual(
331 (yield* h.controller.respond!("owner", {
332 instanceId,
333 flowId: flow.flowId!,
334 interactionId: "terminal",
335 response: { type: "terminal", data: "late\r" },
336 }).pipe(Effect.result))._tag,
337 "Failure",
338 );
339 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
340);
341​
342it.effect("does not report authentication when post-login verification fails", () =>
343 Effect.gen(function* () {
344 const h = yield* makeHarness(terminalMethod, true);
345 yield* h.controller.start("owner");
346 yield* h.phase("waiting");
347 h.exit(0);
348 yield* h.phase("verifying");
349 yield* Deferred.succeed(h.verify, undefined);
350 const failed = yield* h.phase("failed");
351 assert.deepEqual(h.changed, []);
352 assert.isTrue(h.killed());
353 assert.strictEqual(
354 failed.message,
355 "The provider could not create a session after terminal sign-in. Authentication required",
356 );
357 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
358);
359​
360it.effect("surfaces the agent error message when authenticate fails with AcpRequestError", () =>
361 Effect.gen(function* () {
362 const error = new AcpRequestError({
363 method: "authenticate",
364 code: -32000,
365 errorMessage: "Connect to the VPN, then sign in again.",
366 });
367 const h = yield* makeHarness(
368 browserMethod,
369 false,
370 decodeSettings({ agentId: "test-agent" }),
371 instanceId,
372 error,
373 );
374 yield* h.controller.start("owner", Effect.void, "browser");
375 const failed = yield* h.phase("failed");
376 assert.strictEqual(
377 failed.message,
378 "The ACP agent could not complete sign-in. Connect to the VPN, then sign in again.",
379 );
380 assert.deepEqual(h.changed, []);
381 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
382);
383​
384it.effect(
385 "surfaces the agent error message when post-sign-in verification fails for agent auth",
386 () =>
387 Effect.gen(function* () {
388 const h = yield* makeHarness(browserMethod, true);
389 const flow = yield* h.controller.start("owner", Effect.void, "browser");
390 yield* h.phase("waiting");
391 yield* h.controller.respond!("owner", {
392 instanceId,
393 flowId: flow.flowId!,
394 interactionId: "consent",
395 response: { type: "browser", action: "accept" },
396 });
397 yield* h.phase("verifying");
398 yield* Deferred.succeed(h.verify, undefined);
399 const failed = yield* h.phase("failed");
400 assert.strictEqual(
401 failed.message,
402 "The provider could not create a session after sign-in. Authentication required",
403 );
404 assert.deepEqual(h.changed, []);
405 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
406);
407​
408it("formatFailureDetail handles all cause types and formatting edge cases cleanly", () => {
409 const baseWithPeriod = "The ACP agent could not complete sign-in.";
410 const baseWithoutPeriod = "The ACP agent could not complete sign-in";
411​
412 // 1. undefined or null cause
413 assert.strictEqual(formatFailureDetail(baseWithPeriod, undefined), baseWithPeriod);
414 assert.strictEqual(formatFailureDetail(baseWithPeriod, null), baseWithPeriod);
415​
416 // 2. plain Error object, string, number, or object defect
417 assert.strictEqual(
418 formatFailureDetail(baseWithPeriod, new Error("Something broke")),
419 baseWithPeriod,
420 );
421 assert.strictEqual(formatFailureDetail(baseWithPeriod, "string error"), baseWithPeriod);
422 assert.strictEqual(formatFailureDetail(baseWithPeriod, { foo: "bar" }), baseWithPeriod);
423​
424 // 3. AcpRequestError with empty or whitespace-only errorMessage
425 const emptyError = new AcpRequestError({
426 method: "authenticate",
427 code: -32000,
428 errorMessage: "",
429 });
430 const whitespaceError = new AcpRequestError({
431 method: "authenticate",
432 code: -32000,
433 errorMessage: " \t\n ",
434 });
435 assert.strictEqual(formatFailureDetail(baseWithPeriod, emptyError), baseWithPeriod);
436 assert.strictEqual(formatFailureDetail(baseWithPeriod, whitespaceError), baseWithPeriod);
437​
438 // 4. AcpRequestError with valid message: ensure no double periods, clean separation
439 const validError = new AcpRequestError({
440 method: "authenticate",
441 code: -32000,
442 errorMessage: "Connect to the VPN, then sign in again.",
443 });
444 assert.strictEqual(
445 formatFailureDetail(baseWithPeriod, validError),
446 "The ACP agent could not complete sign-in. Connect to the VPN, then sign in again.",
447 );
448 assert.strictEqual(
449 formatFailureDetail(baseWithoutPeriod, validError),
450 "The ACP agent could not complete sign-in. Connect to the VPN, then sign in again.",
451 );
452​
453 // 5. AcpRequestError with trimmed message and message without ending period
454 const unpunctError = new AcpRequestError({
455 method: "authenticate",
456 code: -32000,
457 errorMessage: " Invalid credentials ",
458 });
459 assert.strictEqual(
460 formatFailureDetail(baseWithPeriod, unpunctError),
461 "The ACP agent could not complete sign-in. Invalid credentials",
462 );
463​
464 // 6. Nested Cause (e.g. Cause.fail or Cause.die wrapping AcpRequestError)
465 assert.strictEqual(
466 formatFailureDetail(baseWithPeriod, Cause.fail(validError)),
467 "The ACP agent could not complete sign-in. Connect to the VPN, then sign in again.",
468 );
469 assert.strictEqual(
470 formatFailureDetail(baseWithPeriod, Cause.die(validError)),
471 "The ACP agent could not complete sign-in. Connect to the VPN, then sign in again.",
472 );
473​
474 // 7. Extremely long error message: truncates to 500 characters with ellipsis
475 const longText = "A".repeat(600);
476 const longError = new AcpRequestError({
477 method: "authenticate",
478 code: -32000,
479 errorMessage: longText,
480 });
481 const expectedLong = `The ACP agent could not complete sign-in. ${"A".repeat(500)}…`;
482 assert.strictEqual(formatFailureDetail(baseWithPeriod, longError), expectedLong);
483});