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 ORCHESTRATION_V2_WS_METHODS,
12 AuthOrchestrationReadScope,
13 AuthSourceControlWriteScope,
14 AuthPreviewOperateScope,
15 AuthRelayReadScope,
16 AuthRelayWriteScope,
17 AuthTerminalReadScope,
18 AuthTerminalOperateScope,
19 WS_METHODS,
20 WsRpcGroup,
21} from "@t3tools/contracts";
22import { describe, expect, it } from "@effect/vitest";
23import * as Effect from "effect/Effect";
24import * as Layer from "effect/Layer";
25import * as Stream from "effect/Stream";
26import * as RpcTest from "effect/rpc/RpcTest";
27
28import {
29 RPC_REQUIRED_SCOPES,
30 requiredScopeForRpcMethod,
31 requiredScopeForDeviceList,
32} from "./RpcAuthorization.ts";
33import * as RpcAuthorization from "./RpcAuthorization.ts";
34
35describe("RPC authorization scopes", () => {
36 it("declares exactly one scope for every RPC in the server group", () => {
37 expect(new Set(Object.keys(RPC_REQUIRED_SCOPES))).toEqual(new Set(WsRpcGroup.requests.keys()));
38 });
39
40 it("requires operate access to stop a workflow", () => {
41 expect(requiredScopeForRpcMethod(ORCHESTRATION_V2_WS_METHODS.stopWorkflow)).toBe(
42 AuthOrchestrationOperateScope,
43 );
44 });
45
46 it("authorizes background policy reporting and observation deliberately", () => {
47 expect(requiredScopeForRpcMethod(WS_METHODS.serverReportClientActivity)).toBe(
48 AuthOrchestrationReadScope,
49 );
50 expect(requiredScopeForRpcMethod(WS_METHODS.serverReportHostPowerState)).toBe(
51 AuthEnvironmentMaintainScope,
52 );
53 expect(requiredScopeForRpcMethod(WS_METHODS.serverGetBackgroundPolicy)).toBe(
54 AuthOrchestrationReadScope,
55 );
56 expect(requiredScopeForRpcMethod(WS_METHODS.subscribeBackgroundPolicy)).toBe(
57 AuthOrchestrationReadScope,
58 );
59 });
60
61 it("keeps webhook delivery logs, which hold request bodies, behind operate scope", () => {
62 for (const method of [
63 WS_METHODS.scheduledTasksListWebhookDeliveries,
64 WS_METHODS.scheduledTasksGetWebhookDelivery,
65 WS_METHODS.scheduledTasksRotateWebhookToken,
66 ]) {
67 expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationOperateScope);
68 }
69 });
70
71 it("allows relay status reads without granting relay installation access", () => {
72 expect(requiredScopeForRpcMethod(WS_METHODS.cloudGetRelayClientStatus)).toBe(
73 AuthRelayReadScope,
74 );
75 expect(requiredScopeForRpcMethod(WS_METHODS.cloudInstallRelayClient)).toBe(AuthRelayWriteScope);
76 });
77
78 it("requires permission to operate on a thread before uploading feedback", () => {
79 expect(requiredScopeForRpcMethod(WS_METHODS.providerUploadFeedback)).toBe(
80 AuthOrchestrationOperateScope,
81 );
82 });
83
84 it("requires write access to import agent session history", () => {
85 expect(requiredScopeForRpcMethod(WS_METHODS.agentSessionsScan)).toBe(
86 AuthOrchestrationReadScope,
87 );
88 expect(requiredScopeForRpcMethod(WS_METHODS.agentSessionsImport)).toBe(
89 AuthOrchestrationOperateScope,
90 );
91 });
92
93 it("separates ACP Registry discovery from provisioning", () => {
94 expect(requiredScopeForRpcMethod(WS_METHODS.serverSearchAcpRegistry)).toBe(
95 AuthOrchestrationReadScope,
96 );
97 expect(requiredScopeForRpcMethod(WS_METHODS.serverPrepareAcpRegistryAgent)).toBe(
98 AuthProvidersManageScope,
99 );
100 expect(requiredScopeForRpcMethod(WS_METHODS.serverUninstallAcpRegistryManagedBinary)).toBe(
101 AuthProvidersManageScope,
102 );
103 expect(requiredScopeForRpcMethod(WS_METHODS.serverAcceptAcpRegistryUrlAuth)).toBe(
104 AuthProvidersManageScope,
105 );
106 expect(requiredScopeForRpcMethod(WS_METHODS.serverListAcpRegistrySessions)).toBe(
107 AuthOrchestrationReadScope,
108 );
109 expect(requiredScopeForRpcMethod(WS_METHODS.serverImportAcpRegistrySession)).toBe(
110 AuthOrchestrationOperateScope,
111 );
112 expect(requiredScopeForRpcMethod(WS_METHODS.serverLogoutAcpRegistry)).toBe(
113 AuthProvidersManageScope,
114 );
115 });
116
117 it("reads the reviewer menu under the same scope as the pull request it belongs to", () => {
118 expect(requiredScopeForRpcMethod(WS_METHODS.pullRequestsChecks)).toBe(
119 AuthOrchestrationReadScope,
120 );
121 expect(requiredScopeForRpcMethod(WS_METHODS.pullRequestsReviewerCandidates)).toBe(
122 requiredScopeForRpcMethod(WS_METHODS.pullRequestsDetail),
123 );
124 expect(requiredScopeForRpcMethod(WS_METHODS.pullRequestsRequestReviewers)).toBe(
125 requiredScopeForRpcMethod(WS_METHODS.pullRequestsComment),
126 );
127 });
128
129 it("requires source control writes to start, retry, or cancel project clones", () => {
130 for (const method of [
131 WS_METHODS.projectCloneStart,
132 WS_METHODS.projectCloneRetry,
133 WS_METHODS.projectCloneCancel,
134 ]) {
135 expect(requiredScopeForRpcMethod(method)).toBe(AuthSourceControlWriteScope);
136 }
137 expect(requiredScopeForRpcMethod(WS_METHODS.subscribeProjectClones)).toBe(
138 AuthOrchestrationReadScope,
139 );
140 });
141
142 it("separates viewing pull request file progress from writing it", () => {
143 expect(requiredScopeForRpcMethod(WS_METHODS.pullRequestsFilesViewed)).toBe(
144 AuthOrchestrationReadScope,
145 );
146 expect(requiredScopeForRpcMethod(WS_METHODS.pullRequestsSetFilesViewed)).toBe(
147 AuthSourceControlWriteScope,
148 );
149 });
150
151 it("separates preview control from observation", () => {
152 for (const method of [
153 WS_METHODS.previewOpen,
154 WS_METHODS.previewNavigate,
155 WS_METHODS.previewResize,
156 WS_METHODS.previewRefresh,
157 WS_METHODS.previewClose,
158 WS_METHODS.previewReportStatus,
159 WS_METHODS.previewAdjust,
160 WS_METHODS.previewClearProfile,
161 WS_METHODS.previewReportProfiles,
162 ]) {
163 expect(requiredScopeForRpcMethod(method)).toBe(AuthPreviewOperateScope);
164 }
165 for (const method of [
166 WS_METHODS.previewList,
167 WS_METHODS.subscribePreviewEvents,
168 WS_METHODS.subscribeDiscoveredLocalServers,
169 ]) {
170 expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationReadScope);
171 }
172 });
173
174 it("separates passive terminal observation from operations that can change a shell", () => {
175 for (const method of [
176 WS_METHODS.terminalObserve,
177 WS_METHODS.subscribeTerminalEvents,
178 WS_METHODS.subscribeTerminalMetadata,
179 ]) {
180 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalReadScope);
181 }
182 for (const method of [
183 WS_METHODS.terminalAttach,
184 WS_METHODS.terminalOpen,
185 WS_METHODS.terminalWrite,
186 WS_METHODS.terminalResize,
187 WS_METHODS.terminalClear,
188 WS_METHODS.terminalRestart,
189 WS_METHODS.terminalClose,
190 ]) {
191 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalOperateScope);
192 }
193 });
194
195 it("rejects unknown RPC method names", () => {
196 for (const method of ["server.notRegistered", "toString", "constructor"]) {
197 expect(() => requiredScopeForRpcMethod(method)).toThrow(
198 `RPC method ${method} has no declared authorization scope.`,
199 );
200 }
201 });
202});
203
204it("requires operate permission for host retry while preserving read-only listing", () => {
205 expect(requiredScopeForDeviceList({})).toBe(AuthOrchestrationReadScope);
206 expect(requiredScopeForDeviceList({ retryHostId: "remote-host" })).toBe(
207 AuthOrchestrationOperateScope,
208 );
209});
210
211it("requires operate permission for tool updates even alongside a read-only check", () => {
212 expect(requiredScopeForDeviceList({ updateTool: "agent", inspectOnly: true })).toBe(
213 AuthOrchestrationOperateScope,
214 );
215 expect(requiredScopeForDeviceList({ updateTool: "hub" })).toBe(AuthOrchestrationOperateScope);
216});
217
218describe("RPC scope middleware", () => {
219 const tested = [WS_METHODS.serverProbe, WS_METHODS.serverRetryResourceTelemetry] as const;
220 const group = WsRpcGroup.omit(
221 ...[...WsRpcGroup.requests.keys()].filter(
222 (tag): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, (typeof tested)[number]> =>
223 !(tested as ReadonlyArray<string>).includes(tag),
224 ),
225 );
226
227 it.effect.each([
228 { scopes: [AuthOrchestrationReadScope], missing: AuthEnvironmentMaintainScope },
229 {
230 scopes: [AuthOrchestrationReadScope, AuthEnvironmentMaintainScope],
231 missing: AuthDiagnosticsReadScope,
232 },
233 {
234 scopes: [AuthOrchestrationReadScope, AuthDiagnosticsReadScope],
235 missing: AuthEnvironmentMaintainScope,
236 },
237 ])("rejects telemetry retry without $missing before its handler runs", ({ scopes, missing }) =>
238 Effect.gen(function* () {
239 const handled: Array<string> = [];
240 const client = yield* RpcTest.makeClient(group).pipe(
241 Effect.provide(
242 Layer.mergeAll(
243 group.toLayerHandler(WS_METHODS.serverProbe, () => Effect.succeed({})),
244 group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () =>
245 Effect.sync(() => handled.push("retry")).pipe(Effect.andThen(Effect.never)),
246 ),
247 RpcAuthorization.layer(scopes),
248 ),
249 ),
250 );
251
252 expect(yield* client[WS_METHODS.serverProbe]({})).toEqual({});
253 expect(
254 yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(Effect.flip),
255 ).toMatchObject({
256 _tag: "EnvironmentAuthorizationError",
257 requiredPermission: missing,
258 });
259 expect(handled).toEqual([]);
260 }).pipe(Effect.scoped),
261 );
262
263 it.effect("reports only authorized requests that succeed", () =>
264 Effect.gen(function* () {
265 const observed: Array<string> = [];
266 const client = yield* RpcTest.makeClient(group).pipe(
267 Effect.provide(
268 Layer.mergeAll(
269 group.toLayerHandler(WS_METHODS.serverProbe, () => Effect.succeed({})),
270 group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () => Effect.never),
271 RpcAuthorization.layer([AuthOrchestrationReadScope], (method) =>
272 Effect.sync(() => void observed.push(method)),
273 ),
274 ),
275 ),
276 );
277
278 yield* client[WS_METHODS.serverProbe]({});
279 yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(Effect.flip);
280 expect(observed).toEqual([WS_METHODS.serverProbe]);
281 }).pipe(Effect.scoped),
282 );
283});
284
285describe("settings mutation authorization", () => {
286 const group = WsRpcGroup.omit(
287 ...[...WsRpcGroup.requests.keys()].filter(
288 (
289 tag,
290 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.serverUpdateSettings> =>
291 tag !== WS_METHODS.serverUpdateSettings,
292 ),
293 );
294 const providerInstanceMutation = {
295 operation: "remove" as const,
296 instanceId: ProviderInstanceId.make("codex_work"),
297 };
298
299 it.effect("allows provider-only mutations while denying mixed settings without their grant", () =>
300 Effect.gen(function* () {
301 let handled = 0;
302 const client = yield* RpcTest.makeClient(group).pipe(
303 Effect.provide(
304 Layer.mergeAll(
305 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
306 Effect.sync(() => {
307 handled++;
308 return DEFAULT_SERVER_SETTINGS;
309 }),
310 ),
311 RpcAuthorization.layer([AuthProvidersManageScope]),
312 ),
313 ),
314 );
315 yield* client[WS_METHODS.serverUpdateSettings]({ patch: {}, providerInstanceMutation });
316 expect(handled).toBe(1);
317 expect(
318 yield* client[WS_METHODS.serverUpdateSettings]({
319 patch: { defaultRuntimeMode: "full-access" },
320 providerInstanceMutation,
321 }).pipe(Effect.flip),
322 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
323 expect(handled).toBe(1);
324 }).pipe(Effect.scoped),
325 );
326
327 it.effect("does not let a settings grant create or remove providers", () =>
328 Effect.gen(function* () {
329 let handled = false;
330 const client = yield* RpcTest.makeClient(group).pipe(
331 Effect.provide(
332 Layer.mergeAll(
333 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
334 Effect.sync(() => {
335 handled = true;
336 return DEFAULT_SERVER_SETTINGS;
337 }),
338 ),
339 RpcAuthorization.layer([AuthSettingsWriteScope]),
340 ),
341 ),
342 );
343 expect(
344 yield* client[WS_METHODS.serverUpdateSettings]({
345 patch: {},
346 providerInstanceMutation,
347 }).pipe(Effect.flip),
348 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
349 expect(handled).toBe(false);
350 }).pipe(Effect.scoped),
351 );
352});
353
354it.effect("requires task permission before attaching a prepared worktree to a thread", () =>
355 Effect.gen(function* () {
356 const group = WsRpcGroup.omit(
357 ...[...WsRpcGroup.requests.keys()].filter(
358 (
359 tag,
360 ): tag is Exclude<
361 keyof typeof RPC_REQUIRED_SCOPES,
362 typeof WS_METHODS.gitPreparePullRequestThread
363 > => tag !== WS_METHODS.gitPreparePullRequestThread,
364 ),
365 );
366 let handled = false;
367 const client = yield* RpcTest.makeClient(group).pipe(
368 Effect.provide(
369 Layer.mergeAll(
370 group.toLayerHandler(WS_METHODS.gitPreparePullRequestThread, () =>
371 Effect.sync(() => {
372 handled = true;
373 }).pipe(Effect.andThen(Effect.never)),
374 ),
375 RpcAuthorization.layer([AuthSourceControlWriteScope]),
376 ),
377 ),
378 );
379 expect(
380 yield* client[WS_METHODS.gitPreparePullRequestThread]({
381 cwd: "/repo",
382 reference: "42",
383 mode: "worktree",
384 threadId: ThreadId.make("thread"),
385 }).pipe(Effect.flip),
386 ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope });
387 expect(handled).toBe(false);
388 }).pipe(Effect.scoped),
389);
390
391describe("thread context authorization", () => {
392 const group = WsRpcGroup.omit(
393 ...[...WsRpcGroup.requests.keys()].filter(
394 (
395 tag,
396 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.gitRunStackedAction> =>
397 tag !== WS_METHODS.gitRunStackedAction,
398 ),
399 );
400
401 it.effect.each(["commit", "push", "commit_push", "create_pr", "commit_push_pr"] as const)(
402 "%s needs thread read permission only when generating a PR from a thread",
403 (action) =>
404 Effect.gen(function* () {
405 const handled: string[] = [];
406 const handler = group.toLayerHandler(WS_METHODS.gitRunStackedAction, ({ actionId }) =>
407 Stream.fromEffect(Effect.sync(() => handled.push(actionId))).pipe(Stream.drain),
408 );
409 const client = yield* RpcTest.makeClient(group).pipe(
410 Effect.provide(
411 Layer.merge(handler, RpcAuthorization.layer([AuthSourceControlWriteScope])),
412 ),
413 );
414 const input = { actionId: "without-thread", cwd: "/repo", action };
415 const withThread = { ...input, actionId: "with-thread", threadId: ThreadId.make("thread") };
416 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](input));
417 if (action === "create_pr" || action === "commit_push_pr") {
418 expect(
419 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread)).pipe(
420 Effect.flip,
421 ),
422 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
423 expect(handled).toEqual(["without-thread"]);
424 } else {
425 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread));
426 expect(handled).toEqual(["without-thread", "with-thread"]);
427 }
428 const reader = yield* RpcTest.makeClient(group).pipe(
429 Effect.provide(
430 Layer.merge(
431 handler,
432 RpcAuthorization.layer([AuthSourceControlWriteScope, AuthOrchestrationReadScope]),
433 ),
434 ),
435 );
436 yield* Stream.runDrain(
437 reader[WS_METHODS.gitRunStackedAction]({ ...withThread, actionId: "allowed" }),
438 );
439 expect(handled.at(-1)).toBe("allowed");
440 }).pipe(Effect.scoped),
441 );
442});
443
444it.effect("separates host file URLs from readable attachment URLs", () =>
445 Effect.gen(function* () {
446 const group = WsRpcGroup.omit(
447 ...[...WsRpcGroup.requests.keys()].filter(
448 (
449 tag,
450 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.assetsCreateUrl> =>
451 tag !== WS_METHODS.assetsCreateUrl,
452 ),
453 );
454 let handled = 0;
455 const client = yield* RpcTest.makeClient(group).pipe(
456 Effect.provide(
457 Layer.mergeAll(
458 group.toLayerHandler(WS_METHODS.assetsCreateUrl, () =>
459 Effect.sync(() => {
460 handled++;
461 return { relativeUrl: "/api/assets/file", expiresAt: 1 };
462 }),
463 ),
464 RpcAuthorization.layer([AuthOrchestrationReadScope]),
465 ),
466 ),
467 );
468 yield* client[WS_METHODS.assetsCreateUrl]({
469 resource: { _tag: "attachment", attachmentId: "image" },
470 });
471 for (const resource of [
472 { _tag: "workspace-file", threadId: ThreadId.make("thread"), path: "file.txt" },
473 { _tag: "media-file", threadId: ThreadId.make("thread"), path: "/repo/image.png" },
474 { _tag: "draft-workspace-file", cwd: "/repo", path: "file.txt" },
475 ] as const) {
476 expect(
477 yield* client[WS_METHODS.assetsCreateUrl]({ resource }).pipe(Effect.flip),
478 ).toMatchObject({
479 requiredScope: AuthOrchestrationReadScope,
480 requiredPermission: AuthFilesystemReadScope,
481 });
482 }
483 expect(handled).toBe(1);
484 }).pipe(Effect.scoped),
485);
486
487it.effect("denies manual cleanup before the handler without settings permission", () =>
488 Effect.gen(function* () {
489 const group = WsRpcGroup.omit(
490 ...[...WsRpcGroup.requests.keys()].filter(
491 (
492 tag,
493 ): tag is Exclude<
494 keyof typeof RPC_REQUIRED_SCOPES,
495 typeof WS_METHODS.serverRunStorageCleanup
496 > => tag !== WS_METHODS.serverRunStorageCleanup,
497 ),
498 );
499 let handled = false;
500 const client = yield* RpcTest.makeClient(group).pipe(
501 Effect.provide(
502 Layer.mergeAll(
503 group.toLayerHandler(WS_METHODS.serverRunStorageCleanup, () =>
504 Effect.sync(() => {
505 handled = true;
506 return {
507 trigger: "manual" as const,
508 startedAt: "2026-10-09T12:00:00.000Z",
509 finishedAt: "2026-10-09T12:00:00.000Z",
510 entries: [],
511 counts: { removed: 0, kept: 0, failed: 0 },
512 omittedCount: 0,
513 bytesFreed: 0,
514 };
515 }),
516 ),
517 RpcAuthorization.layer([AuthOrchestrationReadScope]),
518 ),
519 ),
520 );
521 expect(yield* client[WS_METHODS.serverRunStorageCleanup]({}).pipe(Effect.flip)).toMatchObject({
522 requiredPermission: AuthSettingsWriteScope,
523 });
524 expect(handled).toBe(false);
525 }).pipe(Effect.scoped),
526);