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

RpcAuthorization.test.ts

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