Files
supabase/apps/studio/data/storage/iceberg-wrapper-create-mutation.platform.test.tsx
CharisandClaude bef73a722c feat(studio): gate storage, cron, and realtime key consumers on grants (#52728)
Part 4 of 4 in a stack for
[FE-4694](https://linear.app/supabase/issue/FE-4694/pilot-split-api-keys-queries-and-add-first-refinement-reveal-variant).
Based on #52727.

## Stack
1. #52723 Reveal refinement and split api-keys queries
2. #52724 API keys settings UI and command menu
3. #52727 Database and edge functions consumers that reveal secret keys
4. 👉 Storage, cron, and Realtime consumers; remove the transitional
reveal path

## Changes
Moves the remaining consumers that need secret keys onto the `reveal`
grant with `revealedApiKeysQueryOptions`, replacing their V2 permission
checks:
- Analytics bucket configuration details and the update catalog token
dialog
- The Iceberg wrapper create mutation. Its V2 check only covered
`api_gateway_keys_secret_read`, which didn't match the endpoint's
requirement. Without keys it used to save a placeholder as the vault
token; it now throws unless the grant is granted, and returns the grant
so callers can explain why. The bucket create form disables Create and
the missing-wrapper callout disables "Install wrapper", both showing
`ApiKeysAccessNote`. The `storage_config_write` check is unchanged.
- Cron job HTTP headers (edge function variant)

`RealtimeTokensPopover` only reads the anon and publishable keys, so it
moves to the plain grant and `apiKeysQueryOptions` instead of requesting
revealed keys.

With no `reveal: true` callers left, the transitional `useAPIKeysQuery`
/ `useAPIKeys` hooks drop their reveal path and only mint a plain grant.
They remain for the publishable-only consumers until FE-4731.

## Testing
- `iceberg-wrapper-create-mutation.platform.test.tsx`: `mutateAsync`
throws without the reveal grant and makes no credentials request; the
granted case exposes the grant.
- `BucketCallouts.platform.test.tsx`: "Install wrapper" is enabled when
granted, and disabled with the note when denied or with an error when
the permission check fails.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-04 11:36:17 -05:00

141 lines
4.6 KiB
TypeScript

import { waitFor } from '@testing-library/react'
import { HttpResponse } from 'msw'
import { describe, expect, it, vi } from 'vitest'
import { useIcebergWrapperCreateMutation } from './iceberg-wrapper-create-mutation'
import { FGA_PERMISSIONS } from '@/hooks/misc/useCheckPermissionsV2'
import { customRenderHook } from '@/tests/lib/custom-render'
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
import { ALL_FGA_PERMISSIONS, type PermissionsV2Response } from '@/tests/lib/permissions-fixtures'
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
import { mockProjectGrantContext } from '@/tests/lib/project-grant-mocks'
vi.mock('common', async () => {
const actual = await vi.importActual<Record<string, unknown>>('common')
return { ...actual, useIsLoggedIn: () => true, useParams: () => ({ ref: 'default' }) }
})
const permissionsWithout = (denied: string): PermissionsV2Response => ({
organizations: [
{
slug: 'acme',
role: 'developer',
permissions: ALL_FGA_PERMISSIONS.filter((permission) => permission !== denied),
projects: [],
},
],
})
const renderMutation = () =>
customRenderHook(() => useIcebergWrapperCreateMutation(), {
profileContext: createMockProfileContext(),
})
const secretKey = {
type: 'secret' as const,
name: 'default',
api_key: 'sb_secret_abc',
id: 'id',
hash: 'hash',
prefix: 'sb_secret_',
inserted_at: '2024-01-01',
secret_jwt_template: { role: 'service_role' },
}
const mockS3Credentials = (requests: () => void) =>
addAPIMock({
method: 'post',
path: '/platform/storage/:ref/credentials',
response: () => {
requests()
return HttpResponse.json<APIErrorBody>({ message: 'unexpected request' }, { status: 500 })
},
})
describe('useIcebergWrapperCreateMutation', () => {
it('is ready once a secret key has been revealed', async () => {
mockProjectGrantContext({ ref: 'default' })
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/api-keys',
response: [secretKey],
})
const { result } = renderMutation()
await waitFor(() => expect(result.current.isApiKeyReady).toBe(true))
})
it('refuses to create anything when the API keys request fails', async () => {
const s3KeyRequests = vi.fn()
mockProjectGrantContext({ ref: 'default' })
mockS3Credentials(s3KeyRequests)
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/api-keys',
response: () => HttpResponse.json<APIErrorBody>({ message: 'boom' }, { status: 500 }),
})
const { result } = renderMutation()
await waitFor(() => expect(result.current.apiKeyState).toBe('error'))
expect(result.current.isApiKeyReady).toBe(false)
await expect(result.current.mutateAsync({ bucketName: 'bucket' })).rejects.toThrow(
'Unable to load a secret API key'
)
expect(s3KeyRequests).not.toHaveBeenCalled()
})
it('refuses to create anything when no secret or service key is returned', async () => {
const s3KeyRequests = vi.fn()
mockProjectGrantContext({ ref: 'default' })
mockS3Credentials(s3KeyRequests)
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/api-keys',
response: [],
})
const { result } = renderMutation()
await waitFor(() => expect(result.current.apiKeyState).toBe('missing'))
expect(result.current.isApiKeyReady).toBe(false)
await expect(result.current.mutateAsync({ bucketName: 'bucket' })).rejects.toThrow(
'Unable to load a secret API key'
)
expect(s3KeyRequests).not.toHaveBeenCalled()
})
it('refuses to create the wrapper without access to secret API keys', async () => {
const s3KeyRequests = vi.fn()
mockProjectGrantContext({
ref: 'default',
permissions: permissionsWithout(FGA_PERMISSIONS.PROJECT.API_GATEWAY_KEYS_SECRET_READ),
})
addAPIMock({
method: 'post',
path: '/platform/storage/:ref/credentials',
response: () => {
s3KeyRequests()
return HttpResponse.json<APIErrorBody>({ message: 'unexpected request' }, { status: 500 })
},
})
const { result } = renderMutation()
await waitFor(() => expect(result.current.apiKeysGrant.status).toBe('denied'))
await expect(result.current.mutateAsync({ bucketName: 'bucket' })).rejects.toThrow(
'You need additional permissions to view API keys'
)
expect(s3KeyRequests).not.toHaveBeenCalled()
})
it('exposes a granted grant when the user can read secret keys', async () => {
mockProjectGrantContext({ ref: 'default' })
const { result } = renderMutation()
await waitFor(() => expect(result.current.apiKeysGrant.status).toBe('granted'))
})
})