Skip to content

Commit 9f640a6

Browse files
authored
feat: make personal API access keys rotatable (#2926)
## Summary **Personal API access keys can now be rotated** from Team Settings → API & Agents. The key is the bearer token for the external API v2 and the MCP server, but it was generated once at account creation and could never be changed. A leaked key could only be dealt with by **deleting the user**. **What's new** - `PATCH /me/accessKey`, plus a **Rotate access key** button on the Personal API access key card, mirroring the ingestion key flow directly above it. - Rotation is **immediate, with no grace period**. Your browser session stays signed in. **Two deliberate limits** - The route takes **no user identifier** (the id comes from the session), so it can only ever rotate the caller's own key. - It is **not** exposed on the bearer-authed external API v2. A leaked key can already read itself there, so letting it also rotate would let someone lock the owner out of their own tooling. **Also in this diff** - Both rotate flows now use the shared **`useConfirm`** dialog instead of a bespoke modal (review feedback). The ingestion flow loses its modal title as a result, and its confirm/cancel testids become the shared `confirm-*` ones. - `APIKeyCopyButton` emitted `data-test-id`, which neither Playwright nor Testing Library queries by default, and both key displays shared the value `api-key`. Now `data-testid`, split into `ingestion-api-key` and `personal-access-key`. - **Sentence case applied to the whole card**, including the pre-existing ingestion key labels, per `agent_docs/code_style.md`. Half-converting it would have looked like an oversight. `MCP.md` references the same labels, so it moves too. - **Agent docs**: a required-pattern section for `useConfirm`, and a fix to the `AGENTS.md` pointer that said to read `code_style.md` "only when actively coding". This PR shipped title-case labels and a hand-rolled modal because that invited deferring the file past planning, with both rules already written down. ### How to test on Vercel preview **N/A. Not reachable on the preview build.** `useMe()` returns `null` under LOCAL_MODE and the Personal API access key card only renders when `me != null`, so neither the card nor its Rotate button exists there. Covered by integration, component and E2E tests instead. ### References - Linear Issue: HDX-5099
1 parent a8317c2 commit 9f640a6

13 files changed

Lines changed: 599 additions & 79 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@hyperdx/api': patch
3+
'@hyperdx/app': patch
4+
'@hyperdx/common-utils': patch
5+
---
6+
7+
Add a Rotate action for the personal API access key in Team Settings → API & Agents. Previously the personal access key — the bearer token for the external API v2 and the MCP server — was generated once at account creation and could never be changed, so a leaked key could only be remediated by deleting the user. Rotating immediately revokes the previous key, so MCP / AI agent configs, external API v2 clients, Terraform / IaC providers, and CI scripts using the old key must be updated with the new one. Browser sessions are unaffected.

‎AGENTS.md‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,12 @@ directory:
6161
- `agent_docs/architecture.md` - Detailed architecture patterns and data models
6262
- `agent_docs/tech_stack.md` - Technology stack details and component patterns
6363
- `agent_docs/development.md` - Development workflows, testing, and common tasks
64-
- `agent_docs/code_style.md` - Code patterns and best practices (read only when
65-
actively coding)
64+
- `agent_docs/code_style.md` - Code patterns and best practices. **Read this
65+
before writing or planning any `packages/app` UI change**, not just while
66+
typing code. It carries required patterns that are invisible from the
67+
surrounding file (sentence-case UI text, mandated Button/ActionIcon variants,
68+
`useConfirm` for confirmation dialogs, `EmptyState`), so copying the
69+
conventions of the component you are editing is not sufficient.
6670
- `agent_docs/observability.md` - Instrumentation standards (tracing, metrics,
6771
context) and the shared helpers (read when adding or changing a feature)
6872

@@ -87,7 +91,9 @@ before stopping.
8791
similar files before implementing
8892
4. **Component size**: Keep files under 300 lines; break down large components
8993
5. **UI Components**: Use custom Button/ActionIcon variants (`primary`,
90-
`secondary`, `danger`) - see `agent_docs/code_style.md` for required patterns
94+
`secondary`, `danger`), `useConfirm` for "are you sure?" dialogs rather than
95+
a hand-rolled `Modal`, and sentence case for all user-facing text - see
96+
`agent_docs/code_style.md` for required patterns
9197
6. **Testing**: Tests live in `__tests__/` directories; use Jest for
9298
unit/integration tests
9399
7. **Observability**: This is an observability product - instrument new code as

