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

RpcAuthorization.test.ts

380 lines13.3 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 AuthTerminalReadScope,
14 AuthTerminalOperateScope,
15 WS_METHODS,
16 WsRpcGroup,
17} from "@t3tools/contracts";
18import { describe, expect, it } from "@effect/vitest";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Stream from "effect/Stream";
22import * as RpcTest from "effect/rpc/RpcTest";
23​
24import {
25 RPC_REQUIRED_SCOPES,
26 requiredScopeForRpcMethod,
27 requiredScopeForDeviceList,
28} from "./RpcAuthorization.ts";
29import * as RpcAuthorization from "./RpcAuthorization.ts";
30​
31describe("RPC authorization scopes", () => {
32 it("declares exactly one scope for every RPC in the server group", () => {
33 expect(new Set(Object.keys(RPC_REQUIRED_SCOPES))).toEqual(new Set(WsRpcGroup.requests.keys()));
34 });
35​
36 it("keeps webhook delivery logs, which hold request bodies, behind operate scope", () => {
37 for (const method of [
38 WS_METHODS.scheduledTasksListWebhookDeliveries,
39 WS_METHODS.scheduledTasksGetWebhookDelivery,
40 WS_METHODS.scheduledTasksRotateWebhookToken,
41 ]) {
42 expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationOperateScope);
43 }
44 });
45​
46 it("keeps triage, which seeds an agent that reads logs and the database, behind operate scope", () => {
47 expect(requiredScopeForRpcMethod(WS_METHODS.serverPrepareTriage)).toBe(
48 AuthOrchestrationOperateScope,
49 );
50 });
51​
52 it("separates passive terminal observation from operations that can change a shell", () => {
53 for (const method of [
54 WS_METHODS.terminalObserve,
55 WS_METHODS.subscribeTerminalEvents,
56 WS_METHODS.subscribeTerminalMetadata,
57 ]) {
58 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalReadScope);
59 }
60 for (const method of [
61 WS_METHODS.terminalAttach,
62 WS_METHODS.terminalOpen,
63 WS_METHODS.terminalWrite,
64 WS_METHODS.terminalResize,
65 WS_METHODS.terminalClear,
66 WS_METHODS.terminalRestart,
67 WS_METHODS.terminalClose,
68 WS_METHODS.previewStopLocalServer,
69 ]) {
70 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalOperateScope);
71 }
72 });
73​
74 it("rejects unknown RPC method names", () => {
75 for (const method of ["server.notRegistered", "toString", "constructor"]) {
76 expect(() => requiredScopeForRpcMethod(method)).toThrow(
77 `RPC method ${method} has no declared authorization scope.`,
78 );
79 }
80 });
81});
82​
83it("requires operate permission for host retry while preserving read-only listing", () => {
84 expect(requiredScopeForDeviceList({})).toBe(AuthOrchestrationReadScope);
85 expect(requiredScopeForDeviceList({ retryHostId: "remote-host" })).toBe(
86 AuthOrchestrationOperateScope,
87 );
88});
89​
90it("requires operate permission for tool updates even alongside a read-only check", () => {
91 expect(requiredScopeForDeviceList({ updateTool: "agent", inspectOnly: true })).toBe(
92 AuthOrchestrationOperateScope,
93 );
94 expect(requiredScopeForDeviceList({ updateTool: "hub" })).toBe(AuthOrchestrationOperateScope);
95});
96​
97describe("RPC scope middleware", () => {
98 const tested = [WS_METHODS.serverProbe, WS_METHODS.serverRetryResourceTelemetry] as const;
99 const group = WsRpcGroup.omit(
100 ...[...WsRpcGroup.requests.keys()].filter(
101 (tag): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, (typeof tested)[number]> =>
102 !(tested as ReadonlyArray<string>).includes(tag),
103 ),
104 );
105​
106 it.effect.each([
107 { scopes: [AuthOrchestrationReadScope], missing: AuthEnvironmentMaintainScope },
108 {
109 scopes: [AuthOrchestrationReadScope, AuthEnvironmentMaintainScope],
110 missing: AuthDiagnosticsReadScope,
111 },
112 ])("rejects telemetry retry without $missing before its handler runs", ({ scopes, missing }) =>
113 Effect.gen(function* () {
114 const handled: Array<string> = [];
115 const client = yield* RpcTest.makeClient(group).pipe(
116 Effect.provide(
117 Layer.mergeAll(
118 group.toLayerHandler(WS_METHODS.serverProbe, () => Effect.succeed({})),
119 group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () =>
120 Effect.sync(() => handled.push("retry")).pipe(Effect.andThen(Effect.never)),
121 ),
122 RpcAuthorization.layer(scopes),
123 ),
124 ),
125 );
126​
127 expect(yield* client[WS_METHODS.serverProbe]({})).toEqual({});
128 expect(
129 yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(Effect.flip),
130 ).toMatchObject({
131 _tag: "EnvironmentAuthorizationError",
132 requiredPermission: missing,
133 });
134 expect(handled).toEqual([]);
135 }).pipe(Effect.scoped),
136 );
137});
138​
139describe("settings mutation authorization", () => {
140 const group = WsRpcGroup.omit(
141 ...[...WsRpcGroup.requests.keys()].filter(
142 (
143 tag,
144 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.serverUpdateSettings> =>
145 tag !== WS_METHODS.serverUpdateSettings,
146 ),
147 );
148 const providerInstanceMutation = {
149 operation: "remove" as const,
150 instanceId: ProviderInstanceId.make("codex_work"),
151 };
152​
153 it.effect("allows provider-only mutations while denying mixed settings without their grant", () =>
154 Effect.gen(function* () {
155 let handled = 0;
156 const client = yield* RpcTest.makeClient(group).pipe(
157 Effect.provide(
158 Layer.mergeAll(
159 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
160 Effect.sync(() => {
161 handled++;
162 return DEFAULT_SERVER_SETTINGS;
163 }),
164 ),
165 RpcAuthorization.layer([AuthProvidersManageScope]),
166 ),
167 ),
168 );
169 yield* client[WS_METHODS.serverUpdateSettings]({ patch: {}, providerInstanceMutation });
170 expect(handled).toBe(1);
171 expect(
172 yield* client[WS_METHODS.serverUpdateSettings]({
173 patch: { defaultRuntimeMode: "full-access" },
174 providerInstanceMutation,
175 }).pipe(Effect.flip),
176 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
177 expect(handled).toBe(1);
178 }).pipe(Effect.scoped),
179 );
180​
181 it.effect("does not let a settings grant create or remove providers", () =>
182 Effect.gen(function* () {
183 let handled = false;
184 const client = yield* RpcTest.makeClient(group).pipe(
185 Effect.provide(
186 Layer.mergeAll(
187 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
188 Effect.sync(() => {
189 handled = true;
190 return DEFAULT_SERVER_SETTINGS;
191 }),
192 ),
193 RpcAuthorization.layer([AuthSettingsWriteScope]),
194 ),
195 ),
196 );
197 expect(
198 yield* client[WS_METHODS.serverUpdateSettings]({
199 patch: {},
200 providerInstanceMutation,
201 }).pipe(Effect.flip),
202 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
203 expect(handled).toBe(false);
204 }).pipe(Effect.scoped),
205 );
206});
207​
208it.effect("requires task permission before attaching a prepared worktree to a thread", () =>
209 Effect.gen(function* () {
210 const group = WsRpcGroup.omit(
211 ...[...WsRpcGroup.requests.keys()].filter(
212 (
213 tag,
214 ): tag is Exclude<
215 keyof typeof RPC_REQUIRED_SCOPES,
216 typeof WS_METHODS.gitPreparePullRequestThread
217 > => tag !== WS_METHODS.gitPreparePullRequestThread,
218 ),
219 );
220 let handled = false;
221 const client = yield* RpcTest.makeClient(group).pipe(
222 Effect.provide(
223 Layer.mergeAll(
224 group.toLayerHandler(WS_METHODS.gitPreparePullRequestThread, () =>
225 Effect.sync(() => {
226 handled = true;
227 }).pipe(Effect.andThen(Effect.never)),
228 ),
229 RpcAuthorization.layer([AuthSourceControlWriteScope]),
230 ),
231 ),
232 );
233 expect(
234 yield* client[WS_METHODS.gitPreparePullRequestThread]({
235 cwd: "/repo",
236 reference: "42",
237 mode: "worktree",
238 threadId: ThreadId.make("thread"),
239 }).pipe(Effect.flip),
240 ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope });
241 expect(handled).toBe(false);
242 }).pipe(Effect.scoped),
243);
244​
245describe("thread context authorization", () => {
246 const group = WsRpcGroup.omit(
247 ...[...WsRpcGroup.requests.keys()].filter(
248 (
249 tag,
250 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.gitRunStackedAction> =>
251 tag !== WS_METHODS.gitRunStackedAction,
252 ),
253 );
254​
255 it.effect.each(["commit", "create_pr", "commit_push_pr"] as const)(
256 "%s needs thread read permission only when generating a PR from a thread",
257 (action) =>
258 Effect.gen(function* () {
259 const handled: string[] = [];
260 const handler = group.toLayerHandler(WS_METHODS.gitRunStackedAction, ({ actionId }) =>
261 Stream.fromEffect(Effect.sync(() => handled.push(actionId))).pipe(Stream.drain),
262 );
263 const client = yield* RpcTest.makeClient(group).pipe(
264 Effect.provide(
265 Layer.merge(handler, RpcAuthorization.layer([AuthSourceControlWriteScope])),
266 ),
267 );
268 const input = { actionId: "without-thread", cwd: "/repo", action };
269 const withThread = { ...input, actionId: "with-thread", threadId: ThreadId.make("thread") };
270 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](input));
271 if (action === "create_pr" || action === "commit_push_pr") {
272 expect(
273 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread)).pipe(
274 Effect.flip,
275 ),
276 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
277 expect(handled).toEqual(["without-thread"]);
278 } else {
279 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread));
280 expect(handled).toEqual(["without-thread", "with-thread"]);
281 }
282 const reader = yield* RpcTest.makeClient(group).pipe(
283 Effect.provide(
284 Layer.merge(
285 handler,
286 RpcAuthorization.layer([AuthSourceControlWriteScope, AuthOrchestrationReadScope]),
287 ),
288 ),
289 );
290 yield* Stream.runDrain(
291 reader[WS_METHODS.gitRunStackedAction]({ ...withThread, actionId: "allowed" }),
292 );
293 expect(handled.at(-1)).toBe("allowed");
294 }).pipe(Effect.scoped),
295 );
296});
297​
298it.effect("separates host file URLs from readable attachment URLs", () =>
299 Effect.gen(function* () {
300 const group = WsRpcGroup.omit(
301 ...[...WsRpcGroup.requests.keys()].filter(
302 (
303 tag,
304 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.assetsCreateUrl> =>
305 tag !== WS_METHODS.assetsCreateUrl,
306 ),
307 );
308 let handled = 0;
309 const client = yield* RpcTest.makeClient(group).pipe(
310 Effect.provide(
311 Layer.mergeAll(
312 group.toLayerHandler(WS_METHODS.assetsCreateUrl, () =>
313 Effect.sync(() => {
314 handled++;
315 return { relativeUrl: "/api/assets/file", expiresAt: 1 };
316 }),
317 ),
318 RpcAuthorization.layer([AuthOrchestrationReadScope]),
319 ),
320 ),
321 );
322 yield* client[WS_METHODS.assetsCreateUrl]({
323 resource: { _tag: "attachment", attachmentId: "image" },
324 });
325 for (const resource of [
326 { _tag: "workspace-file", threadId: ThreadId.make("thread"), path: "file.txt" },
327 { _tag: "media-file", threadId: ThreadId.make("thread"), path: "/repo/image.png" },
328 { _tag: "draft-workspace-file", cwd: "/repo", path: "file.txt" },
329 ] as const) {
330 expect(
331 yield* client[WS_METHODS.assetsCreateUrl]({ resource }).pipe(Effect.flip),
332 ).toMatchObject({
333 requiredScope: AuthOrchestrationReadScope,
334 requiredPermission: AuthFilesystemReadScope,
335 });
336 }
337 expect(handled).toBe(1);
338 }).pipe(Effect.scoped),
339);
340​
341it.effect("denies manual cleanup before the handler without settings permission", () =>
342 Effect.gen(function* () {
343 const group = WsRpcGroup.omit(
344 ...[...WsRpcGroup.requests.keys()].filter(
345 (
346 tag,
347 ): tag is Exclude<
348 keyof typeof RPC_REQUIRED_SCOPES,
349 typeof WS_METHODS.serverRunStorageCleanup
350 > => tag !== WS_METHODS.serverRunStorageCleanup,
351 ),
352 );
353 let handled = false;
354 const client = yield* RpcTest.makeClient(group).pipe(
355 Effect.provide(
356 Layer.mergeAll(
357 group.toLayerHandler(WS_METHODS.serverRunStorageCleanup, () =>
358 Effect.sync(() => {
359 handled = true;
360 return {
361 trigger: "manual" as const,
362 startedAt: "2026-10-09T12:00:00.000Z",
363 finishedAt: "2026-10-09T12:00:00.000Z",
364 entries: [],
365 counts: { removed: 0, kept: 0, failed: 0 },
366 omittedCount: 0,
367 bytesFreed: 0,
368 };
369 }),
370 ),
371 RpcAuthorization.layer([AuthOrchestrationReadScope]),
372 ),
373 ),
374 );
375 expect(yield* client[WS_METHODS.serverRunStorageCleanup]({}).pipe(Effect.flip)).toMatchObject({
376 requiredPermission: AuthSettingsWriteScope,
377 });
378 expect(handled).toBe(false);
379 }).pipe(Effect.scoped),
380);