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

RpcAuthorization.test.ts

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