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

RpcAuthorization.test.ts

833 lines29.6 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("keeps triage, which seeds an agent that reads logs and the database, behind operate scope", () => {
58 expect(requiredScopeForRpcMethod(WS_METHODS.serverPrepareTriage)).toBe(
59 AuthOrchestrationOperateScope,
60 );
61 });
62​
63 it("separates passive terminal observation from operations that can change a shell", () => {
64 for (const method of [WS_METHODS.terminalObserve, WS_METHODS.subscribeTerminalMetadata]) {
65 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalReadScope);
66 }
67 for (const method of [
68 WS_METHODS.terminalAttach,
69 WS_METHODS.terminalOpen,
70 WS_METHODS.terminalWrite,
71 WS_METHODS.terminalResize,
72 WS_METHODS.terminalClear,
73 WS_METHODS.terminalClose,
74 WS_METHODS.previewStopLocalServer,
75 ]) {
76 expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalOperateScope);
77 }
78 });
79​
80 it("lets thread readers observe and refresh checkout branches", () => {
81 for (const method of [WS_METHODS.subscribeVcsBranch, WS_METHODS.vcsRefreshBranch]) {
82 expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationReadScope);
83 }
84 });
85​
86 it("lets file readers see a task folder and takes source control to add a repository to it", () => {
87 expect(requiredScopeForRpcMethod(WS_METHODS.workspaceTaskFolder)).toBe(AuthFilesystemReadScope);
88 expect(requiredScopeForRpcMethod(WS_METHODS.workspaceAddTaskFolderRepository)).toBe(
89 AuthSourceControlWriteScope,
90 );
91 });
92​
93 it("still lets readers load settings the way installed Swift clients ask", () => {
94 expect(requiredScopeForRpcMethod("server.getSettings")).toBe(AuthOrchestrationReadScope);
95 });
96​
97 it("rejects unknown RPC method names", () => {
98 for (const method of ["server.notRegistered", "toString", "constructor"]) {
99 expect(() => requiredScopeForRpcMethod(method)).toThrow(
100 `RPC method ${method} has no declared authorization scope.`,
101 );
102 }
103 });
104});
105​
106it("requires operate permission for host retry while preserving read-only listing", () => {
107 expect(requiredScopeForDeviceList({})).toBe(AuthOrchestrationReadScope);
108 expect(requiredScopeForDeviceList({ retryHostId: "remote-host" })).toBe(
109 AuthOrchestrationOperateScope,
110 );
111});
112​
113it("requires operate permission for tool updates even alongside a read-only check", () => {
114 expect(requiredScopeForDeviceList({ updateTool: "agent", inspectOnly: true })).toBe(
115 AuthOrchestrationOperateScope,
116 );
117 expect(requiredScopeForDeviceList({ updateTool: "hub" })).toBe(AuthOrchestrationOperateScope);
118});
119​
120describe("RPC scope middleware", () => {
121 const tested = [WS_METHODS.serverProbe, WS_METHODS.serverRetryResourceTelemetry] as const;
122 const group = WsRpcGroup.omit(
123 ...[...WsRpcGroup.requests.keys()].filter(
124 (tag): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, (typeof tested)[number]> =>
125 !(tested as ReadonlyArray<string>).includes(tag),
126 ),
127 );
128​
129 it.effect.each([
130 { scopes: [AuthOrchestrationReadScope], missing: AuthEnvironmentMaintainScope },
131 {
132 scopes: [AuthOrchestrationReadScope, AuthEnvironmentMaintainScope],
133 missing: AuthDiagnosticsReadScope,
134 },
135 ])("rejects telemetry retry without $missing before its handler runs", ({ scopes, missing }) =>
136 Effect.gen(function* () {
137 const handled: Array<string> = [];
138 const client = yield* RpcTest.makeClient(group).pipe(
139 Effect.provide(
140 Layer.mergeAll(
141 group.toLayerHandler(WS_METHODS.serverProbe, () => Effect.succeed({})),
142 group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () =>
143 Effect.sync(() => handled.push("retry")).pipe(Effect.andThen(Effect.never)),
144 ),
145 RpcAuthorization.layer(scopes),
146 ),
147 ),
148 );
149​
150 expect(yield* client[WS_METHODS.serverProbe]({})).toEqual({});
151 expect(
152 yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(Effect.flip),
153 ).toMatchObject({
154 _tag: "EnvironmentAuthorizationError",
155 requiredPermission: missing,
156 });
157 expect(handled).toEqual([]);
158 }),
159 );
160});
161​
162it.effect("allows issue reads but requires a source-control grant before commenting", () =>
163 Effect.gen(function* () {
164 const tested = [WS_METHODS.issuesList, WS_METHODS.issuesComment] as const;
165 const group = WsRpcGroup.omit(
166 ...[...WsRpcGroup.requests.keys()].filter(
167 (tag): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, (typeof tested)[number]> =>
168 !(tested as ReadonlyArray<string>).includes(tag),
169 ),
170 );
171 const comments: string[] = [];
172 const handlers = Layer.mergeAll(
173 group.toLayerHandler(WS_METHODS.issuesList, () =>
174 Effect.succeed({ entries: [], trackers: [], errors: [], viewers: {}, nextCursors: {} }),
175 ),
176 group.toLayerHandler(WS_METHODS.issuesComment, ({ body }) =>
177 Effect.sync(() => {
178 comments.push(body);
179 }),
180 ),
181 );
182 const reader = yield* RpcTest.makeClient(group).pipe(
183 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthOrchestrationReadScope]))),
184 );
185 const comment = {
186 projectId: ProjectId.make("web"),
187 tracker: IssueTrackerKind.make("github"),
188 scope: "acme/web",
189 key: "42",
190 body: "Repro attached.",
191 };
192​
193 expect((yield* reader[WS_METHODS.issuesList]({ state: "open" })).entries).toEqual([]);
194 expect(yield* reader[WS_METHODS.issuesComment](comment).pipe(Effect.flip)).toMatchObject({
195 _tag: "EnvironmentAuthorizationError",
196 requiredPermission: AuthSourceControlWriteScope,
197 });
198 expect(comments).toEqual([]);
199​
200 const writer = yield* RpcTest.makeClient(group).pipe(
201 Effect.provide(
202 Layer.merge(
203 handlers,
204 RpcAuthorization.layer([AuthOrchestrationReadScope, AuthSourceControlWriteScope]),
205 ),
206 ),
207 );
208 yield* writer[WS_METHODS.issuesComment](comment);
209 expect(comments).toEqual(["Repro attached."]);
210 }).pipe(Effect.scoped),
211);
212​
213it.effect("reads a linked environment's thread only for a client that may read threads here", () =>
214 Effect.gen(function* () {
215 const linkedThreadTags = [
216 WS_METHODS.peerLinksSubscribeThread,
217 WS_METHODS.peerLinksThreadHistoryPage,
218 WS_METHODS.peerLinksThreadItem,
219 WS_METHODS.peerLinksNames,
220 ] as const;
221 const group = WsRpcGroup.omit(
222 ...[...WsRpcGroup.requests.keys()].filter(
223 (
224 tag,
225 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, (typeof linkedThreadTags)[number]> =>
226 !(linkedThreadTags as ReadonlyArray<string>).includes(tag),
227 ),
228 );
229 const read: string[] = [];
230 const input = {
231 environmentId: EnvironmentId.make("environment-box"),
232 threadId: ThreadId.make("thread:box"),
233 };
234 const handlers = group.toLayer({
235 [WS_METHODS.peerLinksSubscribeThread]: ({ threadId }) =>
236 Stream.sync(() => {
237 read.push(threadId);
238 return { kind: "synchronized" as const };
239 }),
240 [WS_METHODS.peerLinksThreadHistoryPage]: () => Effect.die("unused"),
241 [WS_METHODS.peerLinksThreadItem]: ({ threadId }) =>
242 Effect.sync(() => {
243 read.push(threadId);
244 return { item: null };
245 }),
246 // A thread link resolves to the linked environment by its name.
247 [WS_METHODS.peerLinksNames]: () =>
248 Effect.succeed({ links: [{ environmentId: input.environmentId, label: "Box" }] }),
249 });
250 // Managing links and writing settings here say nothing about reading threads.
251 const outsider = yield* RpcTest.makeClient(group).pipe(
252 Effect.provide(
253 Layer.merge(
254 handlers,
255 RpcAuthorization.layer([AuthAccessWriteScope, AuthSettingsWriteScope]),
256 ),
257 ),
258 );
259 const refused = {
260 _tag: "EnvironmentAuthorizationError",
261 requiredPermission: AuthOrchestrationReadScope,
262 };
263 expect(
264 yield* outsider[WS_METHODS.peerLinksSubscribeThread](input).pipe(
265 Stream.runCollect,
266 Effect.flip,
267 ),
268 ).toMatchObject(refused);
269 expect(
270 yield* outsider[WS_METHODS.peerLinksThreadItem]({
271 ...input,
272 itemId: TurnItemId.make("item:1"),
273 }).pipe(Effect.flip),
274 ).toMatchObject(refused);
275 expect(
276 yield* outsider[WS_METHODS.peerLinksThreadHistoryPage]({ ...input, cursor: "c" }).pipe(
277 Effect.flip,
278 ),
279 ).toMatchObject(refused);
280 expect(read).toEqual([]);
281 expect(yield* outsider[WS_METHODS.peerLinksNames]({}).pipe(Effect.flip)).toMatchObject({
282 requiredPermission: AuthOrchestrationReadScope,
283 });
284​
285 const reader = yield* RpcTest.makeClient(group).pipe(
286 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthOrchestrationReadScope]))),
287 );
288 expect(
289 Array.from(yield* reader[WS_METHODS.peerLinksSubscribeThread](input).pipe(Stream.runCollect)),
290 ).toEqual([{ kind: "synchronized" }]);
291 expect(read).toEqual([input.threadId]);
292 expect((yield* reader[WS_METHODS.peerLinksNames]({})).links).toEqual([
293 { environmentId: input.environmentId, label: "Box" },
294 ]);
295 }).pipe(Effect.scoped),
296);
297​
298it.effect("pairs a client with a linked environment only for one that may hand out access", () =>
299 Effect.gen(function* () {
300 const group = WsRpcGroup.omit(
301 ...[...WsRpcGroup.requests.keys()].filter(
302 (
303 tag,
304 ): tag is Exclude<
305 keyof typeof RPC_REQUIRED_SCOPES,
306 typeof WS_METHODS.peerLinksPairClient
307 > => tag !== WS_METHODS.peerLinksPairClient,
308 ),
309 );
310 let asked = 0;
311 const environmentId = EnvironmentId.make("environment-box");
312 const handlers = group.toLayerHandler(WS_METHODS.peerLinksPairClient, () =>
313 Effect.sync(() => {
314 asked++;
315 return {
316 type: "unsupported" as const,
317 reason: "link_access" as const,
318 environmentId,
319 label: "Box",
320 urls: [],
321 };
322 }),
323 );
324 // Running agents and reading the access list do not include handing access out.
325 const operator = yield* RpcTest.makeClient(group).pipe(
326 Effect.provide(
327 Layer.merge(
328 handlers,
329 RpcAuthorization.layer([AuthOrchestrationReadScope, AuthOrchestrationOperateScope]),
330 ),
331 ),
332 );
333 expect(
334 yield* operator[WS_METHODS.peerLinksPairClient]({ environmentId }).pipe(Effect.flip),
335 ).toMatchObject({
336 _tag: "EnvironmentAuthorizationError",
337 requiredPermission: AuthAccessWriteScope,
338 });
339 expect(asked).toBe(0);
340​
341 const manager = yield* RpcTest.makeClient(group).pipe(
342 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthAccessWriteScope]))),
343 );
344 expect((yield* manager[WS_METHODS.peerLinksPairClient]({ environmentId })).type).toBe(
345 "unsupported",
346 );
347 expect(asked).toBe(1);
348 }).pipe(Effect.scoped),
349);
350​
351it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as const)(
352 "enforces read permission on stream %s",
353 (method) =>
354 Effect.gen(function* () {
355 const group = WsRpcGroup.omit(
356 ...[...WsRpcGroup.requests.keys()].filter(
357 (
358 tag,
359 ): tag is Exclude<
360 keyof typeof RPC_REQUIRED_SCOPES,
361 typeof WS_METHODS.subscribeVcsBranch | typeof WS_METHODS.subscribeVcsStatus
362 > => tag !== WS_METHODS.subscribeVcsBranch && tag !== WS_METHODS.subscribeVcsStatus,
363 ),
364 );
365 let handled = 0;
366 const handlers = Layer.mergeAll(
367 group.toLayerHandler(WS_METHODS.subscribeVcsBranch, () =>
368 Stream.fromEffect(
369 Effect.sync(() => {
370 handled++;
371 return { refName: "main" };
372 }),
373 ),
374 ),
375 group.toLayerHandler(WS_METHODS.subscribeVcsStatus, () =>
376 Stream.fromEffect(
377 Effect.sync(() => {
378 handled++;
379 }),
380 ).pipe(Stream.drain),
381 ),
382 );
383 const denied = yield* RpcTest.makeClient(group).pipe(
384 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([]))),
385 );
386 expect(
387 yield* Stream.runDrain(
388 method === WS_METHODS.subscribeVcsBranch
389 ? denied[method]({ cwd: "/repo" }).pipe(Stream.drain)
390 : denied[method]({ cwd: "/repo" }).pipe(Stream.drain),
391 ).pipe(Effect.flip),
392 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
393 expect(handled).toBe(0);
394 const granted = yield* RpcTest.makeClient(group).pipe(
395 Effect.provide(Layer.merge(handlers, RpcAuthorization.layer([AuthOrchestrationReadScope]))),
396 );
397 yield* Stream.runDrain(
398 method === WS_METHODS.subscribeVcsBranch
399 ? granted[method]({ cwd: "/repo" }).pipe(Stream.drain)
400 : granted[method]({ cwd: "/repo" }).pipe(Stream.drain),
401 );
402 expect(handled).toBe(1);
403 }),
404);
405​
406describe("settings mutation authorization", () => {
407 const group = WsRpcGroup.omit(
408 ...[...WsRpcGroup.requests.keys()].filter(
409 (
410 tag,
411 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.serverUpdateSettings> =>
412 tag !== WS_METHODS.serverUpdateSettings,
413 ),
414 );
415 const providerInstanceMutation = {
416 operation: "remove" as const,
417 instanceId: ProviderInstanceId.make("codex_work"),
418 };
419​
420 it.effect("allows provider-only mutations while denying mixed settings without their grant", () =>
421 Effect.gen(function* () {
422 let handled = 0;
423 const client = yield* RpcTest.makeClient(group).pipe(
424 Effect.provide(
425 Layer.mergeAll(
426 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
427 Effect.sync(() => {
428 handled++;
429 return DEFAULT_SERVER_SETTINGS;
430 }),
431 ),
432 RpcAuthorization.layer([AuthProvidersManageScope]),
433 ),
434 ),
435 );
436 yield* client[WS_METHODS.serverUpdateSettings]({ patch: {}, providerInstanceMutation });
437 expect(handled).toBe(1);
438 yield* client[WS_METHODS.serverUpdateSettings]({
439 patch: {},
440 providerInstanceMutation: {
441 operation: "upsert",
442 instanceId: ProviderInstanceId.make("codex_work"),
443 instance: {
444 driver: ProviderDriverKind.make("codex"),
445 environment: [
446 {
447 name: "OPENAI_API_KEY",
448 sensitive: true,
449 value: {
450 provider: SecretProviderId.make("personal"),
451 reference: "op://Private/OpenAI/credential",
452 },
453 },
454 ],
455 },
456 },
457 });
458 expect(handled).toBe(2);
459 expect(
460 yield* client[WS_METHODS.serverUpdateSettings]({
461 patch: { defaultRuntimeMode: "full-access" },
462 providerInstanceMutation,
463 }).pipe(Effect.flip),
464 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
465 // Removing a secret provider clears settings fields that read from it.
466 expect(
467 yield* client[WS_METHODS.serverUpdateSettings]({
468 patch: { secretProviders: { [SecretProviderId.make("personal")]: null } },
469 }).pipe(Effect.flip),
470 ).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
471 expect(handled).toBe(2);
472 }),
473 );
474​
475 it.effect(
476 "does not let a settings grant manage providers or turn off T3 Connect device approval",
477 () =>
478 Effect.gen(function* () {
479 let handled = false;
480 const client = yield* RpcTest.makeClient(group).pipe(
481 Effect.provide(
482 Layer.mergeAll(
483 group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
484 Effect.sync(() => {
485 handled = true;
486 return DEFAULT_SERVER_SETTINGS;
487 }),
488 ),
489 RpcAuthorization.layer([AuthSettingsWriteScope]),
490 ),
491 ),
492 );
493 expect(
494 yield* client[WS_METHODS.serverUpdateSettings]({
495 patch: {},
496 providerInstanceMutation,
497 }).pipe(Effect.flip),
498 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
499 expect(
500 yield* client[WS_METHODS.serverUpdateSettings]({
501 patch: { secretProviders: { [SecretProviderId.make("personal")]: null } },
502 }).pipe(Effect.flip),
503 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
504 expect(
505 yield* client[WS_METHODS.serverUpdateSettings]({
506 patch: { requireConnectDeviceApproval: false },
507 }).pipe(Effect.flip),
508 ).toMatchObject({ requiredPermission: AuthAccessWriteScope });
509 // A reference names any secret the store holds, and the host entry names where it goes.
510 expect(
511 yield* client[WS_METHODS.serverUpdateSettings]({
512 patch: {
513 simlockDeviceHosts: [
514 {
515 kind: "simlock",
516 id: "simlock_evil",
517 label: "Gateway",
518 gatewayUrl: "https://attacker.example",
519 agentToken: {
520 provider: SecretProviderId.make("personal"),
521 reference: "op://Private/OpenAI/credential",
522 },
523 maxLeases: 2,
524 maxLeaseMinutes: 60,
525 },
526 ],
527 },
528 }).pipe(Effect.flip),
529 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
530 expect(handled).toBe(false);
531 }),
532 );
533​
534 it.effect("does not let a settings grant send a named secret to a gateway it picks", () =>
535 Effect.gen(function* () {
536 const group = WsRpcGroup.omit(
537 ...[...WsRpcGroup.requests.keys()].filter(
538 (
539 tag,
540 ): tag is Exclude<
541 keyof typeof RPC_REQUIRED_SCOPES,
542 typeof WS_METHODS.deviceSimlockIdentity
543 > => tag !== WS_METHODS.deviceSimlockIdentity,
544 ),
545 );
546 let handled = 0;
547 const client = yield* RpcTest.makeClient(group).pipe(
548 Effect.provide(
549 Layer.mergeAll(
550 group.toLayerHandler(WS_METHODS.deviceSimlockIdentity, () =>
551 Effect.sync(() => {
552 handled++;
553 return {
554 gatewayUrl: "https://attacker.example",
555 signedInAs: "agent",
556 tokenSource: "entered" as const,
557 };
558 }),
559 ),
560 RpcAuthorization.layer([AuthSettingsWriteScope]),
561 ),
562 ),
563 );
564 yield* client[WS_METHODS.deviceSimlockIdentity]({
565 gatewayUrl: "https://attacker.example",
566 agentToken: "typed-token",
567 });
568 expect(handled).toBe(1);
569 expect(
570 yield* client[WS_METHODS.deviceSimlockIdentity]({
571 gatewayUrl: "https://attacker.example",
572 agentToken: {
573 provider: SecretProviderId.make("personal"),
574 reference: "op://Private/OpenAI/credential",
575 },
576 }).pipe(Effect.flip),
577 ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
578 expect(handled).toBe(1);
579 }),
580 );
581});
582​
583it.effect("requires task permission before attaching a prepared worktree to a thread", () =>
584 Effect.gen(function* () {
585 const group = WsRpcGroup.omit(
586 ...[...WsRpcGroup.requests.keys()].filter(
587 (
588 tag,
589 ): tag is Exclude<
590 keyof typeof RPC_REQUIRED_SCOPES,
591 typeof WS_METHODS.gitPreparePullRequestThread
592 > => tag !== WS_METHODS.gitPreparePullRequestThread,
593 ),
594 );
595 let handled = false;
596 const client = yield* RpcTest.makeClient(group).pipe(
597 Effect.provide(
598 Layer.mergeAll(
599 group.toLayerHandler(WS_METHODS.gitPreparePullRequestThread, () =>
600 Effect.sync(() => {
601 handled = true;
602 }).pipe(Effect.andThen(Effect.never)),
603 ),
604 RpcAuthorization.layer([AuthSourceControlWriteScope]),
605 ),
606 ),
607 );
608 expect(
609 yield* client[WS_METHODS.gitPreparePullRequestThread]({
610 cwd: "/repo",
611 reference: "42",
612 mode: "worktree",
613 threadId: ThreadId.make("thread"),
614 }).pipe(Effect.flip),
615 ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope });
616 expect(handled).toBe(false);
617 }),
618);
619​
620describe("thread context authorization", () => {
621 const group = WsRpcGroup.omit(
622 ...[...WsRpcGroup.requests.keys()].filter(
623 (
624 tag,
625 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.gitRunStackedAction> =>
626 tag !== WS_METHODS.gitRunStackedAction,
627 ),
628 );
629​
630 it.effect.each(["commit", "create_pr", "commit_push_pr"] as const)(
631 "%s needs thread read permission only when generating a PR from a thread",
632 (action) =>
633 Effect.gen(function* () {
634 const handled: string[] = [];
635 const handler = group.toLayerHandler(WS_METHODS.gitRunStackedAction, ({ actionId }) =>
636 Stream.fromEffect(Effect.sync(() => handled.push(actionId))).pipe(Stream.drain),
637 );
638 const client = yield* RpcTest.makeClient(group).pipe(
639 Effect.provide(
640 Layer.merge(handler, RpcAuthorization.layer([AuthSourceControlWriteScope])),
641 ),
642 );
643 const input = { actionId: "without-thread", cwd: "/repo", action };
644 const withThread = { ...input, actionId: "with-thread", threadId: ThreadId.make("thread") };
645 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](input));
646 if (action === "create_pr" || action === "commit_push_pr") {
647 expect(
648 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread)).pipe(
649 Effect.flip,
650 ),
651 ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
652 expect(handled).toEqual(["without-thread"]);
653 } else {
654 yield* Stream.runDrain(client[WS_METHODS.gitRunStackedAction](withThread));
655 expect(handled).toEqual(["without-thread", "with-thread"]);
656 }
657 const reader = yield* RpcTest.makeClient(group).pipe(
658 Effect.provide(
659 Layer.merge(
660 handler,
661 RpcAuthorization.layer([AuthSourceControlWriteScope, AuthOrchestrationReadScope]),
662 ),
663 ),
664 );
665 yield* Stream.runDrain(
666 reader[WS_METHODS.gitRunStackedAction]({ ...withThread, actionId: "allowed" }),
667 );
668 expect(handled.at(-1)).toBe("allowed");
669 }),
670 );
671});
672​
673it.effect("separates host file URLs from readable attachment URLs", () =>
674 Effect.gen(function* () {
675 const group = WsRpcGroup.omit(
676 ...[...WsRpcGroup.requests.keys()].filter(
677 (
678 tag,
679 ): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof WS_METHODS.assetsCreateUrl> =>
680 tag !== WS_METHODS.assetsCreateUrl,
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.assetsCreateUrl, () =>
688 Effect.sync(() => {
689 handled++;
690 return { relativeUrl: "/api/assets/file", expiresAt: 1 };
691 }),
692 ),
693 RpcAuthorization.layer([AuthOrchestrationReadScope]),
694 ),
695 ),
696 );
697 yield* client[WS_METHODS.assetsCreateUrl]({
698 resource: { _tag: "attachment", attachmentId: "image" },
699 });
700 yield* client[WS_METHODS.assetsCreateUrl]({
701 resource: { _tag: "native-app-icon", app: { _tag: "app-id", appId: "com.apple.calculator" } },
702 });
703 for (const resource of [
704 { _tag: "workspace-file", threadId: ThreadId.make("thread"), path: "file.txt" },
705 { _tag: "media-file", threadId: ThreadId.make("thread"), path: "/repo/image.png" },
706 { _tag: "draft-workspace-file", cwd: "/repo", path: "file.txt" },
707 { _tag: "native-app-icon", app: { _tag: "app-path", path: "/private/Secret.app" } },
708 ] as const) {
709 expect(
710 yield* client[WS_METHODS.assetsCreateUrl]({ resource }).pipe(Effect.flip),
711 ).toMatchObject({
712 requiredScope: AuthOrchestrationReadScope,
713 requiredPermission: AuthFilesystemReadScope,
714 });
715 }
716 expect(handled).toBe(2);
717 }),
718);
719​
720it.effect("denies manual cleanup before the handler without settings permission", () =>
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.serverRunStorageCleanup
729 > => tag !== WS_METHODS.serverRunStorageCleanup,
730 ),
731 );
732 let handled = false;
733 const client = yield* RpcTest.makeClient(group).pipe(
734 Effect.provide(
735 Layer.mergeAll(
736 group.toLayerHandler(WS_METHODS.serverRunStorageCleanup, () =>
737 Effect.sync(() => {
738 handled = true;
739 return {
740 trigger: "manual" as const,
741 startedAt: "2026-10-09T12:00:00.000Z",
742 finishedAt: "2026-10-09T12:00:00.000Z",
743 entries: [],
744 counts: { removed: 0, kept: 0, failed: 0 },
745 omittedCount: 0,
746 bytesFreed: 0,
747 };
748 }),
749 ),
750 RpcAuthorization.layer([AuthOrchestrationReadScope]),
751 ),
752 ),
753 );
754 expect(yield* client[WS_METHODS.serverRunStorageCleanup]({}).pipe(Effect.flip)).toMatchObject({
755 requiredPermission: AuthSettingsWriteScope,
756 });
757 expect(handled).toBe(false);
758 }),
759);
760​
761it.effect("requires provider management to send /logout through chat", () =>
762 Effect.gen(function* () {
763 const group = WsRpcGroup.omit(
764 ...[...WsRpcGroup.requests.keys()].filter(
765 (
766 tag,
767 ): tag is Exclude<
768 keyof typeof RPC_REQUIRED_SCOPES,
769 typeof ORCHESTRATION_V2_WS_METHODS.dispatchCommand
770 > => tag !== ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
771 ),
772 );
773 const handled: string[] = [];
774 const handler = group.toLayerHandler(ORCHESTRATION_V2_WS_METHODS.dispatchCommand, (command) =>
775 Effect.sync(() => {
776 handled.push(command.commandId);
777 return { sequence: 1 };
778 }),
779 );
780 const message = (commandId: string, text: string) => ({
781 type: "message.dispatch" as const,
782 createdBy: "user" as const,
783 creationSource: "web" as const,
784 commandId: CommandId.make(commandId),
785 threadId: ThreadId.make("thread"),
786 messageId: MessageId.make(commandId),
787 text,
788 attachments: [],
789 dispatchMode: { type: "start_immediately" as const },
790 });
791 const edit = (commandId: string) => ({
792 type: "queued-run.edit" as const,
793 commandId: CommandId.make(commandId),
794 threadId: ThreadId.make("thread"),
795 runId: RunId.make("run"),
796 text: "/logout",
797 });
798 // With an attachment, `/logout` reaches the provider as a prompt, not a sign-out.
799 const attachments = [
800 { type: "image" as const, id: "shot", name: "shot.png", mimeType: "image/png", sizeBytes: 1 },
801 ];
802 const operator = yield* RpcTest.makeClient(group).pipe(
803 Effect.provide(Layer.merge(handler, RpcAuthorization.layer([AuthOrchestrationOperateScope]))),
804 );
805 const dispatch = operator[ORCHESTRATION_V2_WS_METHODS.dispatchCommand];
806 yield* dispatch(message("hello", "hello"));
807 yield* dispatch({ ...message("attached", "/logout"), attachments });
808 yield* dispatch({ ...edit("attached-edit"), attachments });
809 // This edit keeps the queued attachments; message intake decides it.
810 yield* dispatch(edit("kept-attachments-edit"));
811 for (const command of [message("logout", " /LOGOUT "), { ...edit("edit"), attachments: [] }]) {
812 expect(yield* dispatch(command).pipe(Effect.flip)).toMatchObject({
813 requiredPermission: AuthProvidersManageScope,
814 });
815 }
816 const manager = yield* RpcTest.makeClient(group).pipe(
817 Effect.provide(
818 Layer.merge(
819 handler,
820 RpcAuthorization.layer([AuthOrchestrationOperateScope, AuthProvidersManageScope]),
821 ),
822 ),
823 );
824 yield* manager[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](message("manager", "/logout"));
825 expect(handled).toEqual([
826 "hello",
827 "attached",
828 "attached-edit",
829 "kept-attachments-edit",
830 "manager",
831 ]);
832 }).pipe(Effect.scoped),
833);