From c738331d79bff0459a88d1f72efb2fdec821cfa8 Mon Sep 17 00:00:00 2001 From: Hydra Date: Sun, 15 Nov 2026 13:23:05 +0200 Subject: [PATCH 1/3] fix(security): enforce administrative role ceilings across transports --- CHANGELOG.md | 6 +++ SECURITY.md | 6 +++ apps/api/src/lib/route-permission.ts | 11 ++--- apps/api/src/modules/mcp/mcp-tools.ts | 7 ++- apps/api/src/modules/mcp/mcp.routes.ts | 1 + .../permission-grant-satisfiability.test.ts | 3 +- .../test/lib/permission-own-projects.test.ts | 3 +- .../lib/permission-wildcard-list-arm.test.ts | 5 +- .../deployments/native-sdk-parity.test.ts | 30 ++++++++---- .../test/modules/mcp/mcp-tools-filter.test.ts | 11 +++++ .../notifications-sdk-parity.test.ts | 2 +- .../system/server-exec-authorization.test.ts | 48 +++++++++++++++++++ .../modules/tokens/mint-org-binding.test.ts | 10 ++++ docs/ship-sdk-plan.md | 2 +- packages/platform/src/authorization.ts | 11 +++-- .../modules/system/server.operations.ts | 5 +- packages/platform/test/authorization.test.ts | 39 +++++++++++++++ packages/platform/test/domains.test.ts | 2 +- 18 files changed, 173 insertions(+), 29 deletions(-) create mode 100644 apps/api/test/modules/system/server-exec-authorization.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c1cae888..0d57b1d29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ Runtime security notices use the signed feed published from `security-advisories ## Unreleased +### Authorization + +- Require administrative authority for admin operations across HTTP, SDK, native and + MCP access. Ordinary organization membership no longer grants host command execution; + token grants remain bounded by the user's current built-in role (#1783). + ### Cloud billing - Open checkout only when its payment URL is ready, with a visible fallback button. diff --git a/SECURITY.md b/SECURITY.md index 87c2474ab..29b19ad67 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -57,6 +57,12 @@ violation. ## Scope +Organization owners and administrators can perform host administration. Ordinary +members retain read/write access but cannot perform operations requiring `admin`, +including server shell execution. Restricted users require explicit resource grants; +scoped tokens also respect their user's current built-in role. Host commands execute +as the server's configured account, so delegate server administration accordingly. + In scope — all Openship components: - Managed Openship Cloud diff --git a/apps/api/src/lib/route-permission.ts b/apps/api/src/lib/route-permission.ts index 42fc2697e..36deb84ae 100644 --- a/apps/api/src/lib/route-permission.ts +++ b/apps/api/src/lib/route-permission.ts @@ -476,13 +476,10 @@ export function isPublicSpec(spec: RouteSpec): spec is PublicSpec { * Be precise about what that org-wide check buys, because it is easy to misread as * a defense it is not: it is strict only for a RESTRICTED principal (a scoped * token), which needs an all-GitHub grant to pass. For a session-authenticated - * owner/admin/**member** it is satisfied by bare membership — - * `roleAllowsResourceType` (permission.ts) ignores the action level for those - * roles, so `github:admin` is no higher a bar than `github:read`. The per-repo, - * read-vs-write authority for those principals is enforced ONLY by - * `github-access.ts` at the token funnel and at the mutating service helpers. - * Reading this comment as "the route layer already gates writes" is what let - * GHSA-hp2g-hw7g-f3vm sit behind a `github:admin` tag. + * owner/admin it is satisfied by broad membership authority. Ordinary members + * cannot satisfy an admin action. Per-repo read/write authority still belongs + * to `github-access.ts` at the token funnel and mutating service helpers; an + * org-wide tag never substitutes for that repository-specific check. * Paramless GitHub routes (/home, /status, /repos) also stay on the org-wide * path: `filterToolsForPrincipal` already hides them from a scoped token via * `perm.wildcard`, and their handlers narrow results through diff --git a/apps/api/src/modules/mcp/mcp-tools.ts b/apps/api/src/modules/mcp/mcp-tools.ts index 030f788ab..d95a76c89 100644 --- a/apps/api/src/modules/mcp/mcp-tools.ts +++ b/apps/api/src/modules/mcp/mcp-tools.ts @@ -76,6 +76,8 @@ export interface McpPrincipal { /** Resolved with the same persisted instance-authority policy as HTTP calls. */ instanceAdmin?: boolean; role: "owner" | "admin" | "member" | "restricted"; + /** Current membership before narrowing it to the credential's grants. */ + membershipRole?: "owner" | "admin" | "member" | "restricted"; readOnly: boolean; /** Resource types the token holds grants on — only consulted when role === "restricted". */ grantedRootTypes: ReadonlySet; @@ -353,6 +355,9 @@ export function filterToolsForPrincipal( principal: McpPrincipal, ): McpToolDef[] { return tools.filter((t) => { + const action = assertedAction(t.perm.action); + if (principal.membershipRole && principal.membershipRole !== "restricted" && + !roleAllowsResourceType(principal.membershipRole, t.perm.leaf as CheckedResourceType, action)) return false; // Read-only tokens can only call GET — the runtime gate rejects mutations by // HTTP method, so mirror that exactly rather than guessing from the tag. if (principal.readOnly && t.method !== "GET") return false; @@ -377,7 +382,7 @@ export function filterToolsForPrincipal( } if (principal.role !== "restricted") { - return roleAllowsResourceType(principal.role, t.perm.leaf as CheckedResourceType); + return roleAllowsResourceType(principal.role, t.perm.leaf as CheckedResourceType, action); } // "Own projects" scope: the create-capable project wildcard grant reaches the // dedicated create routes (POST /projects, POST /apps) and the project list diff --git a/apps/api/src/modules/mcp/mcp.routes.ts b/apps/api/src/modules/mcp/mcp.routes.ts index 9a80ecf68..14da7d1db 100644 --- a/apps/api/src/modules/mcp/mcp.routes.ts +++ b/apps/api/src/modules/mcp/mcp.routes.ts @@ -128,6 +128,7 @@ async function resolveMcpCaller(token: string, headers: Headers): Promise ({ repos: { - member: { find: vi.fn(async () => ({ id: "m1", role: "member" })) }, + member: { find: vi.fn(async () => ({ id: "m1", role: "owner" })) }, project: { findById: vi.fn(async (id: string) => (id === "*" ? null : { id, organizationId: "org1" })), findEnvVarById: vi.fn(async () => null), diff --git a/apps/api/test/lib/permission-own-projects.test.ts b/apps/api/test/lib/permission-own-projects.test.ts index d1b2a52b9..0f3a3edf0 100644 --- a/apps/api/test/lib/permission-own-projects.test.ts +++ b/apps/api/test/lib/permission-own-projects.test.ts @@ -3,9 +3,10 @@ import { describe, it, expect, vi } from "vitest"; // checkPermission touches only member.find (membership gate) and, for a // concrete project id, project.findById (org resolution). We pass the grant // source explicitly via opts, so resourceGrant is never consulted. +// The owner can delegate project admin; the token must still satisfy each grant. vi.mock("@repo/db", () => ({ repos: { - member: { find: vi.fn(async () => ({ id: "m1", role: "member" })) }, + member: { find: vi.fn(async () => ({ id: "m1", role: "owner" })) }, project: { findById: vi.fn(async (id: string) => id === "*" ? null : { id, organizationId: "org1" }, diff --git a/apps/api/test/lib/permission-wildcard-list-arm.test.ts b/apps/api/test/lib/permission-wildcard-list-arm.test.ts index d92e3788a..0620fa0ff 100644 --- a/apps/api/test/lib/permission-wildcard-list-arm.test.ts +++ b/apps/api/test/lib/permission-wildcard-list-arm.test.ts @@ -19,9 +19,10 @@ import { describe, it, expect, vi } from "vitest"; +// The owner's role ceiling permits delegation; the tests enforce grant widths. vi.mock("@repo/db", () => ({ repos: { - member: { find: vi.fn(async () => ({ id: "m1", role: "member" })) }, + member: { find: vi.fn(async () => ({ id: "m1", role: "owner" })) }, project: { findById: vi.fn(async (id: string) => (id === "*" ? null : { id, organizationId: "org1" })), findEnvVarById: vi.fn(async () => null), @@ -198,7 +199,7 @@ describe("a full project wildcard now lists and creates (deliberate widening)", }); describe("non-restricted roles are untouched by this arm", () => { - it("a member is authorized by role, without consulting grants", async () => { + it("an owner is authorized by role, without consulting grants", async () => { const boom = { findForResource: async () => { throw new Error("the role arm must return before any grant lookup"); diff --git a/apps/api/test/modules/deployments/native-sdk-parity.test.ts b/apps/api/test/modules/deployments/native-sdk-parity.test.ts index 6a1cf68ba..4b0e0ec0d 100644 --- a/apps/api/test/modules/deployments/native-sdk-parity.test.ts +++ b/apps/api/test/modules/deployments/native-sdk-parity.test.ts @@ -1897,8 +1897,8 @@ describe("domain and DNS HTTP/native parity", () => { const local = await native(); h.members.set("org-a:alice", { id: "member-a", role: "member" }); for (const dns of [remote().dns, local.dns]) { - await expect(dns.addCredential(input)).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); - await expect(dns.removeCredential("dns-a")).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(dns.addCredential(input)).rejects.toMatchObject({ code: "NOT_FOUND" }); + await expect(dns.removeCredential("dns-a")).rejects.toMatchObject({ code: "NOT_FOUND" }); } expect(h.dnsAdd).not.toHaveBeenCalled(); expect(h.dnsRemove).not.toHaveBeenCalled(); @@ -2045,10 +2045,10 @@ describe("provider credential HTTP/native parity", () => { const local = await native(); h.members.set("org-a:alice", { id: "member-a", role: "member" }); for (const credentials of [local.credentials, remote().credentials]) { - await expect(credentials.create({ provider: "docker-registry", name: "Registry", values: { secret: "value" } })).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); - await expect(credentials.update("credential-a", { name: "Renamed" })).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); - await expect(credentials.remove("credential-a")).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); - await expect(credentials.verify("credential-a")).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(credentials.create({ provider: "docker-registry", name: "Registry", values: { secret: "value" } })).rejects.toMatchObject({ code: "NOT_FOUND" }); + await expect(credentials.update("credential-a", { name: "Renamed" })).rejects.toMatchObject({ code: "NOT_FOUND" }); + await expect(credentials.remove("credential-a")).rejects.toMatchObject({ code: "NOT_FOUND" }); + await expect(credentials.verify("credential-a")).rejects.toMatchObject({ code: "NOT_FOUND" }); } expect(h.credentialCreate).not.toHaveBeenCalled(); expect(h.credentialUpdate).not.toHaveBeenCalled(); @@ -2492,6 +2492,20 @@ describe("server HTTP/native parity", () => { expect(h.serverRemove).not.toHaveBeenCalled(); }); + it("denies ordinary members host execution through native, SDK and raw HTTP operations", async () => { + h.members.set("org-a:alice", { id: "member-a", role: "member" }); + const local = await native(); + for (const servers of [local.servers, remote().servers]) { + await expect(servers.exec("server-a", { command: "whoami" })).rejects.toMatchObject({ code: "NOT_FOUND" }); + } + const response = await app.request("/api/system/servers/server-a/exec", { + method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ command: "whoami" }), + }); + expect(response.status).toBe(404); + expect(h.serverWithExecutor).not.toHaveBeenCalled(); + expect(h.audit.mock.calls.filter(([event]) => event.eventType === "server.exec")).toHaveLength(0); + }); + it("returns the same partial teardown result and keeps HTTP 409", async () => { h.serverWorkloads.mockResolvedValue([{ id: "project-a", name: "Application", appTemplateId: null }]); h.projectTeardown.mockResolvedValue({ rowDeleted: false, orphaned: [], unrecoverable: [{ error: "volume busy" }] }); @@ -2584,11 +2598,11 @@ describe("HTTP/native system parity", () => { for (const system of [local.system, remote().system]) { await expect(system.updateSettings({ productMode: "mail" })).rejects.toMatchObject({ statusCode: 403 }); await expect(system.updateEmailSettings({ host: null })).rejects.toMatchObject({ statusCode: 403 }); - await expect(system.resetSettings()).rejects.toMatchObject({ statusCode: 403 }); + await expect(system.resetSettings()).rejects.toMatchObject({ statusCode: role === "member" ? 404 : 403 }); await expect(system.health()).rejects.toMatchObject({ statusCode: 403 }); await expect(system.browse({ path: "/" })).rejects.toMatchObject({ statusCode: 403 }); await expect(system.listUntrackedEdgeSites()).rejects.toMatchObject({ statusCode: 403 }); - await expect(system.removeUntrackedEdgeSite({ hostname: "orphan.example.test" })).rejects.toMatchObject({ statusCode: 403 }); + await expect(system.removeUntrackedEdgeSite({ hostname: "orphan.example.test" })).rejects.toMatchObject({ statusCode: role === "member" ? 404 : 403 }); } } expect(h.settingsUpsert).not.toHaveBeenCalled(); diff --git a/apps/api/test/modules/mcp/mcp-tools-filter.test.ts b/apps/api/test/modules/mcp/mcp-tools-filter.test.ts index 719dad2d2..be9f00362 100644 --- a/apps/api/test/modules/mcp/mcp-tools-filter.test.ts +++ b/apps/api/test/modules/mcp/mcp-tools-filter.test.ts @@ -135,6 +135,7 @@ function principal( const granted = new Set([...(p.grantedRootTypes ?? []), ...Object.keys(wildcards)]); return { role: p.role ?? "restricted", + membershipRole: p.membershipRole, readOnly: p.readOnly ?? false, grantedRootTypes: granted, wildcardGrants: p.wildcardGrants ?? new Map(Object.entries(wildcards)), @@ -147,6 +148,16 @@ function principal( const RWA: Permission[] = ["read", "write", "admin"]; describe("filterToolsForPrincipal", () => { + it("hides server administration from members and their existing scoped tokens", () => { + const read = tool({ name: "server_read", method: "GET", perm: { root: "server", leaf: "server", grantRoot: "server", action: "read", wildcard: false } }); + const exec = tool({ name: "server_exec", method: "POST", perm: { root: "server", leaf: "server", grantRoot: "server", action: "admin", wildcard: false } }); + for (const caller of [ + principal({ role: "member" }), + principal({ role: "restricted", membershipRole: "member", grantedRootTypes: new Set(["server"]), wildcards: { server: RWA } }), + ]) expect(names(filterToolsForPrincipal([read, exec], caller))).toEqual(["server_read"]); + expect(names(filterToolsForPrincipal([read, exec], principal({ role: "admin" })))).toEqual(["server_exec", "server_read"]); + }); + it("owner sees everything", () => { const out = filterToolsForPrincipal(ALL, principal({ role: "owner" })); expect(out.length).toBe(ALL.length); diff --git a/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts b/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts index 0f616742c..06ab6469c 100644 --- a/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts +++ b/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts @@ -133,7 +133,7 @@ describe("notifications shared SDK/HTTP operations", () => { expect(await c.native.listDefaults()).toEqual([value]); expect(await c.native.categories()).toEqual(await c.remote.categories()); await db.update(schema.member).set({ role: "member" }).where(eq(schema.member.userId, owner.userId)); - for (const client of [c.native, c.remote]) await expect(client.upsertDefault({ category: "deploy.failed", defaultEnabled: false })).rejects.toMatchObject({ code: "FORBIDDEN" }); + for (const client of [c.native, c.remote]) await expect(client.upsertDefault({ category: "deploy.failed", defaultEnabled: false })).rejects.toMatchObject({ code: "NOT_FOUND" }); }); it("does not verify a replacement configuration or hide normal delivery failures", async () => { diff --git a/apps/api/test/modules/system/server-exec-authorization.test.ts b/apps/api/test/modules/system/server-exec-authorization.test.ts new file mode 100644 index 000000000..754a3fcb9 --- /dev/null +++ b/apps/api/test/modules/system/server-exec-authorization.test.ts @@ -0,0 +1,48 @@ +import "../jobs/_env"; +import { beforeEach, expect, it, vi } from "vitest"; +import { Hono } from "hono"; +import { and, eq } from "@repo/db"; + +const host = vi.hoisted(() => ({ execute: vi.fn(), command: vi.fn() })); +vi.mock("@repo/platform/engine/lib/server-execution", async original => ({ + ...await original(), + withServerExecution: host.execute, +})); +vi.mock("@repo/platform/engine/lib/agent-exec", () => ({ execOnHost: host.command })); + +import { db, schema, seedOwner } from "../jobs/_harness"; +import { serverResourceRoutes } from "../../../src/modules/system/server-resource.routes"; +import { handleApiError } from "../../../src/middleware/error-handler"; + +const app = new Hono().onError(handleApiError).route("/api/system", serverResourceRoutes); +beforeEach(() => { + vi.clearAllMocks(); + host.command.mockResolvedValue({ output: "probe", exitCode: 0, timedOut: false, truncated: false, durationMs: 1 }); + host.execute.mockImplementation(async (_org, _id, work) => work({})); +}); + +it("rejects an authenticated member before host dispatch and preserves administrator execution", async () => { + const actor = await seedOwner(); + const id = `server-${actor.userId}`; + await db.insert(schema.servers).values({ id, organizationId: actor.orgId, name: "Fixture host", sshHost: "203.0.113.10", sshUser: "root" }); + const membership = and(eq(schema.member.userId, actor.userId), eq(schema.member.organizationId, actor.orgId)); + const execute = (serverId = id) => app.request(`/api/system/servers/${serverId}/exec`, { + method: "POST", headers: { ...actor.auth, "Content-Type": "application/json" }, body: JSON.stringify({ command: "id" }), + }); + await db.update(schema.member).set({ role: "member" }).where(membership); + expect((await execute()).status).toBe(404); + expect(host.execute).not.toHaveBeenCalled(); + expect(host.command).not.toHaveBeenCalled(); + await db.update(schema.member).set({ role: "admin" }).where(membership); + expect((await execute()).status).toBe(200); + expect(host.execute).toHaveBeenCalledOnce(); + expect(host.command).toHaveBeenCalledOnce(); + const other = await seedOwner(); + const otherServer = `server-${other.userId}`; + await db.insert(schema.servers).values({ id: otherServer, organizationId: other.orgId, name: "Other organization", sshHost: "203.0.113.11" }); + expect((await execute(otherServer)).status).toBe(404); + expect(host.command).toHaveBeenCalledOnce(); + await db.update(schema.member).set({ role: "member" }).where(membership); + expect((await execute()).status).toBe(404); + expect(host.command).toHaveBeenCalledOnce(); +}); diff --git a/apps/api/test/modules/tokens/mint-org-binding.test.ts b/apps/api/test/modules/tokens/mint-org-binding.test.ts index 88e421d30..b0998efd1 100644 --- a/apps/api/test/modules/tokens/mint-org-binding.test.ts +++ b/apps/api/test/modules/tokens/mint-org-binding.test.ts @@ -188,6 +188,16 @@ beforeEach(() => { }); describe("finding 1: grant width is checked in the org the binding is written to", () => { + it("refuses server administration grants for an ordinary member", async () => { + const grants = [{ resourceType: "server", resourceId: "*", permissions: ["admin"] }]; + const refused = await authorize(OWNER_ORG, { clientId: "cli", organizationId: VICTIM_ORG, grants }); + expect(refused.status).toBe(403); + expect(refused.body.code).toBe("GRANT_EXCEEDS_ACCESS"); + expect(upsertOAuthBindingWithGrants).not.toHaveBeenCalled(); + const allowed = await authorize(OWNER_ORG, { clientId: "cli", organizationId: OWNER_ORG, grants }); + expect(allowed.status).toBe(200); + }); + /** * `billing` and `audit` are the two types `roleAllowsResourceType` denies a * member, and both are grantable — so they isolate "authority comes from the diff --git a/docs/ship-sdk-plan.md b/docs/ship-sdk-plan.md index 924be50de..9ffc7387c 100644 --- a/docs/ship-sdk-plan.md +++ b/docs/ship-sdk-plan.md @@ -202,7 +202,7 @@ Existing patterns can support the main embedding models: - One organization per customer: a stable external customer mapping selects the organization; every operation stays within it. - One personal organization per user: personal project spaces use the existing organization/membership model. -- Several users in one customer organization: restricted roles and project grants provide project-level access. Ordinary membership may be broader, so use the appropriate policy deliberately. +- Several users in one customer organization: restricted roles and project grants provide project-level access. Ordinary members have read/write access but cannot satisfy admin operations; token grants respect the user's current built-in role. - Automated project creation: reuse the create-and-grant semantics of scoped tokens, and extend them deliberately for verified native principals. Project creation and the associated access grant must have defined transactional behavior. - Namespace-oriented products: first map external namespace keys to an existing tenant or appropriate grouping. If nested namespace isolation is required, add a tenant-owned namespace model, grant semantics, scoped queries, and migrations. A string prefix or renamed project group is insufficient. diff --git a/packages/platform/src/authorization.ts b/packages/platform/src/authorization.ts index ec818a7db..fae50597e 100644 --- a/packages/platform/src/authorization.ts +++ b/packages/platform/src/authorization.ts @@ -118,14 +118,15 @@ export const PROJECT_ROOTED: ReadonlySet = new Set([ "build_session", ]); -/** Shared with capability discovery; restricted roles use grants instead. */ +/** Shared role ceiling for execution and discovery; restricted roles use grants. */ export function roleAllowsResourceType( role: "owner" | "admin" | "member", type: CheckedResourceType, + action: Permission = "read", ): boolean { if (role === "owner") return true; if (role === "admin") return type !== "billing"; - return type !== "billing" && type !== "audit"; + return action !== "admin" && type !== "billing" && type !== "audit"; } export function permitsAction(permissions: readonly GrantPermission[], action: Permission): boolean { @@ -262,9 +263,13 @@ export function createAuthorization(deps: AuthorizationDependencies) { if (!["read", "write", "admin", "create"].includes(input.action)) return false; const persistedRole = membershipRole(member); if (!persistedRole) return false; + // A token narrows its user's current authority. A previously minted grant + // must not retain administration after that user is demoted to member. + if (persistedRole !== "restricted" && !roleAllowsResourceType(persistedRole, input.resourceType, input.action)) + return false; const role = opts?.roleOverride ?? persistedRole; if (role === "owner" || role === "admin" || role === "member") - return roleAllowsResourceType(role, input.resourceType); + return roleAllowsResourceType(role, input.resourceType, input.action); if (role !== "restricted") return false; const source = opts?.grants ?? repos.resourceGrant; diff --git a/packages/platform/src/engine/modules/system/server.operations.ts b/packages/platform/src/engine/modules/system/server.operations.ts index b683ac6e8..207b73bfd 100644 --- a/packages/platform/src/engine/modules/system/server.operations.ts +++ b/packages/platform/src/engine/modules/system/server.operations.ts @@ -820,9 +820,8 @@ async function execOnServer( body: Parameters[1], ) { - // Primary gate: permission resolver (404 on deny, IDOR-safe). Asserted BEFORE the - // row is read, so a caller without access cannot distinguish "no such server" - // from "not yours". + // The shared server operation asserts server:admin before calling this service + // for every transport. Retain the organization-scoped lookup here as well. const server = await repos.server.getInOrganization(id, ctx.organizationId); if (!server) return failServer({ error: "Server not found" }, 404); diff --git a/packages/platform/test/authorization.test.ts b/packages/platform/test/authorization.test.ts index 465ec67bd..2fb4948d9 100644 --- a/packages/platform/test/authorization.test.ts +++ b/packages/platform/test/authorization.test.ts @@ -31,6 +31,45 @@ beforeEach(async () => { }); describe("shared authorization", () => { + it("does not grant administration to an ordinary member", async () => { + state.members.set("org-a:alice", { id: "member-a", role: "member" }); + state.servers.set("server-a", { organizationId: "org-a" }); + const input = { resourceType: "server" as const, resourceId: "server-a", action: "admin" as const }; + expect(await auth.checkPermission("alice", "org-a", input)).toBe(false); + expect(await auth.checkPermissionOnResource(context, input)).toBe(false); + await expect(auth.authorize(context, input)).rejects.toMatchObject({ code: "NOT_FOUND" }); + }); + + it("does not let an existing token retain administration after its owner becomes a member", async () => { + state.servers.set("server-a", { organizationId: "org-a" }); + state.tokenGrants.set("token-a:server:server-a", { permissions: ["admin"] }); + const token = await auth.resolveScope({ ...alice, tokenScope: { tokenId: "token-a" }, + credential: { organizationId: "org-a", readOnly: false } }, "org-a"); + const input = { resourceType: "server" as const, resourceId: "server-a", action: "admin" as const }; + await expect(auth.authorize(token, input)).resolves.toBeDefined(); + state.members.set("org-a:alice", { id: "member-a", role: "member" }); + await expect(auth.authorize(token, input)).rejects.toMatchObject({ code: "NOT_FOUND" }); + }); + + it.each(["project", "server", "mail_server", "settings", "job"] as const)( + "keeps member read/write access separate from %s administration", async resourceType => { + state.members.set("org-a:alice", { id: "member-a", role: "member" }); + const input = { resourceType, resourceId: "*" }; + for (const action of ["read", "write"] as const) + expect(await auth.checkPermission("alice", "org-a", { ...input, action })).toBe(true); + expect(await auth.checkPermission("alice", "org-a", { ...input, action: "admin" })).toBe(false); + }, + ); + + it("preserves explicitly delegated administration for a restricted user on one server", async () => { + state.members.set("org-a:alice", { id: "member-a", role: "restricted" }); + state.servers.set("server-a", { organizationId: "org-a" }); + state.servers.set("server-other", { organizationId: "org-a" }); + state.grants.set("org-a:alice:server:server-a", { permissions: ["admin"] }); + await expect(auth.authorize(context, { resourceType: "server", resourceId: "server-a", action: "admin" })).resolves.toBeDefined(); + await expect(auth.authorize(context, { resourceType: "server", resourceId: "server-other", action: "admin" })).rejects.toMatchObject({ code: "NOT_FOUND" }); + }); + it("derives checked resources from core without widening the existing type", () => { expectTypeOf().toEqualTypeOf(); expect(new Set(CHECKED_RESOURCE_TYPES).size).toBe(CHECKED_RESOURCE_TYPES.length); diff --git a/packages/platform/test/domains.test.ts b/packages/platform/test/domains.test.ts index 3717aee3e..131f3e09a 100644 --- a/packages/platform/test/domains.test.ts +++ b/packages/platform/test/domains.test.ts @@ -121,7 +121,7 @@ describe("organization-scoped DNS operations", () => { const dns = createDnsOperations(authorization, { operations: { addCredential } as never, requireAdmin }); const input = { provider: "cloudflare" as const, name: "Production", apiToken: "private" }; state.members.set("org-a:alice", { id: "member-a", role: "member" }); - await expect(dns.addCredential(ctx, input)).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(dns.addCredential(ctx, input)).rejects.toMatchObject({ code: "NOT_FOUND" }); expect(addCredential).not.toHaveBeenCalled(); state.members.set("org-a:alice", { id: "member-a", role: "owner" }); const identity = { ...alice, tokenScope: { tokenId: "token" }, credential: { organizationId: "org-a", readOnly: false } }; From e2d4037d7c20f8117d4b0c93e7a2bcb4fc416cf3 Mon Sep 17 00:00:00 2001 From: Hydra Date: Sun, 15 Nov 2026 13:29:45 +0200 Subject: [PATCH 2/3] test: cover member denial across Cloud relays and native credentials --- .../api/test/modules/cloud-execution-access.test.ts | 13 ++++++++++++- apps/api/test/modules/dns/managed-ingress.test.ts | 2 +- packages/sdk/test/native-runtime.test.ts | 2 +- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/apps/api/test/modules/cloud-execution-access.test.ts b/apps/api/test/modules/cloud-execution-access.test.ts index 973417ce7..1812cf15b 100644 --- a/apps/api/test/modules/cloud-execution-access.test.ts +++ b/apps/api/test/modules/cloud-execution-access.test.ts @@ -120,7 +120,7 @@ describe("Cloud relays cannot substitute Cloud feature access for host administr expect(await response.json()).toMatchObject({ data: { token: "provider-secret" } }); }); - it.each(["owner", "admin", "member"])( + it.each(["owner", "admin"])( "preserves existing full host access for the %s role", async (role) => { await db.update(schema.member).set({ role }).where(eq(schema.member.id, memberId)); @@ -129,6 +129,17 @@ describe("Cloud relays cannot substitute Cloud feature access for host administr }, ); + it("denies members host credentials through both Cloud relay selectors", async () => { + await db.update(schema.member).set({ role: "member" }).where(eq(schema.member.id, memberId)); + for (const path of ["token", `token?serverId=${serverId}`, "resource-proxy", `resource-proxy?serverId=${serverId}`]) { + const response = await post(path, { operation: "list" }); + expect(response.status, await response.clone().text()).toBe(404); + } + expect(h.token).not.toHaveBeenCalled(); + expect(h.namespace).not.toHaveBeenCalled(); + expect(h.pages).not.toHaveBeenCalled(); + }); + it("does not bootstrap a server or credentials for an empty organization without host authority", async () => { actor = await seedOwner(); const membership = (await repos.member.find(actor.orgId, actor.userId))!; diff --git a/apps/api/test/modules/dns/managed-ingress.test.ts b/apps/api/test/modules/dns/managed-ingress.test.ts index 9bc116e4c..9593efea9 100644 --- a/apps/api/test/modules/dns/managed-ingress.test.ts +++ b/apps/api/test/modules/dns/managed-ingress.test.ts @@ -94,6 +94,6 @@ describe("managed ingress through authenticated HTTP and the public SDK", () => headers, body: JSON.stringify({ credentialId: "no-secret" }), }); - expect(denied.status).toBe(403); + expect(denied.status).toBe(404); }); }); diff --git a/packages/sdk/test/native-runtime.test.ts b/packages/sdk/test/native-runtime.test.ts index daa1440f4..9c607c1ac 100644 --- a/packages/sdk/test/native-runtime.test.ts +++ b/packages/sdk/test/native-runtime.test.ts @@ -729,7 +729,7 @@ describe("owned native platform on Node", () => { await controls.setSleepMode(projectId, { sleep_mode: "always_on" }); expect((await controls.getResources(projectId)).sleepMode).toBe("always_on"); const bobScope = await first!.ship.scope({ identity: "bob", organizationId: first!.customer.organizationId }); - await expect(bobScope.credentials.create({ provider: "docker-registry", name: "Not an admin", values: { secret: "value" } })).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(bobScope.credentials.create({ provider: "docker-registry", name: "Not an admin", values: { secret: "value" } })).rejects.toMatchObject({ code: "NOT_FOUND" }); await first!.ship.operator!.setMembership({ organizationId: first!.customer.organizationId, userId: first!.bob.user.id, role: null }); await expect(bobScope.projects.get(projects[0]!.id)).rejects.toMatchObject({ code: "NOT_FOUND" }); await expect(bobScope.projects.setBranch(projectId, { branch: "forbidden" })).rejects.toMatchObject({ code: "NOT_FOUND" }); From d5fab2c34ecb993a491a8e53701937b5197f8c9f Mon Sep 17 00:00:00 2001 From: Hydra Date: Sun, 15 Nov 2026 14:31:10 +0200 Subject: [PATCH 3/3] fix: preserve cross-workspace MCP discovery with shared role checks --- apps/api/src/modules/mcp/mcp-tools.ts | 15 +++++++-------- apps/api/src/modules/mcp/mcp.routes.ts | 2 +- apps/api/test/modules/mcp/mcp-workspaces.test.ts | 16 ++++++++++++++++ packages/platform/src/authorization.ts | 15 +++++++-------- 4 files changed, 31 insertions(+), 17 deletions(-) diff --git a/apps/api/src/modules/mcp/mcp-tools.ts b/apps/api/src/modules/mcp/mcp-tools.ts index d95a76c89..12cf298e5 100644 --- a/apps/api/src/modules/mcp/mcp-tools.ts +++ b/apps/api/src/modules/mcp/mcp-tools.ts @@ -76,7 +76,7 @@ export interface McpPrincipal { /** Resolved with the same persisted instance-authority policy as HTTP calls. */ instanceAdmin?: boolean; role: "owner" | "admin" | "member" | "restricted"; - /** Current membership before narrowing it to the credential's grants. */ + /** For scoped tokens, the current membership in their bound organization. */ membershipRole?: "owner" | "admin" | "member" | "restricted"; readOnly: boolean; /** Resource types the token holds grants on — only consulted when role === "restricted". */ @@ -356,8 +356,9 @@ export function filterToolsForPrincipal( ): McpToolDef[] { return tools.filter((t) => { const action = assertedAction(t.perm.action); - if (principal.membershipRole && principal.membershipRole !== "restricted" && - !roleAllowsResourceType(principal.membershipRole, t.perm.leaf as CheckedResourceType, action)) return false; + const role = principal.membershipRole ?? principal.role; + if (role !== "restricted" && + !roleAllowsResourceType(role, t.perm.leaf as CheckedResourceType, action)) return false; // Read-only tokens can only call GET — the runtime gate rejects mutations by // HTTP method, so mirror that exactly rather than guessing from the tag. if (principal.readOnly && t.method !== "GET") return false; @@ -381,9 +382,7 @@ export function filterToolsForPrincipal( if (principal.role === "restricted" && !caps?.has(needed)) return false; } - if (principal.role !== "restricted") { - return roleAllowsResourceType(principal.role, t.perm.leaf as CheckedResourceType, action); - } + if (principal.role !== "restricted") return true; // "Own projects" scope: the create-capable project wildcard grant reaches the // dedicated create routes (POST /projects, POST /apps) and the project list // (which the caller filters to its self-created projects). Checked before the @@ -409,11 +408,11 @@ export function filterToolsForPrincipal( // A per-id grant still fails here, correctly: `wildcardGrants` holds only // resourceId "*" rows. const held = principal.wildcardGrants.get(t.perm.leaf); - return held ? permitsAction(held, assertedAction(t.perm.action)) : false; + return held ? permitsAction(held, action) : false; } if (principalHasGrantFor(principal.grantedRootTypes, t.perm.grantRoot)) return true; // Same mapping the permission check uses: `domain:admin` ⇒ `domains:delete`. - const capability = capabilityFor(t.perm.leaf, assertedAction(t.perm.action)); + const capability = capabilityFor(t.perm.leaf, action); return !!capability && !!principal.grantedCapabilities?.has(capability); }); } diff --git a/apps/api/src/modules/mcp/mcp.routes.ts b/apps/api/src/modules/mcp/mcp.routes.ts index 14da7d1db..16d90eab1 100644 --- a/apps/api/src/modules/mcp/mcp.routes.ts +++ b/apps/api/src/modules/mcp/mcp.routes.ts @@ -128,7 +128,7 @@ async function resolveMcpCaller(token: string, headers: Headers): Promise { expect(denied.isError).toBe(true); }); + it.each([false, true])("advertises administration in another workspace only for an unbound credential (bound=%s)", async bound => { + const owner = await seedOwner({ bound }); + await secondWorkspace(owner, "admin"); + await db.update(schema.member).set({ role: "member" }).where(and(eq(schema.member.userId, owner.userId), eq(schema.member.organizationId, owner.orgId))); + const listed = await (await rpc(owner, "tools/list")).json() as { result: { tools: { name: string }[] } }; + expect(listed.result.tools.some(tool => tool.name === "delete_projects_by_id")).toBe(!bound); + if (!bound) { + const group = await repos.projectGroup.create({ organizationId: owner.orgId, name: "Member project", slug: "member-project" }); + const project = await repos.project.create({ organizationId: owner.orgId, groupId: group.id, name: "Member project", slug: "member-project" }); + const denied = await call(owner, "delete_projects_by_id", { id: project.id, organizationId: owner.orgId }); + expect(denied).toMatchObject({ isError: true, data: { code: "NOT_FOUND" } }); + expect(forwarding.fetch).toHaveBeenCalled(); + expect(await repos.project.findById(project.id)).toMatchObject({ id: project.id }); + } + }); + it("shares the discovery contract with SDKs and respects fixed native scopes", async () => { const owner = await seedOwner({ bound: false }); const target = await secondWorkspace(owner); diff --git a/packages/platform/src/authorization.ts b/packages/platform/src/authorization.ts index fae50597e..1411936e1 100644 --- a/packages/platform/src/authorization.ts +++ b/packages/platform/src/authorization.ts @@ -99,7 +99,8 @@ export interface AuthorizationDependencies { } export interface PermissionOptions { - roleOverride?: ContextRole; + /** A credential may narrow membership authority to its own grants. */ + roleOverride?: "restricted"; grants?: PermissionGrantSource; } @@ -122,7 +123,7 @@ export const PROJECT_ROOTED: ReadonlySet = new Set([ export function roleAllowsResourceType( role: "owner" | "admin" | "member", type: CheckedResourceType, - action: Permission = "read", + action: Permission, ): boolean { if (role === "owner") return true; if (role === "admin") return type !== "billing"; @@ -265,12 +266,10 @@ export function createAuthorization(deps: AuthorizationDependencies) { if (!persistedRole) return false; // A token narrows its user's current authority. A previously minted grant // must not retain administration after that user is demoted to member. - if (persistedRole !== "restricted" && !roleAllowsResourceType(persistedRole, input.resourceType, input.action)) - return false; - const role = opts?.roleOverride ?? persistedRole; - if (role === "owner" || role === "admin" || role === "member") - return roleAllowsResourceType(role, input.resourceType, input.action); - if (role !== "restricted") return false; + if (persistedRole !== "restricted") { + if (!roleAllowsResourceType(persistedRole, input.resourceType, input.action)) return false; + if (opts?.roleOverride !== "restricted") return true; + } const source = opts?.grants ?? repos.resourceGrant; // A create-only wildcard permits creation and a filtered list, never an