fix(mcp): gate API-key collection with system:admin-access so superusers can issue keys
The MCP plugin's key collection was gated by hasRoles(), which reads only
the legacy roles enum column. All current admins authenticate through
dynamic roleDocs superuser roles, so nobody could create an MCP API key
and every client of /api/mcp got 401. Both override blocks (MCP keys and
the AI plugin instructions) now use requirePermission('system:admin-access'),
and the sync-only admin.hidden checks were dropped in favor of the read
gate, matching the repo's requireAdminPageAccess pattern.
Adds tests/int/mcp-api-keys.int.spec.ts covering the plain-user rejection,
dynamic-superuser key creation with HMAC index resolution (mirroring the
plugin's resolveAccessSettings), explicit system:admin-access grants, and
read visibility.
This commit is contained in:
parent
a96eddf32c
commit
f97912f1c1
2 changed files with 199 additions and 17 deletions
|
|
@ -92,7 +92,7 @@ import { CustomRadioTestScores } from "@/collections/minigames/CustomRadioTestSc
|
|||
import { RibbonSubmissions } from "@/collections/users/RibbonSubmissions";
|
||||
import { PromotionNominations } from "@/collections/users/PromotionNominations";
|
||||
import { LeadershipTransfers } from "@/collections/users/LeadershipTransfers";
|
||||
import hasRoles from "@/utils/access-control/hasRoles";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
import { scopedAdminPageAccess } from "@/utils/access-control/divisionAccess";
|
||||
import { payloadAiPlugin, PayloadAiPluginLexicalEditorFeature } from "@ai-stack/payloadcms";
|
||||
import type { SeedPromptFunction } from "@ai-stack/payloadcms/types";
|
||||
|
|
@ -101,7 +101,6 @@ import { formBuilderPlugin } from "@payloadcms/plugin-form-builder";
|
|||
import { surveyFormBuilderConfig } from "@/lib/surveys/formBuilderConfig";
|
||||
import { createOpenAI } from "@ai-sdk/openai";
|
||||
import { createTextStreamResponse, jsonSchema, streamObject } from "ai";
|
||||
import type { User } from "@/payload-types";
|
||||
|
||||
// Ornith-9B is served by the "Apex" Unsloth connection (a separate machine,
|
||||
// apex-lnx / 192.168.1.7), reached through Unsloth Studio's OpenAI-compatible
|
||||
|
|
@ -509,18 +508,22 @@ export default buildConfig({
|
|||
// storage-adapter-placeholder
|
||||
mcpPlugin({
|
||||
collections: mcpCollections,
|
||||
// MCP API keys let a client act as their user, so issuing them is a
|
||||
// superuser-tier operation: `system:admin-access` passes for dynamic
|
||||
// superusers (hasPermission bypass) and for roles explicitly holding it.
|
||||
// The legacy `hasRoles` enum check this replaced read only the old
|
||||
// `roles` column, which every current admin user lacks, so nobody could
|
||||
// create or see keys and no MCP client could authenticate. Admin-panel
|
||||
// visibility follows the read gate (the repo's requireAdminPageAccess
|
||||
// pattern); `admin.hidden` is sync-only and cannot run permission lookups.
|
||||
overrideApiKeyCollection: (collection) => ({
|
||||
...collection,
|
||||
admin: {
|
||||
...collection.admin,
|
||||
hidden: ({ user }) => !hasRoles(["admin", "developer"], user as User),
|
||||
},
|
||||
access: {
|
||||
...collection.access,
|
||||
read: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
|
||||
update: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
|
||||
create: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
|
||||
delete: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
|
||||
read: requirePermission("system:admin-access"),
|
||||
update: requirePermission("system:admin-access"),
|
||||
create: requirePermission("system:admin-access"),
|
||||
delete: requirePermission("system:admin-access"),
|
||||
},
|
||||
}),
|
||||
}),
|
||||
|
|
@ -589,15 +592,14 @@ export default buildConfig({
|
|||
[Labels.slug]: true,
|
||||
},
|
||||
debugging: true,
|
||||
// Same superuser-tier gate as the MCP API keys above; the AI plugin's
|
||||
// instructions collection is admin-only tooling.
|
||||
overrideInstructions: {
|
||||
admin: {
|
||||
hidden: ({ user }) => !hasRoles(["admin", "developer"], user as User),
|
||||
},
|
||||
access: {
|
||||
read: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
|
||||
update: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
|
||||
create: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
|
||||
delete: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
|
||||
read: requirePermission("system:admin-access"),
|
||||
update: requirePermission("system:admin-access"),
|
||||
create: requirePermission("system:admin-access"),
|
||||
delete: requirePermission("system:admin-access"),
|
||||
},
|
||||
},
|
||||
generationModels: [
|
||||
|
|
|
|||
180
tests/int/mcp-api-keys.int.spec.ts
Normal file
180
tests/int/mcp-api-keys.int.spec.ts
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
import crypto from "crypto";
|
||||
import { getPayload, Payload } from "payload";
|
||||
import config from "@/payload.config";
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
import type { Role, User } from "@/payload-types";
|
||||
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
|
||||
|
||||
let payload: Payload;
|
||||
|
||||
const RUN = `mcpkeys-${Date.now().toString(36)}`;
|
||||
const TIMEOUT = 30_000;
|
||||
|
||||
/**
|
||||
* The MCP plugin exposes its API-key collection (`payload-mcp-api-keys`) to
|
||||
* every logged-in user by default ("manage only their OWN keys"). The app's
|
||||
* override restricts it to the superuser tier via `requirePermission
|
||||
* ("system:admin-access")`. An earlier override used the legacy `hasRoles`
|
||||
* enum check, which no current admin user satisfies, so NOBODY could create
|
||||
* keys and no MCP client could authenticate (the endpoint 401'd for everyone).
|
||||
*/
|
||||
describe("MCP API key collection access (payload-mcp-api-keys)", () => {
|
||||
const roleIds: number[] = [];
|
||||
const userIds: number[] = [];
|
||||
const keyIds: number[] = [];
|
||||
|
||||
let plainUser: User;
|
||||
let superUser: User;
|
||||
let scopedAdminUser: User;
|
||||
|
||||
const makeRole = async (label: string, extra: Partial<Role> = {}): Promise<Role> => {
|
||||
const role = (await payload.create({
|
||||
collection: "roles",
|
||||
data: { name: `${RUN}-${label}`, slug: `${RUN}-${label}`, ...extra },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as Role;
|
||||
roleIds.push(role.id);
|
||||
invalidatePermissionCache();
|
||||
return role;
|
||||
};
|
||||
|
||||
const makeUser = async (label: string, roleId: number): Promise<User> => {
|
||||
const user = (await payload.create({
|
||||
collection: "users",
|
||||
data: {
|
||||
username: `${RUN}-${label}`,
|
||||
discordUsername: `${RUN}-${label}`,
|
||||
displayName: label.toUpperCase(),
|
||||
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
||||
password: "Test123",
|
||||
roleDocs: [roleId],
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as User;
|
||||
userIds.push(user.id);
|
||||
invalidatePermissionCache();
|
||||
return user;
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({ config });
|
||||
|
||||
const plainRole = await makeRole("plain");
|
||||
const superRole = await makeRole("super", { isSuperuser: true });
|
||||
const scopedRole = await makeRole("scoped", { permissions: ["system:admin-access"] });
|
||||
|
||||
plainUser = await makeUser("plain", plainRole.id);
|
||||
superUser = await makeUser("super", superRole.id);
|
||||
scopedAdminUser = await makeUser("scoped", scopedRole.id);
|
||||
}, TIMEOUT);
|
||||
|
||||
afterAll(async () => {
|
||||
if (!payload) return;
|
||||
for (const id of keyIds) {
|
||||
await payload
|
||||
.delete({ collection: "payload-mcp-api-keys", id, overrideAccess: true })
|
||||
.catch(() => {});
|
||||
}
|
||||
for (const id of userIds) {
|
||||
// User creation auto-creates a Profile; its user_id is NOT NULL, so it
|
||||
// must go before the user (the repo's other specs do the same).
|
||||
const profiles = await payload
|
||||
.find({ collection: "profiles", where: { user: { equals: id } }, overrideAccess: true })
|
||||
.catch(() => ({ docs: [] as { id: number | string }[] }));
|
||||
for (const p of profiles.docs) {
|
||||
await payload.delete({ collection: "profiles", id: p.id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
for (const id of roleIds) {
|
||||
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
invalidatePermissionCache();
|
||||
}, TIMEOUT);
|
||||
|
||||
it(
|
||||
"rejects key creation by regular users",
|
||||
async () => {
|
||||
await expect(
|
||||
payload.create({
|
||||
collection: "payload-mcp-api-keys",
|
||||
data: { label: `${RUN}-nope`, enableAPIKey: true, user: plainUser.id },
|
||||
user: plainUser,
|
||||
overrideAccess: false,
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"lets a dynamic superuser create a key that resolves like the MCP endpoint does",
|
||||
async () => {
|
||||
// Payload stores whatever plaintext key the creator supplies (the admin
|
||||
// panel's Generate button does the same via the auth route); the plugin
|
||||
// authenticates by HMAC-SHA256-indexing it with the Payload secret.
|
||||
const rawKey = `${RUN}-${crypto.randomBytes(24).toString("hex")}`;
|
||||
const key = await payload.create({
|
||||
collection: "payload-mcp-api-keys",
|
||||
data: { label: `${RUN}-super`, enableAPIKey: true, apiKey: rawKey, user: superUser.id },
|
||||
user: superUser,
|
||||
overrideAccess: false,
|
||||
});
|
||||
keyIds.push(key.id as number);
|
||||
|
||||
expect((key as unknown as Record<string, unknown>).apiKey).toBe(rawKey);
|
||||
|
||||
const apiKeyIndex = crypto
|
||||
.createHmac("sha256", payload.secret)
|
||||
.update(rawKey)
|
||||
.digest("hex");
|
||||
const { docs } = await payload.find({
|
||||
collection: "payload-mcp-api-keys",
|
||||
where: { apiKeyIndex: { equals: apiKeyIndex } },
|
||||
depth: 1,
|
||||
limit: 1,
|
||||
pagination: false,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(docs).toHaveLength(1);
|
||||
const owner = docs[0].user as unknown as User | number;
|
||||
expect(typeof owner === "object" ? owner.id : owner).toBe(superUser.id);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"lets a role explicitly granted system:admin-access create keys too",
|
||||
async () => {
|
||||
const key = await payload.create({
|
||||
collection: "payload-mcp-api-keys",
|
||||
data: { label: `${RUN}-scoped`, enableAPIKey: true, user: scopedAdminUser.id },
|
||||
user: scopedAdminUser,
|
||||
overrideAccess: false,
|
||||
});
|
||||
keyIds.push(key.id as number);
|
||||
expect(key.id).toBeDefined();
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"hides existing keys from regular users",
|
||||
async () => {
|
||||
// The gate returns a boolean false for non-superusers, so Payload
|
||||
// rejects the query outright rather than filtering to an empty list.
|
||||
await expect(
|
||||
payload.find({
|
||||
collection: "payload-mcp-api-keys",
|
||||
user: plainUser,
|
||||
overrideAccess: false,
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
});
|
||||
Loading…
Reference in a new issue