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

RpcAuthorization.test.ts

381 lines13.5 KB

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