Skip to content

feat: let org API keys be restricted to MCP or the External API - #3869

Merged
kodiakhq[bot] merged 6 commits into
mainfrom
agent/hdx-6234-org-key-surfaces
Nov 30, 2026
Merged

kodiakhq[bot] merged 6 commits into
mainfrom
agent/hdx-6234-org-key-surfaces

Conversation

@brandon-pereira

@brandon-pereira brandon-pereira commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Summary

Organization API keys can now be limited to a single surface. Before this, a key handed to an MCP client could also call /api/v2 and read connections the MCP tools deliberately hide, so "give the agent a key" meant "give the agent the whole External API". A key is created with allowedSurfaces: ['mcp'] or ['api'], and an unrestricted key keeps working on both.

  • New requireOrgKeySurface middleware runs after validateUserAccessKey on every /api/v2 route (including GET /) and on POST /mcp. A denied request gets 403 with a short reason, so a client can tell "wrong surface" from "bad key".
  • allowedSurfaces is optional on create and cannot be changed afterwards. Team Settings has an opt-in "Restrict where this key can be used" checkbox and a new Access column showing All / MCP / API.
  • Personal access keys and virtual users that are not org keys are never checked.

Design notes

  • Absent vs empty. undefined means unrestricted, matching keys created before the field existed. A stored empty list denies every surface (fails closed). The create schema rejects [] with .min(1), so that state is only reachable by direct DB writes.
  • Mongoose array default. Array paths default to [], which would silently turn every key into "deny all", so the schema sets default: undefined.
  • Response shape. The API returns null for unrestricted and [] for a stored empty list, so the two remain distinguishable.

Screenshots or video

Screenshot 2026-11-30 at 1 29 36 PM Screenshot 2026-11-30 at 1 29 30 PM

How to reproduce

Starting point: yarn dev (this needs the API and MongoDB; Team Settings hides the key section in local mode). Open /team.

On main:

  1. Create an organization API key with a 30 day expiry.
  2. curl -H "Authorization: Bearer <key>" localhost:3000/api/v2/dashboards returns 200.
  3. The same key works against POST /mcp, so there is no way to scope it to one surface.

On this branch:

  1. Create an organization API key with "Restrict where this key can be used" checked and "External API" unchecked.
  2. The same /api/v2/dashboards request now returns 403 {"message":"This API key is limited to MCP"}.
  3. POST /mcp with that key still returns 200.
  4. Team Settings shows MCP in the Access column for the key.

How to test on Vercel preview

N/A — non-preview-testable. The key section only renders outside local mode (TeamPage.tsx gates it on IS_LOCAL_MODE) and the feature requires the API and MongoDB, neither of which the preview runs.

References


Note

Medium Risk
Changes authentication on every External API v2 and MCP bearer request; behavior is backward compatible for unrestricted keys but misconfiguration could block automation until keys are recreated.

Overview
Organization API keys can now be scoped to MCP, the External API, or both at create time via optional allowedSurfaces, closing the bypass where an MCP-intended key could still call /api/v2 (e.g. connections).

Enforcement: New orgKeyAuthChain(surface) replaces bare validateUserAccessKey on POST /mcp and all /api/v2 routes. Org keys on the wrong surface get 403 with a clear message (not 401). Personal keys and legacy unrestricted org keys are unchanged; empty allowedSurfaces denies all surfaces.

Data & API: allowedSurfaces is stored on org-key virtual users, returned as null when unrestricted, and create rejects an empty list. Last-used is recorded only after a successful surface check.

UI: Team Settings adds an opt-in surface restrictor on create and an Access column (All / MCP / API).

Reviewed by Cursor Bugbot for commit 60a5e80. Bugbot is set up for automated code reviews on this repo. Configure here.

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.
@brandon-pereira
brandon-pereira requested a review from a team as a code owner November 30, 2026 19:33
@vercel

