test(api): lock POST /api/integration-keys/[id]/rotate branches

Rotation is the leak-response path: when a user thinks they've burnt
a key they MUST actually have burnt it. Silent regressions here would
either falsely-fail rotation (user keeps shipping a leaked key) or
misroute exceptions (a generic 500 instead of the 403 / 404 envelopes
the UI is built against).

7ddc1311 shipped the route without tests. This commit locks the 5
branches following the bdef16f4 pattern.

Tests:
  - 401 when no session user (service never called)
  - 403 on ActorNotPermittedError (user lost the right to act as the
    key's actor since mint); apiForbidden called with the canonical
    string; generic 500 + 404 paths verified NOT taken
  - 404 on "Key not found" sentinel error; apiNotFound('Integration key');
    other branches verified NOT taken — operators rely on this 404
    not being a 409 so probers can't distinguish missing-key from
    wrong-owner
  - 500 fall-through to handleApiError for unknown exceptions
    (e.g. connection_reset); branch routing assertions confirm
    apiForbidden + apiNotFound were skipped
  - 201 happy path returns key + plaintext via apiSuccess with the
    correct status; rotateIntegrationKey called with (id, userId)

Mock pattern mirrors the existing deliveries route tests (bdef16f4):
explicit standardResponse mocks return shaped objects, ActorNotPermittedError
inlined as a class in the integrationKeys mock so `instanceof` checks
work inside the handler.

Suite: 51 suites · 664 tests · 0 failures. tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georgy ButaevandClaude Opus 4.7 committed 2026-06-04 02:37:59 +02:00
1 parent 79d97fa260
commit 38d8282d00
1 file changed
+147
@@ -0,0 +1,147 @@
/**
* POST /api/integration-keys/[id]/rotate — handler-level branch tests.
*
* Rotation is the leak-response path: when a user thinks they've burnt
* a key, they MUST actually have burnt it. Silent regressions here
* (e.g. an error path that 500s instead of 403/404, or a misclassified
* exception that's never reached) would either falsely-fail rotation
* (user keeps shipping the leaked key) or falsely-succeed it (old key
* stays live). Lock the 5 branches before customers hit them.
*
* Created: 2026-06-04
*/
jest.mock('@/lib/supabase/server', () => ({
createServerClient: jest.fn(),
}));
jest.mock('@/services/auth/integrationKeys', () => {
class ActorNotPermittedError extends Error {}
return {
rotateIntegrationKey: jest.fn(),
ActorNotPermittedError,
};
});
jest.mock('@/lib/api/standardResponse', () => ({
apiSuccess: jest.fn((payload: unknown, opts?: { status?: number }) => ({
ok: true,
data: payload,
status: opts?.status ?? 200,
})),
apiUnauthorized: jest.fn(() => ({ ok: false, error: 'Unauthorized', status: 401 })),
apiForbidden: jest.fn((msg: string) => ({ ok: false, error: msg, status: 403 })),
apiNotFound: jest.fn((what: string) => ({ ok: false, error: `${what} not found`, status: 404 })),
handleApiError: jest.fn((err: Error) => ({ ok: false, error: err.message, status: 500 })),
}));
import { POST } from '@/app/api/integration-keys/[id]/rotate/route';
import { createServerClient } from '@/lib/supabase/server';
import { rotateIntegrationKey, ActorNotPermittedError } from '@/services/auth/integrationKeys';
import {
apiSuccess,
apiUnauthorized,
apiForbidden,
apiNotFound,
handleApiError,
} from '@/lib/api/standardResponse';
const mockUser = { id: 'u-1' };
function setSession(user: { id: string } | null) {
(createServerClient as jest.Mock).mockResolvedValue({
auth: {
getUser: jest.fn().mockResolvedValue({ data: { user } }),
},
});
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function makeRequest(): any {
return { url: 'http://x/api/integration-keys/k-1/rotate' };
}
function withParams<T extends Record<string, string>>(p: T): { params: Promise<T> } {
return { params: Promise.resolve(p) };
}
beforeEach(() => {
jest.clearAllMocks();
});
describe('POST /api/integration-keys/[id]/rotate', () => {
it('returns 401 when no session user', async () => {
setSession(null);
const res = (await POST(makeRequest(), withParams({ id: 'k-1' }))) as { status: number };
expect(res.status).toBe(401);
expect(apiUnauthorized).toHaveBeenCalled();
expect(rotateIntegrationKey).not.toHaveBeenCalled();
});
it("returns 403 when the user is no longer permitted to act as the key's actor", async () => {
setSession(mockUser);
(rotateIntegrationKey as jest.Mock).mockRejectedValue(
new ActorNotPermittedError('lost group membership')
);
const res = (await POST(makeRequest(), withParams({ id: 'k-1' }))) as { status: number };
expect(res.status).toBe(403);
expect(apiForbidden).toHaveBeenCalledWith(
"You are no longer permitted to act as this key's actor."
);
// Generic 500 must NOT have been called — the branch routing matters.
expect(handleApiError).not.toHaveBeenCalled();
expect(apiNotFound).not.toHaveBeenCalled();
});
it('returns 404 (Integration key) on the "Key not found" sentinel error', async () => {
setSession(mockUser);
(rotateIntegrationKey as jest.Mock).mockRejectedValue(new Error('Key not found'));
const res = (await POST(makeRequest(), withParams({ id: 'k-1' }))) as { status: number };
expect(res.status).toBe(404);
// 404 — never 409 — so probers can't tell missing-key from wrong-owner.
expect(apiNotFound).toHaveBeenCalledWith('Integration key');
expect(handleApiError).not.toHaveBeenCalled();
});
it('falls through to handleApiError for unknown exceptions', async () => {
setSession(mockUser);
(rotateIntegrationKey as jest.Mock).mockRejectedValue(new Error('connection_reset'));
const res = (await POST(makeRequest(), withParams({ id: 'k-1' }))) as { status: number };
expect(res.status).toBe(500);
expect(handleApiError).toHaveBeenCalled();
// Specific branches did not also fire.
expect(apiForbidden).not.toHaveBeenCalled();
expect(apiNotFound).not.toHaveBeenCalled();
});
it('returns 201 with key + plaintext on success', async () => {
setSession(mockUser);
const minted = {
key: { id: 'k-2', key_prefix: 'ock_abcdefg', name: 'rotated' },
plaintext: 'ock_full_secret_value',
};
(rotateIntegrationKey as jest.Mock).mockResolvedValue(minted);
const res = (await POST(makeRequest(), withParams({ id: 'k-1' }))) as {
ok: boolean;
data: { key: unknown; plaintext: string };
status: number;
};
expect(res.status).toBe(201);
expect(res.ok).toBe(true);
expect(rotateIntegrationKey).toHaveBeenCalledWith('k-1', mockUser.id);
expect(apiSuccess).toHaveBeenCalledWith(
{ key: minted.key, plaintext: minted.plaintext },
{ status: 201 }
);
});
});