Files
supabase/apps/studio/data/api-keys/api-keys-query.test.tsx
Charis 121de3dff7 feat(studio): gate api key create and delete on endpoint grants (#52966)
Part 6 of 6 in a stack for
[FE-4731](https://linear.app/supabase/issue/FE-4731/grants-rollout-api-keys-consumers-that-only-need-publishable-keys).
Based on #52965.

## Stack
1. #52961 Docs and project API docs consumers
2. #52962 Edge functions and vector bucket examples
3. #52963 Integrations landing data
4. #52964 Connect sheet and project connection popover; remove the
transitional api-keys hooks
5. #52965 `reveal` refinement for single api-key reads; API key pill
6. 👉 #52966 API key create and delete

## Changes
Gates the api-key write endpoints (both require
`api_gateway_keys_write`) on grants instead of `unguarded.migrating`:
- `api-key-create-mutation` and `api-key-delete-mutation` take the grant
in their variables.
- `APIKeyDeleteDialog` uses the `DELETE` grant instead of its V2 check,
and is disabled with a tooltip when denied or errored. `SecretAPIKeys`
and `PublishableAPIKeys` pass the grant to the mutation.
- `CreateNewAPIKeysButton` and the create publishable and secret key
dialogs mint the `POST` grant. Their triggers and submit buttons are
disabled with a tooltip unless granted.
- `useConnectedResourceMutations`: the api-key delete call takes the
grant. Without it, the mutation shows an error toast and throws.

**New guard:** creating API keys had no UI guard. Users without
`api_gateway_keys_write` could open the dialogs and get a 403; the
controls are now disabled for them. The delete guard already matched the
annotation.

Out of scope: the legacy API key toggle and status (FE-4732).

## Testing
- `CreateAPIKeyDialogs.platform.test.tsx` (renamed from
`CreateAPIKeyDialogs.test.tsx`, the mutation mock removed): denied and
permission-check error disable the triggers and the submit button.
- `APIKeyDeleteDialog.platform.test.tsx`: granted, denied, and
permission-check error.
- `data/api-keys/api-key-write-mutations.test.ts`: create and delete
send their requests with a grant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-11-10 14:01:40 +00:00

87 lines
2.9 KiB
TypeScript

import { QueryClient, useQuery } from '@tanstack/react-query'
import { screen, waitFor } from '@testing-library/react'
import { HttpResponse } from 'msw'
import { describe, expect, test } from 'vitest'
import { useAPIKeyDeleteMutation } from './api-key-delete-mutation'
import { apiKeysQueryOptions, type APIKeysGrant } from './api-keys-query'
import { apiKeysKeys } from './keys'
import type { components } from '@/data/api'
import { customRender, customRenderHook } from '@/tests/lib/custom-render'
import { addAPIMock } from '@/tests/lib/msw'
import { testGrant } from '@/tests/lib/test-grant'
type APIKeyResponse = components['schemas']['ApiKeyResponse_Output']
const PROJECT_REF = 'default'
const grant: APIKeysGrant = testGrant('GET /v1/projects/{ref}/api-keys', {
projectRef: PROJECT_REF,
})
const KEYS = [
{
api_key: 'anon-key',
id: 'anon-id',
name: 'anon',
type: 'legacy' as const,
},
]
function KeysReader({ label, grant }: { label: string; grant?: APIKeysGrant }) {
const { status } = useQuery(apiKeysQueryOptions({ projectRef: PROJECT_REF, grant }))
return <div data-testid={label}>{status}</div>
}
describe('apiKeysQueryOptions', () => {
test('invalidation still refetches when a grant-less observer rendered last', async () => {
let getCount = 0
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/api-keys',
response: () => {
getCount += 1
return HttpResponse.json<APIKeyResponse[]>(KEYS)
},
})
addAPIMock({
method: 'delete',
path: '/v1/projects/:ref/api-keys/:id',
response: () => HttpResponse.json<APIKeyResponse>(KEYS[0]),
})
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
// Component A holds a grant and fetches.
const { rerender } = customRender(<KeysReader label="a" grant={grant} />, { queryClient })
await waitFor(() => expect(screen.getByTestId('a')).toHaveTextContent('success'))
expect(getCount).toBe(1)
// Component B has no grant and renders last, so it is the last writer of the query's options.
rerender(
<>
<KeysReader label="a" grant={grant} />
<KeysReader label="b" />
</>
)
await waitFor(() => expect(screen.getByTestId('b')).toBeInTheDocument())
// Invalidate through the delete mutation.
const { result } = customRenderHook(() => useAPIKeyDeleteMutation(), { queryClient })
await result.current.mutateAsync({
projectRef: PROJECT_REF,
grant: testGrant('DELETE /v1/projects/{ref}/api-keys/{id}', { projectRef: PROJECT_REF }),
id: 'anon-id',
})
await waitFor(() => expect(getCount).toBe(2))
await waitFor(() => {
expect(queryClient.getQueryState(apiKeysKeys.list(PROJECT_REF, false))?.status).toBe(
'success'
)
})
expect(screen.getByTestId('a')).toHaveTextContent('success')
})
})