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

RpcAuthorization.test.ts

608 lines21.6 KB

1import {
2 AuthEnvironmentMaintainScope,
3 AuthDiagnosticsReadScope,
4 AuthFilesystemReadScope,
5 AuthProvidersManageScope,
6 AuthSettingsWriteScope,
7 AuthAccessWriteScope,
8 DEFAULT_SERVER_SETTINGS,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 ProjectId,
12 IssueTrackerKind,
13 SecretProviderId,
14 ThreadId,
15 AuthOrchestrationOperateScope,
16 AuthOrchestrationReadScope,
17 AuthSourceControlWriteScope,
18 AuthTerminalReadScope,
19 AuthTerminalOperateScope,
20 WS_METHODS,
21 WsRpcGroup,
22} from "@t3tools/contracts";
23import { describe, expect, it } from "@effect/vitest";
24import * as Effect from "effect/Effect";
25import * as Layer from "effect/Layer";
26import * as Stream from "effect/Stream";
27import * as RpcTest from "effect/rpc/RpcTest";
28​
29import {
30 RPC_REQUIRED_SCOPES,
31 requiredScopeForRpcMethod,
32 requiredScopeForDeviceList,
33} from "./RpcAuthorization.ts";
34import * as RpcAuthorization from "./RpcAuthorization.ts";
35​
36describe("RPC authorization scopes", () => {
37 it("declares exactly one scope for every RPC in the server group", () => {
38 expect(new Set(Object.keys(RPC_REQUIRED_SCOPES))).toEqual(new Set(WsRpcGroup.requests.keys()));
39 });
40​
41 it("keeps webhook delivery logs, which hold request bodies, behind operate scope", () => {
42 for (const method of [
43 WS_METHODS.scheduledTasksListWebhookDeliveries,
44 WS_METHODS.scheduledTasksGetWebhookDelivery,
45 WS_METHODS.scheduledTasksRotateWebhookToken,
46 ]) {
47 expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationOperateScope);
48 }
49 });
50​
51 it("keeps triage, which seeds an agent that reads logs and the database, behind operate scope", () => {
52 expect(requiredScopeForRpcMethod(WS_METHODS.serverPrepareTriage)).toBe(
53 AuthOrchestrationOperateScope,
54 );
55 });
56​
57 it("separates passive terminal observation from operations that can change a shell", () => {
58 for (const method of [WS_METHODS.terminalObserve, WS_METHODS.subscribeTerminalMetadata]) {
59 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalReadScope);
60 }
61 for (const method of [
62 WS_METHODS.terminalAttach,
63 WS_METHODS.terminalOpen,
64 WS_METHODS.terminalWrite,
65 WS_METHODS.terminalResize,
66 WS_METHODS.terminalClear,
67 WS_METHODS.terminalClose,
68 WS_METHODS.previewStopLocalServer,
69 ]) {
70 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalOperateScope);
71 }
72 });
73​
74 it("lets thread readers observe and refresh checkout branches", () => {
75 for (const method of [WS_METHODS.subscribeVcsBranch, WS_METHODS.vcsRefreshBranch]) {
76 expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationReadScope);
77 }
78 });
79​
80 it("still lets readers load settings the way installed Swift clients ask", () => {
81 expect(requiredScopeForRpcMethod("server.getSettings")).toBe(AuthOrchestrationReadScope);
82 });
83​
84 it("rejects unknown RPC method names", () => {
85 for (const method of ["server.notRegistered", "toString", "constructor"]) {
86 expect(() => requiredScopeForRpcMethod(method)).toThrow(
87 `RPC method ${method} has no declared authorization scope.`,
88 );
89 }
90 });
91});
92​
93it("requires operate permission for host retry while preserving read-only listing", () => {
94 expect(requiredScopeForDeviceList({})).toBe(AuthOrchestrationReadScope);
95 expect(requiredScopeForDeviceList({ retryHostId: "remote-host" })).toBe(
96 AuthOrchestrationOperateScope,
97 );
98});
99​
100it("requires operate permission for tool updates even alongside a read-only check", () => {
101 expect(requiredScopeForDeviceList({ updateTool: "agent", inspectOnly: true })).toBe(
102 AuthOrchestrationOperateScope,
103 );
104 expect(requiredScopeForDeviceList({ updateTool: "hub" })).toBe(AuthOrchestrationOperateScope);
105});
106​
107describe("RPC scope middleware", () => {
108 const tested = [WS_METHODS.serverProbe, WS_METHODS.serverRetryResourceTelemetry] as const;
109 const group = WsRpcGroup.omit(
110 ...[...WsRpcGroup.requests.keys()].filter(
111 (tag): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, (typeof tested)[number]> =>
112 !(tested as ReadonlyArray<string>).includes(tag),
113 ),
114 );
115​
116 it.effect.each([
117 { scopes: [AuthOrchestrationReadScope], missing: AuthEnvironmentMaintainScope },
118 {
119 scopes: [AuthOrchestrationReadScope, AuthEnvironmentMaintainScope],
120 missing: AuthDiagnosticsReadScope,
121 },
122 ])("rejects telemetry retry without $missing before its handler runs", ({ scopes, missing }) =>
123 Effect.gen(function* () {
124 const handled: Array<string> = [];
125 const client = yield* RpcTest.makeClient(group).pipe(
126 Effect.provide(
127 Layer.mergeAll(
128 group.toLayerHandler(WS_METHODS.serverProbe, () => Effect.succeed({})),
129 group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () =>
130 Effect.sync(() => handled.push("retry")).pipe(Effect.andThen(Effect.never)),
131 ),
132 RpcAuthorization.layer(scopes),
133 ),
134 ),
135 );
136​
137 expect(yield* client[WS_METHODS.serverProbe]({})).toEqual({});
138 expect(
139 yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(Effect.flip),
140 ).toMatchObject({
141 _tag: "EnvironmentAuthorizationError",
142 requiredPermission: missing,
143 });
144 expect(handled).toEqual([]);
145 }),
146 );
147});
148​
149it.effect("allows issue reads but requires a source-control grant before commenting", () =>
150 Effect.gen(function* () {
151 const tested = [WS_METHODS.issuesList, WS_METHODS.issuesComment] as const;
152 const group = WsRpcGroup.omit(
153 ...[...WsRpcGroup.requests.keys()].filter(
154 (tag): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, (typeof tested)[number]> =>
155 !(tested as ReadonlyArray<string>).includes(tag),
156 ),
157 );
158 const comments: string[] = [];
159 const handlers = Layer.mergeAll(
160 group.toLayerHandler(WS_METHODS.issuesList, () =>
161 Effect.succeed({ entries: [], trackers: [], errors: [], viewers: {}, nextCursors: {} }),
162 ),
163 group.toLayerHandler(WS_METHODS.issuesComment, ({ body }) =>
164 Effect.sync(() => {
165 comments.push(body);
166 }),
167 ),
168 );
169 const reader = yield* RpcTest.makeClient(group).pipe(
170 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthOrchestrationReadScope]))),
171 );
172 const comment = {
173 projectId: ProjectId.make("web"),
174 tracker: IssueTrackerKind.make("github"),
175 scope: "acme/web",
176 key: "42",
177 body: "Repro attached.",
178 };
179​
180 expect((yield* reader[WS_METHODS.issuesList]({ state: "open" })).entries).toEqual([]);
181 expect(yield* reader[WS_METHODS.issuesComment](comment).pipe(Effect.flip)).toMatchObject({
182 _tag: "EnvironmentAuthorizationError",
183 requiredPermission: AuthSourceControlWriteScope,
184 });
185 expect(comments).toEqual([]);
186​
187 const writer = yield* RpcTest.makeClient(group).pipe(
188 Effect.provide(
189 Layer.merge(
190 handlers,
191 RpcAuthorization.layer([AuthOrchestrationReadScope, AuthSourceControlWriteScope]),
192 ),
193 ),
194 );
195 yield* writer[WS_METHODS.issuesComment](comment);
196 expect(comments).toEqual(["Repro attached."]);
197 }).pipe(Effect.scoped),
198);
199​
200it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as const)(
201 "enforces read permission on stream %s",
202 (method) =>
203 Effect.gen(function* () {
204 const group = WsRpcGroup.omit(
205 ...[...WsRpcGroup.requests.keys()].filter(
206 (
207 tag,
208 ): tag is Exclude<
209 keyof typeof RPC_REQUIRED_SCOPES,
210 typeof WS_METHODS.subscribeVcsBranch | typeof WS_METHODS.subscribeVcsStatus
211 > => tag !== WS_METHODS.subscribeVcsBranch && tag !== WS_METHODS.subscribeVcsStatus,
212 ),
213 );
214 let handled = 0;
215 const handlers = Layer.mergeAll(
216 group.toLayerHandler(WS_METHODS.subscribeVcsBranch, () =>
217 Stream.fromEffect(
218 Effect.sync(() => {
219 handled++;
220 return { refName: "main" };
221 }),
222 ),
223 ),
224 group.toLayerHandler(WS_METHODS.subscribeVcsStatus, () =>
225 Stream.fromEffect(
226 Effect.sync(() => {
227 handled++;
228 }),
229 ).pipe(Stream.drain),
230 ),
231 );
232 const denied = yield* RpcTest.makeClient(group).pipe(
233 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([]))),
234 );
235 expect(
236 yield* Stream.runDrain(
237 method === WS_METHODS.subscribeVcsBranch
238 ? denied[method]({ cwd: "/repo" }).pipe(Stream.drain)
239 : denied[method]({ cwd: "/repo" }).pipe(Stream.drain),
240 ).pipe(Effect.flip),
241 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
242 expect(handled).toBe(0);
243 const granted = yield* RpcTest.makeClient(group).pipe(
244 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthOrchestrationReadScope]))),
245 );
246 yield* Stream.runDrain(
247 method === WS_METHODS.subscribeVcsBranch
248 ? granted[method]({ cwd: "/repo" }).pipe(Stream.drain)
249 : granted[method]({ cwd: "/repo" }).pipe(Stream.drain),
250 );
251 expect(handled).toBe(1);
252 }),
253);
254​
255describe("settings mutation authorization", () => {
256 const group = WsRpcGroup.omit(
257 ...[...WsRpcGroup.requests.keys()].filter(
258 (
259 tag,
260 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.serverUpdateSettings> =>
261 tag !== WS_METHODS.serverUpdateSettings,
262 ),
263 );
264 const providerInstanceMutation = {
265 operation: "remove" as const,
266 instanceId: ProviderInstanceId.make("codex_work"),
267 };
268​
269 it.effect("allows provider-only mutations while denying mixed settings without their grant", () =>
270 Effect.gen(function* () {
271 let handled = 0;
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++;
278 return DEFAULT_SERVER_SETTINGS;
279 }),
280 ),
281 RpcAuthorization.layer([AuthProvidersManageScope]),
282 ),
283 ),
284 );
285 yield* client[WS_METHODS.serverUpdateSettings]({ patch: {}, providerInstanceMutation });
286 expect(handled).toBe(1);
287 yield* client[WS_METHODS.serverUpdateSettings]({
288 patch: {},
289 providerInstanceMutation: {
290 operation: "upsert",
291 instanceId: ProviderInstanceId.make("codex_work"),
292 instance: {
293 driver: ProviderDriverKind.make("codex"),
294 environment: [
295 {
296 name: "OPENAI_API_KEY",
297 sensitive: true,
298 value: {
299 provider: SecretProviderId.make("personal"),
300 reference: "op://Private/OpenAI/credential",
301 },
302 },
303 ],
304 },
305 },
306 });
307 expect(handled).toBe(2);
308 expect(
309 yield* client[WS_METHODS.serverUpdateSettings]({
310 patch: { defaultRuntimeMode: "full-access" },
311 providerInstanceMutation,
312 }).pipe(Effect.flip),
313 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
314 // Removing a secret provider clears settings fields that read from it.
315 expect(
316 yield* client[WS_METHODS.serverUpdateSettings]({
317 patch: { secretProviders: { [SecretProviderId.make("personal")]: null } },
318 }).pipe(Effect.flip),
319 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
320 expect(handled).toBe(2);
321 }),
322 );
323​
324 it.effect(
325 "does not let a settings grant manage providers or turn off T3 Connect device approval",
326 () =>
327 Effect.gen(function* () {
328 let handled = false;
329 const client = yield* RpcTest.makeClient(group).pipe(
330 Effect.provide(
331 Layer.mergeAll(
332 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
333 Effect.sync(() => {
334 handled = true;
335 return DEFAULT_SERVER_SETTINGS;
336 }),
337 ),
338 RpcAuthorization.layer([AuthSettingsWriteScope]),
339 ),
340 ),
341 );
342 expect(
343 yield* client[WS_METHODS.serverUpdateSettings]({
344 patch: {},
345 providerInstanceMutation,
346 }).pipe(Effect.flip),
347 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
348 expect(
349 yield* client[WS_METHODS.serverUpdateSettings]({
350 patch: { secretProviders: { [SecretProviderId.make("personal")]: null } },
351 }).pipe(Effect.flip),
352 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
353 expect(
354 yield* client[WS_METHODS.serverUpdateSettings]({
355 patch: { requireConnectDeviceApproval: false },
356 }).pipe(Effect.flip),
357 ).toMatchObject({ requiredPermission: AuthAccessWriteScope });
358 // A reference names any secret the store holds, and the host entry names where it goes.
359 expect(
360 yield* client[WS_METHODS.serverUpdateSettings]({
361 patch: {
362 simlockDeviceHosts: [
363 {
364 kind: "simlock",
365 id: "simlock_evil",
366 label: "Gateway",
367 gatewayUrl: "https://attacker.example",
368 agentToken: {
369 provider: SecretProviderId.make("personal"),
370 reference: "op://Private/OpenAI/credential",
371 },
372 maxLeases: 2,
373 maxLeaseMinutes: 60,
374 },
375 ],
376 },
377 }).pipe(Effect.flip),
378 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
379 expect(handled).toBe(false);
380 }),
381 );
382​
383 it.effect("does not let a settings grant send a named secret to a gateway it picks", () =>
384 Effect.gen(function* () {
385 const group = WsRpcGroup.omit(
386 ...[...WsRpcGroup.requests.keys()].filter(
387 (
388 tag,
389 ): tag is Exclude<
390 keyof typeof RPC_REQUIRED_SCOPES,
391 typeof WS_METHODS.deviceSimlockIdentity
392 > => tag !== WS_METHODS.deviceSimlockIdentity,
393 ),
394 );
395 let handled = 0;
396 const client = yield* RpcTest.makeClient(group).pipe(
397 Effect.provide(
398 Layer.mergeAll(
399 group.toLayerHandler(WS_METHODS.deviceSimlockIdentity, () =>
400 Effect.sync(() => {
401 handled++;
402 return {
403 gatewayUrl: "https://attacker.example",
404 signedInAs: "agent",
405 tokenSource: "entered" as const,
406 };
407 }),
408 ),
409 RpcAuthorization.layer([AuthSettingsWriteScope]),
410 ),
411 ),
412 );
413 yield* client[WS_METHODS.deviceSimlockIdentity]({
414 gatewayUrl: "https://attacker.example",
415 agentToken: "typed-token",
416 });
417 expect(handled).toBe(1);
418 expect(
419 yield* client[WS_METHODS.deviceSimlockIdentity]({
420 gatewayUrl: "https://attacker.example",
421 agentToken: {
422 provider: SecretProviderId.make("personal"),
423 reference: "op://Private/OpenAI/credential",
424 },
425 }).pipe(Effect.flip),
426 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
427 expect(handled).toBe(1);
428 }),
429 );
430});
431​
432it.effect("requires task permission before attaching a prepared worktree to a thread", () =>
433 Effect.gen(function* () {
434 const group = WsRpcGroup.omit(
435 ...[...WsRpcGroup.requests.keys()].filter(
436 (
437 tag,
438 ): tag is Exclude<
439 keyof typeof RPC_REQUIRED_SCOPES,
440 typeof WS_METHODS.gitPreparePullRequestThread
441 > => tag !== WS_METHODS.gitPreparePullRequestThread,
442 ),
443 );
444 let handled = false;
445 const client = yield* RpcTest.makeClient(group).pipe(
446 Effect.provide(
447 Layer.mergeAll(
448 group.toLayerHandler(WS_METHODS.gitPreparePullRequestThread, () =>
449 Effect.sync(() => {
450 handled = true;
451 }).pipe(Effect.andThen(Effect.never)),
452 ),
453 RpcAuthorization.layer([AuthSourceControlWriteScope]),
454 ),
455 ),
456 );
457 expect(
458 yield* client[WS_METHODS.gitPreparePullRequestThread]({
459 cwd: "/repo",
460 reference: "42",
461 mode: "worktree",
462 threadId: ThreadId.make("thread"),
463 }).pipe(Effect.flip),
464 ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope });
465 expect(handled).toBe(false);
466 }),
467);
468​
469describe("thread context authorization", () => {
470 const group = WsRpcGroup.omit(
471 ...[...WsRpcGroup.requests.keys()].filter(
472 (
473 tag,
474 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.gitRunStackedAction> =>
475 tag !== WS_METHODS.gitRunStackedAction,
476 ),
477 );
478​
479 it.effect.each(["commit", "create_pr", "commit_push_pr"] as const)(
480 "%s needs thread read permission only when generating a PR from a thread",
481 (action) =>
482 Effect.gen(function* () {
483 const handled: string[] = [];
484 const handler = group.toLayerHandler(WS_METHODS.gitRunStackedAction, ({ actionId }) =>
485 Stream.fromEffect(Effect.sync(() => handled.push(actionId))).pipe(Stream.drain),
486 );
487 const client = yield* RpcTest.makeClient(group).pipe(
488 Effect.provide(
489 Layer.merge(handler, RpcAuthorization.layer([AuthSourceControlWriteScope])),
490 ),
491 );
492 const input = { actionId: "without-thread", cwd: "/repo", action };
493 const withThread = { ...input, actionId: "with-thread", threadId: ThreadId.make("thread") };
494 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](input));
495 if (action === "create_pr" || action === "commit_push_pr") {
496 expect(
497 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread)).pipe(
498 Effect.flip,
499 ),
500 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
501 expect(handled).toEqual(["without-thread"]);
502 } else {
503 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread));
504 expect(handled).toEqual(["without-thread", "with-thread"]);
505 }
506 const reader = yield* RpcTest.makeClient(group).pipe(
507 Effect.provide(
508 Layer.merge(
509 handler,
510 RpcAuthorization.layer([AuthSourceControlWriteScope, AuthOrchestrationReadScope]),
511 ),
512 ),
513 );
514 yield* Stream.runDrain(
515 reader[WS_METHODS.gitRunStackedAction]({ ...withThread, actionId: "allowed" }),
516 );
517 expect(handled.at(-1)).toBe("allowed");
518 }),
519 );
520});
521​
522it.effect("separates host file URLs from readable attachment URLs", () =>
523 Effect.gen(function* () {
524 const group = WsRpcGroup.omit(
525 ...[...WsRpcGroup.requests.keys()].filter(
526 (
527 tag,
528 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.assetsCreateUrl> =>
529 tag !== WS_METHODS.assetsCreateUrl,
530 ),
531 );
532 let handled = 0;
533 const client = yield* RpcTest.makeClient(group).pipe(
534 Effect.provide(
535 Layer.mergeAll(
536 group.toLayerHandler(WS_METHODS.assetsCreateUrl, () =>
537 Effect.sync(() => {
538 handled++;
539 return { relativeUrl: "/api/assets/file", expiresAt: 1 };
540 }),
541 ),
542 RpcAuthorization.layer([AuthOrchestrationReadScope]),
543 ),
544 ),
545 );
546 yield* client[WS_METHODS.assetsCreateUrl]({
547 resource: { _tag: "attachment", attachmentId: "image" },
548 });
549 yield* client[WS_METHODS.assetsCreateUrl]({
550 resource: { _tag: "native-app-icon", app: { _tag: "app-id", appId: "com.apple.calculator" } },
551 });
552 for (const resource of [
553 { _tag: "workspace-file", threadId: ThreadId.make("thread"), path: "file.txt" },
554 { _tag: "media-file", threadId: ThreadId.make("thread"), path: "/repo/image.png" },
555 { _tag: "draft-workspace-file", cwd: "/repo", path: "file.txt" },
556 { _tag: "native-app-icon", app: { _tag: "app-path", path: "/private/Secret.app" } },
557 ] as const) {
558 expect(
559 yield* client[WS_METHODS.assetsCreateUrl]({ resource }).pipe(Effect.flip),
560 ).toMatchObject({
561 requiredScope: AuthOrchestrationReadScope,
562 requiredPermission: AuthFilesystemReadScope,
563 });
564 }
565 expect(handled).toBe(2);
566 }),
567);
568​
569it.effect("denies manual cleanup before the handler without settings permission", () =>
570 Effect.gen(function* () {
571 const group = WsRpcGroup.omit(
572 ...[...WsRpcGroup.requests.keys()].filter(
573 (
574 tag,
575 ): tag is Exclude<
576 keyof typeof RPC_REQUIRED_SCOPES,
577 typeof WS_METHODS.serverRunStorageCleanup
578 > => tag !== WS_METHODS.serverRunStorageCleanup,
579 ),
580 );
581 let handled = false;
582 const client = yield* RpcTest.makeClient(group).pipe(
583 Effect.provide(
584 Layer.mergeAll(
585 group.toLayerHandler(WS_METHODS.serverRunStorageCleanup, () =>
586 Effect.sync(() => {
587 handled = true;
588 return {
589 trigger: "manual" as const,
590 startedAt: "2026-10-09T12:00:00.000Z",
591 finishedAt: "2026-10-09T12:00:00.000Z",
592 entries: [],
593 counts: { removed: 0, kept: 0, failed: 0 },
594 omittedCount: 0,
595 bytesFreed: 0,
596 };
597 }),
598 ),
599 RpcAuthorization.layer([AuthOrchestrationReadScope]),
600 ),
601 ),
602 );
603 expect(yield* client[WS_METHODS.serverRunStorageCleanup]({}).pipe(Effect.flip)).toMatchObject({
604 requiredPermission: AuthSettingsWriteScope,
605 });
606 expect(handled).toBe(false);
607 }),
608);