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

RpcAuthorization.test.ts

482 lines17.1 KB

1import {
2 AuthEnvironmentMaintainScope,
3 AuthDiagnosticsReadScope,
4 AuthFilesystemReadScope,
5 AuthProvidersManageScope,
6 AuthSettingsWriteScope,
7 AuthAccessWriteScope,
8 DEFAULT_SERVER_SETTINGS,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 SecretProviderId,
12 ThreadId,
13 AuthOrchestrationOperateScope,
14 AuthOrchestrationReadScope,
15 AuthSourceControlWriteScope,
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 Stream from "effect/Stream";
25import * as RpcTest from "effect/rpc/RpcTest";
26​
27import {
28 RPC_REQUIRED_SCOPES,
29 requiredScopeForRpcMethod,
30 requiredScopeForDeviceList,
31} from "./RpcAuthorization.ts";
32import * as RpcAuthorization from "./RpcAuthorization.ts";
33​
34describe("RPC authorization scopes", () => {
35 it("declares exactly one scope for every RPC in the server group", () => {
36 expect(new Set(Object.keys(RPC_REQUIRED_SCOPES))).toEqual(new Set(WsRpcGroup.requests.keys()));
37 });
38​
39 it("keeps webhook delivery logs, which hold request bodies, behind operate scope", () => {
40 for (const method of [
41 WS_METHODS.scheduledTasksListWebhookDeliveries,
42 WS_METHODS.scheduledTasksGetWebhookDelivery,
43 WS_METHODS.scheduledTasksRotateWebhookToken,
44 ]) {
45 expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationOperateScope);
46 }
47 });
48​
49 it("keeps triage, which seeds an agent that reads logs and the database, behind operate scope", () => {
50 expect(requiredScopeForRpcMethod(WS_METHODS.serverPrepareTriage)).toBe(
51 AuthOrchestrationOperateScope,
52 );
53 });
54​
55 it("separates passive terminal observation from operations that can change a shell", () => {
56 for (const method of [WS_METHODS.terminalObserve, WS_METHODS.subscribeTerminalMetadata]) {
57 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalReadScope);
58 }
59 for (const method of [
60 WS_METHODS.terminalAttach,
61 WS_METHODS.terminalOpen,
62 WS_METHODS.terminalWrite,
63 WS_METHODS.terminalResize,
64 WS_METHODS.terminalClear,
65 WS_METHODS.terminalClose,
66 WS_METHODS.previewStopLocalServer,
67 ]) {
68 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalOperateScope);
69 }
70 });
71​
72 it("lets thread readers observe and refresh checkout branches", () => {
73 for (const method of [WS_METHODS.subscribeVcsBranch, WS_METHODS.vcsRefreshBranch]) {
74 expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationReadScope);
75 }
76 });
77​
78 it("rejects unknown RPC method names", () => {
79 for (const method of ["server.notRegistered", "toString", "constructor"]) {
80 expect(() => requiredScopeForRpcMethod(method)).toThrow(
81 `RPC method ${method} has no declared authorization scope.`,
82 );
83 }
84 });
85});
86​
87it("requires operate permission for host retry while preserving read-only listing", () => {
88 expect(requiredScopeForDeviceList({})).toBe(AuthOrchestrationReadScope);
89 expect(requiredScopeForDeviceList({ retryHostId: "remote-host" })).toBe(
90 AuthOrchestrationOperateScope,
91 );
92});
93​
94it("requires operate permission for tool updates even alongside a read-only check", () => {
95 expect(requiredScopeForDeviceList({ updateTool: "agent", inspectOnly: true })).toBe(
96 AuthOrchestrationOperateScope,
97 );
98 expect(requiredScopeForDeviceList({ updateTool: "hub" })).toBe(AuthOrchestrationOperateScope);
99});
100​
101describe("RPC scope middleware", () => {
102 const tested = [WS_METHODS.serverProbe, WS_METHODS.serverRetryResourceTelemetry] as const;
103 const group = WsRpcGroup.omit(
104 ...[...WsRpcGroup.requests.keys()].filter(
105 (tag): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, (typeof tested)[number]> =>
106 !(tested as ReadonlyArray<string>).includes(tag),
107 ),
108 );
109​
110 it.effect.each([
111 { scopes: [AuthOrchestrationReadScope], missing: AuthEnvironmentMaintainScope },
112 {
113 scopes: [AuthOrchestrationReadScope, AuthEnvironmentMaintainScope],
114 missing: AuthDiagnosticsReadScope,
115 },
116 ])("rejects telemetry retry without $missing before its handler runs", ({ scopes, missing }) =>
117 Effect.gen(function* () {
118 const handled: Array<string> = [];
119 const client = yield* RpcTest.makeClient(group).pipe(
120 Effect.provide(
121 Layer.mergeAll(
122 group.toLayerHandler(WS_METHODS.serverProbe, () => Effect.succeed({})),
123 group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () =>
124 Effect.sync(() => handled.push("retry")).pipe(Effect.andThen(Effect.never)),
125 ),
126 RpcAuthorization.layer(scopes),
127 ),
128 ),
129 );
130​
131 expect(yield* client[WS_METHODS.serverProbe]({})).toEqual({});
132 expect(
133 yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(Effect.flip),
134 ).toMatchObject({
135 _tag: "EnvironmentAuthorizationError",
136 requiredPermission: missing,
137 });
138 expect(handled).toEqual([]);
139 }),
140 );
141});
142​
143it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as const)(
144 "enforces read permission on stream %s",
145 (method) =>
146 Effect.gen(function* () {
147 const group = WsRpcGroup.omit(
148 ...[...WsRpcGroup.requests.keys()].filter(
149 (
150 tag,
151 ): tag is Exclude<
152 keyof typeof RPC_REQUIRED_SCOPES,
153 typeof WS_METHODS.subscribeVcsBranch | typeof WS_METHODS.subscribeVcsStatus
154 > => tag !== WS_METHODS.subscribeVcsBranch && tag !== WS_METHODS.subscribeVcsStatus,
155 ),
156 );
157 let handled = 0;
158 const handlers = Layer.mergeAll(
159 group.toLayerHandler(WS_METHODS.subscribeVcsBranch, () =>
160 Stream.fromEffect(
161 Effect.sync(() => {
162 handled++;
163 return { refName: "main" };
164 }),
165 ),
166 ),
167 group.toLayerHandler(WS_METHODS.subscribeVcsStatus, () =>
168 Stream.fromEffect(
169 Effect.sync(() => {
170 handled++;
171 }),
172 ).pipe(Stream.drain),
173 ),
174 );
175 const denied = yield* RpcTest.makeClient(group).pipe(
176 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([]))),
177 );
178 expect(
179 yield* Stream.runDrain(
180 method === WS_METHODS.subscribeVcsBranch
181 ? denied[method]({ cwd: "/repo" }).pipe(Stream.drain)
182 : denied[method]({ cwd: "/repo" }).pipe(Stream.drain),
183 ).pipe(Effect.flip),
184 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
185 expect(handled).toBe(0);
186 const granted = yield* RpcTest.makeClient(group).pipe(
187 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthOrchestrationReadScope]))),
188 );
189 yield* Stream.runDrain(
190 method === WS_METHODS.subscribeVcsBranch
191 ? granted[method]({ cwd: "/repo" }).pipe(Stream.drain)
192 : granted[method]({ cwd: "/repo" }).pipe(Stream.drain),
193 );
194 expect(handled).toBe(1);
195 }),
196);
197​
198describe("settings mutation authorization", () => {
199 const group = WsRpcGroup.omit(
200 ...[...WsRpcGroup.requests.keys()].filter(
201 (
202 tag,
203 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.serverUpdateSettings> =>
204 tag !== WS_METHODS.serverUpdateSettings,
205 ),
206 );
207 const providerInstanceMutation = {
208 operation: "remove" as const,
209 instanceId: ProviderInstanceId.make("codex_work"),
210 };
211​
212 it.effect("allows provider-only mutations while denying mixed settings without their grant", () =>
213 Effect.gen(function* () {
214 let handled = 0;
215 const client = yield* RpcTest.makeClient(group).pipe(
216 Effect.provide(
217 Layer.mergeAll(
218 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
219 Effect.sync(() => {
220 handled++;
221 return DEFAULT_SERVER_SETTINGS;
222 }),
223 ),
224 RpcAuthorization.layer([AuthProvidersManageScope]),
225 ),
226 ),
227 );
228 yield* client[WS_METHODS.serverUpdateSettings]({ patch: {}, providerInstanceMutation });
229 expect(handled).toBe(1);
230 yield* client[WS_METHODS.serverUpdateSettings]({
231 patch: {},
232 providerInstanceMutation: {
233 operation: "upsert",
234 instanceId: ProviderInstanceId.make("codex_work"),
235 instance: {
236 driver: ProviderDriverKind.make("codex"),
237 environment: [
238 {
239 name: "OPENAI_API_KEY",
240 sensitive: true,
241 value: {
242 provider: SecretProviderId.make("personal"),
243 reference: "op://Private/OpenAI/credential",
244 },
245 },
246 ],
247 },
248 },
249 });
250 expect(handled).toBe(2);
251 expect(
252 yield* client[WS_METHODS.serverUpdateSettings]({
253 patch: { defaultRuntimeMode: "full-access" },
254 providerInstanceMutation,
255 }).pipe(Effect.flip),
256 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
257 // Removing a secret provider clears settings fields that read from it.
258 expect(
259 yield* client[WS_METHODS.serverUpdateSettings]({
260 patch: { secretProviders: { [SecretProviderId.make("personal")]: null } },
261 }).pipe(Effect.flip),
262 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
263 expect(handled).toBe(2);
264 }),
265 );
266​
267 it.effect(
268 "does not let a settings grant manage providers or turn off T3 Connect device approval",
269 () =>
270 Effect.gen(function* () {
271 let handled = false;
272 const client = yield* RpcTest.makeClient(group).pipe(
273 Effect.provide(
274 Layer.mergeAll(
275 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
276 Effect.sync(() => {
277 handled = true;
278 return DEFAULT_SERVER_SETTINGS;
279 }),
280 ),
281 RpcAuthorization.layer([AuthSettingsWriteScope]),
282 ),
283 ),
284 );
285 expect(
286 yield* client[WS_METHODS.serverUpdateSettings]({
287 patch: {},
288 providerInstanceMutation,
289 }).pipe(Effect.flip),
290 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
291 expect(
292 yield* client[WS_METHODS.serverUpdateSettings]({
293 patch: { secretProviders: { [SecretProviderId.make("personal")]: null } },
294 }).pipe(Effect.flip),
295 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
296 expect(
297 yield* client[WS_METHODS.serverUpdateSettings]({
298 patch: { requireConnectDeviceApproval: false },
299 }).pipe(Effect.flip),
300 ).toMatchObject({ requiredPermission: AuthAccessWriteScope });
301 expect(handled).toBe(false);
302 }),
303 );
304});
305​
306it.effect("requires task permission before attaching a prepared worktree to a thread", () =>
307 Effect.gen(function* () {
308 const group = WsRpcGroup.omit(
309 ...[...WsRpcGroup.requests.keys()].filter(
310 (
311 tag,
312 ): tag is Exclude<
313 keyof typeof RPC_REQUIRED_SCOPES,
314 typeof WS_METHODS.gitPreparePullRequestThread
315 > => tag !== WS_METHODS.gitPreparePullRequestThread,
316 ),
317 );
318 let handled = false;
319 const client = yield* RpcTest.makeClient(group).pipe(
320 Effect.provide(
321 Layer.mergeAll(
322 group.toLayerHandler(WS_METHODS.gitPreparePullRequestThread, () =>
323 Effect.sync(() => {
324 handled = true;
325 }).pipe(Effect.andThen(Effect.never)),
326 ),
327 RpcAuthorization.layer([AuthSourceControlWriteScope]),
328 ),
329 ),
330 );
331 expect(
332 yield* client[WS_METHODS.gitPreparePullRequestThread]({
333 cwd: "/repo",
334 reference: "42",
335 mode: "worktree",
336 threadId: ThreadId.make("thread"),
337 }).pipe(Effect.flip),
338 ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope });
339 expect(handled).toBe(false);
340 }),
341);
342​
343describe("thread context authorization", () => {
344 const group = WsRpcGroup.omit(
345 ...[...WsRpcGroup.requests.keys()].filter(
346 (
347 tag,
348 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.gitRunStackedAction> =>
349 tag !== WS_METHODS.gitRunStackedAction,
350 ),
351 );
352​
353 it.effect.each(["commit", "create_pr", "commit_push_pr"] as const)(
354 "%s needs thread read permission only when generating a PR from a thread",
355 (action) =>
356 Effect.gen(function* () {
357 const handled: string[] = [];
358 const handler = group.toLayerHandler(WS_METHODS.gitRunStackedAction, ({ actionId }) =>
359 Stream.fromEffect(Effect.sync(() => handled.push(actionId))).pipe(Stream.drain),
360 );
361 const client = yield* RpcTest.makeClient(group).pipe(
362 Effect.provide(
363 Layer.merge(handler, RpcAuthorization.layer([AuthSourceControlWriteScope])),
364 ),
365 );
366 const input = { actionId: "without-thread", cwd: "/repo", action };
367 const withThread = { ...input, actionId: "with-thread", threadId: ThreadId.make("thread") };
368 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](input));
369 if (action === "create_pr" || action === "commit_push_pr") {
370 expect(
371 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread)).pipe(
372 Effect.flip,
373 ),
374 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
375 expect(handled).toEqual(["without-thread"]);
376 } else {
377 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread));
378 expect(handled).toEqual(["without-thread", "with-thread"]);
379 }
380 const reader = yield* RpcTest.makeClient(group).pipe(
381 Effect.provide(
382 Layer.merge(
383 handler,
384 RpcAuthorization.layer([AuthSourceControlWriteScope, AuthOrchestrationReadScope]),
385 ),
386 ),
387 );
388 yield* Stream.runDrain(
389 reader[WS_METHODS.gitRunStackedAction]({ ...withThread, actionId: "allowed" }),
390 );
391 expect(handled.at(-1)).toBe("allowed");
392 }),
393 );
394});
395​
396it.effect("separates host file URLs from readable attachment URLs", () =>
397 Effect.gen(function* () {
398 const group = WsRpcGroup.omit(
399 ...[...WsRpcGroup.requests.keys()].filter(
400 (
401 tag,
402 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.assetsCreateUrl> =>
403 tag !== WS_METHODS.assetsCreateUrl,
404 ),
405 );
406 let handled = 0;
407 const client = yield* RpcTest.makeClient(group).pipe(
408 Effect.provide(
409 Layer.mergeAll(
410 group.toLayerHandler(WS_METHODS.assetsCreateUrl, () =>
411 Effect.sync(() => {
412 handled++;
413 return { relativeUrl: "/api/assets/file", expiresAt: 1 };
414 }),
415 ),
416 RpcAuthorization.layer([AuthOrchestrationReadScope]),
417 ),
418 ),
419 );
420 yield* client[WS_METHODS.assetsCreateUrl]({
421 resource: { _tag: "attachment", attachmentId: "image" },
422 });
423 yield* client[WS_METHODS.assetsCreateUrl]({
424 resource: { _tag: "native-app-icon", app: { _tag: "app-id", appId: "com.apple.calculator" } },
425 });
426 for (const resource of [
427 { _tag: "workspace-file", threadId: ThreadId.make("thread"), path: "file.txt" },
428 { _tag: "media-file", threadId: ThreadId.make("thread"), path: "/repo/image.png" },
429 { _tag: "draft-workspace-file", cwd: "/repo", path: "file.txt" },
430 { _tag: "native-app-icon", app: { _tag: "app-path", path: "/private/Secret.app" } },
431 ] as const) {
432 expect(
433 yield* client[WS_METHODS.assetsCreateUrl]({ resource }).pipe(Effect.flip),
434 ).toMatchObject({
435 requiredScope: AuthOrchestrationReadScope,
436 requiredPermission: AuthFilesystemReadScope,
437 });
438 }
439 expect(handled).toBe(2);
440 }),
441);
442​
443it.effect("denies manual cleanup before the handler without settings permission", () =>
444 Effect.gen(function* () {
445 const group = WsRpcGroup.omit(
446 ...[...WsRpcGroup.requests.keys()].filter(
447 (
448 tag,
449 ): tag is Exclude<
450 keyof typeof RPC_REQUIRED_SCOPES,
451 typeof WS_METHODS.serverRunStorageCleanup
452 > => tag !== WS_METHODS.serverRunStorageCleanup,
453 ),
454 );
455 let handled = false;
456 const client = yield* RpcTest.makeClient(group).pipe(
457 Effect.provide(
458 Layer.mergeAll(
459 group.toLayerHandler(WS_METHODS.serverRunStorageCleanup, () =>
460 Effect.sync(() => {
461 handled = true;
462 return {
463 trigger: "manual" as const,
464 startedAt: "2026-10-09T12:00:00.000Z",
465 finishedAt: "2026-10-09T12:00:00.000Z",
466 entries: [],
467 counts: { removed: 0, kept: 0, failed: 0 },
468 omittedCount: 0,
469 bytesFreed: 0,
470 };
471 }),
472 ),
473 RpcAuthorization.layer([AuthOrchestrationReadScope]),
474 ),
475 ),
476 );
477 expect(yield* client[WS_METHODS.serverRunStorageCleanup]({}).pipe(Effect.flip)).toMatchObject({
478 requiredPermission: AuthSettingsWriteScope,
479 });
480 expect(handled).toBe(false);
481 }),
482);