vercel Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
hyperdx-oss Ready Ready Preview Nov 30, 2026 11:01pm UTC
hyperdx-storybook Ready Ready Preview Nov 30, 2026 11:01pm UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 60a5e80

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@hyperdx/api Patch
@hyperdx/app Patch
@hyperdx/common-utils Patch
@hyperdx/otel-collector Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@github-actions github-actions Bot added the review/tier-4 Critical — deep review + domain expert sign-off label Nov 30, 2026
@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

🔴 Tier 4 — Critical

Touches authentication, tenancy data models, the public API or shipped database config — or substantially changes the query rendering engine, background tasks, the OTel pipeline, image build, or release CI.

Why this tier:

  • Security-critical files (1) — auth or input validation, escalated at any size:
    • packages/api/src/middleware/auth.ts
  • Critical-path files (2) — tenancy, public API, or shipped database config:
    • packages/api/src/models/user.ts
    • packages/api/src/routers/external-api/v2/index.ts
  • Cross-layer change: touches frontend (packages/app) + backend (packages/api) + shared utils (packages/common-utils)

Review process: Deep review from a domain expert. Synchronous walkthrough may be required.
SLA: Schedule synchronous review within 2 business days.

Stats
  • Production files changed: 10
  • Production lines changed: 321 (+ 309 in test files, excluded from tier calculation)
  • Critical-path lines changed: 121
  • Branch: agent/hdx-6234-org-key-surfaces
  • Author: brandon-pereira

To override this classification, remove the review/tier-4 label and apply a different review/tier-* label. Manual overrides are preserved on subsequent pushes.

@github-actions

Copy link
Copy Markdown
Contributor

Duplicate code analysis

No new duplicate code introduced by this PR.


jscpd compared this branch against origin/main
across app, api and common-utils. Only new clones are listed; the codebase
currently holds 108 in total (1.10%).
Run yarn dupes locally to reproduce, or yarn dupes:all for the full picture.

@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

PR Review

If you are a coding agent acting for the author, read this first.
Nothing below blocks merge automatically; a maintainer decides. What they will expect:

  • 🔴 P0/P1 in code this PR adds or changes: fix before asking for review.
  • 🟡 P2 in code this PR changes: your call. Fix if small, otherwise reply.
  • 🔵 P3 is collapsed at the bottom: nobody needs to act on it before merge.
  • Anything about surrounding code, or asking you to widen the change (hoist a helper,
    dedupe with another file, fix other call sites): never fix here, whatever the
    priority. Reply with one sentence; if it is P0, say so plainly so a human sees it.

One commit per review round. After two rounds, stop and ask a maintainer to review
scope rather than addressing more automated findings. Full rule: AGENTS.md.

3 finding(s): 🔴 1 P0/P1 · 🟡 2 P2 · 🔵 0 P3

None could be anchored to changed lines; they are listed below.

Findings outside the changed lines

  • 🔴 P1 packages/cli/src/mcp/install.ts:57 — clickstack mcp install rejects MCP-only keys: verifyKey probes GET /api/v2, which now returns 403 for them → An MCP-only org key is the main use case for this PR, but verifyKey (called first in McpInstallPrompt.tsx:90) checks the key against /api/api/v2. With this change that route returns 403 for the key, and the CLI reports "The key was rejected. It may be wrong, revoked, or expired." and stops the install. Make verifyKey check the key against the MCP endpoint (mcpUrl, which listTeams already calls), or accept a 403 surface-denial as a valid key. Then add a test for an ['mcp'] key in mcpInstall.test.ts.
  • 🟡 P2 packages/api/src/middleware/orgApiKeySurface.ts:272 — Denial message is based on the rejected surface, not on what the key allows, so a stored empty list gets a false message → deniedMessage(surface) assumes the key is limited to the other surface. A key with allowedSurfaces: [], which the PR says denies everything, gets "This API key is limited to the External API" on /mcp and "limited to MCP" on /api/v2, and both are false. The same will happen for any third surface added later. Build the message from user.allowedSurfaces (e.g. "not allowed on MCP", or list the allowed surfaces) and handle the empty list separately.
  • 🟡 P2 packages/common-utils/src/types.ts:966 — Create schema accepts duplicate surfaces, and only the UI label dedupes them → z.array(OrgApiKeySurfaceSchema).min(1) accepts ['api','api'] and stores it as is. That is why surfaceLabel in OrgApiKeysSection.tsx needs a new Set and a dedupe test. Reject or normalise duplicates in the schema (e.g. .refine(a => new Set(a).size === a.length) or a transform to unique values) so the stored data is clean, then drop the dedupe from the display code.

