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

RpcAuthorization.test.ts

472 lines16.3 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 it.effect("reports only authorized requests that succeed", () =>
263 Effect.gen(function* () {
264 const observed: Array<string> = [];
265 const client = yield* RpcTest.makeClient(group).pipe(
266 Effect.provide(
267 Layer.mergeAll(
268 group.toLayerHandler(WS_METHODS.serverProbe, () => Effect.succeed({})),
269 group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () => Effect.never),
270 RpcAuthorization.layer([AuthOrchestrationReadScope], (method) =>
271 Effect.sync(() => void observed.push(method)),
272 ),
273 ),
274 ),
275 );
276​
277 yield* client[WS_METHODS.serverProbe]({});
278 yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(Effect.flip);
279 expect(observed).toEqual([WS_METHODS.serverProbe]);
280 }).pipe(Effect.scoped),
281 );
282});
283​
284describe("settings mutation authorization", () => {
285 const group = WsRpcGroup.omit(
286 ...[...WsRpcGroup.requests.keys()].filter(
287 (
288 tag,
289 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.serverUpdateSettings> =>
290 tag !== WS_METHODS.serverUpdateSettings,
291 ),
292 );
293 const providerInstanceMutation = {
294 operation: "remove" as const,
295 instanceId: ProviderInstanceId.make("codex_work"),
296 };
297​
298 it.effect("allows provider-only mutations while denying mixed settings without their grant", () =>
299 Effect.gen(function* () {
300 let handled = 0;
301 const client = yield* RpcTest.makeClient(group).pipe(
302 Effect.provide(
303 Layer.mergeAll(
304 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
305 Effect.sync(() => {
306 handled++;
307 return DEFAULT_SERVER_SETTINGS;
308 }),
309 ),
310 RpcAuthorization.layer([AuthProvidersManageScope]),
311 ),
312 ),
313 );
314 yield* client[WS_METHODS.serverUpdateSettings]({ patch: {}, providerInstanceMutation });
315 expect(handled).toBe(1);
316 expect(
317 yield* client[WS_METHODS.serverUpdateSettings]({
318 patch: { defaultRuntimeMode: "full-access" },
319 providerInstanceMutation,
320 }).pipe(Effect.flip),
321 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
322 expect(handled).toBe(1);
323 }).pipe(Effect.scoped),
324 );
325​
326 it.effect("does not let a settings grant create or remove providers", () =>
327 Effect.gen(function* () {
328 let handled = false;
329 const client = yield* RpcTest.makeClient(group).pipe(
330 Effect.provide(
331 Layer.mergeAll(
332 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
333 Effect.sync(() => {
334 handled = true;
335 return DEFAULT_SERVER_SETTINGS;
336 }),
337 ),
338 RpcAuthorization.layer([AuthSettingsWriteScope]),
339 ),
340 ),
341 );
342 expect(
343 yield* client[WS_METHODS.serverUpdateSettings]({
344 patch: {},
345 providerInstanceMutation,
346 }).pipe(Effect.flip),
347 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
348 expect(handled).toBe(false);
349 }).pipe(Effect.scoped),
350 );
351});
352​
353it.effect("requires task permission before attaching a prepared worktree to a thread", () =>
354 Effect.gen(function* () {
355 const group = WsRpcGroup.omit(
356 ...[...WsRpcGroup.requests.keys()].filter(
357 (
358 tag,
359 ): tag is Exclude<
360 keyof typeof RPC_REQUIRED_SCOPES,
361 typeof WS_METHODS.gitPreparePullRequestThread
362 > => tag !== WS_METHODS.gitPreparePullRequestThread,
363 ),
364 );
365 let handled = false;
366 const client = yield* RpcTest.makeClient(group).pipe(
367 Effect.provide(
368 Layer.mergeAll(
369 group.toLayerHandler(WS_METHODS.gitPreparePullRequestThread, () =>
370 Effect.sync(() => {
371 handled = true;
372 }).pipe(Effect.andThen(Effect.never)),
373 ),
374 RpcAuthorization.layer([AuthSourceControlWriteScope]),
375 ),
376 ),
377 );
378 expect(
379 yield* client[WS_METHODS.gitPreparePullRequestThread]({
380 cwd: "/repo",
381 reference: "42",
382 mode: "worktree",
383 threadId: ThreadId.make("thread"),
384 }).pipe(Effect.flip),
385 ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope });
386 expect(handled).toBe(false);
387 }).pipe(Effect.scoped),
388);
389​
390it.effect("separates host file URLs from readable attachment URLs", () =>
391 Effect.gen(function* () {
392 const group = WsRpcGroup.omit(
393 ...[...WsRpcGroup.requests.keys()].filter(
394 (
395 tag,
396 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.assetsCreateUrl> =>
397 tag !== WS_METHODS.assetsCreateUrl,
398 ),
399 );
400 let handled = 0;
401 const client = yield* RpcTest.makeClient(group).pipe(
402 Effect.provide(
403 Layer.mergeAll(
404 group.toLayerHandler(WS_METHODS.assetsCreateUrl, () =>
405 Effect.sync(() => {
406 handled++;
407 return { relativeUrl: "/api/assets/file", expiresAt: 1 };
408 }),
409 ),
410 RpcAuthorization.layer([AuthOrchestrationReadScope]),
411 ),
412 ),
413 );
414 yield* client[WS_METHODS.assetsCreateUrl]({
415 resource: { _tag: "attachment", attachmentId: "image" },
416 });
417 for (const resource of [
418 { _tag: "workspace-file", threadId: ThreadId.make("thread"), path: "file.txt" },
419 { _tag: "media-file", threadId: ThreadId.make("thread"), path: "/repo/image.png" },
420 { _tag: "draft-workspace-file", cwd: "/repo", path: "file.txt" },
421 ] as const) {
422 expect(
423 yield* client[WS_METHODS.assetsCreateUrl]({ resource }).pipe(Effect.flip),
424 ).toMatchObject({
425 requiredScope: AuthOrchestrationReadScope,
426 requiredPermission: AuthFilesystemReadScope,
427 });
428 }
429 expect(handled).toBe(1);
430 }).pipe(Effect.scoped),
431);
432​
433it.effect("denies manual cleanup before the handler without settings permission", () =>
434 Effect.gen(function* () {
435 const group = WsRpcGroup.omit(
436 ...[...WsRpcGroup.requests.keys()].filter(
437 (
438 tag,
439 ): tag is Exclude<
440 keyof typeof RPC_REQUIRED_SCOPES,
441 typeof WS_METHODS.serverRunStorageCleanup
442 > => tag !== WS_METHODS.serverRunStorageCleanup,
443 ),
444 );
445 let handled = false;
446 const client = yield* RpcTest.makeClient(group).pipe(
447 Effect.provide(
448 Layer.mergeAll(
449 group.toLayerHandler(WS_METHODS.serverRunStorageCleanup, () =>
450 Effect.sync(() => {
451 handled = true;
452 return {
453 trigger: "manual" as const,
454 startedAt: "2026-10-09T12:00:00.000Z",
455 finishedAt: "2026-10-09T12:00:00.000Z",
456 entries: [],
457 counts: { removed: 0, kept: 0, failed: 0 },
458 omittedCount: 0,
459 bytesFreed: 0,
460 };
461 }),
462 ),
463 RpcAuthorization.layer([AuthOrchestrationReadScope]),
464 ),
465 ),
466 );
467 expect(yield* client[WS_METHODS.serverRunStorageCleanup]({}).pipe(Effect.flip)).toMatchObject({
468 requiredPermission: AuthSettingsWriteScope,
469 });
470 expect(handled).toBe(false);
471 }).pipe(Effect.scoped),
472);