‎MCP.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ data sources directly.
99

1010
- A running HyperDX instance (see [CONTRIBUTING.md](/CONTRIBUTING.md) for local
1111
development setup, or [DEPLOY.md](/DEPLOY.md) for self-hosted deployment)
12-
- A **Personal API Access Key** — find yours in the HyperDX UI under **Team
13-
Settings > API Keys > Personal API Access Key**
12+
- A **Personal API access key** — find yours in the HyperDX UI under **Team
13+
Settings > API keys > Personal API access key**
1414

1515
> **Note:** HyperDX v1 ([hyperdx.io](https://hyperdx.io)) does not yet support
1616
> the MCP server. The documentation below applies to self-hosted HyperDX v2

‎agent_docs/code_style.md‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,56 @@ The variant → token mapping is centralized in `packages/app/src/theme/themes/s
131131

132132
**Note**: Existing `<Alert color="...">` call sites are untouched; the semantic variants are opt-in. Prefer the variant for any **new** callout, and migrate nearby `color="..."` alerts when you touch them.
133133

134+
### Confirmation dialogs: use `useConfirm` (REQUIRED)
135+
136+
**Use `useConfirm` (`@/useConfirm`) for any "are you sure?" step. Do not
137+
hand-roll a `<Modal>` with Cancel/Confirm buttons.** The provider is already
138+
mounted app-wide in `pages/_app.tsx`, so there is no setup at the call site.
139+
140+
```tsx
141+
const confirm = useConfirm();
142+
143+
const handleDelete = async () => {
144+
if (
145+
await confirm(
146+
<>
147+
Deleting {name} is <b>not reversible</b>.
148+
</>,
149+
'Delete',
150+
{ variant: 'danger' },
151+
)
152+
) {
153+
await deleteThing.mutateAsync({ id });
154+
}
155+
};
156+
```
157+
158+
- The message is a `ReactNode`, so it can carry emphasis and multiple sentences.
159+
- Pass `{ variant: 'danger' }` for destructive actions; the confirm label
160+
defaults to `Confirm`.
161+
- It resolves **exactly once**, so a double click on Confirm during the modal's
162+
exit transition cannot fire the action twice. A hand-rolled modal has to guard
163+
that itself.
164+
- Test ids are shared and already exist: `confirm-modal`,
165+
`confirm-confirm-button`, `confirm-cancel-button`. **Do not invent per-flow
166+
confirm/cancel test ids** — E2E page objects key off the shared ones.
167+
168+
**Known limits.** It passes no `title` to the Modal and renders the body at
169+
`size="sm" opacity={0.7}`, and CSS opacity applies to the whole subtree so a
170+
nested `<Text>` cannot opt back out. If a flow genuinely needs a heading or
171+
full-contrast body, **extend `useConfirm`** (an optional prop, applied to all
172+
call sites) rather than forking a one-off modal.
173+
174+
**In component tests**, mock it — `ConfirmProvider` pulls in `next/router`,
175+
which is not available in jsdom:
176+
177+
```tsx
178+
jest.mock('@/useConfirm', () => ({ useConfirm: jest.fn() }));
179+
```
180+
181+
Assert on the arguments (and render the message `ReactNode` if you need to check
182+
the copy). Exercise the real dialog in E2E instead.
183+
134184
### EmptyState Component (REQUIRED)
135185

136186
**Use `EmptyState` (`@/components/EmptyState`) for all empty/no-data states.** Do not create ad-hoc inline empty states.

‎packages/api/src/controllers/user.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import mongoose from 'mongoose';
2+
import { v4 as uuidv4 } from 'uuid';
23

34
import type { ObjectId } from '@/models';
45
import Alert from '@/models/alert';
@@ -7,6 +8,17 @@ export function findUserByAccessKey(accessKey: string) {
78
return User.findOne({ accessKey });
89
}
910

11+
/**
12+
* Rotates a user's personal access key, immediately revoking the previous one.
13+
*
14+
* There is exactly one key per user and no grace period: findUserByAccessKey
15+
* above is hit uncached on every bearer request (see validateUserAccessKey), so
16+
* requests presenting the old key start 401ing the instant this returns.
17+
*/
18+
export function rotateUserAccessKey(userId: string | ObjectId) {
19+
return User.findByIdAndUpdate(userId, { accessKey: uuidv4() }, { new: true });
20+
}
21+
1022
export function findUserById(id: string) {
1123
return User.findById(id);
1224
}
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
import { getAgent, getLoggedInAgent, getServer } from '@/fixtures';
2+
import User from '@/models/user';
3+
4+
describe('me router', () => {
5+
const server = getServer();
6+
7+
beforeAll(async () => {
8+
await server.start();
9+
});
10+
11+
afterEach(async () => {
12+
await server.clearDBs();
13+
});
14+
15+
afterAll(async () => {
16+
await server.stop();
17+
});
18+
19+
describe('GET /me', () => {
20+
it('returns the calling user', async () => {
21+
const { agent, team, user } = await getLoggedInAgent(server);
22+
23+
const resp = await agent.get('/me').expect(200);
24+
25+
expect(resp.body.id).toEqual(user._id.toString());
26+
expect(resp.body.email).toEqual('fake@deploysentinel.com');
27+
expect(resp.body.accessKey).toEqual(user.accessKey);
28+
expect(resp.body.team.id).toEqual(team._id.toString());
29+
});
30+
31+
it('rejects an unauthenticated request', async () => {
32+
await getAgent(server).get('/me').expect(401);
33+
});
34+
});
35+
36+
describe('PATCH /me/accessKey', () => {
37+
it('rejects an unauthenticated request', async () => {
38+
// The new verb is covered by the mount-time isUserAuthenticated in
39+
// api-app.ts, not by anything in the handler itself.
40+
await getAgent(server).patch('/me/accessKey').expect(401);
41+
});
42+
43+
it('returns a new key and persists it', async () => {
44+
const { agent, user } = await getLoggedInAgent(server);
45+
46+
const resp = await agent.patch('/me/accessKey').expect(200);
47+
48+
expect(resp.body.newAccessKey).toEqual(expect.any(String));
49+
expect(resp.body.newAccessKey).not.toEqual(user.accessKey);
50+
expect((await User.findById(user._id))?.accessKey).toEqual(
51+
resp.body.newAccessKey,
52+
);
53+
});
54+
55+
it('revokes the old key and accepts the new one', async () => {
56+
const { agent, user } = await getLoggedInAgent(server);
57+
const oldAccessKey = user.accessKey;
58+
59+
// GET /api/v2 is the bearer-authed surface with no rate limiter attached,
60+
// so three sequential calls here are safe.
61+
await agent
62+
.get('/api/v2')
63+
.set('Authorization', `Bearer ${oldAccessKey}`)
64+
.expect(200);
65+
66+
const { body } = await agent.patch('/me/accessKey').expect(200);
67+
68+
await agent
69+
.get('/api/v2')
70+
.set('Authorization', `Bearer ${oldAccessKey}`)
71+
.expect(401);
72+
await agent
73+
.get('/api/v2')
74+
.set('Authorization', `Bearer ${body.newAccessKey}`)
75+
.expect(200);
76+
});
77+
78+
it('does not sign the user out of their browser session', async () => {
79+
// Session auth never reads accessKey (see isUserAuthenticated), so
80+
// rotating must leave the cookie session intact.
81+
const { agent } = await getLoggedInAgent(server);
82+
83+
const { body } = await agent.patch('/me/accessKey').expect(200);
84+
85+
const resp = await agent.get('/me').expect(200);
86+
expect(resp.body.accessKey).toEqual(body.newAccessKey);
87+
});
88+
89+
it("does not touch another user's key", async () => {
90+
const { agent, user } = await getLoggedInAgent(server);
91+
// Created directly rather than via /register/password, which is gated to
92+
// the first user. We only read the schema-defaulted accessKey off it.
93+
const other = await User.create({
94+
email: 'other@deploysentinel.com',
95+
team: user.team,
96+
});
97+
98+
await agent.patch('/me/accessKey').expect(200);
99+
100+
expect((await User.findById(other._id))?.accessKey).toEqual(
101+
other.accessKey,
102+
);
103+
});
104+
});
105+
});

‎packages/api/src/routers/api/me.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1-
import type { MeApiResponse } from '@hyperdx/common-utils/dist/types';
1+
import type {
2+
MeApiResponse,
3+
RotateAccessKeyApiResponse,
4+
} from '@hyperdx/common-utils/dist/types';
25
import express from 'express';
36

47
import { AI_API_KEY, ANTHROPIC_API_KEY, USAGE_STATS_ENABLED } from '@/config';
58
import { getTeam } from '@/controllers/team';
9+
import { rotateUserAccessKey } from '@/controllers/user';
610
import { Api404Error } from '@/utils/errors';
711
import { sendJson } from '@/utils/serialization';
812

@@ -43,4 +47,31 @@ router.get('/', async (req, res: express.Response<MeApiResponse>, next) => {
4347
}
4448
});
4549

50+
type RotateAccessKeyExpRes = express.Response<RotateAccessKeyApiResponse>;
51+
52+
// Rotating your own personal access key. The user id comes from the session
53+
// (isUserAuthenticated, applied at mount time in api-app.ts) and never from the
54+
// request, so this route can only ever rotate the caller's own key.
55+
//
56+
// Deliberately NOT mirrored onto the bearer-authed external API v2: `GET /api/v2`
57+
// echoes the caller's accessKey back, so a leaked key that could also rotate
58+
// would let an attacker lock the legitimate owner out of their own tooling.
59+
router.patch('/accessKey', async (req, res: RotateAccessKeyExpRes, next) => {
60+
try {
61+
const userId = req.user?._id;
62+
if (userId == null) {
63+
throw new Api404Error('Request without user found');
64+
}
65+
66+
const user = await rotateUserAccessKey(userId);
67+
if (user?.accessKey == null) {
68+
throw new Error(`Failed to rotate access key for user ${userId}`);
69+
}
70+
71+
return sendJson(res, { newAccessKey: user.accessKey });
72+
} catch (e) {
73+
next(e);
74+
}
75+
});
76+
4677
export default router;

‎packages/app/src/api.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import type {
1111
MeApiResponse,
1212
PresetDashboard,
1313
PresetDashboardFilter,
14+
RotateAccessKeyApiResponse,
1415
RotateApiKeyApiResponse,
1516
TeamApiResponse,
1617
TeamClickHouseSettingsUpdate,
@@ -23,7 +24,12 @@ import type {
2324
WebhookTestApiResponse,
2425
WebhookUpdateApiResponse,
2526
} from '@hyperdx/common-utils/dist/types';
26-
import { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query';
27+
import {
28+
useInfiniteQuery,
29+
useMutation,
30+
useQuery,
31+
useQueryClient,
32+
} from '@tanstack/react-query';
2733

2834
import { IS_LOCAL_MODE } from './config';
2935
import { getLocalDashboardTags } from './dashboard';
@@ -269,6 +275,24 @@ const api = {
269275
}).json<RotateApiKeyApiResponse>(),
270276
});
271277
},
278+
useRotatePersonalAccessKey() {
279+
const queryClient = useQueryClient();
280+
return useMutation<RotateAccessKeyApiResponse, Error | HTTPError>({
281+
mutationFn: async () =>
282+
hdxServer(`me/accessKey`, {
283+
method: 'PATCH',
284+
}).json<RotateAccessKeyApiResponse>(),
285+
// Seed the cache from the response rather than refetching `me`. The old
286+
// key is already revoked by the time this runs, so a refetch that fails
287+
// would leave every `useMe` consumer rendering a dead credential with no
288+
// way to reach the new one short of a reload.
289+
onSuccess: data => {
290+
queryClient.setQueryData<MeApiResponse | null>(['me'], prev =>
291+
prev == null ? prev : { ...prev, accessKey: data.newAccessKey },
292+
);
293+
},
294+
});
295+
},
272296
useDeleteTeamMember() {
273297
return useMutation<
274298
{ message: string },

0 commit comments

Comments
 (0)