Files
supabase/apps/studio/components/interfaces/APIKeys/CreateAPIKeyDialogs.platform.test.tsx
T
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

172 lines
5.9 KiB
TypeScript

import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { CreatePublishableAPIKeyDialog } from './CreatePublishableAPIKeyDialog'
import { CreateSecretAPIKeyDialog } from './CreateSecretAPIKeyDialog'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { customRender as render } from '@/tests/lib/custom-render'
import { mockPermissionsError } from '@/tests/lib/msw-permissions'
import { NO_PERMISSIONS } from '@/tests/lib/permissions-fixtures'
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
import { mockProjectGrantContext } from '@/tests/lib/project-grant-mocks'
const { mockSetVisible, mockShortcut, mockUseQueryState } = vi.hoisted(() => ({
mockSetVisible: vi.fn(),
mockShortcut: vi.fn(({ children }: any) => <div data-testid="shortcut">{children}</div>),
mockUseQueryState: vi.fn(),
}))
vi.mock('next/navigation', async () => {
const actual = await vi.importActual<typeof import('next/navigation')>('next/navigation')
return {
...actual,
useParams: () => ({ ref: 'project-ref' }),
}
})
vi.mock('nuqs', async () => {
const actual = await vi.importActual<typeof import('nuqs')>('nuqs')
return {
...actual,
useQueryState: mockUseQueryState,
}
})
vi.mock('@/components/ui/Shortcut', () => ({
Shortcut: mockShortcut,
}))
vi.mock('common', async () => {
const actual = await vi.importActual<Record<string, unknown>>('common')
return { ...actual, useIsLoggedIn: () => true, useParams: () => ({ ref: 'project-ref' }) }
})
const profileContext = createMockProfileContext()
describe('API key create dialogs', () => {
beforeEach(() => {
mockUseQueryState.mockReturnValue(['', mockSetVisible])
mockProjectGrantContext({ ref: 'project-ref' })
})
it('registers and surfaces the publishable key shortcut on the visible trigger', async () => {
const user = userEvent.setup()
render(<CreatePublishableAPIKeyDialog />, { profileContext })
expect(mockShortcut).toHaveBeenCalledWith(
expect.objectContaining({
id: SHORTCUT_IDS.API_KEYS_NEW_PUBLISHABLE,
onTrigger: expect.any(Function),
}),
undefined
)
const trigger = screen.getByRole('button', { name: 'New publishable key' })
await waitFor(() => expect(trigger).toBeEnabled())
await user.click(trigger)
expect(mockSetVisible).toHaveBeenCalledWith('publishable')
})
it('registers and surfaces the publishable key submit shortcut on the primary action', () => {
mockUseQueryState.mockReturnValue(['publishable', mockSetVisible])
render(<CreatePublishableAPIKeyDialog />, { profileContext })
expect(mockShortcut).toHaveBeenCalledWith(
expect.objectContaining({
id: SHORTCUT_IDS.API_KEYS_CREATE_PUBLISHABLE,
onTrigger: expect.any(Function),
options: { enabled: true },
}),
undefined
)
expect(screen.getByRole('button', { name: 'Create Publishable API key' })).toBeInTheDocument()
})
it('registers and surfaces the secret key shortcut on the visible trigger', async () => {
const user = userEvent.setup()
render(<CreateSecretAPIKeyDialog />, { profileContext })
expect(mockShortcut).toHaveBeenCalledWith(
expect.objectContaining({
id: SHORTCUT_IDS.API_KEYS_NEW_SECRET,
onTrigger: expect.any(Function),
}),
undefined
)
const trigger = screen.getByRole('button', { name: 'New secret key' })
await waitFor(() => expect(trigger).toBeEnabled())
await user.click(trigger)
expect(mockSetVisible).toHaveBeenCalledWith('secret')
})
it('registers and surfaces the secret key submit shortcut on the primary action', () => {
mockUseQueryState.mockReturnValue(['secret', mockSetVisible])
render(<CreateSecretAPIKeyDialog />, { profileContext })
expect(mockShortcut).toHaveBeenCalledWith(
expect.objectContaining({
id: SHORTCUT_IDS.API_KEYS_CREATE_SECRET,
onTrigger: expect.any(Function),
options: { enabled: true },
}),
undefined
)
expect(screen.getByRole('button', { name: 'Create API key' })).toBeInTheDocument()
})
it.each([
{
name: 'denied',
setup: () => mockProjectGrantContext({ ref: 'project-ref', permissions: NO_PERMISSIONS }),
tooltip: 'You need additional permissions to create API keys',
},
{
name: 'a permission-check error',
setup: () => mockPermissionsError(),
tooltip: 'Failed to check permissions to create API keys',
},
])('keeps the create triggers disabled when the grant is $name', async ({ setup, tooltip }) => {
mockProjectGrantContext({ ref: 'project-ref' })
setup()
const user = userEvent.setup()
render(<CreatePublishableAPIKeyDialog />, { profileContext })
render(<CreateSecretAPIKeyDialog />, { profileContext })
const publishable = screen.getByRole('button', { name: 'New publishable key' })
const secret = screen.getByRole('button', { name: 'New secret key' })
// Wait for the grant to settle: the trigger is also disabled while loading
for (const trigger of [publishable, secret]) {
await user.hover(trigger)
expect((await screen.findAllByText(tooltip)).length).toBeGreaterThan(0)
await user.unhover(trigger)
}
expect(publishable).toBeAriaDisabled()
expect(secret).toBeAriaDisabled()
await user.click(publishable)
await user.click(secret)
expect(mockSetVisible).not.toHaveBeenCalled()
})
it('disables the submit button when the grant is denied', async () => {
mockProjectGrantContext({ ref: 'project-ref', permissions: NO_PERMISSIONS })
mockUseQueryState.mockReturnValue(['secret', mockSetVisible])
render(<CreateSecretAPIKeyDialog />, { profileContext })
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Create API key' })).toBeDisabled()
)
})
})