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