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