Repository navigation
feat: let org API keys be restricted to MCP or the External API #3869
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7b4e1bc
feat: limit org API keys to MCP or the External API
brandon-pereira da61d43
fix: harden surface labels and denial exhaustiveness (deep review P2)
brandon-pereira 8506b58
test(api): clear the login rate-limit suite's rows after it runs
brandon-pereira db690c5
fix(api): guard every v2 route and record key use only when allowed
brandon-pereira 271b74f
refactor(api): build both org-key auth chains from one factory
brandon-pereira 60a5e80
Merge branch 'main' into agent/hdx-6234-org-key-surfaces
kodiakhq[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
68 changes: 68 additions & 0 deletions
68
packages/api/src/mcp/__tests__/orgApiKeySurface.int.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| 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, | ||
| ]; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.