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 expect(handled).toBe(2);
196 }).pipe(Effect.scoped),
197 );
198
199 it.effect("does not let a settings grant create or remove providers or secret providers", () =>
200 Effect.gen(function* () {
201 let handled = false;
202 const client = yield* RpcTest.makeClient(group).pipe(
203 Effect.provide(
204 Layer.mergeAll(
205 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
206 Effect.sync(() => {
207 handled = true;
208 return DEFAULT_SERVER_SETTINGS;
209 }),
210 ),
211 RpcAuthorization.layer([AuthSettingsWriteScope]),
212 ),
213 ),
214 );
215 expect(
216 yield* client[WS_METHODS.serverUpdateSettings]({
217 patch: {},
218 providerInstanceMutation,
219 }).pipe(Effect.flip),
220 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
221 expect(
222 yield* client[WS_METHODS.serverUpdateSettings]({
223 patch: { secretProviders: { [SecretProviderId.make("personal")]: null } },
224 }).pipe(Effect.flip),
225 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
226 expect(handled).toBe(false);
227 }).pipe(Effect.scoped),
228 );
229});
230
231it.effect("requires task permission before attaching a prepared worktree to a thread", () =>
232 Effect.gen(function* () {
233 const group = WsRpcGroup.omit(
234 ...[...WsRpcGroup.requests.keys()].filter(
235 (
236 tag,
237 ): tag is Exclude<
238 keyof typeof RPC_REQUIRED_SCOPES,
239 typeof WS_METHODS.gitPreparePullRequestThread
240 > => tag !== WS_METHODS.gitPreparePullRequestThread,
241 ),
242 );
243 let handled = false;
244 const client = yield* RpcTest.makeClient(group).pipe(
245 Effect.provide(
246 Layer.mergeAll(
247 group.toLayerHandler(WS_METHODS.gitPreparePullRequestThread, () =>
248 Effect.sync(() => {
249 handled = true;
250 }).pipe(Effect.andThen(Effect.never)),
251 ),
252 RpcAuthorization.layer([AuthSourceControlWriteScope]),
253 ),
254 ),
255 );
256 expect(
257 yield* client[WS_METHODS.gitPreparePullRequestThread]({
258 cwd: "/repo",
259 reference: "42",
260 mode: "worktree",
261 threadId: ThreadId.make("thread"),
262 }).pipe(Effect.flip),
263 ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope });
264 expect(handled).toBe(false);
265 }).pipe(Effect.scoped),
266);
267
268describe("thread context authorization", () => {
269 const group = WsRpcGroup.omit(
270 ...[...WsRpcGroup.requests.keys()].filter(
271 (
272 tag,
273 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.gitRunStackedAction> =>
274 tag !== WS_METHODS.gitRunStackedAction,
275 ),
276 );
277
278 it.effect.each(["commit", "create_pr", "commit_push_pr"] as const)(
279 "%s needs thread read permission only when generating a PR from a thread",
280 (action) =>
281 Effect.gen(function* () {
282 const handled: string[] = [];
283 const handler = group.toLayerHandler(WS_METHODS.gitRunStackedAction, ({ actionId }) =>
284 Stream.fromEffect(Effect.sync(() => handled.push(actionId))).pipe(Stream.drain),
285 );
286 const client = yield* RpcTest.makeClient(group).pipe(
287 Effect.provide(
288 Layer.merge(handler, RpcAuthorization.layer([AuthSourceControlWriteScope])),
289 ),
290 );
291 const input = { actionId: "without-thread", cwd: "/repo", action };
292 const withThread = { ...input, actionId: "with-thread", threadId: ThreadId.make("thread") };
293 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](input));
294 if (action === "create_pr" || action === "commit_push_pr") {
295 expect(
296 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread)).pipe(
297 Effect.flip,
298 ),
299 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
300 expect(handled).toEqual(["without-thread"]);
301 } else {
302 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread));
303 expect(handled).toEqual(["without-thread", "with-thread"]);
304 }
305 const reader = yield* RpcTest.makeClient(group).pipe(
306 Effect.provide(
307 Layer.merge(
308 handler,
309 RpcAuthorization.layer([AuthSourceControlWriteScope, AuthOrchestrationReadScope]),
310 ),
311 ),
312 );
313 yield* Stream.runDrain(
314 reader[WS_METHODS.gitRunStackedAction]({ ...withThread, actionId: "allowed" }),
315 );
316 expect(handled.at(-1)).toBe("allowed");
317 }).pipe(Effect.scoped),
318 );
319});
320
321it.effect("separates host file URLs from readable attachment URLs", () =>
322 Effect.gen(function* () {
323 const group = WsRpcGroup.omit(
324 ...[...WsRpcGroup.requests.keys()].filter(
325 (
326 tag,
327 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.assetsCreateUrl> =>
328 tag !== WS_METHODS.assetsCreateUrl,
329 ),
330 );
331 let handled = 0;
332 const client = yield* RpcTest.makeClient(group).pipe(
333 Effect.provide(
334 Layer.mergeAll(
335 group.toLayerHandler(WS_METHODS.assetsCreateUrl, () =>
336 Effect.sync(() => {
337 handled++;
338 return { relativeUrl: "/api/assets/file", expiresAt: 1 };
339 }),
340 ),
341 RpcAuthorization.layer([AuthOrchestrationReadScope]),
342 ),
343 ),
344 );
345 yield* client[WS_METHODS.assetsCreateUrl]({
346 resource: { _tag: "attachment", attachmentId: "image" },
347 });
348 for (const resource of [
349 { _tag: "workspace-file", threadId: ThreadId.make("thread"), path: "file.txt" },
350 { _tag: "media-file", threadId: ThreadId.make("thread"), path: "/repo/image.png" },
351 { _tag: "draft-workspace-file", cwd: "/repo", path: "file.txt" },
352 ] as const) {
353 expect(
354 yield* client[WS_METHODS.assetsCreateUrl]({ resource }).pipe(Effect.flip),
355 ).toMatchObject({
356 requiredScope: AuthOrchestrationReadScope,
357 requiredPermission: AuthFilesystemReadScope,
358 });
359 }
360 expect(handled).toBe(1);
361 }).pipe(Effect.scoped),
362);
363
364it.effect("denies manual cleanup before the handler without settings permission", () =>
365 Effect.gen(function* () {
366 const group = WsRpcGroup.omit(
367 ...[...WsRpcGroup.requests.keys()].filter(
368 (
369 tag,
370 ): tag is Exclude<
371 keyof typeof RPC_REQUIRED_SCOPES,
372 typeof WS_METHODS.serverRunStorageCleanup
373 > => tag !== WS_METHODS.serverRunStorageCleanup,
374 ),
375 );
376 let handled = false;
377 const client = yield* RpcTest.makeClient(group).pipe(
378 Effect.provide(
379 Layer.mergeAll(
380 group.toLayerHandler(WS_METHODS.serverRunStorageCleanup, () =>
381 Effect.sync(() => {
382 handled = true;
383 return {
384 trigger: "manual" as const,
385 startedAt: "2026-10-09T12:00:00.000Z",
386 finishedAt: "2026-10-09T12:00:00.000Z",
387 entries: [],
388 counts: { removed: 0, kept: 0, failed: 0 },
389 omittedCount: 0,
390 bytesFreed: 0,
391 };
392 }),
393 ),
394 RpcAuthorization.layer([AuthOrchestrationReadScope]),
395 ),
396 ),
397 );
398 expect(yield* client[WS_METHODS.serverRunStorageCleanup]({}).pipe(Effect.flip)).toMatchObject({
399 requiredPermission: AuthSettingsWriteScope,
400 });
401 expect(handled).toBe(false);
402 }).pipe(Effect.scoped),
403);