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

RpcAuthorization.test.ts

405 lines14.1 KB

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