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