Open History to see the last commit
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.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as const)(
359 "enforces read permission on stream %s",
360 (method) =>
361 Effect.gen(function* () {
362 const group = WsRpcGroup.omit(
363 ...[...WsRpcGroup.requests.keys()].filter(
364 (
365 tag,
366 ): tag is Exclude<
367 keyof typeof RPC_REQUIRED_SCOPES,
368 typeof WS_METHODS.subscribeVcsBranch | typeof WS_METHODS.subscribeVcsStatus
369 > => tag !== WS_METHODS.subscribeVcsBranch && tag !== WS_METHODS.subscribeVcsStatus,
370 ),
371 );
372 let handled = 0;
373 const handlers = Layer.mergeAll(
374 group.toLayerHandler(WS_METHODS.subscribeVcsBranch, () =>
375 Stream.fromEffect(
376 Effect.sync(() => {
377 handled++;
378 return { refName: "main" };
379 }),
380 ),
381 ),
382 group.toLayerHandler(WS_METHODS.subscribeVcsStatus, () =>
383 Stream.fromEffect(
384 Effect.sync(() => {
385 handled++;
386 }),
387 ).pipe(Stream.drain),
388 ),
389 );
390 const denied = yield* RpcTest.makeClient(group).pipe(
391 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([]))),
392 );
393 expect(
394 yield* Stream.runDrain(
395 method === WS_METHODS.subscribeVcsBranch
396 ? denied[method]({ cwd: "/repo" }).pipe(Stream.drain)
397 : denied[method]({ cwd: "/repo" }).pipe(Stream.drain),
398 ).pipe(Effect.flip),
399 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
400 expect(handled).toBe(0);
401 const granted = yield* RpcTest.makeClient(group).pipe(
402 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthOrchestrationReadScope]))),
403 );
404 yield* Stream.runDrain(
405 method === WS_METHODS.subscribeVcsBranch
406 ? granted[method]({ cwd: "/repo" }).pipe(Stream.drain)
407 : granted[method]({ cwd: "/repo" }).pipe(Stream.drain),
408 );
409 expect(handled).toBe(1);
410 }),
411);
412
413describe("settings mutation authorization", () => {
414 const group = WsRpcGroup.omit(
415 ...[...WsRpcGroup.requests.keys()].filter(
416 (
417 tag,
418 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.serverUpdateSettings> =>
419 tag !== WS_METHODS.serverUpdateSettings,
420 ),
421 );
422 const providerInstanceMutation = {
423 operation: "remove" as const,
424 instanceId: ProviderInstanceId.make("codex_work"),
425 };
426
427 it.effect("allows provider-only mutations while denying mixed settings without their grant", () =>
428 Effect.gen(function* () {
429 let handled = 0;
430 const client = yield* RpcTest.makeClient(group).pipe(
431 Effect.provide(
432 Layer.mergeAll(
433 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
434 Effect.sync(() => {
435 handled++;
436 return DEFAULT_SERVER_SETTINGS;
437 }),
438 ),
439 RpcAuthorization.layer([AuthProvidersManageScope]),
440 ),
441 ),
442 );
443 yield* client[WS_METHODS.serverUpdateSettings]({ patch: {}, providerInstanceMutation });
444 expect(handled).toBe(1);
445 yield* client[WS_METHODS.serverUpdateSettings]({
446 patch: {},
447 providerInstanceMutation: {
448 operation: "upsert",
449 instanceId: ProviderInstanceId.make("codex_work"),
450 instance: {
451 driver: ProviderDriverKind.make("codex"),
452 environment: [
453 {
454 name: "OPENAI_API_KEY",
455 sensitive: true,
456 value: {
457 provider: SecretProviderId.make("personal"),
458 reference: "op://Private/OpenAI/credential",
459 },
460 },
461 ],
462 },
463 },
464 });
465 expect(handled).toBe(2);
466 expect(
467 yield* client[WS_METHODS.serverUpdateSettings]({
468 patch: { defaultRuntimeMode: "full-access" },
469 providerInstanceMutation,
470 }).pipe(Effect.flip),
471 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
472 // Removing a secret provider clears settings fields that read from it.
473 expect(
474 yield* client[WS_METHODS.serverUpdateSettings]({
475 patch: { secretProviders: { [SecretProviderId.make("personal")]: null } },
476 }).pipe(Effect.flip),
477 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
478 expect(handled).toBe(2);
479 }),
480 );
481
482 it.effect(
483 "does not let a settings grant manage providers or turn off T3 Connect device approval",
484 () =>
485 Effect.gen(function* () {
486 let handled = false;
487 const client = yield* RpcTest.makeClient(group).pipe(
488 Effect.provide(
489 Layer.mergeAll(
490 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
491 Effect.sync(() => {
492 handled = true;
493 return DEFAULT_SERVER_SETTINGS;
494 }),
495 ),
496 RpcAuthorization.layer([AuthSettingsWriteScope]),
497 ),
498 ),
499 );
500 expect(
501 yield* client[WS_METHODS.serverUpdateSettings]({
502 patch: {},
503 providerInstanceMutation,
504 }).pipe(Effect.flip),
505 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
506 expect(
507 yield* client[WS_METHODS.serverUpdateSettings]({
508 patch: { secretProviders: { [SecretProviderId.make("personal")]: null } },
509 }).pipe(Effect.flip),
510 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
511 expect(
512 yield* client[WS_METHODS.serverUpdateSettings]({
513 patch: { requireConnectDeviceApproval: false },
514 }).pipe(Effect.flip),
515 ).toMatchObject({ requiredPermission: AuthAccessWriteScope });
516 // A reference names any secret the store holds, and the host entry names where it goes.
517 expect(
518 yield* client[WS_METHODS.serverUpdateSettings]({
519 patch: {
520 simlockDeviceHosts: [
521 {
522 kind: "simlock",
523 id: "simlock_evil",
524 label: "Gateway",
525 gatewayUrl: "https://attacker.example",
526 agentToken: {
527 provider: SecretProviderId.make("personal"),
528 reference: "op://Private/OpenAI/credential",
529 },
530 maxLeases: 2,
531 maxLeaseMinutes: 60,
532 },
533 ],
534 },
535 }).pipe(Effect.flip),
536 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
537 expect(handled).toBe(false);
538 }),
539 );
540
541 it.effect("does not let a settings grant send a named secret to a gateway it picks", () =>
542 Effect.gen(function* () {
543 const group = WsRpcGroup.omit(
544 ...[...WsRpcGroup.requests.keys()].filter(
545 (
546 tag,
547 ): tag is Exclude<
548 keyof typeof RPC_REQUIRED_SCOPES,
549 typeof WS_METHODS.deviceSimlockIdentity
550 > => tag !== WS_METHODS.deviceSimlockIdentity,
551 ),
552 );
553 let handled = 0;
554 const client = yield* RpcTest.makeClient(group).pipe(
555 Effect.provide(
556 Layer.mergeAll(
557 group.toLayerHandler(WS_METHODS.deviceSimlockIdentity, () =>
558 Effect.sync(() => {
559 handled++;
560 return {
561 gatewayUrl: "https://attacker.example",
562 signedInAs: "agent",
563 tokenSource: "entered" as const,
564 };
565 }),
566 ),
567 RpcAuthorization.layer([AuthSettingsWriteScope]),
568 ),
569 ),
570 );
571 yield* client[WS_METHODS.deviceSimlockIdentity]({
572 gatewayUrl: "https://attacker.example",
573 agentToken: "typed-token",
574 });
575 expect(handled).toBe(1);
576 expect(
577 yield* client[WS_METHODS.deviceSimlockIdentity]({
578 gatewayUrl: "https://attacker.example",
579 agentToken: {
580 provider: SecretProviderId.make("personal"),
581 reference: "op://Private/OpenAI/credential",
582 },
583 }).pipe(Effect.flip),
584 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
585 expect(handled).toBe(1);
586 }),
587 );
588});
589
590it.effect("requires task permission before attaching a prepared worktree to a thread", () =>
591 Effect.gen(function* () {
592 const group = WsRpcGroup.omit(
593 ...[...WsRpcGroup.requests.keys()].filter(
594 (
595 tag,
596 ): tag is Exclude<
597 keyof typeof RPC_REQUIRED_SCOPES,
598 typeof WS_METHODS.gitPreparePullRequestThread
599 > => tag !== WS_METHODS.gitPreparePullRequestThread,
600 ),
601 );
602 let handled = false;
603 const client = yield* RpcTest.makeClient(group).pipe(
604 Effect.provide(
605 Layer.mergeAll(
606 group.toLayerHandler(WS_METHODS.gitPreparePullRequestThread, () =>
607 Effect.sync(() => {
608 handled = true;
609 }).pipe(Effect.andThen(Effect.never)),
610 ),
611 RpcAuthorization.layer([AuthSourceControlWriteScope]),
612 ),
613 ),
614 );
615 expect(
616 yield* client[WS_METHODS.gitPreparePullRequestThread]({
617 cwd: "/repo",
618 reference: "42",
619 mode: "worktree",
620 threadId: ThreadId.make("thread"),
621 }).pipe(Effect.flip),
622 ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope });
623 expect(handled).toBe(false);
624 }),
625);
626
627describe("thread context authorization", () => {
628 const group = WsRpcGroup.omit(
629 ...[...WsRpcGroup.requests.keys()].filter(
630 (
631 tag,
632 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.gitRunStackedAction> =>
633 tag !== WS_METHODS.gitRunStackedAction,
634 ),
635 );
636
637 it.effect.each(["commit", "create_pr", "commit_push_pr"] as const)(
638 "%s needs thread read permission only when generating a PR from a thread",
639 (action) =>
640 Effect.gen(function* () {
641 const handled: string[] = [];
642 const handler = group.toLayerHandler(WS_METHODS.gitRunStackedAction, ({ actionId }) =>
643 Stream.fromEffect(Effect.sync(() => handled.push(actionId))).pipe(Stream.drain),
644 );
645 const client = yield* RpcTest.makeClient(group).pipe(
646 Effect.provide(
647 Layer.merge(handler, RpcAuthorization.layer([AuthSourceControlWriteScope])),
648 ),
649 );
650 const input = { actionId: "without-thread", cwd: "/repo", action };
651 const withThread = { ...input, actionId: "with-thread", threadId: ThreadId.make("thread") };
652 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](input));
653 if (action === "create_pr" || action === "commit_push_pr") {
654 expect(
655 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread)).pipe(
656 Effect.flip,
657 ),
658 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
659 expect(handled).toEqual(["without-thread"]);
660 } else {
661 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread));
662 expect(handled).toEqual(["without-thread", "with-thread"]);
663 }
664 const reader = yield* RpcTest.makeClient(group).pipe(
665 Effect.provide(
666 Layer.merge(
667 handler,
668 RpcAuthorization.layer([AuthSourceControlWriteScope, AuthOrchestrationReadScope]),
669 ),
670 ),
671 );
672 yield* Stream.runDrain(
673 reader[WS_METHODS.gitRunStackedAction]({ ...withThread, actionId: "allowed" }),
674 );
675 expect(handled.at(-1)).toBe("allowed");
676 }),
677 );
678});
679
680it.effect("separates host file URLs from readable attachment URLs", () =>
681 Effect.gen(function* () {
682 const group = WsRpcGroup.omit(
683 ...[...WsRpcGroup.requests.keys()].filter(
684 (
685 tag,
686 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.assetsCreateUrl> =>
687 tag !== WS_METHODS.assetsCreateUrl,
688 ),
689 );
690 let handled = 0;
691 const client = yield* RpcTest.makeClient(group).pipe(
692 Effect.provide(
693 Layer.mergeAll(
694 group.toLayerHandler(WS_METHODS.assetsCreateUrl, () =>
695 Effect.sync(() => {
696 handled++;
697 return { relativeUrl: "/api/assets/file", expiresAt: 1 };
698 }),
699 ),
700 RpcAuthorization.layer([AuthOrchestrationReadScope]),
701 ),
702 ),
703 );
704 yield* client[WS_METHODS.assetsCreateUrl]({
705 resource: { _tag: "attachment", attachmentId: "image" },
706 });
707 yield* client[WS_METHODS.assetsCreateUrl]({
708 resource: { _tag: "native-app-icon", app: { _tag: "app-id", appId: "com.apple.calculator" } },
709 });
710 for (const resource of [
711 { _tag: "workspace-file", threadId: ThreadId.make("thread"), path: "file.txt" },
712 { _tag: "media-file", threadId: ThreadId.make("thread"), path: "/repo/image.png" },
713 { _tag: "draft-workspace-file", cwd: "/repo", path: "file.txt" },
714 { _tag: "native-app-icon", app: { _tag: "app-path", path: "/private/Secret.app" } },
715 ] as const) {
716 expect(
717 yield* client[WS_METHODS.assetsCreateUrl]({ resource }).pipe(Effect.flip),
718 ).toMatchObject({
719 requiredScope: AuthOrchestrationReadScope,
720 requiredPermission: AuthFilesystemReadScope,
721 });
722 }
723 expect(handled).toBe(2);
724 }),
725);
726
727it.effect("denies manual cleanup before the handler without settings permission", () =>
728 Effect.gen(function* () {
729 const group = WsRpcGroup.omit(
730 ...[...WsRpcGroup.requests.keys()].filter(
731 (
732 tag,
733 ): tag is Exclude<
734 keyof typeof RPC_REQUIRED_SCOPES,
735 typeof WS_METHODS.serverRunStorageCleanup
736 > => tag !== WS_METHODS.serverRunStorageCleanup,
737 ),
738 );
739 let handled = false;
740 const client = yield* RpcTest.makeClient(group).pipe(
741 Effect.provide(
742 Layer.mergeAll(
743 group.toLayerHandler(WS_METHODS.serverRunStorageCleanup, () =>
744 Effect.sync(() => {
745 handled = true;
746 return {
747 trigger: "manual" as const,
748 startedAt: "2026-10-09T12:00:00.000Z",
749 finishedAt: "2026-10-09T12:00:00.000Z",
750 entries: [],
751 counts: { removed: 0, kept: 0, failed: 0 },
752 omittedCount: 0,
753 bytesFreed: 0,
754 };
755 }),
756 ),
757 RpcAuthorization.layer([AuthOrchestrationReadScope]),
758 ),
759 ),
760 );
761 expect(yield* client[WS_METHODS.serverRunStorageCleanup]({}).pipe(Effect.flip)).toMatchObject({
762 requiredPermission: AuthSettingsWriteScope,
763 });
764 expect(handled).toBe(false);
765 }),
766);
767
768it.effect("requires provider management to send /logout through chat", () =>
769 Effect.gen(function* () {
770 const group = WsRpcGroup.omit(
771 ...[...WsRpcGroup.requests.keys()].filter(
772 (
773 tag,
774 ): tag is Exclude<
775 keyof typeof RPC_REQUIRED_SCOPES,
776 typeof ORCHESTRATION_V2_WS_METHODS.dispatchCommand
777 > => tag !== ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
778 ),
779 );
780 const handled: string[] = [];
781 const handler = group.toLayerHandler(ORCHESTRATION_V2_WS_METHODS.dispatchCommand, (command) =>
782 Effect.sync(() => {
783 handled.push(command.commandId);
784 return { sequence: 1 };
785 }),
786 );
787 const message = (commandId: string, text: string) => ({
788 type: "message.dispatch" as const,
789 createdBy: "user" as const,
790 creationSource: "web" as const,
791 commandId: CommandId.make(commandId),
792 threadId: ThreadId.make("thread"),
793 messageId: MessageId.make(commandId),
794 text,
795 attachments: [],
796 dispatchMode: { type: "start_immediately" as const },
797 });
798 const edit = (commandId: string) => ({
799 type: "queued-run.edit" as const,
800 commandId: CommandId.make(commandId),
801 threadId: ThreadId.make("thread"),
802 runId: RunId.make("run"),
803 text: "/logout",
804 });
805 // With an attachment, `/logout` reaches the provider as a prompt, not a sign-out.
806 const attachments = [
807 { type: "image" as const, id: "shot", name: "shot.png", mimeType: "image/png", sizeBytes: 1 },
808 ];
809 const operator = yield* RpcTest.makeClient(group).pipe(
810 Effect.provide(Layer.merge(handler, RpcAuthorization.layer([AuthOrchestrationOperateScope]))),
811 );
812 const dispatch = operator[ORCHESTRATION_V2_WS_METHODS.dispatchCommand];
813 yield* dispatch(message("hello", "hello"));
814 yield* dispatch({ ...message("attached", "/logout"), attachments });
815 yield* dispatch({ ...edit("attached-edit"), attachments });
816 // This edit keeps the queued attachments; message intake decides it.
817 yield* dispatch(edit("kept-attachments-edit"));
818 for (const command of [message("logout", " /LOGOUT "), { ...edit("edit"), attachments: [] }]) {
819 expect(yield* dispatch(command).pipe(Effect.flip)).toMatchObject({
820 requiredPermission: AuthProvidersManageScope,
821 });
822 }
823 const manager = yield* RpcTest.makeClient(group).pipe(
824 Effect.provide(
825 Layer.merge(
826 handler,
827 RpcAuthorization.layer([AuthOrchestrationOperateScope, AuthProvidersManageScope]),
828 ),
829 ),
830 );
831 yield* manager[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](message("manager", "/logout"));
832 expect(handled).toEqual([
833 "hello",
834 "attached",
835 "attached-edit",
836 "kept-attachments-edit",
837 "manager",
838 ]);
839 }).pipe(Effect.scoped),
840);