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