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

commandPermissions.test.ts

529 lines20.7 KB

1import { requestGuarded, runStreamGuarded } from "../rpc/client.ts";
2import { EnvironmentSupervisor } from "../connection/supervisor.ts";
3import * as SubscriptionRef from "effect/SubscriptionRef";
4import * as Option from "effect/Option";
5import * as Stream from "effect/Stream";
6import type { RpcSession } from "../rpc/session.ts";
7import { describe, expect, it } from "@effect/vitest";
8import { vi } from "vite-plus/test";
9import {
10 AuthAccessReadScope,
11 AuthAccessWriteScope,
12 AuthOrchestrationOperateScope,
13 AuthOrchestrationReadScope,
14 AuthPreviewOperateScope,
15 AuthSettingsWriteScope,
16 AuthSourceControlWriteScope,
17 ThreadId,
18 EnvironmentId,
19 ORCHESTRATION_V2_WS_METHODS,
20 ScheduledTaskId,
21 WS_METHODS,
22 type AuthSessionState,
23 type PeerLinkSummary,
24} from "@t3tools/contracts";
25import * as Cause from "effect/Cause";
26import * as DateTime from "effect/DateTime";
27import * as Effect from "effect/Effect";
28import * as Fiber from "effect/Fiber";
29import * as Layer from "effect/Layer";
30import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity";
31import { EnvironmentRegistry } from "../connection/registry.ts";
32import { createCommandPermissions } from "./commandPermissions.ts";
33import { createEnvironmentRpcCommand } from "./runtime.ts";
34import { AVAILABLE_CONNECTION_STATE } from "../connection/model.ts";
35import { createPeerLinkEnvironmentAtoms } from "./peerLinks.ts";
36​
37vi.mock("./session.ts", () => ({
38 createEnvironmentSessionAtoms: () => ({ sessionStateAtom: sessions }),
39}));
40const sessions = Atom.family((_id: EnvironmentId) =>
41 Atom.make<AsyncResult.AsyncResult<AuthSessionState, string>>(AsyncResult.initial()),
42);
43const env = EnvironmentId.make("target");
44const other = EnvironmentId.make("other");
45const grant = (allowed: boolean): AuthSessionState => ({
46 authenticated: true,
47 auth: {
48 policy: "remote-reachable",
49 bootstrapMethods: [],
50 sessionMethods: [],
51 sessionCookieName: "test",
52 },
53 scopes: allowed ? [AuthOrchestrationOperateScope] : [],
54 permissions: allowed ? [AuthOrchestrationOperateScope] : [],
55});
56const runtime = Atom.runtime(
57 Layer.succeed(EnvironmentRegistry, {
58 run: (_id: EnvironmentId, effect: Effect.Effect<unknown>) => effect,
59 } as unknown as EnvironmentRegistry["Service"]),
60);
61const permissions = createCommandPermissions(runtime, WS_METHODS.scheduledTasksDelete);
62const setup = Effect.gen(function* () {
63 const registry = AtomRegistry.make();
64 registry.mount(sessions(env));
65 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
66 return registry;
67});
68​
69describe("command permissions", () => {
70 it.effect("requires the destination preview grant to close a browser tab", () =>
71 Effect.scoped(
72 Effect.gen(function* () {
73 const registry = yield* setup;
74 const close = createCommandPermissions(runtime, WS_METHODS.previewClose);
75 registry.set(sessions(env), AsyncResult.success(grant(true)));
76 expect(registry.get(close.permissionAtom(env))).toBe(false);
77 expect((yield* close.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
78 "EnvironmentAuthorizationError",
79 );
80 registry.set(
81 sessions(env),
82 AsyncResult.success({
83 ...grant(false),
84 scopes: [AuthPreviewOperateScope],
85 permissions: [AuthPreviewOperateScope],
86 }),
87 );
88 expect(registry.get(close.permissionAtom(env))).toBe(true);
89 yield* close.authorize(registry, env);
90 registry.set(sessions(other), AsyncResult.success(grant(false)));
91 expect(registry.get(close.permissionAtom(other))).toBe(false);
92 expect((yield* close.authorize(registry, other).pipe(Effect.flip))._tag).toBe(
93 "EnvironmentAuthorizationError",
94 );
95 }),
96 ),
97 );
98​
99 it.effect("requires the destination settings grant to run storage cleanup", () =>
100 Effect.scoped(
101 Effect.gen(function* () {
102 const registry = yield* setup;
103 const cleanup = createCommandPermissions(runtime, WS_METHODS.serverRunStorageCleanup);
104 registry.set(sessions(env), AsyncResult.success(grant(true)));
105 expect(registry.get(cleanup.permissionAtom(env))).toBe(false);
106 expect((yield* cleanup.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
107 "EnvironmentAuthorizationError",
108 );
109 registry.set(
110 sessions(env),
111 AsyncResult.success({
112 ...grant(true),
113 scopes: [AuthSettingsWriteScope],
114 permissions: [AuthSettingsWriteScope],
115 }),
116 );
117 expect(registry.get(cleanup.permissionAtom(env))).toBe(true);
118 yield* cleanup.authorize(registry, env);
119 registry.set(sessions(other), AsyncResult.success(grant(false)));
120 expect(registry.get(cleanup.permissionAtom(other))).toBe(false);
121 }),
122 ),
123 );
124​
125 it.effect("requires the destination settings grant to check OTLP endpoints", () =>
126 Effect.scoped(
127 Effect.gen(function* () {
128 const registry = yield* setup;
129 const check = createCommandPermissions(runtime, WS_METHODS.serverCheckOtlpEndpoint);
130 registry.set(sessions(env), AsyncResult.success(grant(true)));
131 expect(registry.get(check.permissionAtom(env))).toBe(false);
132 registry.set(
133 sessions(env),
134 AsyncResult.success({
135 ...grant(false),
136 scopes: [AuthSettingsWriteScope],
137 permissions: [AuthSettingsWriteScope],
138 }),
139 );
140 expect(registry.get(check.permissionAtom(env))).toBe(true);
141 yield* check.authorize(registry, env);
142 }),
143 ),
144 );
145​
146 it.effect.each([WS_METHODS.scheduledTasksDelete, ORCHESTRATION_V2_WS_METHODS.stopWorkflow])(
147 "uses the target grant for both availability and execution of %s",
148 (method) =>
149 Effect.scoped(
150 Effect.gen(function* () {
151 const registry = yield* setup;
152 const permissions = createCommandPermissions(runtime, method);
153 registry.set(sessions(env), AsyncResult.success(grant(true)));
154 expect(registry.get(permissions.permissionAtom(env))).toBe(true);
155 expect(permissions.permissionAtom(env)).toBe(permissions.permissionAtom(env));
156 yield* permissions.authorize(registry, env);
157 registry.set(sessions(other), AsyncResult.success(grant(false)));
158 expect(registry.get(permissions.permissionAtom(other))).toBe(false);
159 const denied = yield* permissions.authorize(registry, other).pipe(Effect.flip);
160 expect(denied._tag).toBe("EnvironmentAuthorizationError");
161 }),
162 ),
163 );
164 it.effect("waits for an initial grant", () =>
165 Effect.scoped(
166 Effect.gen(function* () {
167 const registry = yield* setup;
168 const fiber = yield* permissions.authorize(registry, env).pipe(Effect.forkChild);
169 yield* Effect.yieldNow;
170 registry.set(sessions(env), AsyncResult.success(grant(true)));
171 yield* Fiber.join(fiber);
172 }),
173 ),
174 );
175 it.effect(
176 "denies failed and unauthenticated sessions, but accepts a cached refreshing grant",
177 () =>
178 Effect.scoped(
179 Effect.gen(function* () {
180 const registry = yield* setup;
181 registry.set(sessions(env), AsyncResult.failure(Cause.fail("offline")));
182 expect((yield* permissions.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
183 "EnvironmentAuthorizationError",
184 );
185 registry.set(
186 sessions(env),
187 AsyncResult.success({ ...grant(true), authenticated: false }),
188 );
189 expect((yield* permissions.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
190 "EnvironmentAuthorizationError",
191 );
192 registry.set(sessions(env), AsyncResult.waiting(AsyncResult.success(grant(true))));
193 yield* permissions.authorize(registry, env);
194 }),
195 ),
196 );
197 it("rechecks permission after waiting in a serial command lane", async () => {
198 const registry = AtomRegistry.make();
199 const unmount = registry.mount(sessions(env));
200 registry.set(sessions(env), AsyncResult.success(grant(true)));
201 let release!: () => void;
202 let started!: () => void;
203 const entered = new Promise<void>((resolve) => {
204 started = resolve;
205 });
206 const gate = new Promise<void>((resolve) => {
207 release = resolve;
208 });
209 let calls = 0;
210 const command = createEnvironmentRpcCommand(runtime, {
211 label: "test.delete",
212 tag: WS_METHODS.scheduledTasksDelete,
213 concurrency: { mode: "serial", key: () => "target" },
214 execute: () =>
215 Effect.promise(async () => {
216 calls++;
217 started();
218 await gate;
219 return { id: ScheduledTaskId.make("task") };
220 }),
221 });
222 const target = { environmentId: env, input: { id: ScheduledTaskId.make("task") } };
223 try {
224 const first = command.run(registry, target);
225 await entered;
226 const second = command.run(registry, target);
227 registry.set(sessions(env), AsyncResult.success(grant(false)));
228 release();
229 expect((await first)._tag).toBe("Success");
230 expect((await second)._tag).toBe("Failure");
231 expect(calls).toBe(1);
232 } finally {
233 unmount();
234 registry.dispose();
235 }
236 });
237});
238​
239it.effect(
240 "requires source control alone for git, and both grants when attaching a worktree to a thread",
241 () =>
242 Effect.scoped(
243 Effect.gen(function* () {
244 const registry = yield* setup;
245 registry.set(sessions(env), AsyncResult.success(grant(true)));
246 const git = createCommandPermissions(runtime, WS_METHODS.vcsInit);
247 expect((yield* git.authorize(registry, env).pipe(Effect.flip)).requiredPermission).toBe(
248 AuthSourceControlWriteScope,
249 );
250 registry.set(
251 sessions(env),
252 AsyncResult.success({
253 ...grant(false),
254 scopes: [AuthSourceControlWriteScope],
255 permissions: [AuthSourceControlWriteScope],
256 }),
257 );
258 yield* git.authorize(registry, env);
259 const prepare = createCommandPermissions(runtime, WS_METHODS.gitPreparePullRequestThread);
260 const input = {
261 cwd: "/repo",
262 reference: "123",
263 mode: "worktree",
264 threadId: ThreadId.make("thread"),
265 };
266 expect(registry.get(prepare.permissionAtom(env, input))).toBe(false);
267 expect(
268 (yield* prepare.authorize(registry, env, input).pipe(Effect.flip)).requiredScope,
269 ).toBe(AuthOrchestrationOperateScope);
270 yield* prepare.authorize(registry, env, { ...input, threadId: undefined });
271 registry.set(
272 sessions(env),
273 AsyncResult.success({
274 ...grant(true),
275 scopes: [AuthSourceControlWriteScope, AuthOrchestrationOperateScope],
276 permissions: [AuthSourceControlWriteScope, AuthOrchestrationOperateScope],
277 }),
278 );
279 expect(registry.get(prepare.permissionAtom(env, input))).toBe(true);
280 yield* prepare.authorize(registry, env, input);
281 }),
282 ),
283);
284​
285it.effect.each(["commit", "push", "commit_push", "create_pr", "commit_push_pr"] as const)(
286 "%s needs thread read permission only when generating a PR from a thread",
287 (action) =>
288 Effect.scoped(
289 Effect.gen(function* () {
290 const registry = yield* setup;
291 const command = createCommandPermissions(runtime, WS_METHODS.gitRunStackedAction);
292 const input = { actionId: "action", cwd: "/repo", action };
293 const withThread = { ...input, threadId: ThreadId.make("thread") };
294 const session = {
295 ...grant(false),
296 scopes: [AuthSourceControlWriteScope],
297 permissions: [AuthSourceControlWriteScope],
298 };
299 registry.set(sessions(env), AsyncResult.success(session));
300 expect(registry.get(command.permissionAtom(env, input))).toBe(true);
301 yield* command.authorize(registry, env, input);
302 const readsThread = action === "create_pr" || action === "commit_push_pr";
303 expect(registry.get(command.permissionAtom(env, withThread))).toBe(!readsThread);
304 if (readsThread) {
305 expect(
306 yield* command.authorize(registry, env, withThread).pipe(Effect.flip),
307 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
308 } else {
309 yield* command.authorize(registry, env, withThread);
310 }
311 registry.set(
312 sessions(env),
313 AsyncResult.success({
314 ...session,
315 scopes: [AuthSourceControlWriteScope, AuthOrchestrationReadScope],
316 permissions: [AuthSourceControlWriteScope, AuthOrchestrationReadScope],
317 }),
318 );
319 expect(registry.get(command.permissionAtom(env, withThread))).toBe(true);
320 yield* command.authorize(registry, env, withThread);
321 }),
322 ),
323);
324​
325it.effect(
326 "refreshes linked environments after permitted writes and blocks a read-only session",
327 () =>
328 Effect.scoped(
329 Effect.gen(function* () {
330 const registry = yield* setup;
331 const peer: PeerLinkSummary = {
332 environmentId: EnvironmentId.make("peer"),
333 label: "Box",
334 urls: ["https://box.example.test"],
335 access: "auto",
336 linkedAt: DateTime.makeUnsafe("2026-10-01T12:00:00Z"),
337 expiresAt: DateTime.makeUnsafe("2026-10-31T12:00:00Z"),
338 lastReachedAt: null,
339 lastError: null,
340 status: "reachable",
341 };
342 let links: ReadonlyArray<PeerLinkSummary> = [];
343 const client = {
344 [WS_METHODS.peerLinksList]: () => Effect.sync(() => ({ links })),
345 [WS_METHODS.peerLinksLink]: vi.fn(() =>
346 Effect.sync(() => {
347 links = [peer];
348 return peer;
349 }),
350 ),
351 [WS_METHODS.peerLinksUnlink]: vi.fn(() =>
352 Effect.sync(() => {
353 links = [];
354 return { removed: true };
355 }),
356 ),
357 };
358 const supervisor = {
359 target: { environmentId: env },
360 session: yield* SubscriptionRef.make(Option.some({ client } as unknown as RpcSession)),
361 state: yield* SubscriptionRef.make({
362 ...AVAILABLE_CONNECTION_STATE,
363 phase: "connected" as const,
364 }),
365 } as EnvironmentSupervisor["Service"];
366 const peerRuntime = Atom.runtime(
367 Layer.succeed(EnvironmentRegistry, {
368 run: (id, effect) => {
369 expect(id).toBe(env);
370 return Effect.provideService(effect, EnvironmentSupervisor, supervisor);
371 },
372 followStream: (id, stream) => {
373 expect(id).toBe(env);
374 return Stream.provideService(stream, EnvironmentSupervisor, supervisor);
375 },
376 } as EnvironmentRegistry["Service"]),
377 );
378 const peerLinks = createPeerLinkEnvironmentAtoms(peerRuntime);
379 const list = peerLinks.list({ environmentId: env, input: {} });
380 registry.mount(list);
381 const readLinks = AtomRegistry.getResult(registry, list, { suspendOnWaiting: true });
382 const setAccess = (writable: boolean) =>
383 registry.set(
384 sessions(env),
385 AsyncResult.success({
386 ...grant(false),
387 scopes: [AuthAccessReadScope, ...(writable ? [AuthAccessWriteScope] : [])],
388 permissions: [AuthAccessReadScope, ...(writable ? [AuthAccessWriteScope] : [])],
389 }),
390 );
391 registry.mount(sessions(other));
392 registry.set(
393 sessions(other),
394 AsyncResult.success({
395 ...grant(false),
396 scopes: [AuthAccessWriteScope],
397 permissions: [AuthAccessWriteScope],
398 }),
399 );
400 setAccess(false);
401 expect(yield* readLinks).toEqual({ links: [] });
402 const linkInput = { url: peer.urls[0]!, pairingCode: "test-code", access: peer.access };
403 const link = Effect.promise(() =>
404 peerLinks.link.run(registry, { environmentId: env, input: linkInput }),
405 );
406 const unlink = Effect.promise(() =>
407 peerLinks.unlink.run(registry, {
408 environmentId: env,
409 input: { environmentId: peer.environmentId },
410 }),
411 );
412 expect(registry.get(peerLinks.link.permissionAtom(env))).toBe(false);
413 const deniedLink = yield* link;
414 expect(deniedLink._tag).toBe("Failure");
415 if (deniedLink._tag === "Failure") {
416 expect(Cause.squash(deniedLink.cause)).toMatchObject({
417 _tag: "EnvironmentAuthorizationError",
418 requiredPermission: AuthAccessWriteScope,
419 });
420 }
421 expect(client[WS_METHODS.peerLinksLink]).not.toHaveBeenCalled();
422 setAccess(true);
423 expect(registry.get(peerLinks.link.permissionAtom(env))).toBe(true);
424 expect((yield* link)._tag).toBe("Success");
425 expect(client[WS_METHODS.peerLinksLink]).toHaveBeenCalledExactlyOnceWith(linkInput);
426 expect(yield* readLinks).toEqual({ links: [peer] });
427​
428 setAccess(false);
429 expect(registry.get(peerLinks.unlink.permissionAtom(env))).toBe(false);
430 const deniedUnlink = yield* unlink;
431 expect(deniedUnlink._tag).toBe("Failure");
432 if (deniedUnlink._tag === "Failure") {
433 expect(Cause.squash(deniedUnlink.cause)).toMatchObject({
434 _tag: "EnvironmentAuthorizationError",
435 requiredPermission: AuthAccessWriteScope,
436 });
437 }
438 expect(client[WS_METHODS.peerLinksUnlink]).not.toHaveBeenCalled();
439 expect(yield* readLinks).toEqual({ links: [peer] });
440 setAccess(true);
441 expect(registry.get(peerLinks.unlink.permissionAtom(env))).toBe(true);
442 expect((yield* unlink)._tag).toBe("Success");
443 expect(client[WS_METHODS.peerLinksUnlink]).toHaveBeenCalledExactlyOnceWith({
444 environmentId: peer.environmentId,
445 });
446 expect(yield* readLinks).toEqual({ links: [] });
447 }),
448 ),
449);
450​
451it.effect("requires access management to answer a link request", () =>
452 Effect.scoped(
453 Effect.gen(function* () {
454 const registry = yield* setup;
455 registry.set(sessions(env), AsyncResult.success(grant(true)));
456 const answer = createCommandPermissions(runtime, WS_METHODS.peerLinksAnswerRequest);
457 expect(registry.get(answer.permissionAtom(env))).toBe(false);
458 expect((yield* answer.authorize(registry, env).pipe(Effect.flip)).requiredPermission).toBe(
459 AuthAccessWriteScope,
460 );
461 registry.set(
462 sessions(env),
463 AsyncResult.success({
464 ...grant(false),
465 scopes: [AuthAccessWriteScope],
466 permissions: [AuthAccessWriteScope],
467 }),
468 );
469 expect(registry.get(answer.permissionAtom(env))).toBe(true);
470 yield* answer.authorize(registry, env);
471 }),
472 ),
473);
474​
475it.effect("honors exact empty permissions and preserves legacy parent grants", () =>
476 Effect.scoped(
477 Effect.gen(function* () {
478 const registry = yield* setup;
479 const git = createCommandPermissions(runtime, WS_METHODS.vcsInit);
480 registry.set(sessions(env), AsyncResult.success({ ...grant(true), permissions: [] }));
481 expect(registry.get(git.permissionAtom(env))).toBe(false);
482 const denied = yield* git.authorize(registry, env).pipe(Effect.flip);
483 expect(denied).toMatchObject({
484 requiredPermission: AuthSourceControlWriteScope,
485 requiredScope: AuthOrchestrationOperateScope,
486 });
487 const { permissions: _exact, ...legacy } = grant(true);
488 registry.set(sessions(env), AsyncResult.success(legacy));
489 expect(registry.get(git.permissionAtom(env))).toBe(true);
490 yield* git.authorize(registry, env);
491 }),
492 ),
493);
494​
495it.effect("rejects protected unary and streamed RPCs outside a guarded command", () =>
496 Effect.gen(function* () {
497 let writes = 0;
498 const session = {
499 client: {
500 [WS_METHODS.scheduledTasksDelete]: () =>
501 Effect.sync(() => {
502 writes++;
503 return { id: ScheduledTaskId.make("task") };
504 }),
505 [WS_METHODS.gitRunStackedAction]: () =>
506 Stream.fromEffect(
507 Effect.sync(() => {
508 writes++;
509 }),
510 ),
511 },
512 } as unknown as RpcSession;
513 const supervisor = {
514 target: { environmentId: env, label: "target" },
515 session: yield* SubscriptionRef.make(Option.some(session)),
516 } as unknown as EnvironmentSupervisor["Service"];
517 const unary = yield* requestGuarded(WS_METHODS.scheduledTasksDelete, {
518 id: ScheduledTaskId.make("task"),
519 }).pipe(Effect.provideService(EnvironmentSupervisor, supervisor), Effect.flip);
520 expect(unary._tag).toBe("EnvironmentAuthorizationError");
521 const streamed = yield* runStreamGuarded(WS_METHODS.gitRunStackedAction, {
522 actionId: "test-action",
523 cwd: "/repo",
524 action: "commit",
525 }).pipe(Stream.runDrain, Effect.provideService(EnvironmentSupervisor, supervisor), Effect.flip);
526 expect(streamed._tag).toBe("EnvironmentAuthorizationError");
527 expect(writes).toBe(0);
528 }),
529);