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

RpcAuthorization.test.ts

404 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 ]) {
156 expect(requiredScopeForRpcMethod(method)).toBe(AuthPreviewOperateScope);
157 }
158 for (const method of [
159 WS_METHODS.previewList,
160 WS_METHODS.subscribePreviewEvents,
161 WS_METHODS.subscribeDiscoveredLocalServers,
162 ]) {
163 expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationReadScope);
164 }
165 });
166​
167 it("separates passive terminal observation from operations that can change a shell", () => {
168 for (const method of [
169 WS_METHODS.terminalObserve,
170 WS_METHODS.subscribeTerminalEvents,
171 WS_METHODS.subscribeTerminalMetadata,
172 ]) {
173 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalReadScope);
174 }
175 for (const method of [
176 WS_METHODS.terminalAttach,
177 WS_METHODS.terminalOpen,
178 WS_METHODS.terminalWrite,
179 WS_METHODS.terminalResize,
180 WS_METHODS.terminalClear,
181 WS_METHODS.terminalRestart,
182 WS_METHODS.terminalClose,
183 ]) {
184 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalOperateScope);
185 }
186 });
187​
188 it("rejects unknown RPC method names", () => {
189 for (const method of ["server.notRegistered", "toString", "constructor"]) {
190 expect(() => requiredScopeForRpcMethod(method)).toThrow(
191 `RPC method ${method} has no declared authorization scope.`,
192 );
193 }
194 });
195});
196​
197it("requires operate permission for host retry while preserving read-only listing", () => {
198 expect(requiredScopeForDeviceList({})).toBe(AuthOrchestrationReadScope);
199 expect(requiredScopeForDeviceList({ retryHostId: "remote-host" })).toBe(
200 AuthOrchestrationOperateScope,
201 );
202});
203​
204it("requires operate permission for tool updates even alongside a read-only check", () => {
205 expect(requiredScopeForDeviceList({ updateTool: "agent", inspectOnly: true })).toBe(
206 AuthOrchestrationOperateScope,
207 );
208 expect(requiredScopeForDeviceList({ updateTool: "hub" })).toBe(AuthOrchestrationOperateScope);
209});
210​
211describe("RPC scope middleware", () => {
212 const tested = [WS_METHODS.serverProbe, WS_METHODS.serverRetryResourceTelemetry] as const;
213 const group = WsRpcGroup.omit(
214 ...[...WsRpcGroup.requests.keys()].filter(
215 (tag): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, (typeof tested)[number]> =>
216 !(tested as ReadonlyArray<string>).includes(tag),
217 ),
218 );
219​
220 it.effect.each([
221 { scopes: [AuthOrchestrationReadScope], missing: AuthEnvironmentMaintainScope },
222 {
223 scopes: [AuthOrchestrationReadScope, AuthEnvironmentMaintainScope],
224 missing: AuthDiagnosticsReadScope,
225 },
226 {
227 scopes: [AuthOrchestrationReadScope, AuthDiagnosticsReadScope],
228 missing: AuthEnvironmentMaintainScope,
229 },
230 ])("rejects telemetry retry without $missing before its handler runs", ({ scopes, missing }) =>
231 Effect.gen(function* () {
232 const handled: Array<string> = [];
233 const client = yield* RpcTest.makeClient(group).pipe(
234 Effect.provide(
235 Layer.mergeAll(
236 group.toLayerHandler(WS_METHODS.serverProbe, () => Effect.succeed({})),
237 group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () =>
238 Effect.sync(() => handled.push("retry")).pipe(Effect.andThen(Effect.never)),
239 ),
240 RpcAuthorization.layer(scopes),
241 ),
242 ),
243 );
244​
245 expect(yield* client[WS_METHODS.serverProbe]({})).toEqual({});
246 expect(
247 yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(Effect.flip),
248 ).toMatchObject({
249 _tag: "EnvironmentAuthorizationError",
250 requiredPermission: missing,
251 });
252 expect(handled).toEqual([]);
253 }).pipe(Effect.scoped),
254 );
255});
256​
257describe("settings mutation authorization", () => {
258 const group = WsRpcGroup.omit(
259 ...[...WsRpcGroup.requests.keys()].filter(
260 (
261 tag,
262 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.serverUpdateSettings> =>
263 tag !== WS_METHODS.serverUpdateSettings,
264 ),
265 );
266 const providerInstanceMutation = {
267 operation: "remove" as const,
268 instanceId: ProviderInstanceId.make("codex_work"),
269 };
270​
271 it.effect("allows provider-only mutations while denying mixed settings without their grant", () =>
272 Effect.gen(function* () {
273 let handled = 0;
274 const client = yield* RpcTest.makeClient(group).pipe(
275 Effect.provide(
276 Layer.mergeAll(
277 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
278 Effect.sync(() => {
279 handled++;
280 return DEFAULT_SERVER_SETTINGS;
281 }),
282 ),
283 RpcAuthorization.layer([AuthProvidersManageScope]),
284 ),
285 ),
286 );
287 yield* client[WS_METHODS.serverUpdateSettings]({ patch: {}, providerInstanceMutation });
288 expect(handled).toBe(1);
289 expect(
290 yield* client[WS_METHODS.serverUpdateSettings]({
291 patch: { defaultRuntimeMode: "full-access" },
292 providerInstanceMutation,
293 }).pipe(Effect.flip),
294 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
295 expect(handled).toBe(1);
296 }).pipe(Effect.scoped),
297 );
298​
299 it.effect("does not let a settings grant create or remove providers", () =>
300 Effect.gen(function* () {
301 let handled = false;
302 const client = yield* RpcTest.makeClient(group).pipe(
303 Effect.provide(
304 Layer.mergeAll(
305 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
306 Effect.sync(() => {
307 handled = true;
308 return DEFAULT_SERVER_SETTINGS;
309 }),
310 ),
311 RpcAuthorization.layer([AuthSettingsWriteScope]),
312 ),
313 ),
314 );
315 expect(
316 yield* client[WS_METHODS.serverUpdateSettings]({
317 patch: {},
318 providerInstanceMutation,
319 }).pipe(Effect.flip),
320 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
321 expect(handled).toBe(false);
322 }).pipe(Effect.scoped),
323 );
324});
325​
326it.effect("requires task permission before attaching a prepared worktree to a thread", () =>
327 Effect.gen(function* () {
328 const group = WsRpcGroup.omit(
329 ...[...WsRpcGroup.requests.keys()].filter(
330 (
331 tag,
332 ): tag is Exclude<
333 keyof typeof RPC_REQUIRED_SCOPES,
334 typeof WS_METHODS.gitPreparePullRequestThread
335 > => tag !== WS_METHODS.gitPreparePullRequestThread,
336 ),
337 );
338 let handled = false;
339 const client = yield* RpcTest.makeClient(group).pipe(
340 Effect.provide(
341 Layer.mergeAll(
342 group.toLayerHandler(WS_METHODS.gitPreparePullRequestThread, () =>
343 Effect.sync(() => {
344 handled = true;
345 }).pipe(Effect.andThen(Effect.never)),
346 ),
347 RpcAuthorization.layer([AuthSourceControlWriteScope]),
348 ),
349 ),
350 );
351 expect(
352 yield* client[WS_METHODS.gitPreparePullRequestThread]({
353 cwd: "/repo",
354 reference: "42",
355 mode: "worktree",
356 threadId: ThreadId.make("thread"),
357 }).pipe(Effect.flip),
358 ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope });
359 expect(handled).toBe(false);
360 }).pipe(Effect.scoped),
361);
362​
363it.effect("separates host file URLs from readable attachment URLs", () =>
364 Effect.gen(function* () {
365 const group = WsRpcGroup.omit(
366 ...[...WsRpcGroup.requests.keys()].filter(
367 (
368 tag,
369 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.assetsCreateUrl> =>
370 tag !== WS_METHODS.assetsCreateUrl,
371 ),
372 );
373 let handled = 0;
374 const client = yield* RpcTest.makeClient(group).pipe(
375 Effect.provide(
376 Layer.mergeAll(
377 group.toLayerHandler(WS_METHODS.assetsCreateUrl, () =>
378 Effect.sync(() => {
379 handled++;
380 return { relativeUrl: "/api/assets/file", expiresAt: 1 };
381 }),
382 ),
383 RpcAuthorization.layer([AuthOrchestrationReadScope]),
384 ),
385 ),
386 );
387 yield* client[WS_METHODS.assetsCreateUrl]({
388 resource: { _tag: "attachment", attachmentId: "image" },
389 });
390 for (const resource of [
391 { _tag: "workspace-file", threadId: ThreadId.make("thread"), path: "file.txt" },
392 { _tag: "media-file", threadId: ThreadId.make("thread"), path: "/repo/image.png" },
393 { _tag: "draft-workspace-file", cwd: "/repo", path: "file.txt" },
394 ] as const) {
395 expect(
396 yield* client[WS_METHODS.assetsCreateUrl]({ resource }).pipe(Effect.flip),
397 ).toMatchObject({
398 requiredScope: AuthOrchestrationReadScope,
399 requiredPermission: AuthFilesystemReadScope,
400 });
401 }
402 expect(handled).toBe(1);
403 }).pipe(Effect.scoped),
404);