Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/org-key-allowed-surfaces.md
Original file line number Diff line number Diff line change
@@ -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.
53 changes: 53 additions & 0 deletions packages/api/src/controllers/__tests__/orgApiKey.int.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { CreateOrgApiKeyRequestSchema } from '@hyperdx/common-utils/dist/types';
import mongoose from 'mongoose';

import {
createOrgApiKey,
formatOrgApiKey,
listOrgApiKeys,
revokeOrgApiKey,
touchOrgApiKeyLastUsed,
Expand Down Expand Up @@ -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' });
Expand Down
6 changes: 5 additions & 1 deletion packages/api/src/controllers/orgApiKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 };
}
Expand Down Expand Up @@ -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(),
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/controllers/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export function createVirtualUser({
name: string;
accessKey?: string;
teamId: string | ObjectId;
} & Pick<IUser, 'email' | 'expiresAt' | 'createdBy'>) {
} & Pick<IUser, 'email' | 'expiresAt' | 'createdBy' | 'allowedSurfaces'>) {
return User.create({
name,
team: teamId,
Expand Down
68 changes: 68 additions & 0 deletions packages/api/src/mcp/__tests__/orgApiKeySurface.int.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import type { OrgApiKeySurface } from '@hyperdx/common-utils/dist/types';

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?: OrgApiKeySurface[]) => {
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<typeof getAgent>, 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);
});
});
4 changes: 2 additions & 2 deletions packages/api/src/mcp/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { localhostHostValidation } from '@modelcontextprotocol/sdk/server/middle
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import express from 'express';

import { validateUserAccessKey } from '@/middleware/auth';
import { parseBody } from '@/middleware/bodyParser';
import { orgKeyAuthChain } from '@/middleware/orgApiKeySurface';
import { setBusinessContext } from '@/utils/instrumentation';
import logger from '@/utils/logger';
import rateLimiter, { rateLimiterKeyGenerator } from '@/utils/rateLimiter';
Expand Down Expand Up @@ -41,7 +41,7 @@ const methodNotAllowed = (_req: express.Request, res: express.Response) => {
app.get('/', mcpRateLimiter, methodNotAllowed);
app.delete('/', mcpRateLimiter, methodNotAllowed);

const authorizePost = [mcpRateLimiter, validateUserAccessKey, ...parseBody];
const authorizePost = [mcpRateLimiter, ...orgKeyAuthChain('mcp'), ...parseBody];

app.post('/', authorizePost, async (req, res) => {
const transport = new StreamableHTTPServerTransport({
Expand Down
4 changes: 0 additions & 4 deletions packages/api/src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import type { NextFunction, Request, Response } from 'express';
import { serializeError } from 'serialize-error';

import * as config from '@/config';
import { touchOrgApiKeyLastUsed } from '@/controllers/orgApiKey';
import { findUserByAccessKey, ORG_API_KEY_PREFIX } from '@/controllers/user';
import type { UserDocument } from '@/models/user';
import {
Expand Down Expand Up @@ -109,9 +108,6 @@ export async function validateUserAccessKey(
}

req.user = user;
if (user.isVirtual) {
touchOrgApiKeyLastUsed(user);
}

// Attribute access-key authenticated requests (external API v2 + MCP HTTP)
// with team/user context so their traces are searchable during incidents.
Expand Down
91 changes: 91 additions & 0 deletions packages/api/src/middleware/orgApiKeySurface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import type { OrgApiKeySurface } from '@hyperdx/common-utils/dist/types';
import type { NextFunction, Request, Response } from 'express';

import { touchOrgApiKeyLastUsed } from '@/controllers/orgApiKey';
import { validateUserAccessKey } from '@/middleware/auth';
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): string {
switch (surface) {
case 'api':
return 'This API key is limited to MCP';
case 'mcp':
return 'This API key is limited to the External API';
default: {
// A new surface must decide on its message rather than fall through to
// `undefined`.
const exhaustive: never = surface;
return exhaustive;
}
}
}

/**
* 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.
*/
function requireOrgKeySurface(surface: OrgApiKeySurface) {
return (req: Request, res: Response, next: NextFunction) => {
const user = req.user;
Comment thread
brandon-pereira marked this conversation as resolved.
Resolved
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) });
};
}

/**
* Stamps an org key's last-used time. Runs after the surface check: a request
* refused because the key is limited to another surface was not a successful
* use, and bumping it makes the Team Settings column misleading.
*/
function recordOrgApiKeyUsage(
req: Request,
_res: Response,
next: NextFunction,
) {
const user = req.user;
// Every virtual user, as before this chain existed; not narrowed to org keys.
if (user?.isVirtual) {
touchOrgApiKeyLastUsed(user);
}
next();
}

/**
* The bearer-auth chain for an org-key surface: resolve the key, refuse it when
* it is limited to another surface, then record the use. Both mounts build their
* chain here so a new one cannot authenticate org keys without declaring which
* surface it serves.
*/
export function orgKeyAuthChain(surface: OrgApiKeySurface) {
return [
validateUserAccessKey,
requireOrgKeySurface(surface),
recordOrgApiKeyUsage,
];
}
14 changes: 14 additions & 0 deletions packages/api/src/models/user.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import {
ONBOARDING_TASK_IDS,
type OnboardingData,
type OrgApiKeySurface,
OrgApiKeySurfaceSchema,
} 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';
Expand All @@ -25,6 +27,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;
}

Expand Down Expand Up @@ -52,6 +58,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: OrgApiKeySurfaceSchema.options }],
default: undefined,
},
onboardingData: {
type: new Schema<OnboardingData>(
{
Expand Down
4 changes: 4 additions & 0 deletions packages/api/src/routers/api/__tests__/login.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ describe('POST /login/password rate limit', () => {
});

afterAll(async () => {
// This suite registers a user, and the registration creates a team. Leave
// no rows behind: integration tests share one database and run in file
// order, and a later suite's createTeam fails while any team exists.
await server.clearDBs();
await server.stop();
});

Expand Down
Loading
Loading