Skip to content

Commit 50647de

Browse files
fix(server): check the specific scope for scripts, preview input, and full-access MCP grants (#17772)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent cfbd145 commit 50647de

10 files changed

Lines changed: 140 additions & 18 deletions

File tree

‎apps/server/src/auth/EnvironmentAuth.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import {
44
AuthAdministrativeScopes,
55
AuthOrchestrationOperateScope,
66
AuthOrchestrationReadScope,
7+
AuthSettingsWriteScope,
8+
AuthSourceControlWriteScope,
79
AuthStandardClientScopes,
810
type AuthAccessTokenResult,
911
type AuthBrowserSessionResult,
@@ -74,7 +76,10 @@ export interface IssuedBearerSession {
7476
* token cannot reach the full RPC surface around that cap.
7577
*
7678
* A read-only grant holds `orchestration:read` alone. Any other grant also
77-
* holds `orchestration:operate` and carries its runtime-mode ceiling.
79+
* holds `orchestration:operate` and carries its runtime-mode ceiling. A
80+
* full-access client may also change environment preferences and clone
81+
* repositories, so it holds the scopes those need over RPC. Approving a grant
82+
* requires every scope it holds.
7883
*/
7984
const MCP_CLIENT_SUBJECT = "mcp-client";
8085
const MCP_CLIENT_SESSION_TTL = Duration.days(30);
@@ -84,7 +89,14 @@ export const mcpClientScopes = (
8489
): ReadonlyArray<AuthEnvironmentScope> =>
8590
access === "read-only"
8691
? [AuthOrchestrationReadScope]
87-
: [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
92+
: access === "full-access"
93+
? [
94+
AuthOrchestrationReadScope,
95+
AuthOrchestrationOperateScope,
96+
AuthSettingsWriteScope,
97+
AuthSourceControlWriteScope,
98+
]
99+
: [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
88100

89101
export interface McpClientSession {
90102
readonly sessionId: AuthSessionId;

‎apps/server/src/auth/McpOAuth.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -451,6 +451,15 @@ it.live(
451451
const readOnlyResponse = yield* approveWith(readOnly.credential);
452452
expect(readOnlyResponse.status).toBe(400);
453453
expect(readOnlyResponse.message).toContain("cannot grant this access");
454+
const operator = yield* auth.issuePairingCredential({
455+
scopes: ["orchestration:read", "orchestration:operate"],
456+
});
457+
const operatorFull = yield* decide(handler, params, {
458+
_tag: "pairing-code",
459+
access: "full-access",
460+
code: operator.credential,
461+
});
462+
expect(operatorFull.status).toBe(400);
454463

455464
// A read-only code can approve read-only access.
456465
const readOnlyCode = yield* auth.issuePairingCredential({ scopes: ["orchestration:read"] });

‎apps/server/src/auth/RpcAuthorization.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import {
88
ServerSettingsPatch,
99
ProviderInstanceMutation,
1010
requiredScopesForServerSettingsPatch,
11+
requiredScopesForProjectMutation,
12+
ProjectMutation,
1113
AuthSettingsWriteScope,
1214
AuthProvidersManageScope,
1315
AuthEnvironmentMaintainScope,
@@ -242,6 +244,8 @@ const requiredScopesForSettingsUpdate = (payload: unknown) => {
242244
: [...new Set([...scopes, AuthProvidersManageScope])];
243245
};
244246

247+
const decodeProjectMutation = Schema.decodeUnknownSync(ProjectMutation);
248+
245249
const requiredScopesForRpcCall = (
246250
method: string,
247251
payload: unknown,
@@ -260,6 +264,9 @@ const requiredScopesForRpcCall = (
260264
];
261265
}
262266
if (method === WS_METHODS.serverUpdateSettings) return requiredScopesForSettingsUpdate(payload);
267+
if (method === WS_METHODS.projectsMutate) {
268+
return requiredScopesForProjectMutation(decodeProjectMutation(payload));
269+
}
263270
const guarded = clientRpcRequiredScopes(method, payload);
264271
if (guarded.length > 0) return guarded;
265272
return [requiredScopeForRpcMethod(method)];

‎apps/server/src/preview/ServerBrowser.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1126,6 +1126,35 @@ it.live("a page's file picker goes to the controller and takes its uploaded file
11261126
).pipe(Effect.provide(layer)),
11271127
);
11281128

1129+
it.live("only the current controller can answer a file picker", () =>
1130+
Effect.scoped(
1131+
Effect.gen(function* () {
1132+
const { browser, tabId } = yield* ready;
1133+
const first = yield* browser.attachViewer(viewerInput(tabId, true));
1134+
yield* first.input({ type: "takeControl" });
1135+
const setFiles = vi.fn(async (_files: unknown) => {});
1136+
contexts[0]!.page.emit("filechooser", {
1137+
isMultiple: () => false,
1138+
element: () => ({ getAttribute: async () => "" }),
1139+
setFiles,
1140+
});
1141+
let offered = yield* Queue.take(first.output);
1142+
while (offered._tag !== "fileChooser") offered = yield* Queue.take(first.output);
1143+
const second = yield* browser.attachViewer(viewerInput(tabId, true));
1144+
yield* first.input({ type: "releaseControl" });
1145+
yield* second.input({ type: "takeControl" });
1146+
const answered = yield* browser.answerFileChooser({
1147+
threadId: scope.thread.threadId,
1148+
tabId,
1149+
chooserId: offered.id,
1150+
files: [{ name: "a.txt", mimeType: "text/plain", buffer: Buffer.from("a") }],
1151+
});
1152+
expect(answered).toBe(false);
1153+
expect(setFiles).not.toHaveBeenCalled();
1154+
}),
1155+
).pipe(Effect.provide(layer)),
1156+
);
1157+
11291158
it.live("a file picker replaces a stalled viewer backlog instead of being dropped", () =>
11301159
Effect.scoped(
11311160
Effect.gen(function* () {

‎apps/server/src/preview/ServerBrowser.ts‎

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -310,11 +310,15 @@ interface ServerTab {
310310
readonly openerTabId: string | undefined;
311311
/** Finished downloads, newest last; files live until the tab closes. */
312312
readonly downloads: Array<ServerDownload>;
313-
/** A page's open file picker, waiting for the controlling viewer's files. */
313+
/**
314+
* A page's open file picker, waiting for the controlling viewer's files. Its
315+
* id is reissued for each viewer it is offered to, so only that viewer can answer.
316+
*/
314317
fileChooser: {
315318
readonly id: string;
316319
readonly chooser: FileChooser;
317320
readonly accept: string;
321+
readonly offeredTo: string | null;
318322
} | null;
319323
dialog: Dialog | null;
320324
setting: PreviewViewportSetting;
@@ -1027,14 +1031,27 @@ const make = Effect.gen(function* () {
10271031
.catch(() => null)) ?? "";
10281032
// A newer picker replaces an unanswered one, as a real browser allows only one.
10291033
if (previous) closeFileChooser(tab);
1030-
tab.fileChooser = { id: NodeCrypto.randomUUID(), chooser, accept: accept.slice(0, 1024) };
1034+
tab.fileChooser = {
1035+
id: NodeCrypto.randomUUID(),
1036+
chooser,
1037+
accept: accept.slice(0, 1024),
1038+
offeredTo: null,
1039+
};
10311040
pushFileChooser(tab);
10321041
};
10331042

10341043
const pushFileChooser = (tab: ServerTab) => {
1035-
const message = fileChooserMessage(tab);
1044+
const open = tab.fileChooser;
10361045
const controller = [...tab.viewers].find((viewer) => viewer.id === tab.control.controller);
1037-
if (message) controller?.push(message);
1046+
if (!open || !controller) return;
1047+
if (open.offeredTo !== controller.id) {
1048+
// A new controller gets a fresh id; the previous one can no longer answer.
1049+
tab.fileChooser = { ...open, id: NodeCrypto.randomUUID(), offeredTo: controller.id };
1050+
if (open.offeredTo !== null)
1051+
for (const viewer of tab.viewers) viewer.push({ _tag: "fileChooserClosed", id: open.id });
1052+
}
1053+
const message = fileChooserMessage(tab);
1054+
if (message) controller.push(message);
10381055
};
10391056

10401057
const closeFileChooser = (tab: ServerTab) => {
@@ -1050,7 +1067,14 @@ const make = Effect.gen(function* () {
10501067
) => {
10511068
const tab = tabs.get(tabKey(input.threadId, input.tabId));
10521069
const open = tab?.fileChooser;
1053-
if (!tab || !open || open.id !== input.chooserId) return false;
1070+
if (
1071+
!tab ||
1072+
!open ||
1073+
open.id !== input.chooserId ||
1074+
open.offeredTo === null ||
1075+
open.offeredTo !== tab.control.controller
1076+
)
1077+
return false;
10541078
if (input.files.length > 0) {
10551079
await open.chooser.setFiles(
10561080
open.chooser.isMultiple() ? [...input.files] : input.files.slice(0, 1),

‎apps/server/src/preview/ServerBrowserStream.test.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { expect, it } from "@effect/vitest";
55
import {
66
AuthOrchestrationOperateScope,
77
AuthOrchestrationReadScope,
8+
AuthPreviewOperateScope,
89
AuthSessionId,
910
PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE,
1011
PreviewStreamHostSetup,
@@ -71,7 +72,7 @@ it.effect.each([
7172
Effect.gen(function* () {
7273
const canOperate = hasOperateScope && interactive;
7374
const scopes = hasOperateScope
74-
? [AuthOrchestrationReadScope, AuthOrchestrationOperateScope]
75+
? [AuthOrchestrationReadScope, AuthPreviewOperateScope]
7576
: [AuthOrchestrationReadScope];
7677
const auth = makeAuth(scopes);
7778
const inputs: unknown[] = [];
@@ -293,11 +294,12 @@ it.effect("passes uploaded files to the page's open picker and needs operate sco
293294
});
294295
expect((yield* upload([AuthOrchestrationReadScope], "chooser-1")).status).toBe(403);
295296
expect(answers).toEqual([]);
296-
expect((yield* upload([AuthOrchestrationOperateScope], "chooser-1")).status).toBe(204);
297+
expect((yield* upload([AuthOrchestrationOperateScope], "chooser-1")).status).toBe(403);
298+
expect((yield* upload([AuthPreviewOperateScope], "chooser-1")).status).toBe(204);
297299
expect(answers).toEqual([
298300
{ chooserId: "chooser-1", files: [{ name: "notes.txt", text: "hello" }] },
299301
]);
300-
expect((yield* upload([AuthOrchestrationOperateScope], "stale")).status).toBe(409);
302+
expect((yield* upload([AuthPreviewOperateScope], "stale")).status).toBe(409);
301303
}).pipe(Effect.scoped),
302304
);
303305

‎apps/server/src/preview/ServerBrowserStream.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest";
22
import {
3-
AuthOrchestrationOperateScope,
43
AuthOrchestrationReadScope,
4+
AuthPreviewOperateScope,
55
PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE,
66
PreviewStreamHostSetup,
77
} from "@t3tools/contracts";
@@ -71,9 +71,9 @@ const makeHandler = (browser: ServerBrowser.ServerBrowser["Service"]) =>
7171
}
7272
const session = yield* authenticateMediaRequest(AuthOrchestrationReadScope);
7373
const params = url.value.searchParams;
74+
// Watching needs read access; driving the page is a preview mutation.
7475
const canOperate =
75-
session.scopes.includes(AuthOrchestrationOperateScope) &&
76-
params.get("interactive") !== "false";
76+
session.scopes.includes(AuthPreviewOperateScope) && params.get("interactive") !== "false";
7777
const threadId = params.get("threadId") ?? "";
7878
const tabId = params.get("tabId") ?? "";
7979
if (threadId.length === 0 || tabId.length === 0) {
@@ -238,7 +238,7 @@ const UPLOAD_MAX_FILES = 20;
238238
*/
239239
const receiveUpload = (browser: ServerBrowser.ServerBrowser["Service"], params: URLSearchParams) =>
240240
Effect.gen(function* () {
241-
yield* authenticateMediaRequest(AuthOrchestrationOperateScope);
241+
yield* authenticateMediaRequest(AuthPreviewOperateScope);
242242
const request = yield* HttpServerRequest.HttpServerRequest;
243243
const fs = yield* FileSystem.FileSystem;
244244
const parts = yield* request.multipart.pipe(

‎apps/server/src/project/http.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import {
2-
AuthOrchestrationOperateScope,
32
AuthOrchestrationReadScope,
43
EnvironmentHttpApi,
4+
requiredScopesForProjectMutation,
55
} from "@t3tools/contracts";
66
import * as Effect from "effect/Effect";
77
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
@@ -53,7 +53,9 @@ export const layer = HttpApiBuilder.group(
5353
"mutate",
5454
Effect.fn("environment.projects.mutate")(function* (args) {
5555
yield* annotateEnvironmentRequest(args.endpoint.name);
56-
yield* requireEnvironmentScope(AuthOrchestrationOperateScope);
56+
for (const scope of requiredScopesForProjectMutation(args.payload)) {
57+
yield* requireEnvironmentScope(scope);
58+
}
5759
const operation = projectMutationOperation(projects, args.payload);
5860
return yield* startup
5961
.enqueueCommand(operation)

‎packages/contracts/src/settings.test.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import { describe, expect, it } from "vite-plus/test";
22
import * as Schema from "effect/Schema";
33

4-
import type { ProjectId } from "./baseSchemas.ts";
4+
import type { CommandId, ProjectId } from "./baseSchemas.ts";
55
import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
66
import {
77
ClientSettingsSchema,
88
ClientSettingsPatch,
99
ClaudeSettings,
1010
DEFAULT_SERVER_SETTINGS,
11+
requiredScopesForProjectMutation,
1112
resolveProviderInstanceEnabled,
1213
ServerSettings,
1314
ServerSettingsPatch,
@@ -1068,3 +1069,21 @@ describe("ServerSettings.removeAgentCreditsOnMerge", () => {
10681069
).toBe(true);
10691070
});
10701071
});
1072+
1073+
describe("requiredScopesForProjectMutation", () => {
1074+
it("adds the settings scope only when a mutation carries scripts", () => {
1075+
const projectId = "project-1" as ProjectId;
1076+
const commandId = "command-1" as CommandId;
1077+
expect(
1078+
requiredScopesForProjectMutation({ type: "project.update", commandId, projectId }),
1079+
).toEqual(["orchestration:operate"]);
1080+
expect(
1081+
requiredScopesForProjectMutation({
1082+
type: "project.update",
1083+
commandId,
1084+
projectId,
1085+
scripts: [],
1086+
}),
1087+
).toEqual(["orchestration:operate", "settings:write"]);
1088+
});
1089+
});

‎packages/contracts/src/settings.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { SshDeviceHostConfigs } from "./device.ts";
22
import {
3+
AuthOrchestrationOperateScope,
34
AuthSettingsWriteScope,
45
AuthProvidersManageScope,
56
type AuthEnvironmentScope,
@@ -27,7 +28,7 @@ import {
2728
ProviderOptionSelections,
2829
} from "./model.ts";
2930
import { ModelSelection } from "./modelSelection.ts";
30-
import { ProjectScript } from "./project.ts";
31+
import { ProjectScript, type ProjectMutation } from "./project.ts";
3132
import { DEFAULT_RUNTIME_MODE, RuntimeMode } from "./providerPolicy.ts";
3233
import { BrowserProfile, BrowserProfileId, DEFAULT_BROWSER_PROFILE_ID } from "./browserProfile.ts";
3334
import {
@@ -1583,6 +1584,23 @@ export function requiredScopesForServerSettingsPatch(
15831584
];
15841585
}
15851586

1587+
/**
1588+
* Project scripts run on the host when a worktree is created or a thread
1589+
* settles, so a project mutation that carries them needs the same grant as
1590+
* saving project scripts through settings, on top of `orchestration:operate`.
1591+
*/
1592+
export function requiredScopesForProjectMutation(
1593+
mutation: ProjectMutation,
1594+
): ReadonlyArray<AuthEnvironmentScope> {
1595+
if (mutation.type === "project.delete" || mutation.scripts === undefined) {
1596+
return [AuthOrchestrationOperateScope];
1597+
}
1598+
return [
1599+
AuthOrchestrationOperateScope,
1600+
...requiredScopesForServerSettingsPatch({ defaultProjectScripts: mutation.scripts }),
1601+
];
1602+
}
1603+
15861604
export const ClientSettingsPatch = Schema.Struct({
15871605
notificationMode: Schema.optionalKey(NotificationMode),
15881606
inAppNotificationsEnabled: Schema.optionalKey(Schema.Boolean),

0 commit comments

Comments
 (0)