From 7b4e1bc5550a03c072c9b65d78ba76cd19ce643b Mon Sep 17 00:00:00 2001 From: Brandon Pereira Date: Mon, 30 Nov 2026 13:16:39 -0600 Subject: [PATCH 1/5] feat: limit org API keys to MCP or the External API Org keys get an optional allowedSurfaces list. Absent means both surfaces, so existing keys and PATs keep working; a list restricts the key and an empty list fails closed. A new requireOrgKeySurface middleware enforces it on every /api/v2 route and POST /mcp with a 403. Team Settings gains an opt-in surface restriction on create and an Access column showing All, MCP, or API. --- .changeset/org-key-allowed-surfaces.md | 10 +++ .../__tests__/orgApiKey.int.test.ts | 53 ++++++++++++++ packages/api/src/controllers/orgApiKey.ts | 6 +- packages/api/src/controllers/user.ts | 2 +- .../__tests__/orgApiKeySurface.int.test.ts | 66 +++++++++++++++++ packages/api/src/mcp/app.ts | 8 ++- .../api/src/middleware/orgApiKeySurface.ts | 51 +++++++++++++ packages/api/src/models/user.ts | 13 ++++ .../external-api/__tests__/v2.int.test.ts | 55 +++++++++++++- .../api/src/routers/external-api/v2/index.ts | 32 ++++----- .../TeamSettings/CreateOrgApiKeyModal.tsx | 51 ++++++++++++- .../TeamSettings/OrgApiKeysSection.tsx | 17 ++++- .../__tests__/OrgApiKeysSection.test.tsx | 71 ++++++++++++++++++- packages/common-utils/src/types.ts | 9 +++ 14 files changed, 421 insertions(+), 23 deletions(-) create mode 100644 .changeset/org-key-allowed-surfaces.md create mode 100644 packages/api/src/mcp/__tests__/orgApiKeySurface.int.test.ts create mode 100644 packages/api/src/middleware/orgApiKeySurface.ts diff --git a/.changeset/org-key-allowed-surfaces.md b/.changeset/org-key-allowed-surfaces.md new file mode 100644 index 0000000000..4febba4a22 --- /dev/null +++ b/.changeset/org-key-allowed-surfaces.md @@ -0,0 +1,10 @@ +--- +'@hyperdx/api': patch +'@hyperdx/app': patch +'@hyperdx/common-utils': patch +--- + +feat: let organization API keys be restricted to the MCP server or the +External API. A key created without a restriction keeps working on both, as +does a personal access key. This closes the bypass where an MCP-only key could +call `/api/v2` and read connections hidden from agents. diff --git a/packages/api/src/controllers/__tests__/orgApiKey.int.test.ts b/packages/api/src/controllers/__tests__/orgApiKey.int.test.ts index f5dd34aaa1..2d21d75b08 100644 --- a/packages/api/src/controllers/__tests__/orgApiKey.int.test.ts +++ b/packages/api/src/controllers/__tests__/orgApiKey.int.test.ts @@ -1,7 +1,9 @@ +import { CreateOrgApiKeyRequestSchema } from '@hyperdx/common-utils/dist/types'; import mongoose from 'mongoose'; import { createOrgApiKey, + formatOrgApiKey, listOrgApiKeys, revokeOrgApiKey, touchOrgApiKeyLastUsed, @@ -141,6 +143,57 @@ describe('orgApiKey controller', () => { expect(await lastUsed()).toBe(t6.getTime()); }); + describe('allowed surfaces', () => { + it('stores and returns the restricted surfaces', async () => { + const team = await createTeam({ name: 'A' }); + const { doc } = await createOrgApiKey(team._id, creator, { + description: 'mcp only', + expiry: '30d', + allowedSurfaces: ['mcp'], + }); + + expect(doc.allowedSurfaces).toEqual(['mcp']); + expect((await User.findById(doc._id).lean())?.allowedSurfaces).toEqual([ + 'mcp', + ]); + expect(formatOrgApiKey(doc).allowedSurfaces).toEqual(['mcp']); + }); + + it('returns null for an unrestricted key', async () => { + const team = await createTeam({ name: 'A' }); + const { doc } = await create(team._id); + + expect(doc.allowedSurfaces).toBeUndefined(); + expect(formatOrgApiKey(doc).allowedSurfaces).toBeNull(); + }); + + it('returns a stored empty list instead of treating it as unrestricted', async () => { + const team = await createTeam({ name: 'A' }); + const { doc } = await create(team._id); + await User.updateOne({ _id: doc._id }, { allowedSurfaces: [] }); + + const stored = await User.findById(doc._id); + expect(formatOrgApiKey(stored!).allowedSurfaces).toEqual([]); + }); + + it('rejects an empty list on create', () => { + const base = { description: 'terraform', expiry: '30d' }; + expect( + CreateOrgApiKeyRequestSchema.safeParse({ + ...base, + allowedSurfaces: [], + }).success, + ).toBe(false); + expect( + CreateOrgApiKeyRequestSchema.safeParse({ + ...base, + allowedSurfaces: ['mcp'], + }).success, + ).toBe(true); + expect(CreateOrgApiKeyRequestSchema.safeParse(base).success).toBe(true); + }); + }); + describe('service accounts', () => { it('creates a service account user for each key', async () => { const team = await createTeam({ name: 'A' }); diff --git a/packages/api/src/controllers/orgApiKey.ts b/packages/api/src/controllers/orgApiKey.ts index 059c7ae747..a9a2a898b2 100644 --- a/packages/api/src/controllers/orgApiKey.ts +++ b/packages/api/src/controllers/orgApiKey.ts @@ -40,7 +40,7 @@ function expiresAtFor(expiry: OrgApiKeyExpiry, now: number): Date | null { export async function createOrgApiKey( teamId: string | ObjectId, createdBy: string | ObjectId, - { description, expiry }: CreateOrgApiKeyRequest, + { description, expiry, allowedSurfaces }: CreateOrgApiKeyRequest, ) { const key = `${ORG_API_KEY_PREFIX}${crypto.randomBytes(32).toString('base64url')}`; // `.invalid` is reserved, so the email can never reach a real inbox. @@ -51,6 +51,7 @@ export async function createOrgApiKey( accessKey: hashOrgApiKey(key), expiresAt: expiresAtFor(expiry, Date.now()), createdBy: new mongoose.Types.ObjectId(createdBy), + allowedSurfaces, }); return { doc, key }; } @@ -122,6 +123,9 @@ export function formatOrgApiKey( createdAt: doc.createdAt.toISOString(), expiresAt: doc.expiresAt?.toISOString() ?? null, lastUsedAt: doc.lastUsedAt?.toISOString() ?? null, + // null distinguishes unrestricted from a stored empty list, which denies + // every surface. + allowedSurfaces: doc.allowedSurfaces ? [...doc.allowedSurfaces] : null, createdBy: creator ? { id: creator._id.toString(), diff --git a/packages/api/src/controllers/user.ts b/packages/api/src/controllers/user.ts index 51e8a451e9..e3e9e817ba 100644 --- a/packages/api/src/controllers/user.ts +++ b/packages/api/src/controllers/user.ts @@ -65,7 +65,7 @@ export function createVirtualUser({ name: string; accessKey?: string; teamId: string | ObjectId; -} & Pick) { +} & Pick) { return User.create({ name, team: teamId, diff --git a/packages/api/src/mcp/__tests__/orgApiKeySurface.int.test.ts b/packages/api/src/mcp/__tests__/orgApiKeySurface.int.test.ts new file mode 100644 index 0000000000..4f7bb8d99b --- /dev/null +++ b/packages/api/src/mcp/__tests__/orgApiKeySurface.int.test.ts @@ -0,0 +1,66 @@ +import { createOrgApiKey } from '@/controllers/orgApiKey'; +import { getAgent, getLoggedInAgent, getServer } from '@/fixtures'; +import User from '@/models/user'; + +describe('MCP org API key surfaces', () => { + const server = getServer(); + + beforeAll(async () => { + await server.start(); + }); + + afterEach(async () => { + await server.clearDBs(); + jest.clearAllMocks(); + }); + + afterAll(async () => { + await server.stop(); + }); + + const setup = async (allowedSurfaces?: ('mcp' | 'api')[]) => { + const { agent, team, user } = await getLoggedInAgent(server); + const { doc, key } = await createOrgApiKey(team._id, user._id, { + description: 'terraform', + expiry: '30d', + allowedSurfaces, + }); + return { agent, user, doc, key }; + }; + + const listTools = (agent: ReturnType, key: string) => + agent + .post('/mcp') + .set('Authorization', `Bearer ${key}`) + .set('Accept', 'application/json, text/event-stream') + .send({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }); + + it('allows an MCP-only key', async () => { + const { agent, key } = await setup(['mcp']); + expect((await listTools(agent, key)).status).toBe(200); + }); + + it('allows an unrestricted key', async () => { + const { agent, key } = await setup(); + expect((await listTools(agent, key)).status).toBe(200); + }); + + it('allows personal access keys', async () => { + const { agent, user } = await setup(); + expect((await listTools(agent, user.accessKey)).status).toBe(200); + }); + + it('rejects an External-API-only key', async () => { + const { agent, key } = await setup(['api']); + const res = await listTools(agent, key).expect(403); + expect(res.body.message).toBe( + 'This API key is limited to the External API', + ); + }); + + it('rejects a stored empty surface list', async () => { + const { agent, doc, key } = await setup(); + await User.updateOne({ _id: doc._id }, { allowedSurfaces: [] }); + await listTools(agent, key).expect(403); + }); +}); diff --git a/packages/api/src/mcp/app.ts b/packages/api/src/mcp/app.ts index 2a189914a6..b9a8a1218a 100644 --- a/packages/api/src/mcp/app.ts +++ b/packages/api/src/mcp/app.ts @@ -4,6 +4,7 @@ import express from 'express'; import { validateUserAccessKey } from '@/middleware/auth'; import { parseBody } from '@/middleware/bodyParser'; +import { requireOrgKeySurface } from '@/middleware/orgApiKeySurface'; import { setBusinessContext } from '@/utils/instrumentation'; import logger from '@/utils/logger'; import rateLimiter, { rateLimiterKeyGenerator } from '@/utils/rateLimiter'; @@ -41,7 +42,12 @@ const methodNotAllowed = (_req: express.Request, res: express.Response) => { app.get('/', mcpRateLimiter, methodNotAllowed); app.delete('/', mcpRateLimiter, methodNotAllowed); -const authorizePost = [mcpRateLimiter, validateUserAccessKey, ...parseBody]; +const authorizePost = [ + mcpRateLimiter, + validateUserAccessKey, + requireOrgKeySurface('mcp'), + ...parseBody, +]; app.post('/', authorizePost, async (req, res) => { const transport = new StreamableHTTPServerTransport({ diff --git a/packages/api/src/middleware/orgApiKeySurface.ts b/packages/api/src/middleware/orgApiKeySurface.ts new file mode 100644 index 0000000000..ce1ce396f5 --- /dev/null +++ b/packages/api/src/middleware/orgApiKeySurface.ts @@ -0,0 +1,51 @@ +import type { OrgApiKeySurface } from '@hyperdx/common-utils/dist/types'; +import type { NextFunction, Request, Response } from 'express'; + +import { getCounter, getServerSpan } from '@/utils/instrumentation'; + +const surfaceDenied = getCounter('hyperdx.org_api_key.surface_denied', { + description: + 'Requests refused because an org API key is limited to another surface.', +}); + +// Names the surface the key is limited to, as seen from the one it was denied +// on. +function deniedMessage(surface: OrgApiKeySurface) { + switch (surface) { + case 'api': + return 'This API key is limited to MCP'; + case 'mcp': + return 'This API key is limited to the External API'; + } +} + +/** + * Refuses an org API key presented on a surface it is not allowed on. Personal + * access keys and virtual users that are not org keys pass through unchanged. + * + * Runs after validateUserAccessKey, which is what loads req.user. An absent + * allowedSurfaces list is unrestricted, including for keys created before the + * field existed; a stored empty list denies every surface. + */ +export function requireOrgKeySurface(surface: OrgApiKeySurface) { + return (req: Request, res: Response, next: NextFunction) => { + const user = req.user; + if (!user?.isVirtual || user.createdBy == null) { + return next(); + } + + const allowed = user.allowedSurfaces; + if (allowed == null || allowed.includes(surface)) { + return next(); + } + + surfaceDenied.add(1, { surface }); + getServerSpan()?.setAttributes({ + 'hyperdx.org_api_key.surface': surface, + 'hyperdx.org_api_key.surface_denied': true, + }); + // 403, not 401: a 401 reads as a bad key and can start an MCP client's + // OAuth flow. + res.status(403).json({ message: deniedMessage(surface) }); + }; +} diff --git a/packages/api/src/models/user.ts b/packages/api/src/models/user.ts index 04a78d878f..bba3016aa2 100644 --- a/packages/api/src/models/user.ts +++ b/packages/api/src/models/user.ts @@ -1,6 +1,7 @@ import { ONBOARDING_TASK_IDS, type OnboardingData, + type OrgApiKeySurface, } from '@hyperdx/common-utils/dist/types'; // @ts-expect-error don't install the @types for this package, as it conflicts with mongoose import passportLocalMongoose from '@hyperdx/passport-local-mongoose'; @@ -25,6 +26,10 @@ export interface IUser { lastUsedAt?: Date | null; revokedAt?: Date | null; createdBy?: ObjectId; + // Only meaningful on an org-key virtual user (isVirtual with createdBy); + // requireOrgKeySurface ignores it everywhere else. Absent means every + // surface; a list means only those surfaces. + allowedSurfaces?: OrgApiKeySurface[]; team: ObjectId; } @@ -52,6 +57,14 @@ const UserSchema = new Schema( lastUsedAt: Date, revokedAt: Date, createdBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, + // Org API keys only; see requireOrgKeySurface. Mongoose defaults array + // paths to [], which would read as "no surfaces", so default: undefined + // keeps an unrestricted key indistinguishable from one created before this + // field existed. + allowedSurfaces: { + type: [{ type: String, enum: ['mcp', 'api'] }], + default: undefined, + }, onboardingData: { type: new Schema( { diff --git a/packages/api/src/routers/external-api/__tests__/v2.int.test.ts b/packages/api/src/routers/external-api/__tests__/v2.int.test.ts index afcb0e8708..907b5235d1 100644 --- a/packages/api/src/routers/external-api/__tests__/v2.int.test.ts +++ b/packages/api/src/routers/external-api/__tests__/v2.int.test.ts @@ -32,11 +32,12 @@ describe('external api v2', () => { }); describe('org API keys', () => { - const setup = async () => { + const setup = async (allowedSurfaces?: ('mcp' | 'api')[]) => { const { agent, team, user } = await getLoggedInAgent(server); const { doc, key } = await createOrgApiKey(team._id, user._id, { description: 'terraform', expiry: '30d', + allowedSurfaces, }); return { agent, team, user, doc, key }; }; @@ -130,6 +131,58 @@ describe('external api v2', () => { expect((await listTools()).status).toBe(401); }); + it('rejects an MCP-only key on every External API route', async () => { + const { agent, key } = await setup(['mcp']); + + const root = await agent + .get('/api/v2') + .set('Authorization', `Bearer ${key}`) + .expect(403); + expect(root.body.message).toBe('This API key is limited to MCP'); + + const dashboards = await agent + .get('/api/v2/dashboards') + .set('Authorization', `Bearer ${key}`) + .expect(403); + expect(dashboards.body.message).toBe('This API key is limited to MCP'); + }); + + it('allows an API-only key', async () => { + const { agent, key } = await setup(['api']); + await agent + .get('/api/v2') + .set('Authorization', `Bearer ${key}`) + .expect(200); + }); + + it('allows unrestricted keys, including ones created before the field', async () => { + const { agent, doc, key } = await setup(); + await agent + .get('/api/v2') + .set('Authorization', `Bearer ${key}`) + .expect(200); + + // A key whose stored document predates allowedSurfaces reads as + // unrestricted. + await User.collection.updateOne( + { _id: doc._id }, + { $unset: { allowedSurfaces: '' } }, + ); + await agent + .get('/api/v2') + .set('Authorization', `Bearer ${key}`) + .expect(200); + }); + + it('rejects a stored empty surface list', async () => { + const { agent, doc, key } = await setup(); + await User.updateOne({ _id: doc._id }, { allowedSurfaces: [] }); + await agent + .get('/api/v2') + .set('Authorization', `Bearer ${key}`) + .expect(403); + }); + it('responds with an error when the key lookup fails', async () => { const { agent, key } = await setup(); jest diff --git a/packages/api/src/routers/external-api/v2/index.ts b/packages/api/src/routers/external-api/v2/index.ts index d9bcf20671..1722e732ad 100644 --- a/packages/api/src/routers/external-api/v2/index.ts +++ b/packages/api/src/routers/external-api/v2/index.ts @@ -4,6 +4,7 @@ import omit from 'lodash/omit'; import { EXTERNAL_API_RATE_LIMIT_MAX } from '@/config'; import { validateUserAccessKey } from '@/middleware/auth'; import { parseBody } from '@/middleware/bodyParser'; +import { requireOrgKeySurface } from '@/middleware/orgApiKeySurface'; import alertsRouter from '@/routers/external-api/v2/alerts'; import chartsRouter from '@/routers/external-api/v2/charts'; import connectionsRouter from '@/routers/external-api/v2/connections'; @@ -25,7 +26,12 @@ const defaultRateLimiter = rateLimiter({ keyGenerator: rateLimiterKeyGenerator, }); -router.get('/', validateUserAccessKey, (req, res) => { +// Every v2 route authenticates the same way: resolve the bearer key, then +// refuse an org key that is not allowed on the External API. Applied per route +// (not router-wide) so the rate limiter still runs first. +const authenticate = [validateUserAccessKey, requireOrgKeySurface('api')]; + +router.get('/', authenticate, (req, res) => { const user = req.user?.toJSON(); res.json({ version: 'v2', @@ -37,7 +43,7 @@ router.get('/', validateUserAccessKey, (req, res) => { router.use( '/alerts', defaultRateLimiter, - validateUserAccessKey, + ...authenticate, parseBody, alertsRouter, ); @@ -45,7 +51,7 @@ router.use( router.use( '/charts', defaultRateLimiter, - validateUserAccessKey, + ...authenticate, parseBody, chartsRouter, ); @@ -53,7 +59,7 @@ router.use( router.use( '/connections', defaultRateLimiter, - validateUserAccessKey, + ...authenticate, parseBody, connectionsRouter, ); @@ -61,7 +67,7 @@ router.use( router.use( '/dashboards', defaultRateLimiter, - validateUserAccessKey, + ...authenticate, parseBody, dashboardRouter, ); @@ -69,7 +75,7 @@ router.use( router.use( '/sources', defaultRateLimiter, - validateUserAccessKey, + ...authenticate, parseBody, sourcesRouter, ); @@ -77,7 +83,7 @@ router.use( router.use( '/saved-searches', defaultRateLimiter, - validateUserAccessKey, + ...authenticate, parseBody, savedSearchesRouter, ); @@ -85,7 +91,7 @@ router.use( router.use( '/search', defaultRateLimiter, - validateUserAccessKey, + ...authenticate, parseBody, searchRouter, ); @@ -93,17 +99,11 @@ router.use( router.use( '/webhooks', defaultRateLimiter, - validateUserAccessKey, + ...authenticate, parseBody, webhooksRouter, ); -router.use( - '/team', - defaultRateLimiter, - validateUserAccessKey, - parseBody, - teamRouter, -); +router.use('/team', defaultRateLimiter, ...authenticate, parseBody, teamRouter); export default router; diff --git a/packages/app/src/components/TeamSettings/CreateOrgApiKeyModal.tsx b/packages/app/src/components/TeamSettings/CreateOrgApiKeyModal.tsx index a5795172ed..50be881a2e 100644 --- a/packages/app/src/components/TeamSettings/CreateOrgApiKeyModal.tsx +++ b/packages/app/src/components/TeamSettings/CreateOrgApiKeyModal.tsx @@ -2,9 +2,12 @@ import { useState } from 'react'; import { type OrgApiKeyExpiry, OrgApiKeyExpirySchema, + type OrgApiKeySurface, + OrgApiKeySurfaceSchema, } from '@hyperdx/common-utils/dist/types'; import { Button, + Checkbox, Group, Modal, SegmentedControl, @@ -23,6 +26,13 @@ const EXPIRY_OPTIONS = [ { value: 'never', label: 'Never' }, ]; +const SURFACE_OPTIONS: { value: OrgApiKeySurface; label: string }[] = [ + { value: 'mcp', label: 'MCP server' }, + { value: 'api', label: 'External API' }, +]; + +const ALL_SURFACES = SURFACE_OPTIONS.map(option => option.value); + export default function CreateOrgApiKeyModal({ opened, onClose, @@ -33,6 +43,8 @@ export default function CreateOrgApiKeyModal({ const createKey = api.useCreateOrgApiKey(); const [description, setDescription] = useState(''); const [expiry, setExpiry] = useState('30d'); + const [restrictSurfaces, setRestrictSurfaces] = useState(false); + const [surfaces, setSurfaces] = useState(ALL_SURFACES); const [createdKey, setCreatedKey] = useState(null); // Closing mid-request would let the late response reopen on the old key. @@ -42,13 +54,19 @@ export default function CreateOrgApiKeyModal({ } setDescription(''); setExpiry('30d'); + setRestrictSurfaces(false); + setSurfaces(ALL_SURFACES); setCreatedKey(null); onClose(); }; const onCreate = () => { createKey.mutate( - { description: description.trim(), expiry }, + { + description: description.trim(), + expiry, + ...(restrictSurfaces ? { allowedSurfaces: surfaces } : {}), + }, { onSuccess: data => setCreatedKey(data.key), onError: e => { @@ -111,6 +129,37 @@ export default function CreateOrgApiKeyModal({ onChange={value => setExpiry(OrgApiKeyExpirySchema.parse(value))} /> + setRestrictSurfaces(e.currentTarget.checked)} + /> + {restrictSurfaces && ( + { + const parsed = next.flatMap(value => { + const surface = OrgApiKeySurfaceSchema.safeParse(value); + return surface.success ? [surface.data] : []; + }); + // At least one must stay selected. + if (parsed.length > 0) { + setSurfaces(parsed); + } + }} + > + + {SURFACE_OPTIONS.map(option => ( + + ))} + + + )}