Priority comes from a separate grading pass over the finished review. P3 is folded here instead of posted inline. No finding blocks merge automatically; a maintainer decides.

@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 478 passed • 1 skipped • 1279s

Status Count
✅ Passed 478
❌ Failed 0
⚠️ Flaky 13
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found. The surface-restriction guard is sound: validateUserAccessKey is now reachable only through orgKeyAuthChain (both POST /mcp and every /api/v2 route), enforcement runs before usage is recorded, denial fails closed (empty list denies all), and the Mongoose default: undefined correctly keeps pre-field keys unrestricted. No auth/authz bypass, crash, or data-loss path was found by the correctness, security, or adversarial reviewers.

One recommended (P2) observability regression and a handful of nits follow.

🟡 P2 -- recommended

  • packages/api/src/routers/external-api/v2/index.ts:44 -- Moving auth from per-path mounts (router.use('/alerts', validateUserAccessKey, …)) to a path-less router.use(authenticate) makes req.baseUrl resolve to /api/v2 instead of /api/v2/alerts, so nextWithQueryAttribution now stamps the identical ClickHouse attribution label on all nine sub-routes, collapsing the per-route granularity the auth.ts comment says it preserves for incident search.
    • Fix: Capture the attribution label from the matched sub-route (e.g. derive from req.originalUrl or set it per sub-router) so each external-API route keeps a distinct label.
    • adversarial
🔵 P3 nitpicks (5)
  • packages/api/src/middleware/orgApiKeySurface.ts:24 -- The exhaustiveness default assigns surface to never then returns it, so if the surface union ever grows without a matching case the runtime emits the raw surface string as the user-facing 403 message; the switch wording also assumes exactly two surfaces (denied on one implies restricted to the other).
    • Fix: Keep the never assignment for the compile-time check but throw in the default instead of returning it.
    • kieran-typescript, correctness, maintainability
  • packages/app/src/components/TeamSettings/OrgApiKeysSection.tsx:28 -- The two-surface enum now has three divergent label vocabularies, including two identically named SURFACE_LABELS maps ({mcp:'MCP',api:'API'} here vs {mcp:'MCP server',api:'External API'} in CreateOrgApiKeyModal.tsx) plus the hardcoded strings in deniedMessage.
    • Fix: Export one canonical label map (e.g. {short, long} per surface) from common-utils and consume it in both components.
    • maintainability
  • packages/api/src/middleware/orgApiKeySurface.ts:56 -- The POST /mcp endpoint speaks JSON-RPC 2.0, but a surface-denied key receives a plain HTTP 403 {message} rather than a {jsonrpc, error:{code,message}, id} envelope, which a strict MCP client may not render as a readable protocol error.
    • Fix: Confirm MCP clients surface the plain 403 acceptably, or emit a JSON-RPC error body on denial.
    • api-contract
  • packages/app/src/components/TeamSettings/CreateOrgApiKeyModal.tsx:67 -- Checking "Restrict" with every box left selected stores an explicit ['mcp','api'] list rather than omitting the field; it reads as All today but, being an allowlist, would silently exclude any surface added later, unlike a truly unrestricted (null) key.
    • Fix: When the selected set covers every surface, omit allowedSurfaces so the key stays unrestricted.
    • adversarial, kieran-typescript
  • packages/api/src/routers/api/__tests__/login.int.test.ts:30 -- The added afterAll clearDBs is a correct local fix but a band-aid for fragile cross-suite coupling (shared DB, file-order execution, a later createTeam failing if any team is left behind); the convention is already inconsistent with suites that use afterEach(clearDBs).
    • Fix: Move DB reset into a shared per-suite fixture hook so a suite that forgets cleanup cannot break unrelated later suites.
    • testing

