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 AuthOrchestrationOperateScope,
11 AuthOrchestrationReadScope,
12 AuthPreviewOperateScope,
13 AuthSettingsWriteScope,
14 AuthSourceControlWriteScope,
15 ThreadId,
16 EnvironmentId,
17 ScheduledTaskId,
18 WS_METHODS,
19 type AuthSessionState,
20} from "@t3tools/contracts";
21import * as Cause from "effect/Cause";
22import * as Effect from "effect/Effect";
23import * as Fiber from "effect/Fiber";
24import * as Layer from "effect/Layer";
25import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity";
26import { EnvironmentRegistry } from "../connection/registry.ts";
27import { createCommandPermissions } from "./commandPermissions.ts";
28import { createEnvironmentRpcCommand } from "./runtime.ts";
29
30vi.mock("./session.ts", () => ({
31 createEnvironmentSessionAtoms: () => ({ sessionStateAtom: sessions }),
32}));
33const sessions = Atom.family((_id: EnvironmentId) =>
34 Atom.make<AsyncResult.AsyncResult<AuthSessionState, string>>(AsyncResult.initial()),
35);
36const env = EnvironmentId.make("target");
37const other = EnvironmentId.make("other");
38const grant = (allowed: boolean): AuthSessionState => ({
39 authenticated: true,
40 auth: {
41 policy: "remote-reachable",
42 bootstrapMethods: [],
43 sessionMethods: [],
44 sessionCookieName: "test",
45 },
46 scopes: allowed ? [AuthOrchestrationOperateScope] : [],
47 permissions: allowed ? [AuthOrchestrationOperateScope] : [],
48});
49const runtime = Atom.runtime(
50 Layer.succeed(EnvironmentRegistry, {
51 run: (_id: EnvironmentId, effect: Effect.Effect<unknown>) => effect,
52 } as unknown as EnvironmentRegistry["Service"]),
53);
54const permissions = createCommandPermissions(runtime, WS_METHODS.scheduledTasksDelete);
55const setup = Effect.gen(function* () {
56 const registry = AtomRegistry.make();
57 registry.mount(sessions(env));
58 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
59 return registry;
60});
61
62describe("command permissions", () => {
63 it.effect("requires the destination preview grant to close a browser tab", () =>
64 Effect.scoped(
65 Effect.gen(function* () {
66 const registry = yield* setup;
67 const close = createCommandPermissions(runtime, WS_METHODS.previewClose);
68 registry.set(sessions(env), AsyncResult.success(grant(true)));
69 expect(registry.get(close.permissionAtom(env))).toBe(false);
70 expect((yield* close.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
71 "EnvironmentAuthorizationError",
72 );
73 registry.set(
74 sessions(env),
75 AsyncResult.success({
76 ...grant(false),
77 scopes: [AuthPreviewOperateScope],
78 permissions: [AuthPreviewOperateScope],
79 }),
80 );
81 expect(registry.get(close.permissionAtom(env))).toBe(true);
82 yield* close.authorize(registry, env);
83 registry.set(sessions(other), AsyncResult.success(grant(false)));
84 expect(registry.get(close.permissionAtom(other))).toBe(false);
85 expect((yield* close.authorize(registry, other).pipe(Effect.flip))._tag).toBe(
86 "EnvironmentAuthorizationError",
87 );
88 }),
89 ),
90 );
91
92 it.effect("requires the destination settings grant to run storage cleanup", () =>
93 Effect.scoped(
94 Effect.gen(function* () {
95 const registry = yield* setup;
96 const cleanup = createCommandPermissions(runtime, WS_METHODS.serverRunStorageCleanup);
97 registry.set(sessions(env), AsyncResult.success(grant(true)));
98 expect(registry.get(cleanup.permissionAtom(env))).toBe(false);
99 expect((yield* cleanup.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
100 "EnvironmentAuthorizationError",
101 );
102 registry.set(
103 sessions(env),
104 AsyncResult.success({
105 ...grant(true),
106 scopes: [AuthSettingsWriteScope],
107 permissions: [AuthSettingsWriteScope],
108 }),
109 );
110 expect(registry.get(cleanup.permissionAtom(env))).toBe(true);
111 yield* cleanup.authorize(registry, env);
112 registry.set(sessions(other), AsyncResult.success(grant(false)));
113 expect(registry.get(cleanup.permissionAtom(other))).toBe(false);
114 }),
115 ),
116 );
117
118 it.effect("uses the target grant for both availability and execution", () =>
119 Effect.scoped(
120 Effect.gen(function* () {
121 const registry = yield* setup;
122 registry.set(sessions(env), AsyncResult.success(grant(true)));
123 expect(registry.get(permissions.permissionAtom(env))).toBe(true);
124 expect(permissions.permissionAtom(env)).toBe(permissions.permissionAtom(env));
125 yield* permissions.authorize(registry, env);
126 registry.set(sessions(other), AsyncResult.success(grant(false)));
127 expect(registry.get(permissions.permissionAtom(other))).toBe(false);
128 const denied = yield* permissions.authorize(registry, other).pipe(Effect.flip);
129 expect(denied._tag).toBe("EnvironmentAuthorizationError");
130 }),
131 ),
132 );
133 it.effect("waits for an initial grant", () =>
134 Effect.scoped(
135 Effect.gen(function* () {
136 const registry = yield* setup;
137 const fiber = yield* permissions.authorize(registry, env).pipe(Effect.forkChild);
138 yield* Effect.yieldNow;
139 registry.set(sessions(env), AsyncResult.success(grant(true)));
140 yield* Fiber.join(fiber);
141 }),
142 ),
143 );
144 it.effect(
145 "denies failed and unauthenticated sessions, but accepts a cached refreshing grant",
146 () =>
147 Effect.scoped(
148 Effect.gen(function* () {
149 const registry = yield* setup;
150 registry.set(sessions(env), AsyncResult.failure(Cause.fail("offline")));
151 expect((yield* permissions.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
152 "EnvironmentAuthorizationError",
153 );
154 registry.set(
155 sessions(env),
156 AsyncResult.success({ ...grant(true), authenticated: false }),
157 );
158 expect((yield* permissions.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
159 "EnvironmentAuthorizationError",
160 );
161 registry.set(sessions(env), AsyncResult.waiting(AsyncResult.success(grant(true))));
162 yield* permissions.authorize(registry, env);
163 }),
164 ),
165 );
166 it("rechecks permission after waiting in a serial command lane", async () => {
167 const registry = AtomRegistry.make();
168 const unmount = registry.mount(sessions(env));
169 registry.set(sessions(env), AsyncResult.success(grant(true)));
170 let release!: () => void;
171 let started!: () => void;
172 const entered = new Promise<void>((resolve) => {
173 started = resolve;
174 });
175 const gate = new Promise<void>((resolve) => {
176 release = resolve;
177 });
178 let calls = 0;
179 const command = createEnvironmentRpcCommand(runtime, {
180 label: "test.delete",
181 tag: WS_METHODS.scheduledTasksDelete,
182 concurrency: { mode: "serial", key: () => "target" },
183 execute: () =>
184 Effect.promise(async () => {
185 calls++;
186 started();
187 await gate;
188 return { id: ScheduledTaskId.make("task") };
189 }),
190 });
191 const target = { environmentId: env, input: { id: ScheduledTaskId.make("task") } };
192 try {
193 const first = command.run(registry, target);
194 await entered;
195 const second = command.run(registry, target);
196 registry.set(sessions(env), AsyncResult.success(grant(false)));
197 release();
198 expect((await first)._tag).toBe("Success");
199 expect((await second)._tag).toBe("Failure");
200 expect(calls).toBe(1);
201 } finally {
202 unmount();
203 registry.dispose();
204 }
205 });
206});
207
208it.effect(
209 "requires source control alone for git, and both grants when attaching a worktree to a thread",
210 () =>
211 Effect.scoped(
212 Effect.gen(function* () {
213 const registry = yield* setup;
214 registry.set(sessions(env), AsyncResult.success(grant(true)));
215 const git = createCommandPermissions(runtime, WS_METHODS.vcsInit);
216 expect((yield* git.authorize(registry, env).pipe(Effect.flip)).requiredPermission).toBe(
217 AuthSourceControlWriteScope,
218 );
219 registry.set(
220 sessions(env),
221 AsyncResult.success({
222 ...grant(false),
223 scopes: [AuthSourceControlWriteScope],
224 permissions: [AuthSourceControlWriteScope],
225 }),
226 );
227 yield* git.authorize(registry, env);
228 const prepare = createCommandPermissions(runtime, WS_METHODS.gitPreparePullRequestThread);
229 const input = {
230 cwd: "/repo",
231 reference: "123",
232 mode: "worktree",
233 threadId: ThreadId.make("thread"),
234 };
235 expect(registry.get(prepare.permissionAtom(env, input))).toBe(false);
236 expect(
237 (yield* prepare.authorize(registry, env, input).pipe(Effect.flip)).requiredScope,
238 ).toBe(AuthOrchestrationOperateScope);
239 yield* prepare.authorize(registry, env, { ...input, threadId: undefined });
240 registry.set(
241 sessions(env),
242 AsyncResult.success({
243 ...grant(true),
244 scopes: [AuthSourceControlWriteScope, AuthOrchestrationOperateScope],
245 permissions: [AuthSourceControlWriteScope, AuthOrchestrationOperateScope],
246 }),
247 );
248 expect(registry.get(prepare.permissionAtom(env, input))).toBe(true);
249 yield* prepare.authorize(registry, env, input);
250 }),
251 ),
252);
253
254it.effect.each(["commit", "push", "commit_push", "create_pr", "commit_push_pr"] as const)(
255 "%s needs thread read permission only when generating a PR from a thread",
256 (action) =>
257 Effect.scoped(
258 Effect.gen(function* () {
259 const registry = yield* setup;
260 const command = createCommandPermissions(runtime, WS_METHODS.gitRunStackedAction);
261 const input = { actionId: "action", cwd: "/repo", action };
262 const withThread = { ...input, threadId: ThreadId.make("thread") };
263 const session = {
264 ...grant(false),
265 scopes: [AuthSourceControlWriteScope],
266 permissions: [AuthSourceControlWriteScope],
267 };
268 registry.set(sessions(env), AsyncResult.success(session));
269 expect(registry.get(command.permissionAtom(env, input))).toBe(true);
270 yield* command.authorize(registry, env, input);
271 const readsThread = action === "create_pr" || action === "commit_push_pr";
272 expect(registry.get(command.permissionAtom(env, withThread))).toBe(!readsThread);
273 if (readsThread) {
274 expect(
275 yield* command.authorize(registry, env, withThread).pipe(Effect.flip),
276 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
277 } else {
278 yield* command.authorize(registry, env, withThread);
279 }
280 registry.set(
281 sessions(env),
282 AsyncResult.success({
283 ...session,
284 scopes: [AuthSourceControlWriteScope, AuthOrchestrationReadScope],
285 permissions: [AuthSourceControlWriteScope, AuthOrchestrationReadScope],
286 }),
287 );
288 expect(registry.get(command.permissionAtom(env, withThread))).toBe(true);
289 yield* command.authorize(registry, env, withThread);
290 }),
291 ),
292);
293
294it.effect("honors exact empty permissions and preserves legacy parent grants", () =>
295 Effect.scoped(
296 Effect.gen(function* () {
297 const registry = yield* setup;
298 const git = createCommandPermissions(runtime, WS_METHODS.vcsInit);
299 registry.set(sessions(env), AsyncResult.success({ ...grant(true), permissions: [] }));
300 expect(registry.get(git.permissionAtom(env))).toBe(false);
301 const denied = yield* git.authorize(registry, env).pipe(Effect.flip);
302 expect(denied).toMatchObject({
303 requiredPermission: AuthSourceControlWriteScope,
304 requiredScope: AuthOrchestrationOperateScope,
305 });
306 const { permissions: _exact, ...legacy } = grant(true);
307 registry.set(sessions(env), AsyncResult.success(legacy));
308 expect(registry.get(git.permissionAtom(env))).toBe(true);
309 yield* git.authorize(registry, env);
310 }),
311 ),
312);
313
314it.effect("rejects protected unary and streamed RPCs outside a guarded command", () =>
315 Effect.gen(function* () {
316 let writes = 0;
317 const session = {
318 client: {
319 [WS_METHODS.scheduledTasksDelete]: () =>
320 Effect.sync(() => {
321 writes++;
322 return { id: ScheduledTaskId.make("task") };
323 }),
324 [WS_METHODS.gitRunStackedAction]: () =>
325 Stream.fromEffect(
326 Effect.sync(() => {
327 writes++;
328 }),
329 ),
330 },
331 } as unknown as RpcSession;
332 const supervisor = {
333 target: { environmentId: env, label: "target" },
334 session: yield* SubscriptionRef.make(Option.some(session)),
335 } as unknown as EnvironmentSupervisor["Service"];
336 const unary = yield* requestGuarded(WS_METHODS.scheduledTasksDelete, {
337 id: ScheduledTaskId.make("task"),
338 }).pipe(Effect.provideService(EnvironmentSupervisor, supervisor), Effect.flip);
339 expect(unary._tag).toBe("EnvironmentAuthorizationError");
340 const streamed = yield* runStreamGuarded(WS_METHODS.gitRunStackedAction, {
341 actionId: "test-action",
342 cwd: "/repo",
343 action: "commit",
344 }).pipe(Stream.runDrain, Effect.provideService(EnvironmentSupervisor, supervisor), Effect.flip);
345 expect(streamed._tag).toBe("EnvironmentAuthorizationError");
346 expect(writes).toBe(0);
347 }),
348);