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 AuthPreviewOperateScope,
12 AuthSettingsWriteScope,
13 AuthSourceControlWriteScope,
14 ThreadId,
15 EnvironmentId,
16 ScheduledTaskId,
17 WS_METHODS,
18 type AuthSessionState,
19} from "@t3tools/contracts";
20import * as Cause from "effect/Cause";
21import * as Effect from "effect/Effect";
22import * as Fiber from "effect/Fiber";
23import * as Layer from "effect/Layer";
24import * as TestClock from "effect/testing/TestClock";
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("requires the destination settings grant to check OTLP endpoints", () =>
119 Effect.scoped(
120 Effect.gen(function* () {
121 const registry = yield* setup;
122 const check = createCommandPermissions(runtime, WS_METHODS.serverCheckOtlpEndpoint);
123 registry.set(sessions(env), AsyncResult.success(grant(true)));
124 expect(registry.get(check.permissionAtom(env))).toBe(false);
125 registry.set(
126 sessions(env),
127 AsyncResult.success({
128 ...grant(false),
129 scopes: [AuthSettingsWriteScope],
130 permissions: [AuthSettingsWriteScope],
131 }),
132 );
133 expect(registry.get(check.permissionAtom(env))).toBe(true);
134 yield* check.authorize(registry, env);
135 }),
136 ),
137 );
138
139 it.effect("uses the target grant for both availability and execution", () =>
140 Effect.scoped(
141 Effect.gen(function* () {
142 const registry = yield* setup;
143 registry.set(sessions(env), AsyncResult.success(grant(true)));
144 expect(registry.get(permissions.permissionAtom(env))).toBe(true);
145 expect(permissions.permissionAtom(env)).toBe(permissions.permissionAtom(env));
146 yield* permissions.authorize(registry, env);
147 registry.set(sessions(other), AsyncResult.success(grant(false)));
148 expect(registry.get(permissions.permissionAtom(other))).toBe(false);
149 const denied = yield* permissions.authorize(registry, other).pipe(Effect.flip);
150 expect(denied._tag).toBe("EnvironmentAuthorizationError");
151 }),
152 ),
153 );
154 it.effect("waits for an initial grant", () =>
155 Effect.scoped(
156 Effect.gen(function* () {
157 const registry = yield* setup;
158 const fiber = yield* permissions.authorize(registry, env).pipe(Effect.forkChild);
159 yield* Effect.yieldNow;
160 registry.set(sessions(env), AsyncResult.success(grant(true)));
161 yield* Fiber.join(fiber);
162 }),
163 ),
164 );
165 it.effect("bounds a session that never loads", () =>
166 Effect.scoped(
167 Effect.gen(function* () {
168 const registry = yield* setup;
169 const fiber = yield* permissions
170 .authorize(registry, env)
171 .pipe(Effect.flip, Effect.forkChild);
172 yield* TestClock.adjust("6 seconds");
173 expect((yield* Fiber.join(fiber))._tag).toBe("EnvironmentAuthorizationError");
174 }),
175 ),
176 );
177 it.effect(
178 "denies failed and unauthenticated sessions, but accepts a cached refreshing grant",
179 () =>
180 Effect.scoped(
181 Effect.gen(function* () {
182 const registry = yield* setup;
183 registry.set(sessions(env), AsyncResult.failure(Cause.fail("offline")));
184 expect((yield* permissions.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
185 "EnvironmentAuthorizationError",
186 );
187 registry.set(
188 sessions(env),
189 AsyncResult.success({ ...grant(true), authenticated: false }),
190 );
191 expect((yield* permissions.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
192 "EnvironmentAuthorizationError",
193 );
194 registry.set(sessions(env), AsyncResult.waiting(AsyncResult.success(grant(true))));
195 yield* permissions.authorize(registry, env);
196 }),
197 ),
198 );
199 it("rechecks permission after waiting in a serial command lane", async () => {
200 const registry = AtomRegistry.make();
201 const unmount = registry.mount(sessions(env));
202 registry.set(sessions(env), AsyncResult.success(grant(true)));
203 let release!: () => void;
204 let started!: () => void;
205 const entered = new Promise<void>((resolve) => {
206 started = resolve;
207 });
208 const gate = new Promise<void>((resolve) => {
209 release = resolve;
210 });
211 let calls = 0;
212 const command = createEnvironmentRpcCommand(runtime, {
213 label: "test.delete",
214 tag: WS_METHODS.scheduledTasksDelete,
215 concurrency: { mode: "serial", key: () => "target" },
216 execute: () =>
217 Effect.promise(async () => {
218 calls++;
219 started();
220 await gate;
221 return { id: ScheduledTaskId.make("task") };
222 }),
223 });
224 const target = { environmentId: env, input: { id: ScheduledTaskId.make("task") } };
225 try {
226 const first = command.run(registry, target);
227 await entered;
228 const second = command.run(registry, target);
229 registry.set(sessions(env), AsyncResult.success(grant(false)));
230 release();
231 expect((await first)._tag).toBe("Success");
232 expect((await second)._tag).toBe("Failure");
233 expect(calls).toBe(1);
234 } finally {
235 unmount();
236 registry.dispose();
237 }
238 });
239});
240
241it.effect(
242 "requires source control alone for git, and both grants when attaching a worktree to a thread",
243 () =>
244 Effect.scoped(
245 Effect.gen(function* () {
246 const registry = yield* setup;
247 registry.set(sessions(env), AsyncResult.success(grant(true)));
248 const git = createCommandPermissions(runtime, WS_METHODS.vcsInit);
249 expect((yield* git.authorize(registry, env).pipe(Effect.flip)).requiredPermission).toBe(
250 AuthSourceControlWriteScope,
251 );
252 registry.set(
253 sessions(env),
254 AsyncResult.success({
255 ...grant(false),
256 scopes: [AuthSourceControlWriteScope],
257 permissions: [AuthSourceControlWriteScope],
258 }),
259 );
260 yield* git.authorize(registry, env);
261 const prepare = createCommandPermissions(runtime, WS_METHODS.gitPreparePullRequestThread);
262 const input = {
263 cwd: "/repo",
264 reference: "123",
265 mode: "worktree",
266 threadId: ThreadId.make("thread"),
267 };
268 expect(registry.get(prepare.permissionAtom(env, input))).toBe(false);
269 expect(
270 (yield* prepare.authorize(registry, env, input).pipe(Effect.flip)).requiredScope,
271 ).toBe(AuthOrchestrationOperateScope);
272 yield* prepare.authorize(registry, env, { ...input, threadId: undefined });
273 registry.set(
274 sessions(env),
275 AsyncResult.success({
276 ...grant(true),
277 scopes: [AuthSourceControlWriteScope, AuthOrchestrationOperateScope],
278 permissions: [AuthSourceControlWriteScope, AuthOrchestrationOperateScope],
279 }),
280 );
281 expect(registry.get(prepare.permissionAtom(env, input))).toBe(true);
282 yield* prepare.authorize(registry, env, input);
283 }),
284 ),
285);
286
287it.effect("honors exact empty permissions and preserves legacy parent grants", () =>
288 Effect.scoped(
289 Effect.gen(function* () {
290 const registry = yield* setup;
291 const git = createCommandPermissions(runtime, WS_METHODS.vcsInit);
292 registry.set(sessions(env), AsyncResult.success({ ...grant(true), permissions: [] }));
293 expect(registry.get(git.permissionAtom(env))).toBe(false);
294 const denied = yield* git.authorize(registry, env).pipe(Effect.flip);
295 expect(denied).toMatchObject({
296 requiredPermission: AuthSourceControlWriteScope,
297 requiredScope: AuthOrchestrationOperateScope,
298 });
299 const { permissions: _exact, ...legacy } = grant(true);
300 registry.set(sessions(env), AsyncResult.success(legacy));
301 expect(registry.get(git.permissionAtom(env))).toBe(true);
302 yield* git.authorize(registry, env);
303 }),
304 ),
305);
306
307it.effect("rejects protected unary and streamed RPCs outside a guarded command", () =>
308 Effect.gen(function* () {
309 let writes = 0;
310 const session = {
311 client: {
312 [WS_METHODS.scheduledTasksDelete]: () =>
313 Effect.sync(() => {
314 writes++;
315 return { id: ScheduledTaskId.make("task") };
316 }),
317 [WS_METHODS.gitRunStackedAction]: () =>
318 Stream.fromEffect(
319 Effect.sync(() => {
320 writes++;
321 }),
322 ),
323 },
324 } as unknown as RpcSession;
325 const supervisor = {
326 target: { environmentId: env, label: "target" },
327 session: yield* SubscriptionRef.make(Option.some(session)),
328 } as unknown as EnvironmentSupervisor["Service"];
329 const unary = yield* requestGuarded(WS_METHODS.scheduledTasksDelete, {
330 id: ScheduledTaskId.make("task"),
331 }).pipe(Effect.provideService(EnvironmentSupervisor, supervisor), Effect.flip);
332 expect(unary._tag).toBe("EnvironmentAuthorizationError");
333 const streamed = yield* runStreamGuarded(WS_METHODS.gitRunStackedAction, {
334 actionId: "test-action",
335 cwd: "/repo",
336 action: "commit",
337 }).pipe(Stream.runDrain, Effect.provideService(EnvironmentSupervisor, supervisor), Effect.flip);
338 expect(streamed._tag).toBe("EnvironmentAuthorizationError");
339 expect(writes).toBe(0);
340 }),
341);