Reviewers (8): correctness, security, adversarial, testing, maintainability, api-contract, kieran-typescript, previous-comments.

Testing gaps:

  • No end-to-end test exercises a genuinely stored empty allowedSurfaces: [] document (the fail-closed deny-all path) — reachable only via out-of-band DB writes, so the branch the design leans on is unverified against a real document.
  • Personal-access-key passthrough is asserted only on the MCP mount, not on the /api/v2 (External API) mount.
  • No test pins the query-attribution label per v2 sub-route, so the /api/v2/alerts → /api/v2 collapse would go undetected.
  • CreateOrgApiKeyModal's close-time reset of restrictSurfaces/surfaces is uncovered, leaving a possible state-leak regression across modal reopens.
  • The recordOrgApiKeyUsage / requireOrgKeySurface passthrough for a createdBy-less virtual user is untested (currently defensive, as the only createVirtualUser caller always sets createdBy).

No finding blocks merge automatically. A maintainer will expect P0/P1 findings in code this PR changes to be fixed; P2/P3 are your call -- fix or reply. Never fix findings about surrounding code here; reply instead. Do not widen the PR. How to respond

deniedMessage now has an explicit return type and an exhaustive default, so
a new surface fails to compile instead of producing a 403 with no message.

surfaceLabel compares the unique surface set against
OrgApiKeySurfaceSchema.options instead of counting two values, so a partial
list is spelled out, a duplicated value does not read as All, and the stored
empty list still reads as None. The mongoose enum and UI labels now derive
from the shared schema.

Adds label coverage for the explicit-all, empty, and duplicate cases.
The suite registers a user in beforeAll, which creates a team, and never
cleared it. Integration test files share one database and run serially in
size order, so tasks/checkAlerts/bodyExpressionFallback (which calls
createTeam and fails while any team exists) started on a dirty database once
v2.int.test.ts grew large enough to run before login.int.test.ts. Passed on
main only because v2.int.test.ts ran after login and its afterEach cleared
the rows.

Clear the database in afterAll so the suite no longer depends on what runs
next.
Mount the v2 authentication chain once at the router level instead of
spreading it onto each route, so a sub-route added later inherits the surface
restriction rather than quietly skipping it. The rate limiter still runs
first; only unknown paths change behaviour, now answering 401 instead of 404.

Record an org key's last-used time from a middleware that runs after the
surface check, so a request refused with 403 no longer shows up as a
successful use in Team Settings. Covers the denied path with a test.
orgKeyAuthChain(surface) pairs bearer auth with the surface check and the
last-used stamp, so a new mount cannot authenticate org keys without naming
its surface. GET /api/v2 goes back to skipping the rate limiter, as on main.

The create modal derives its surface options from OrgApiKeySurfaceSchema.
Tests: assert the last-use spy directly instead of sleeping, cover a key
allowed on both surfaces, and type helpers as OrgApiKeySurface[].

@jordan-simonovski jordan-simonovski left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for jumping on this so quickly!

@kodiakhq
kodiakhq Bot merged commit 73ec0d5 into main Nov 30, 2026
29 of 30 checks passed
@kodiakhq
kodiakhq Bot deleted the agent/hdx-6234-org-key-surfaces branch November 30, 2026 23:09

This branch was successfully deployed

2 active deployments
Preview – hyperdx-oss — 60a5e802 Deployed Nov 30, 2026 by vercel[bot]
Preview – hyperdx-storybook — 60a5e802 Deployed Nov 30, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

automerge review/tier-4 Critical — deep review + domain expert sign-off

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants