Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

RpcAuthorization.test.ts

451 lines15.5 KB

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