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

RpcAuthorization.test.ts

1,031 lines37.0 KB

1import {
2 AuthEnvironmentMaintainScope,
3 AuthDiagnosticsReadScope,
4 AuthFilesystemReadScope,
5 AuthProvidersManageScope,
6 AuthSettingsWriteScope,
7 AuthAccessWriteScope,
8 DEFAULT_SERVER_SETTINGS,
9 EnvironmentId,
10 ProviderDriverKind,
11 ProviderInstanceId,
12 ProjectId,
13 IssueTrackerKind,
14 SecretProviderId,
15 ThreadId,
16 TurnItemId,
17 AuthOrchestrationOperateScope,
18 AuthOrchestrationReadScope,
19 AuthSourceControlWriteScope,
20 AuthTerminalReadScope,
21 AuthTerminalOperateScope,
22 CommandId,
23 MessageId,
24 ORCHESTRATION_V2_WS_METHODS,
25 RunId,
26 WS_METHODS,
27 WsRpcGroup,
28} from "@t3tools/contracts";
29import { describe, expect, it } from "@effect/vitest";
30import * as Effect from "effect/Effect";
31import * as Layer from "effect/Layer";
32import * as Stream from "effect/Stream";
33import * as RpcTest from "effect/rpc/RpcTest";
34​
35import {
36 RPC_REQUIRED_SCOPES,
37 requiredScopeForRpcMethod,
38 requiredScopeForDeviceList,
39} from "./RpcAuthorization.ts";
40import * as RpcAuthorization from "./RpcAuthorization.ts";
41​
42describe("RPC authorization scopes", () => {
43 it("declares exactly one scope for every RPC in the server group", () => {
44 expect(new Set(Object.keys(RPC_REQUIRED_SCOPES))).toEqual(new Set(WsRpcGroup.requests.keys()));
45 });
46​
47 it("keeps webhook delivery logs, which hold request bodies, behind operate scope", () => {
48 for (const method of [
49 WS_METHODS.scheduledTasksListWebhookDeliveries,
50 WS_METHODS.scheduledTasksGetWebhookDelivery,
51 WS_METHODS.scheduledTasksRotateWebhookToken,
52 ]) {
53 expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationOperateScope);
54 }
55 });
56​
57 it("lets only a session that operates threads approve sending a feedback report", () => {
58 // Guest links have no RPC session, and read-only sessions lack this scope.
59 expect(requiredScopeForRpcMethod(WS_METHODS.agentFeedbackAnswerRequest)).toBe(
60 AuthOrchestrationOperateScope,
61 );
62 });
63​
64 it("keeps triage, which seeds an agent that reads logs and the database, behind operate scope", () => {
65 expect(requiredScopeForRpcMethod(WS_METHODS.serverPrepareTriage)).toBe(
66 AuthOrchestrationOperateScope,
67 );
68 });
69​
70 it("separates passive terminal observation from operations that can change a shell", () => {
71 for (const method of [WS_METHODS.terminalObserve, WS_METHODS.subscribeTerminalMetadata]) {
72 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalReadScope);
73 }
74 for (const method of [
75 WS_METHODS.terminalAttach,
76 WS_METHODS.terminalOpen,
77 WS_METHODS.terminalWrite,
78 WS_METHODS.terminalResize,
79 WS_METHODS.terminalClear,
80 WS_METHODS.terminalClose,
81 WS_METHODS.previewStopLocalServer,
82 ]) {
83 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalOperateScope);
84 }
85 });
86​
87 it("lets thread readers observe and refresh checkout branches", () => {
88 for (const method of [WS_METHODS.subscribeVcsBranch, WS_METHODS.vcsRefreshBranch]) {
89 expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationReadScope);
90 }
91 });
92​
93 it("lets file readers see a task folder and takes source control to add a repository to it", () => {
94 expect(requiredScopeForRpcMethod(WS_METHODS.workspaceTaskFolder)).toBe(AuthFilesystemReadScope);
95 expect(requiredScopeForRpcMethod(WS_METHODS.workspaceAddTaskFolderRepository)).toBe(
96 AuthSourceControlWriteScope,
97 );
98 });
99​
100 it("still lets readers load settings the way installed Swift clients ask", () => {
101 expect(requiredScopeForRpcMethod("server.getSettings")).toBe(AuthOrchestrationReadScope);
102 });
103​
104 it("rejects unknown RPC method names", () => {
105 for (const method of ["server.notRegistered", "toString", "constructor"]) {
106 expect(() => requiredScopeForRpcMethod(method)).toThrow(
107 `RPC method ${method} has no declared authorization scope.`,
108 );
109 }
110 });
111});
112​
113it("requires operate permission for host retry while preserving read-only listing", () => {
114 expect(requiredScopeForDeviceList({})).toBe(AuthOrchestrationReadScope);
115 expect(requiredScopeForDeviceList({ retryHostId: "remote-host" })).toBe(
116 AuthOrchestrationOperateScope,
117 );
118});
119​
120it("requires operate permission for tool updates even alongside a read-only check", () => {
121 expect(requiredScopeForDeviceList({ updateTool: "agent", inspectOnly: true })).toBe(
122 AuthOrchestrationOperateScope,
123 );
124 expect(requiredScopeForDeviceList({ updateTool: "hub" })).toBe(AuthOrchestrationOperateScope);
125});
126​
127describe("RPC scope middleware", () => {
128 const tested = [WS_METHODS.serverProbe, WS_METHODS.serverRetryResourceTelemetry] as const;
129 const group = WsRpcGroup.omit(
130 ...[...WsRpcGroup.requests.keys()].filter(
131 (tag): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, (typeof tested)[number]> =>
132 !(tested as ReadonlyArray<string>).includes(tag),
133 ),
134 );
135​
136 it.effect.each([
137 { scopes: [AuthOrchestrationReadScope], missing: AuthEnvironmentMaintainScope },
138 {
139 scopes: [AuthOrchestrationReadScope, AuthEnvironmentMaintainScope],
140 missing: AuthDiagnosticsReadScope,
141 },
142 ])("rejects telemetry retry without $missing before its handler runs", ({ scopes, missing }) =>
143 Effect.gen(function* () {
144 const handled: Array<string> = [];
145 const client = yield* RpcTest.makeClient(group).pipe(
146 Effect.provide(
147 Layer.mergeAll(
148 group.toLayerHandler(WS_METHODS.serverProbe, () => Effect.succeed({})),
149 group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () =>
150 Effect.sync(() => handled.push("retry")).pipe(Effect.andThen(Effect.never)),
151 ),
152 RpcAuthorization.layer(scopes),
153 ),
154 ),
155 );
156​
157 expect(yield* client[WS_METHODS.serverProbe]({})).toEqual({});
158 expect(
159 yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(Effect.flip),
160 ).toMatchObject({
161 _tag: "EnvironmentAuthorizationError",
162 requiredPermission: missing,
163 });
164 expect(handled).toEqual([]);
165 }),
166 );
167});
168​
169it.effect("allows issue reads but requires a source-control grant before commenting", () =>
170 Effect.gen(function* () {
171 const tested = [WS_METHODS.issuesList, WS_METHODS.issuesComment] as const;
172 const group = WsRpcGroup.omit(
173 ...[...WsRpcGroup.requests.keys()].filter(
174 (tag): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, (typeof tested)[number]> =>
175 !(tested as ReadonlyArray<string>).includes(tag),
176 ),
177 );
178 const comments: string[] = [];
179 const handlers = Layer.mergeAll(
180 group.toLayerHandler(WS_METHODS.issuesList, () =>
181 Effect.succeed({ entries: [], trackers: [], errors: [], viewers: {}, nextCursors: {} }),
182 ),
183 group.toLayerHandler(WS_METHODS.issuesComment, ({ body }) =>
184 Effect.sync(() => {
185 comments.push(body);
186 }),
187 ),
188 );
189 const reader = yield* RpcTest.makeClient(group).pipe(
190 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthOrchestrationReadScope]))),
191 );
192 const comment = {
193 projectId: ProjectId.make("web"),
194 tracker: IssueTrackerKind.make("github"),
195 scope: "acme/web",
196 key: "42",
197 body: "Repro attached.",
198 };
199​
200 expect((yield* reader[WS_METHODS.issuesList]({ state: "open" })).entries).toEqual([]);
201 expect(yield* reader[WS_METHODS.issuesComment](comment).pipe(Effect.flip)).toMatchObject({
202 _tag: "EnvironmentAuthorizationError",
203 requiredPermission: AuthSourceControlWriteScope,
204 });
205 expect(comments).toEqual([]);
206​
207 const writer = yield* RpcTest.makeClient(group).pipe(
208 Effect.provide(
209 Layer.merge(
210 handlers,
211 RpcAuthorization.layer([AuthOrchestrationReadScope, AuthSourceControlWriteScope]),
212 ),
213 ),
214 );
215 yield* writer[WS_METHODS.issuesComment](comment);
216 expect(comments).toEqual(["Repro attached."]);
217 }).pipe(Effect.scoped),
218);
219​
220it.effect("reads a linked environment's thread only for a client that may read threads here", () =>
221 Effect.gen(function* () {
222 const linkedThreadTags = [
223 WS_METHODS.peerLinksSubscribeThread,
224 WS_METHODS.peerLinksThreadHistoryPage,
225 WS_METHODS.peerLinksThreadItem,
226 WS_METHODS.peerLinksNames,
227 ] as const;
228 const group = WsRpcGroup.omit(
229 ...[...WsRpcGroup.requests.keys()].filter(
230 (
231 tag,
232 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, (typeof linkedThreadTags)[number]> =>
233 !(linkedThreadTags as ReadonlyArray<string>).includes(tag),
234 ),
235 );
236 const read: string[] = [];
237 const input = {
238 environmentId: EnvironmentId.make("environment-box"),
239 threadId: ThreadId.make("thread:box"),
240 };
241 const handlers = group.toLayer({
242 [WS_METHODS.peerLinksSubscribeThread]: ({ threadId }) =>
243 Stream.sync(() => {
244 read.push(threadId);
245 return { kind: "synchronized" as const };
246 }),
247 [WS_METHODS.peerLinksThreadHistoryPage]: () => Effect.die("unused"),
248 [WS_METHODS.peerLinksThreadItem]: ({ threadId }) =>
249 Effect.sync(() => {
250 read.push(threadId);
251 return { item: null };
252 }),
253 // A thread link resolves to the linked environment by its name.
254 [WS_METHODS.peerLinksNames]: () =>
255 Effect.succeed({ links: [{ environmentId: input.environmentId, label: "Box" }] }),
256 });
257 // Managing links and writing settings here say nothing about reading threads.
258 const outsider = yield* RpcTest.makeClient(group).pipe(
259 Effect.provide(
260 Layer.merge(
261 handlers,
262 RpcAuthorization.layer([AuthAccessWriteScope, AuthSettingsWriteScope]),
263 ),
264 ),
265 );
266 const refused = {
267 _tag: "EnvironmentAuthorizationError",
268 requiredPermission: AuthOrchestrationReadScope,
269 };
270 expect(
271 yield* outsider[WS_METHODS.peerLinksSubscribeThread](input).pipe(
272 Stream.runCollect,
273 Effect.flip,
274 ),
275 ).toMatchObject(refused);
276 expect(
277 yield* outsider[WS_METHODS.peerLinksThreadItem]({
278 ...input,
279 itemId: TurnItemId.make("item:1"),
280 }).pipe(Effect.flip),
281 ).toMatchObject(refused);
282 expect(
283 yield* outsider[WS_METHODS.peerLinksThreadHistoryPage]({ ...input, cursor: "c" }).pipe(
284 Effect.flip,
285 ),
286 ).toMatchObject(refused);
287 expect(read).toEqual([]);
288 expect(yield* outsider[WS_METHODS.peerLinksNames]({}).pipe(Effect.flip)).toMatchObject({
289 requiredPermission: AuthOrchestrationReadScope,
290 });
291​
292 const reader = yield* RpcTest.makeClient(group).pipe(
293 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthOrchestrationReadScope]))),
294 );
295 expect(
296 Array.from(yield* reader[WS_METHODS.peerLinksSubscribeThread](input).pipe(Stream.runCollect)),
297 ).toEqual([{ kind: "synchronized" }]);
298 expect(read).toEqual([input.threadId]);
299 expect((yield* reader[WS_METHODS.peerLinksNames]({})).links).toEqual([
300 { environmentId: input.environmentId, label: "Box" },
301 ]);
302 }).pipe(Effect.scoped),
303);
304​
305it.effect("pairs a client with a linked environment only for one that may hand out access", () =>
306 Effect.gen(function* () {
307 const group = WsRpcGroup.omit(
308 ...[...WsRpcGroup.requests.keys()].filter(
309 (
310 tag,
311 ): tag is Exclude<
312 keyof typeof RPC_REQUIRED_SCOPES,
313 typeof WS_METHODS.peerLinksPairClient
314 > => tag !== WS_METHODS.peerLinksPairClient,
315 ),
316 );
317 let asked = 0;
318 const environmentId = EnvironmentId.make("environment-box");
319 const handlers = group.toLayerHandler(WS_METHODS.peerLinksPairClient, () =>
320 Effect.sync(() => {
321 asked++;
322 return {
323 type: "unsupported" as const,
324 reason: "link_access" as const,
325 environmentId,
326 label: "Box",
327 urls: [],
328 };
329 }),
330 );
331 // Running agents and reading the access list do not include handing access out.
332 const operator = yield* RpcTest.makeClient(group).pipe(
333 Effect.provide(
334 Layer.merge(
335 handlers,
336 RpcAuthorization.layer([AuthOrchestrationReadScope, AuthOrchestrationOperateScope]),
337 ),
338 ),
339 );
340 expect(
341 yield* operator[WS_METHODS.peerLinksPairClient]({ environmentId }).pipe(Effect.flip),
342 ).toMatchObject({
343 _tag: "EnvironmentAuthorizationError",
344 requiredPermission: AuthAccessWriteScope,
345 });
346 expect(asked).toBe(0);
347​
348 const manager = yield* RpcTest.makeClient(group).pipe(
349 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthAccessWriteScope]))),
350 );
351 expect((yield* manager[WS_METHODS.peerLinksPairClient]({ environmentId })).type).toBe(
352 "unsupported",
353 );
354 expect(asked).toBe(1);
355 }).pipe(Effect.scoped),
356);
357​
358it.effect("hands out a link code or a guest link only within what the session itself holds", () =>
359 Effect.gen(function* () {
360 const group = WsRpcGroup.omit(
361 ...[...WsRpcGroup.requests.keys()].filter(
362 (
363 tag,
364 ): tag is Exclude<
365 keyof typeof RPC_REQUIRED_SCOPES,
366 typeof WS_METHODS.peerLinksPairLink | typeof WS_METHODS.guestShareCreate
367 > => tag !== WS_METHODS.peerLinksPairLink && tag !== WS_METHODS.guestShareCreate,
368 ),
369 );
370 let handled = 0;
371 const environmentId = EnvironmentId.make("environment-box");
372 const threadId = ThreadId.make("thread-1");
373 const handlers = Layer.mergeAll(
374 group.toLayerHandler(WS_METHODS.peerLinksPairLink, () =>
375 Effect.sync(() => {
376 handled++;
377 return {
378 type: "unsupported" as const,
379 reason: "link_access" as const,
380 environmentId,
381 label: "Box",
382 urls: [],
383 };
384 }),
385 ),
386 group.toLayerHandler(WS_METHODS.guestShareCreate, () =>
387 Effect.sync(() => handled++).pipe(Effect.andThen(Effect.die("no share in this test"))),
388 ),
389 );
390 const clientWith = (scopes: Parameters<typeof RpcAuthorization.layer>[0]) =>
391 RpcTest.makeClient(group).pipe(
392 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer(scopes))),
393 );
394​
395 // Managing access alone is not running agents or reading threads.
396 const manager = yield* clientWith([AuthAccessWriteScope]);
397 expect(
398 yield* manager[WS_METHODS.peerLinksPairLink]({ environmentId, access: "read-only" }).pipe(
399 Effect.flip,
400 ),
401 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
402 expect(
403 yield* manager[WS_METHODS.guestShareCreate]({ threadId }).pipe(Effect.flip),
404 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
405​
406 const supervisor = yield* clientWith([
407 AuthAccessWriteScope,
408 AuthOrchestrationReadScope,
409 AuthOrchestrationOperateScope,
410 ]);
411 expect(
412 yield* supervisor[WS_METHODS.peerLinksPairLink]({
413 environmentId,
414 access: "full-access",
415 }).pipe(Effect.flip),
416 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
417 expect(handled).toBe(0);
418​
419 expect(
420 (yield* supervisor[WS_METHODS.peerLinksPairLink]({ environmentId, access: "auto" })).type,
421 ).toBe("unsupported");
422 expect(handled).toBe(1);
423 yield* supervisor[WS_METHODS.guestShareCreate]({ threadId }).pipe(Effect.exit);
424 expect(handled).toBe(2);
425 }).pipe(Effect.scoped),
426);
427​
428it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as const)(
429 "enforces read permission on stream %s",
430 (method) =>
431 Effect.gen(function* () {
432 const group = WsRpcGroup.omit(
433 ...[...WsRpcGroup.requests.keys()].filter(
434 (
435 tag,
436 ): tag is Exclude<
437 keyof typeof RPC_REQUIRED_SCOPES,
438 typeof WS_METHODS.subscribeVcsBranch | typeof WS_METHODS.subscribeVcsStatus
439 > => tag !== WS_METHODS.subscribeVcsBranch && tag !== WS_METHODS.subscribeVcsStatus,
440 ),
441 );
442 let handled = 0;
443 const handlers = Layer.mergeAll(
444 group.toLayerHandler(WS_METHODS.subscribeVcsBranch, () =>
445 Stream.fromEffect(
446 Effect.sync(() => {
447 handled++;
448 return { refName: "main" };
449 }),
450 ),
451 ),
452 group.toLayerHandler(WS_METHODS.subscribeVcsStatus, () =>
453 Stream.fromEffect(
454 Effect.sync(() => {
455 handled++;
456 }),
457 ).pipe(Stream.drain),
458 ),
459 );
460 const denied = yield* RpcTest.makeClient(group).pipe(
461 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([]))),
462 );
463 expect(
464 yield* Stream.runDrain(
465 method === WS_METHODS.subscribeVcsBranch
466 ? denied[method]({ cwd: "/repo" }).pipe(Stream.drain)
467 : denied[method]({ cwd: "/repo" }).pipe(Stream.drain),
468 ).pipe(Effect.flip),
469 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
470 expect(handled).toBe(0);
471 const granted = yield* RpcTest.makeClient(group).pipe(
472 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthOrchestrationReadScope]))),
473 );
474 yield* Stream.runDrain(
475 method === WS_METHODS.subscribeVcsBranch
476 ? granted[method]({ cwd: "/repo" }).pipe(Stream.drain)
477 : granted[method]({ cwd: "/repo" }).pipe(Stream.drain),
478 );
479 expect(handled).toBe(1);
480 }),
481);
482​
483describe("settings mutation authorization", () => {
484 const group = WsRpcGroup.omit(
485 ...[...WsRpcGroup.requests.keys()].filter(
486 (
487 tag,
488 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.serverUpdateSettings> =>
489 tag !== WS_METHODS.serverUpdateSettings,
490 ),
491 );
492 const providerInstanceMutation = {
493 operation: "remove" as const,
494 instanceId: ProviderInstanceId.make("codex_work"),
495 };
496​
497 it.effect("allows provider-only mutations while denying mixed settings without their grant", () =>
498 Effect.gen(function* () {
499 let handled = 0;
500 const client = yield* RpcTest.makeClient(group).pipe(
501 Effect.provide(
502 Layer.mergeAll(
503 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
504 Effect.sync(() => {
505 handled++;
506 return DEFAULT_SERVER_SETTINGS;
507 }),
508 ),
509 RpcAuthorization.layer([AuthProvidersManageScope]),
510 ),
511 ),
512 );
513 yield* client[WS_METHODS.serverUpdateSettings]({ patch: {}, providerInstanceMutation });
514 expect(handled).toBe(1);
515 yield* client[WS_METHODS.serverUpdateSettings]({
516 patch: {},
517 providerInstanceMutation: {
518 operation: "upsert",
519 instanceId: ProviderInstanceId.make("codex_work"),
520 instance: {
521 driver: ProviderDriverKind.make("codex"),
522 environment: [
523 {
524 name: "OPENAI_API_KEY",
525 sensitive: true,
526 value: {
527 provider: SecretProviderId.make("personal"),
528 reference: "op://Private/OpenAI/credential",
529 },
530 },
531 ],
532 },
533 },
534 });
535 expect(handled).toBe(2);
536 expect(
537 yield* client[WS_METHODS.serverUpdateSettings]({
538 patch: { defaultRuntimeMode: "full-access" },
539 providerInstanceMutation,
540 }).pipe(Effect.flip),
541 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
542 // Removing a secret provider clears settings fields that read from it.
543 expect(
544 yield* client[WS_METHODS.serverUpdateSettings]({
545 patch: { secretProviders: { [SecretProviderId.make("personal")]: null } },
546 }).pipe(Effect.flip),
547 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
548 expect(handled).toBe(2);
549 }),
550 );
551​
552 it.effect(
553 "does not let a settings grant manage providers or turn off T3 Connect device approval",
554 () =>
555 Effect.gen(function* () {
556 let handled = false;
557 const client = yield* RpcTest.makeClient(group).pipe(
558 Effect.provide(
559 Layer.mergeAll(
560 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
561 Effect.sync(() => {
562 handled = true;
563 return DEFAULT_SERVER_SETTINGS;
564 }),
565 ),
566 RpcAuthorization.layer([AuthSettingsWriteScope]),
567 ),
568 ),
569 );
570 expect(
571 yield* client[WS_METHODS.serverUpdateSettings]({
572 patch: {},
573 providerInstanceMutation,
574 }).pipe(Effect.flip),
575 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
576 expect(
577 yield* client[WS_METHODS.serverUpdateSettings]({
578 patch: { secretProviders: { [SecretProviderId.make("personal")]: null } },
579 }).pipe(Effect.flip),
580 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
581 expect(
582 yield* client[WS_METHODS.serverUpdateSettings]({
583 patch: { requireConnectDeviceApproval: false },
584 }).pipe(Effect.flip),
585 ).toMatchObject({ requiredPermission: AuthAccessWriteScope });
586 // A reference names any secret the store holds, and the host entry names where it goes.
587 expect(
588 yield* client[WS_METHODS.serverUpdateSettings]({
589 patch: {
590 simlockDeviceHosts: [
591 {
592 kind: "simlock",
593 id: "simlock_evil",
594 label: "Gateway",
595 gatewayUrl: "https://attacker.example",
596 agentToken: {
597 provider: SecretProviderId.make("personal"),
598 reference: "op://Private/OpenAI/credential",
599 },
600 maxLeases: 2,
601 maxLeaseMinutes: 60,
602 },
603 ],
604 },
605 }).pipe(Effect.flip),
606 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
607 expect(handled).toBe(false);
608 }),
609 );
610​
611 it.effect("saving project scripts needs task operation as well as the settings grant", () =>
612 Effect.gen(function* () {
613 const projectId = ProjectId.make("project-1");
614 const scripts = [
615 {
616 id: "setup",
617 name: "Setup",
618 command: "pnpm install",
619 icon: "play" as const,
620 runOnWorktreeCreate: true,
621 },
622 ];
623 const update = (scopes: Parameters<typeof RpcAuthorization.layer>[0]) => {
624 let handled = 0;
625 return RpcTest.makeClient(group).pipe(
626 Effect.provide(
627 Layer.mergeAll(
628 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
629 Effect.sync(() => {
630 handled++;
631 return DEFAULT_SERVER_SETTINGS;
632 }),
633 ),
634 RpcAuthorization.layer(scopes),
635 ),
636 ),
637 Effect.map((client) => ({ client, handled: () => handled })),
638 );
639 };
640 const patches = [
641 { defaultProjectScripts: scripts },
642 { projectScriptOverrides: { [projectId]: scripts } },
643 { projectSettingsOverrides: { [projectId]: { defaultProjectScripts: scripts } } },
644 ];
645​
646 const settingsOnly = yield* update([AuthSettingsWriteScope]);
647 for (const patch of patches) {
648 expect(
649 yield* settingsOnly.client[WS_METHODS.serverUpdateSettings]({ patch }).pipe(Effect.flip),
650 ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope });
651 }
652 expect(settingsOnly.handled()).toBe(0);
653 // Settings that carry no script stay with the settings grant alone.
654 yield* settingsOnly.client[WS_METHODS.serverUpdateSettings]({
655 patch: {
656 defaultAutoPull: true,
657 projectScriptOverrides: { [projectId]: null },
658 projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } },
659 },
660 });
661 expect(settingsOnly.handled()).toBe(1);
662​
663 const operator = yield* update([AuthSettingsWriteScope, AuthOrchestrationOperateScope]);
664 for (const patch of patches) {
665 yield* operator.client[WS_METHODS.serverUpdateSettings]({ patch });
666 }
667 expect(operator.handled()).toBe(patches.length);
668 }),
669 );
670​
671 it.effect("does not let a settings grant send a named secret to a gateway it picks", () =>
672 Effect.gen(function* () {
673 const group = WsRpcGroup.omit(
674 ...[...WsRpcGroup.requests.keys()].filter(
675 (
676 tag,
677 ): tag is Exclude<
678 keyof typeof RPC_REQUIRED_SCOPES,
679 typeof WS_METHODS.deviceSimlockIdentity
680 > => tag !== WS_METHODS.deviceSimlockIdentity,
681 ),
682 );
683 let handled = 0;
684 const client = yield* RpcTest.makeClient(group).pipe(
685 Effect.provide(
686 Layer.mergeAll(
687 group.toLayerHandler(WS_METHODS.deviceSimlockIdentity, () =>
688 Effect.sync(() => {
689 handled++;
690 return {
691 gatewayUrl: "https://attacker.example",
692 signedInAs: "agent",
693 tokenSource: "entered" as const,
694 };
695 }),
696 ),
697 RpcAuthorization.layer([AuthSettingsWriteScope]),
698 ),
699 ),
700 );
701 yield* client[WS_METHODS.deviceSimlockIdentity]({
702 gatewayUrl: "https://attacker.example",
703 agentToken: "typed-token",
704 });
705 expect(handled).toBe(1);
706 expect(
707 yield* client[WS_METHODS.deviceSimlockIdentity]({
708 gatewayUrl: "https://attacker.example",
709 agentToken: {
710 provider: SecretProviderId.make("personal"),
711 reference: "op://Private/OpenAI/credential",
712 },
713 }).pipe(Effect.flip),
714 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
715 expect(handled).toBe(1);
716 }),
717 );
718});
719​
720it.effect("answering a secret request with a reference needs provider management", () =>
721 Effect.gen(function* () {
722 const group = WsRpcGroup.omit(
723 ...[...WsRpcGroup.requests.keys()].filter(
724 (
725 tag,
726 ): tag is Exclude<
727 keyof typeof RPC_REQUIRED_SCOPES,
728 typeof WS_METHODS.secretsAnswerRequest
729 > => tag !== WS_METHODS.secretsAnswerRequest,
730 ),
731 );
732 const handled: string[] = [];
733 const handler = group.toLayerHandler(WS_METHODS.secretsAnswerRequest, ({ answer }) =>
734 Effect.sync(() => {
735 handled.push(answer.type);
736 }),
737 );
738 const clientWith = (...scopes: Parameters<typeof RpcAuthorization.layer>[0]) =>
739 RpcTest.makeClient(group).pipe(
740 Effect.provide(Layer.merge(handler, RpcAuthorization.layer(scopes))),
741 );
742 const request = { threadId: ThreadId.make("thread"), turnItemId: TurnItemId.make("item") };
743 const reference = {
744 type: "reference" as const,
745 reference: {
746 provider: SecretProviderId.make("personal"),
747 reference: "op://Private/OpenAI/credential",
748 },
749 };
750​
751 const operate = yield* clientWith(AuthOrchestrationOperateScope);
752 expect(
753 yield* operate[WS_METHODS.secretsAnswerRequest]({ ...request, answer: reference }).pipe(
754 Effect.flip,
755 ),
756 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
757 expect(handled).toEqual([]);
758 // Typed values stay with the scope that runs the thread, whatever the fields are called.
759 yield* operate[WS_METHODS.secretsAnswerRequest]({
760 ...request,
761 answer: { type: "save", secret: "typed-value" },
762 });
763 yield* operate[WS_METHODS.secretsAnswerRequest]({
764 ...request,
765 answer: { type: "save", values: { provider: "personal", reference: "typed-value" } },
766 });
767 expect(handled).toEqual(["save", "save"]);
768​
769 const manage = yield* clientWith(AuthOrchestrationOperateScope, AuthProvidersManageScope);
770 yield* manage[WS_METHODS.secretsAnswerRequest]({ ...request, answer: reference });
771 expect(handled).toEqual(["save", "save", "reference"]);
772 const manageOnly = yield* clientWith(AuthProvidersManageScope);
773 expect(
774 yield* manageOnly[WS_METHODS.secretsAnswerRequest]({ ...request, answer: reference }).pipe(
775 Effect.flip,
776 ),
777 ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope });
778 }),
779);
780​
781it.effect("requires task permission before attaching a prepared worktree to a thread", () =>
782 Effect.gen(function* () {
783 const group = WsRpcGroup.omit(
784 ...[...WsRpcGroup.requests.keys()].filter(
785 (
786 tag,
787 ): tag is Exclude<
788 keyof typeof RPC_REQUIRED_SCOPES,
789 typeof WS_METHODS.gitPreparePullRequestThread
790 > => tag !== WS_METHODS.gitPreparePullRequestThread,
791 ),
792 );
793 let handled = false;
794 const client = yield* RpcTest.makeClient(group).pipe(
795 Effect.provide(
796 Layer.mergeAll(
797 group.toLayerHandler(WS_METHODS.gitPreparePullRequestThread, () =>
798 Effect.sync(() => {
799 handled = true;
800 }).pipe(Effect.andThen(Effect.never)),
801 ),
802 RpcAuthorization.layer([AuthSourceControlWriteScope]),
803 ),
804 ),
805 );
806 expect(
807 yield* client[WS_METHODS.gitPreparePullRequestThread]({
808 cwd: "/repo",
809 reference: "42",
810 mode: "worktree",
811 threadId: ThreadId.make("thread"),
812 }).pipe(Effect.flip),
813 ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope });
814 expect(handled).toBe(false);
815 }),
816);
817​
818describe("thread context authorization", () => {
819 const group = WsRpcGroup.omit(
820 ...[...WsRpcGroup.requests.keys()].filter(
821 (
822 tag,
823 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.gitRunStackedAction> =>
824 tag !== WS_METHODS.gitRunStackedAction,
825 ),
826 );
827​
828 it.effect.each(["commit", "create_pr", "commit_push_pr"] as const)(
829 "%s needs thread read permission only when generating a PR from a thread",
830 (action) =>
831 Effect.gen(function* () {
832 const handled: string[] = [];
833 const handler = group.toLayerHandler(WS_METHODS.gitRunStackedAction, ({ actionId }) =>
834 Stream.fromEffect(Effect.sync(() => handled.push(actionId))).pipe(Stream.drain),
835 );
836 const client = yield* RpcTest.makeClient(group).pipe(
837 Effect.provide(
838 Layer.merge(handler, RpcAuthorization.layer([AuthSourceControlWriteScope])),
839 ),
840 );
841 const input = { actionId: "without-thread", cwd: "/repo", action };
842 const withThread = { ...input, actionId: "with-thread", threadId: ThreadId.make("thread") };
843 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](input));
844 if (action === "create_pr" || action === "commit_push_pr") {
845 expect(
846 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread)).pipe(
847 Effect.flip,
848 ),
849 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
850 expect(handled).toEqual(["without-thread"]);
851 } else {
852 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread));
853 expect(handled).toEqual(["without-thread", "with-thread"]);
854 }
855 const reader = yield* RpcTest.makeClient(group).pipe(
856 Effect.provide(
857 Layer.merge(
858 handler,
859 RpcAuthorization.layer([AuthSourceControlWriteScope, AuthOrchestrationReadScope]),
860 ),
861 ),
862 );
863 yield* Stream.runDrain(
864 reader[WS_METHODS.gitRunStackedAction]({ ...withThread, actionId: "allowed" }),
865 );
866 expect(handled.at(-1)).toBe("allowed");
867 }),
868 );
869});
870​
871it.effect("separates host file URLs from readable attachment URLs", () =>
872 Effect.gen(function* () {
873 const group = WsRpcGroup.omit(
874 ...[...WsRpcGroup.requests.keys()].filter(
875 (
876 tag,
877 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.assetsCreateUrl> =>
878 tag !== WS_METHODS.assetsCreateUrl,
879 ),
880 );
881 let handled = 0;
882 const client = yield* RpcTest.makeClient(group).pipe(
883 Effect.provide(
884 Layer.mergeAll(
885 group.toLayerHandler(WS_METHODS.assetsCreateUrl, () =>
886 Effect.sync(() => {
887 handled++;
888 return { relativeUrl: "/api/assets/file", expiresAt: 1 };
889 }),
890 ),
891 RpcAuthorization.layer([AuthOrchestrationReadScope]),
892 ),
893 ),
894 );
895 yield* client[WS_METHODS.assetsCreateUrl]({
896 resource: { _tag: "attachment", attachmentId: "image" },
897 });
898 yield* client[WS_METHODS.assetsCreateUrl]({
899 resource: { _tag: "native-app-icon", app: { _tag: "app-id", appId: "com.apple.calculator" } },
900 });
901 for (const resource of [
902 { _tag: "workspace-file", threadId: ThreadId.make("thread"), path: "file.txt" },
903 { _tag: "media-file", threadId: ThreadId.make("thread"), path: "/repo/image.png" },
904 { _tag: "draft-workspace-file", cwd: "/repo", path: "file.txt" },
905 { _tag: "native-app-icon", app: { _tag: "app-path", path: "/private/Secret.app" } },
906 ] as const) {
907 expect(
908 yield* client[WS_METHODS.assetsCreateUrl]({ resource }).pipe(Effect.flip),
909 ).toMatchObject({
910 requiredScope: AuthOrchestrationReadScope,
911 requiredPermission: AuthFilesystemReadScope,
912 });
913 }
914 expect(handled).toBe(2);
915 }),
916);
917​
918it.effect("denies manual cleanup before the handler without settings permission", () =>
919 Effect.gen(function* () {
920 const group = WsRpcGroup.omit(
921 ...[...WsRpcGroup.requests.keys()].filter(
922 (
923 tag,
924 ): tag is Exclude<
925 keyof typeof RPC_REQUIRED_SCOPES,
926 typeof WS_METHODS.serverRunStorageCleanup
927 > => tag !== WS_METHODS.serverRunStorageCleanup,
928 ),
929 );
930 let handled = false;
931 const client = yield* RpcTest.makeClient(group).pipe(
932 Effect.provide(
933 Layer.mergeAll(
934 group.toLayerHandler(WS_METHODS.serverRunStorageCleanup, () =>
935 Effect.sync(() => {
936 handled = true;
937 return {
938 trigger: "manual" as const,
939 startedAt: "2026-10-09T12:00:00.000Z",
940 finishedAt: "2026-10-09T12:00:00.000Z",
941 entries: [],
942 counts: { removed: 0, kept: 0, failed: 0 },
943 omittedCount: 0,
944 bytesFreed: 0,
945 };
946 }),
947 ),
948 RpcAuthorization.layer([AuthOrchestrationReadScope]),
949 ),
950 ),
951 );
952 expect(yield* client[WS_METHODS.serverRunStorageCleanup]({}).pipe(Effect.flip)).toMatchObject({
953 requiredPermission: AuthSettingsWriteScope,
954 });
955 expect(handled).toBe(false);
956 }),
957);
958​
959it.effect("requires provider management to send /logout through chat", () =>
960 Effect.gen(function* () {
961 const group = WsRpcGroup.omit(
962 ...[...WsRpcGroup.requests.keys()].filter(
963 (
964 tag,
965 ): tag is Exclude<
966 keyof typeof RPC_REQUIRED_SCOPES,
967 typeof ORCHESTRATION_V2_WS_METHODS.dispatchCommand
968 > => tag !== ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
969 ),
970 );
971 const handled: string[] = [];
972 const handler = group.toLayerHandler(ORCHESTRATION_V2_WS_METHODS.dispatchCommand, (command) =>
973 Effect.sync(() => {
974 handled.push(command.commandId);
975 return { sequence: 1 };
976 }),
977 );
978 const message = (commandId: string, text: string) => ({
979 type: "message.dispatch" as const,
980 createdBy: "user" as const,
981 creationSource: "web" as const,
982 commandId: CommandId.make(commandId),
983 threadId: ThreadId.make("thread"),
984 messageId: MessageId.make(commandId),
985 text,
986 attachments: [],
987 dispatchMode: { type: "start_immediately" as const },
988 });
989 const edit = (commandId: string) => ({
990 type: "queued-run.edit" as const,
991 commandId: CommandId.make(commandId),
992 threadId: ThreadId.make("thread"),
993 runId: RunId.make("run"),
994 text: "/logout",
995 });
996 // With an attachment, `/logout` reaches the provider as a prompt, not a sign-out.
997 const attachments = [
998 { type: "image" as const, id: "shot", name: "shot.png", mimeType: "image/png", sizeBytes: 1 },
999 ];
1000 const operator = yield* RpcTest.makeClient(group).pipe(
1001 Effect.provide(Layer.merge(handler, RpcAuthorization.layer([AuthOrchestrationOperateScope]))),
1002 );
1003 const dispatch = operator[ORCHESTRATION_V2_WS_METHODS.dispatchCommand];
1004 yield* dispatch(message("hello", "hello"));
1005 yield* dispatch({ ...message("attached", "/logout"), attachments });
1006 yield* dispatch({ ...edit("attached-edit"), attachments });
1007 // This edit keeps the queued attachments; message intake decides it.
1008 yield* dispatch(edit("kept-attachments-edit"));
1009 for (const command of [message("logout", " /LOGOUT "), { ...edit("edit"), attachments: [] }]) {
1010 expect(yield* dispatch(command).pipe(Effect.flip)).toMatchObject({
1011 requiredPermission: AuthProvidersManageScope,
1012 });
1014 const manager = yield* RpcTest.makeClient(group).pipe(
1015 Effect.provide(
1016 Layer.merge(
1017 handler,
1018 RpcAuthorization.layer([AuthOrchestrationOperateScope, AuthProvidersManageScope]),
1019 ),
1020 ),
1021 );
1022 yield* manager[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](message("manager", "/logout"));
1023 expect(handled).toEqual([
1024 "hello",
1025 "attached",
1026 "attached-edit",
1027 "kept-attachments-edit",
1028 "manager",
1029 ]);
1030 }).pipe(Effect.scoped),