Open History to see the last commit
1import {
2 AuthEnvironmentMaintainScope,
3 AuthDiagnosticsReadScope,
4 AuthFilesystemReadScope,
5 AuthProvidersManageScope,
6 AuthSettingsWriteScope,
7 DEFAULT_SERVER_SETTINGS,
8 ProviderInstanceId,
9 ThreadId,
10 AuthOrchestrationOperateScope,
11 AuthOrchestrationReadScope,
12 AuthSourceControlWriteScope,
13 AuthTerminalReadScope,
14 AuthTerminalOperateScope,
15 WS_METHODS,
16 WsRpcGroup,
17} from "@t3tools/contracts";
18import { describe, expect, it } from "@effect/vitest";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Stream from "effect/Stream";
22import * as RpcTest from "effect/rpc/RpcTest";
23
24import {
25 RPC_REQUIRED_SCOPES,
26 requiredScopeForRpcMethod,
27 requiredScopeForDeviceList,
28} from "./RpcAuthorization.ts";
29import * as RpcAuthorization from "./RpcAuthorization.ts";
30
31describe("RPC authorization scopes", () => {
32 it("declares exactly one scope for every RPC in the server group", () => {
33 expect(new Set(Object.keys(RPC_REQUIRED_SCOPES))).toEqual(new Set(WsRpcGroup.requests.keys()));
34 });
35
36 it("keeps webhook delivery logs, which hold request bodies, behind operate scope", () => {
37 for (const method of [
38 WS_METHODS.scheduledTasksListWebhookDeliveries,
39 WS_METHODS.scheduledTasksGetWebhookDelivery,
40 WS_METHODS.scheduledTasksRotateWebhookToken,
41 ]) {
42 expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationOperateScope);
43 }
44 });
45
46 it("keeps triage, which seeds an agent that reads logs and the database, behind operate scope", () => {
47 expect(requiredScopeForRpcMethod(WS_METHODS.serverPrepareTriage)).toBe(
48 AuthOrchestrationOperateScope,
49 );
50 });
51
52 it("separates passive terminal observation from operations that can change a shell", () => {
53 for (const method of [WS_METHODS.terminalObserve, WS_METHODS.subscribeTerminalMetadata]) {
54 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalReadScope);
55 }
56 for (const method of [
57 WS_METHODS.terminalAttach,
58 WS_METHODS.terminalOpen,
59 WS_METHODS.terminalWrite,
60 WS_METHODS.terminalResize,
61 WS_METHODS.terminalClear,
62 WS_METHODS.terminalClose,
63 WS_METHODS.previewStopLocalServer,
64 ]) {
65 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalOperateScope);
66 }
67 });
68
69 it("rejects unknown RPC method names", () => {
70 for (const method of ["server.notRegistered", "toString", "constructor"]) {
71 expect(() => requiredScopeForRpcMethod(method)).toThrow(
72 `RPC method ${method} has no declared authorization scope.`,
73 );
74 }
75 });
76});
77
78it("requires operate permission for host retry while preserving read-only listing", () => {
79 expect(requiredScopeForDeviceList({})).toBe(AuthOrchestrationReadScope);
80 expect(requiredScopeForDeviceList({ retryHostId: "remote-host" })).toBe(
81 AuthOrchestrationOperateScope,
82 );
83});
84
85it("requires operate permission for tool updates even alongside a read-only check", () => {
86 expect(requiredScopeForDeviceList({ updateTool: "agent", inspectOnly: true })).toBe(
87 AuthOrchestrationOperateScope,
88 );
89 expect(requiredScopeForDeviceList({ updateTool: "hub" })).toBe(AuthOrchestrationOperateScope);
90});
91
92describe("RPC scope middleware", () => {
93 const tested = [WS_METHODS.serverProbe, WS_METHODS.serverRetryResourceTelemetry] as const;
94 const group = WsRpcGroup.omit(
95 ...[...WsRpcGroup.requests.keys()].filter(
96 (tag): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, (typeof tested)[number]> =>
97 !(tested as ReadonlyArray<string>).includes(tag),
98 ),
99 );
100
101 it.effect.each([
102 { scopes: [AuthOrchestrationReadScope], missing: AuthEnvironmentMaintainScope },
103 {
104 scopes: [AuthOrchestrationReadScope, AuthEnvironmentMaintainScope],
105 missing: AuthDiagnosticsReadScope,
106 },
107 ])("rejects telemetry retry without $missing before its handler runs", ({ scopes, missing }) =>
108 Effect.gen(function* () {
109 const handled: Array<string> = [];
110 const client = yield* RpcTest.makeClient(group).pipe(
111 Effect.provide(
112 Layer.mergeAll(
113 group.toLayerHandler(WS_METHODS.serverProbe, () => Effect.succeed({})),
114 group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () =>
115 Effect.sync(() => handled.push("retry")).pipe(Effect.andThen(Effect.never)),
116 ),
117 RpcAuthorization.layer(scopes),
118 ),
119 ),
120 );
121
122 expect(yield* client[WS_METHODS.serverProbe]({})).toEqual({});
123 expect(
124 yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(Effect.flip),
125 ).toMatchObject({
126 _tag: "EnvironmentAuthorizationError",
127 requiredPermission: missing,
128 });
129 expect(handled).toEqual([]);
130 }).pipe(Effect.scoped),
131 );
132});
133
134describe("settings mutation authorization", () => {
135 const group = WsRpcGroup.omit(
136 ...[...WsRpcGroup.requests.keys()].filter(
137 (
138 tag,
139 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.serverUpdateSettings> =>
140 tag !== WS_METHODS.serverUpdateSettings,
141 ),
142 );
143 const providerInstanceMutation = {
144 operation: "remove" as const,
145 instanceId: ProviderInstanceId.make("codex_work"),
146 };
147
148 it.effect("allows provider-only mutations while denying mixed settings without their grant", () =>
149 Effect.gen(function* () {
150 let handled = 0;
151 const client = yield* RpcTest.makeClient(group).pipe(
152 Effect.provide(
153 Layer.mergeAll(
154 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
155 Effect.sync(() => {
156 handled++;
157 return DEFAULT_SERVER_SETTINGS;
158 }),
159 ),
160 RpcAuthorization.layer([AuthProvidersManageScope]),
161 ),
162 ),
163 );
164 yield* client[WS_METHODS.serverUpdateSettings]({ patch: {}, providerInstanceMutation });
165 expect(handled).toBe(1);
166 expect(
167 yield* client[WS_METHODS.serverUpdateSettings]({
168 patch: { defaultRuntimeMode: "full-access" },
169 providerInstanceMutation,
170 }).pipe(Effect.flip),
171 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
172 expect(handled).toBe(1);
173 }).pipe(Effect.scoped),
174 );
175
176 it.effect("does not let a settings grant create or remove providers", () =>
177 Effect.gen(function* () {
178 let handled = false;
179 const client = yield* RpcTest.makeClient(group).pipe(
180 Effect.provide(
181 Layer.mergeAll(
182 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
183 Effect.sync(() => {
184 handled = true;
185 return DEFAULT_SERVER_SETTINGS;
186 }),
187 ),
188 RpcAuthorization.layer([AuthSettingsWriteScope]),
189 ),
190 ),
191 );
192 expect(
193 yield* client[WS_METHODS.serverUpdateSettings]({
194 patch: {},
195 providerInstanceMutation,
196 }).pipe(Effect.flip),
197 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
198 expect(handled).toBe(false);
199 }).pipe(Effect.scoped),
200 );
201});
202
203it.effect("requires task permission before attaching a prepared worktree to a thread", () =>
204 Effect.gen(function* () {
205 const group = WsRpcGroup.omit(
206 ...[...WsRpcGroup.requests.keys()].filter(
207 (
208 tag,
209 ): tag is Exclude<
210 keyof typeof RPC_REQUIRED_SCOPES,
211 typeof WS_METHODS.gitPreparePullRequestThread
212 > => tag !== WS_METHODS.gitPreparePullRequestThread,
213 ),
214 );
215 let handled = false;
216 const client = yield* RpcTest.makeClient(group).pipe(
217 Effect.provide(
218 Layer.mergeAll(
219 group.toLayerHandler(WS_METHODS.gitPreparePullRequestThread, () =>
220 Effect.sync(() => {
221 handled = true;
222 }).pipe(Effect.andThen(Effect.never)),
223 ),
224 RpcAuthorization.layer([AuthSourceControlWriteScope]),
225 ),
226 ),
227 );
228 expect(
229 yield* client[WS_METHODS.gitPreparePullRequestThread]({
230 cwd: "/repo",
231 reference: "42",
232 mode: "worktree",
233 threadId: ThreadId.make("thread"),
234 }).pipe(Effect.flip),
235 ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope });
236 expect(handled).toBe(false);
237 }).pipe(Effect.scoped),
238);
239
240describe("thread context authorization", () => {
241 const group = WsRpcGroup.omit(
242 ...[...WsRpcGroup.requests.keys()].filter(
243 (
244 tag,
245 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.gitRunStackedAction> =>
246 tag !== WS_METHODS.gitRunStackedAction,
247 ),
248 );
249
250 it.effect.each(["commit", "create_pr", "commit_push_pr"] as const)(
251 "%s needs thread read permission only when generating a PR from a thread",
252 (action) =>
253 Effect.gen(function* () {
254 const handled: string[] = [];
255 const handler = group.toLayerHandler(WS_METHODS.gitRunStackedAction, ({ actionId }) =>
256 Stream.fromEffect(Effect.sync(() => handled.push(actionId))).pipe(Stream.drain),
257 );
258 const client = yield* RpcTest.makeClient(group).pipe(
259 Effect.provide(
260 Layer.merge(handler, RpcAuthorization.layer([AuthSourceControlWriteScope])),
261 ),
262 );
263 const input = { actionId: "without-thread", cwd: "/repo", action };
264 const withThread = { ...input, actionId: "with-thread", threadId: ThreadId.make("thread") };
265 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](input));
266 if (action === "create_pr" || action === "commit_push_pr") {
267 expect(
268 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread)).pipe(
269 Effect.flip,
270 ),
271 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
272 expect(handled).toEqual(["without-thread"]);
273 } else {
274 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread));
275 expect(handled).toEqual(["without-thread", "with-thread"]);
276 }
277 const reader = yield* RpcTest.makeClient(group).pipe(
278 Effect.provide(
279 Layer.merge(
280 handler,
281 RpcAuthorization.layer([AuthSourceControlWriteScope, AuthOrchestrationReadScope]),
282 ),
283 ),
284 );
285 yield* Stream.runDrain(
286 reader[WS_METHODS.gitRunStackedAction]({ ...withThread, actionId: "allowed" }),
287 );
288 expect(handled.at(-1)).toBe("allowed");
289 }).pipe(Effect.scoped),
290 );
291});
292
293it.effect("separates host file URLs from readable attachment URLs", () =>
294 Effect.gen(function* () {
295 const group = WsRpcGroup.omit(
296 ...[...WsRpcGroup.requests.keys()].filter(
297 (
298 tag,
299 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.assetsCreateUrl> =>
300 tag !== WS_METHODS.assetsCreateUrl,
301 ),
302 );
303 let handled = 0;
304 const client = yield* RpcTest.makeClient(group).pipe(
305 Effect.provide(
306 Layer.mergeAll(
307 group.toLayerHandler(WS_METHODS.assetsCreateUrl, () =>
308 Effect.sync(() => {
309 handled++;
310 return { relativeUrl: "/api/assets/file", expiresAt: 1 };
311 }),
312 ),
313 RpcAuthorization.layer([AuthOrchestrationReadScope]),
314 ),
315 ),
316 );
317 yield* client[WS_METHODS.assetsCreateUrl]({
318 resource: { _tag: "attachment", attachmentId: "image" },
319 });
320 for (const resource of [
321 { _tag: "workspace-file", threadId: ThreadId.make("thread"), path: "file.txt" },
322 { _tag: "media-file", threadId: ThreadId.make("thread"), path: "/repo/image.png" },
323 { _tag: "draft-workspace-file", cwd: "/repo", path: "file.txt" },
324 ] as const) {
325 expect(
326 yield* client[WS_METHODS.assetsCreateUrl]({ resource }).pipe(Effect.flip),
327 ).toMatchObject({
328 requiredScope: AuthOrchestrationReadScope,
329 requiredPermission: AuthFilesystemReadScope,
330 });
331 }
332 expect(handled).toBe(1);
333 }).pipe(Effect.scoped),
334);
335
336it.effect("denies manual cleanup before the handler without settings permission", () =>
337 Effect.gen(function* () {
338 const group = WsRpcGroup.omit(
339 ...[...WsRpcGroup.requests.keys()].filter(
340 (
341 tag,
342 ): tag is Exclude<
343 keyof typeof RPC_REQUIRED_SCOPES,
344 typeof WS_METHODS.serverRunStorageCleanup
345 > => tag !== WS_METHODS.serverRunStorageCleanup,
346 ),
347 );
348 let handled = false;
349 const client = yield* RpcTest.makeClient(group).pipe(
350 Effect.provide(
351 Layer.mergeAll(
352 group.toLayerHandler(WS_METHODS.serverRunStorageCleanup, () =>
353 Effect.sync(() => {
354 handled = true;
355 return {
356 trigger: "manual" as const,
357 startedAt: "2026-10-09T12:00:00.000Z",
358 finishedAt: "2026-10-09T12:00:00.000Z",
359 entries: [],
360 counts: { removed: 0, kept: 0, failed: 0 },
361 omittedCount: 0,
362 bytesFreed: 0,
363 };
364 }),
365 ),
366 RpcAuthorization.layer([AuthOrchestrationReadScope]),
367 ),
368 ),
369 );
370 expect(yield* client[WS_METHODS.serverRunStorageCleanup]({}).pipe(Effect.flip)).toMatchObject({
371 requiredPermission: AuthSettingsWriteScope,
372 });
373 expect(handled).toBe(false);
374 }).pipe(Effect.scoped),
375);