mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 15:39:13 +00:00
Resolves [FE-4732](https://linear.app/supabase/issue/FE-4732/grants-rollout-jwt-signing-keys-legacy-api-keys-and-third-party-auth). ## Changes Gates the JWT signing keys, legacy API keys, and third-party auth endpoints on grants instead of `unguarded.migrating`, and replaces their V2 permission guards with `useGrant`: - **Data layer (11 sites):** `data/jwt-signing-keys/*`, `data/api-keys/legacy-api-keys-status-query`, `data/api-keys/legacy-api-key-toggle-mutation`, and `data/third-party-auth/*`. Queries become grant-gated query option factories; mutations take the grant in their variables. - **Consumers:** the JWT settings page, the JWT signing keys table and its dialogs, `jwt-settings`, `ToggleLegacyApiKeys`, `Project/APIKeys`, and the third-party auth page, form, and create dialogs. Each consumer renders denied and error states. - **JWT signing keys table:** - It's gated only on the signing keys reads (`GET signing-keys` and `GET signing-keys/legacy`, both `auth_signing_keys_read`). - The legacy API keys status is only used by the revoke dialogs. If it can't be read, revoking the legacy JWT secret fails closed: the user sees the "disable legacy API keys first" warning, with copy explaining why, instead of the confirm modal. - **Legacy JWT secret query:** a 404 (secret not imported as a signing key yet) resolves to `null` and shows the "Migrate JWT secret" panel. Other errors now render an error instead of being treated as "not migrated". - **Write actions:** - `getWriteGrantTooltip` moves from `APIKeys.utils` to `lib/grants` and takes a resource noun. Disabled write actions use it to explain why they're disabled. - New `getWriteGrantToastMessage`: handlers that run without a grant now show a toast instead of silently doing nothing. This includes the API keys handlers from #52966. ## Permission changes - **Legacy API keys toggle and status** (`GET`/`PUT /v1/projects/{ref}/api-keys/legacy`): the guard moves from `auth_signing_keys_read`/`_write` to the endpoint annotation, `api_gateway_keys_read`/`_write`. The annotation was confirmed against the backend controller (FE-4728). As a result, the JWT signing keys table's legacy revoke check now depends on `api_gateway_keys_read`. - **API keys last-used analytics** (`/platform/projects/{ref}/analytics/endpoints/api_keys.last_used.otel`): this endpoint uses legacy permissions (`analytics:Read` on `logflare`), not FGA. Its check moves from the V2 `auth_signing_keys_read` check to `useAsyncCheckPermissions(PermissionAction.ANALYTICS_READ, 'logflare')`. - Every other guard already matched its annotation: - `auth_signing_keys_read`/`_write` for signing keys - `auth_config_read`/`_write` for third-party auth ## Testing - Data layer: `jwt-signing-keys.test.ts`, `legacy-api-keys.test.ts`, and `third-party-auth.test.ts` cover every migrated fetcher, check that factories stay disabled without a grant, and cover legacy-key 404 vs. 500. - `jwt-secret-keys-table/index.platform.test.tsx`: - Legacy status denied: the table still renders, and revoking the legacy key shows only the warning. - Legacy status known enabled or disabled. - Signing keys read denied. - Legacy key 404 vs. 500. - `create-key-dialog.platform.test.tsx`: triggering create without a grant shows the toast and sends no request. - `ToggleLegacyApiKeys.platform.test.tsx`, `ThirdPartyAuthForm.platform.test.tsx`, and `settings/jwt/index.platform.test.tsx`: granted, denied, error, and partial-permission cases. - `lib/grants.test.ts`: the tooltip and toast helpers. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
493 lines
16 KiB
TypeScript
493 lines
16 KiB
TypeScript
// @vitest-environment jsdom
|
|
import { QueryClient } from '@tanstack/react-query'
|
|
import { waitFor } from '@testing-library/react'
|
|
import { HttpResponse } from 'msw'
|
|
import { beforeEach, describe, expect, expectTypeOf, test, vi } from 'vitest'
|
|
|
|
import {
|
|
ensureGrant,
|
|
getGrant,
|
|
getWriteGrantToastMessage,
|
|
getWriteGrantTooltip,
|
|
useGrant,
|
|
type Grant,
|
|
type GrantFor,
|
|
type GrantForVariants,
|
|
type GrantResult,
|
|
} from './grants'
|
|
import { projectKeys } from '@/data/projects/keys'
|
|
import type { ProjectDetailData } from '@/data/projects/project-detail-query'
|
|
import { createMockOrganizationResponse } from '@/tests/helpers'
|
|
import { customRenderHook } from '@/tests/lib/custom-render'
|
|
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
|
|
import { mockPermissions, mockPermissionsError } from '@/tests/lib/msw-permissions'
|
|
import type { PermissionsV2Response } from '@/tests/lib/permissions-fixtures'
|
|
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
|
|
|
|
type OrganizationResponse = ReturnType<typeof createMockOrganizationResponse>
|
|
|
|
const mocks = vi.hoisted((): { isPlatform: boolean; params: { ref?: string } } => ({
|
|
isPlatform: true,
|
|
params: { ref: 'default' },
|
|
}))
|
|
|
|
vi.mock('common', async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import('common')>()
|
|
return {
|
|
...actual,
|
|
useParams: () => mocks.params,
|
|
useIsLoggedIn: () => true,
|
|
}
|
|
})
|
|
|
|
vi.mock('@/lib/constants', async (importOriginal) => {
|
|
const actual = await importOriginal<Record<string, unknown>>()
|
|
return {
|
|
...actual,
|
|
get IS_PLATFORM() {
|
|
return mocks.isPlatform
|
|
},
|
|
}
|
|
})
|
|
|
|
const ORG_SLUG = 'test-org'
|
|
const BRANCHES = 'GET /v1/projects/{ref}/branches'
|
|
const PG_META_QUERY = 'POST /platform/pg-meta/{ref}/query'
|
|
const DELETE_BRANCH = 'DELETE /v1/branches/{branch_id_or_ref}'
|
|
const PROFILE_CONTEXT = createMockProfileContext()
|
|
|
|
function permissionsFor(
|
|
org: Partial<PermissionsV2Response['organizations'][number]> = {}
|
|
): PermissionsV2Response {
|
|
return {
|
|
organizations: [{ slug: ORG_SLUG, role: 'developer', permissions: [], projects: [], ...org }],
|
|
}
|
|
}
|
|
|
|
function mockOrganizations(details: Partial<OrganizationResponse> = {}) {
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/organizations',
|
|
response: () =>
|
|
HttpResponse.json<OrganizationResponse[]>([
|
|
createMockOrganizationResponse({ id: 1, slug: ORG_SLUG, ...details }),
|
|
]),
|
|
})
|
|
}
|
|
|
|
const BRANCH_PROJECT: ProjectDetailData = {
|
|
cloud_provider: 'AWS',
|
|
connectionString: 'postgresql://postgres:password@db.branch-ref.supabase.co:5432/postgres',
|
|
db_host: 'db.branch-ref.supabase.co',
|
|
dbVersion: 'supabase-postgres-15.1.0',
|
|
high_availability: false,
|
|
id: 2,
|
|
infra_compute_size: 'micro',
|
|
inserted_at: '2026-01-01T00:00:00.000Z',
|
|
integration_source: null,
|
|
is_branch_enabled: false,
|
|
is_physical_backups_enabled: false,
|
|
name: 'Branch',
|
|
organization_id: 1,
|
|
parent_project_ref: 'parent-ref',
|
|
ref: 'branch-ref',
|
|
region: 'us-east-1',
|
|
restUrl: 'https://branch-ref.supabase.co',
|
|
status: 'ACTIVE_HEALTHY',
|
|
subscription_id: 'subscription-1',
|
|
updated_at: '2026-01-01T00:00:00.000Z',
|
|
}
|
|
|
|
function mockProjectDetail() {
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/projects/:ref',
|
|
response: ({ params }) =>
|
|
HttpResponse.json<ProjectDetailData>(
|
|
params.ref === BRANCH_PROJECT.ref
|
|
? BRANCH_PROJECT
|
|
: { ...BRANCH_PROJECT, ref: String(params.ref), parent_project_ref: undefined }
|
|
),
|
|
})
|
|
}
|
|
|
|
beforeEach(() => {
|
|
mocks.isPlatform = true
|
|
mocks.params = { ref: 'default' }
|
|
})
|
|
|
|
describe('getGrant', () => {
|
|
const scope = { organizationSlug: ORG_SLUG, projectRef: 'proj', permissionsProjectRef: 'proj' }
|
|
|
|
test('mints from any satisfied group of an OR-of-AND requirement', () => {
|
|
const dev = permissionsFor({ permissions: ['branching_development_read'] })
|
|
const prod = permissionsFor({ permissions: ['branching_production_read'] })
|
|
|
|
expect(getGrant(dev, BRANCHES, scope).status).toBe('granted')
|
|
expect(getGrant(prod, BRANCHES, scope).status).toBe('granted')
|
|
})
|
|
|
|
test('records the endpoint and scope on the grant', () => {
|
|
const result = getGrant(
|
|
permissionsFor({ permissions: ['branching_production_read'] }),
|
|
BRANCHES,
|
|
scope
|
|
)
|
|
|
|
expect(result).toEqual({
|
|
status: 'granted',
|
|
grant: {
|
|
endpoint: BRANCHES,
|
|
variant: undefined,
|
|
organizationSlug: ORG_SLUG,
|
|
projectRef: 'proj',
|
|
permissionsProjectRef: 'proj',
|
|
},
|
|
})
|
|
})
|
|
|
|
test('denies when no group is satisfied or permissions are missing', () => {
|
|
expect(getGrant(permissionsFor(), BRANCHES, scope)).toEqual({ status: 'denied' })
|
|
expect(getGrant(undefined, BRANCHES, scope)).toEqual({ status: 'denied' })
|
|
expect(
|
|
getGrant(permissionsFor({ permissions: ['branching_production_read'] }), BRANCHES, {
|
|
...scope,
|
|
organizationSlug: 'other-org',
|
|
})
|
|
).toEqual({ status: 'denied' })
|
|
})
|
|
|
|
test('evaluates against permissionsProjectRef and records both refs', () => {
|
|
const data = permissionsFor({
|
|
role: 'member',
|
|
projects: [
|
|
{ ref: 'parent-ref', role: 'developer', permissions: ['branching_production_read'] },
|
|
],
|
|
})
|
|
|
|
const result = getGrant(data, BRANCHES, {
|
|
...scope,
|
|
projectRef: 'branch-ref',
|
|
permissionsProjectRef: 'parent-ref',
|
|
})
|
|
expect(result.status).toBe('granted')
|
|
if (result.status === 'granted') {
|
|
expect(result.grant.projectRef).toBe('branch-ref')
|
|
expect(result.grant.permissionsProjectRef).toBe('parent-ref')
|
|
}
|
|
|
|
expect(
|
|
getGrant(data, BRANCHES, {
|
|
...scope,
|
|
projectRef: 'branch-ref',
|
|
permissionsProjectRef: 'branch-ref',
|
|
}).status
|
|
).toBe('denied')
|
|
})
|
|
|
|
test('supports an explicit project scope for endpoints without the project in the path', () => {
|
|
const data = permissionsFor({
|
|
role: 'member',
|
|
projects: [{ ref: 'proj', role: 'developer', permissions: ['branching_development_delete'] }],
|
|
})
|
|
|
|
expect(getGrant(data, DELETE_BRANCH, scope).status).toBe('granted')
|
|
expect(
|
|
getGrant(data, DELETE_BRANCH, {
|
|
...scope,
|
|
projectRef: 'other',
|
|
permissionsProjectRef: 'other',
|
|
}).status
|
|
).toBe('denied')
|
|
})
|
|
|
|
test('mints without permission data when self-hosted', () => {
|
|
mocks.isPlatform = false
|
|
|
|
expect(
|
|
getGrant(undefined, BRANCHES, { projectRef: 'proj', permissionsProjectRef: 'proj' }).status
|
|
).toBe('granted')
|
|
})
|
|
|
|
test('requires database_write for the write variant of the pg-meta query', () => {
|
|
const readOnly = permissionsFor({ permissions: ['database_read'] })
|
|
const readWrite = permissionsFor({ permissions: ['database_read', 'database_write'] })
|
|
|
|
expect(getGrant(readOnly, PG_META_QUERY, scope, { variant: 'write' })).toEqual({
|
|
status: 'denied',
|
|
})
|
|
expect(getGrant(readWrite, PG_META_QUERY, scope, { variant: 'write' }).status).toBe('granted')
|
|
expect(getGrant(readOnly, PG_META_QUERY, scope, { variant: 'read' }).status).toBe('granted')
|
|
})
|
|
|
|
test('GrantForVariants is the union of the variant grants', () => {
|
|
expectTypeOf<GrantForVariants<'POST', '/platform/pg-meta/{ref}/query'>>().toEqualTypeOf<
|
|
Grant<typeof PG_META_QUERY, 'read'> | Grant<typeof PG_META_QUERY, 'write'>
|
|
>()
|
|
})
|
|
|
|
test('denies an unknown variant at runtime', () => {
|
|
const data = permissionsFor({ permissions: ['branching_production_read'] })
|
|
|
|
const result = getGrant(data, BRANCHES, scope, { variant: 'write' as never })
|
|
expect(result).toEqual({ status: 'denied' })
|
|
})
|
|
})
|
|
|
|
describe('getWriteGrantTooltip', () => {
|
|
test('explains a denied grant using the action and resource', () => {
|
|
expect(getWriteGrantTooltip('denied', 'create', 'API keys')).toBe(
|
|
'You need additional permissions to create API keys'
|
|
)
|
|
expect(getWriteGrantTooltip('denied', 'add', 'third-party auth integrations')).toBe(
|
|
'You need additional permissions to add third-party auth integrations'
|
|
)
|
|
})
|
|
|
|
test('explains a grant check that failed', () => {
|
|
expect(getWriteGrantTooltip('error', 'delete', 'signing keys')).toBe(
|
|
'Failed to check permissions to delete signing keys'
|
|
)
|
|
})
|
|
|
|
test('returns undefined while loading or granted', () => {
|
|
expect(getWriteGrantTooltip('loading', 'create', 'API keys')).toBeUndefined()
|
|
expect(getWriteGrantTooltip('granted', 'create', 'API keys')).toBeUndefined()
|
|
})
|
|
})
|
|
|
|
describe('getWriteGrantToastMessage', () => {
|
|
test('reuses the tooltip text for a denied grant', () => {
|
|
expect(getWriteGrantToastMessage('denied', 'create', 'API keys')).toBe(
|
|
getWriteGrantTooltip('denied', 'create', 'API keys')
|
|
)
|
|
})
|
|
|
|
test('reuses the tooltip text for a grant check that failed', () => {
|
|
expect(getWriteGrantToastMessage('error', 'delete', 'signing keys')).toBe(
|
|
'Failed to check permissions to delete signing keys'
|
|
)
|
|
})
|
|
|
|
test('asks the user to retry while the grant is loading', () => {
|
|
expect(getWriteGrantToastMessage('loading', 'add', 'third-party auth integrations')).toBe(
|
|
'Still checking permissions to add third-party auth integrations. Try again in a moment.'
|
|
)
|
|
})
|
|
})
|
|
|
|
describe('useGrant', () => {
|
|
test('moves from loading to granted', async () => {
|
|
mockPermissions(permissionsFor({ permissions: ['branching_production_read'] }))
|
|
|
|
const { result } = customRenderHook(
|
|
() => useGrant(BRANCHES, { organizationSlug: ORG_SLUG, projectRef: 'proj' }),
|
|
{ profileContext: PROFILE_CONTEXT }
|
|
)
|
|
|
|
expect(result.current.status).toBe('loading')
|
|
await waitFor(() => expect(result.current.status).toBe('granted'))
|
|
expect(result.current.grant).toEqual({
|
|
endpoint: BRANCHES,
|
|
variant: undefined,
|
|
organizationSlug: ORG_SLUG,
|
|
projectRef: 'proj',
|
|
permissionsProjectRef: 'proj',
|
|
})
|
|
})
|
|
|
|
test('denies when the permissions are missing', async () => {
|
|
mockPermissions(permissionsFor())
|
|
|
|
const { result } = customRenderHook(
|
|
() => useGrant(BRANCHES, { organizationSlug: ORG_SLUG, projectRef: 'proj' }),
|
|
{ profileContext: PROFILE_CONTEXT }
|
|
)
|
|
|
|
await waitFor(() => expect(result.current.status).toBe('denied'))
|
|
expect(result.current.grant).toBeUndefined()
|
|
})
|
|
|
|
test('reports an error when the permissions request fails', async () => {
|
|
mockPermissionsError({ message: 'Boom' })
|
|
|
|
const { result } = customRenderHook(
|
|
() => useGrant(BRANCHES, { organizationSlug: ORG_SLUG, projectRef: 'proj' }),
|
|
{ profileContext: PROFILE_CONTEXT }
|
|
)
|
|
|
|
await waitFor(() => expect(result.current.status).toBe('error'))
|
|
expect(result.current).toMatchObject({ error: { message: 'Boom' } })
|
|
})
|
|
|
|
test('grants immediately when self-hosted', () => {
|
|
mocks.isPlatform = false
|
|
|
|
const { result } = customRenderHook(() => useGrant(BRANCHES, { projectRef: 'proj' }), {
|
|
profileContext: PROFILE_CONTEXT,
|
|
})
|
|
|
|
expect(result.current.status).toBe('granted')
|
|
})
|
|
|
|
test('resolves a branch from the URL to its parent but records the branch ref', async () => {
|
|
mocks.params = { ref: 'branch-ref' }
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/projects/:ref',
|
|
response: () => HttpResponse.json<ProjectDetailData>(BRANCH_PROJECT),
|
|
})
|
|
mockOrganizations()
|
|
mockPermissions(
|
|
permissionsFor({
|
|
role: 'member',
|
|
projects: [
|
|
{ ref: 'parent-ref', role: 'developer', permissions: ['branching_production_read'] },
|
|
],
|
|
})
|
|
)
|
|
|
|
const { result } = customRenderHook(() => useGrant(BRANCHES, {}), {
|
|
profileContext: PROFILE_CONTEXT,
|
|
})
|
|
|
|
await waitFor(() => expect(result.current.status).toBe('granted'))
|
|
expect(result.current.grant).toMatchObject({
|
|
organizationSlug: ORG_SLUG,
|
|
projectRef: 'branch-ref',
|
|
})
|
|
})
|
|
|
|
test('returns a stable result across rerenders', async () => {
|
|
mockPermissions(permissionsFor({ permissions: ['branching_production_read'] }))
|
|
|
|
const { result, rerender } = customRenderHook(
|
|
() => useGrant(BRANCHES, { organizationSlug: ORG_SLUG, projectRef: 'proj' }),
|
|
{ profileContext: PROFILE_CONTEXT }
|
|
)
|
|
|
|
await waitFor(() => expect(result.current.status).toBe('granted'))
|
|
const first = result.current
|
|
rerender()
|
|
expect(result.current).toBe(first)
|
|
})
|
|
})
|
|
|
|
describe('ensureGrant', () => {
|
|
const scope = { organizationSlug: ORG_SLUG, projectRef: 'proj' }
|
|
|
|
beforeEach(() => {
|
|
mockProjectDetail()
|
|
})
|
|
|
|
test('grants when permissions allow', async () => {
|
|
mockPermissions(permissionsFor({ permissions: ['branching_production_read'] }))
|
|
|
|
const result = await ensureGrant(new QueryClient(), BRANCHES, scope)
|
|
|
|
expect(result.status).toBe('granted')
|
|
})
|
|
|
|
test('denies when permissions are missing', async () => {
|
|
mockPermissions(permissionsFor())
|
|
|
|
expect(await ensureGrant(new QueryClient(), BRANCHES, scope)).toEqual({ status: 'denied' })
|
|
})
|
|
|
|
test('returns an error when permissions cannot be fetched', async () => {
|
|
mockPermissionsError({ message: 'Boom' })
|
|
|
|
const result = await ensureGrant(new QueryClient(), BRANCHES, scope)
|
|
|
|
expect(result).toMatchObject({ status: 'error', error: { message: 'Boom' } })
|
|
})
|
|
|
|
test('grants without fetching when self-hosted', async () => {
|
|
mocks.isPlatform = false
|
|
|
|
const result = await ensureGrant(new QueryClient(), BRANCHES, scope)
|
|
|
|
expect(result.status).toBe('granted')
|
|
})
|
|
|
|
test('fetches the project detail to resolve the parent ref', async () => {
|
|
mockPermissions(
|
|
permissionsFor({
|
|
role: 'member',
|
|
projects: [
|
|
{ ref: 'parent-ref', role: 'developer', permissions: ['branching_production_read'] },
|
|
],
|
|
})
|
|
)
|
|
const queryClient = new QueryClient()
|
|
|
|
const result = await ensureGrant(queryClient, BRANCHES, {
|
|
organizationSlug: ORG_SLUG,
|
|
projectRef: 'branch-ref',
|
|
})
|
|
|
|
expect(result.status).toBe('granted')
|
|
if (result.status === 'granted') expect(result.grant.projectRef).toBe('branch-ref')
|
|
expect(queryClient.getQueryData(projectKeys.detail('branch-ref'))).toMatchObject({
|
|
parent_project_ref: 'parent-ref',
|
|
})
|
|
})
|
|
|
|
test('returns an error when the project detail cannot be fetched', async () => {
|
|
mockPermissions(permissionsFor({ permissions: ['branching_production_read'] }))
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/projects/:ref',
|
|
response: () => HttpResponse.json<APIErrorBody>({ message: 'Boom' }, { status: 500 }),
|
|
})
|
|
|
|
const result = await ensureGrant(new QueryClient(), BRANCHES, scope)
|
|
|
|
expect(result).toMatchObject({ status: 'error', error: { message: 'Boom' } })
|
|
})
|
|
})
|
|
|
|
describe('types', () => {
|
|
type BranchesGrant = Grant<'GET /v1/projects/{ref}/branches'>
|
|
type CreateBranchGrant = Grant<'POST /v1/projects/{ref}/branches'>
|
|
|
|
test('grants are bound to their endpoint', () => {
|
|
function check(grant: BranchesGrant) {
|
|
// @ts-expect-error a grant for another endpoint is not interchangeable
|
|
const other: CreateBranchGrant = grant
|
|
return other
|
|
}
|
|
expect(check).toBeDefined()
|
|
})
|
|
|
|
test('a plain object is not a grant', () => {
|
|
const plain = {
|
|
endpoint: 'GET /v1/projects/{ref}/branches' as const,
|
|
variant: undefined,
|
|
organizationSlug: 'org',
|
|
projectRef: 'proj',
|
|
}
|
|
// @ts-expect-error the brand can only be minted by getGrant
|
|
const grant: BranchesGrant = plain
|
|
expect(grant).toBeDefined()
|
|
})
|
|
|
|
test('GrantFor resolves annotated endpoints and is never otherwise', () => {
|
|
expectTypeOf<GrantFor<'GET', '/v1/projects/{ref}/branches'>>().toEqualTypeOf<BranchesGrant>()
|
|
expectTypeOf<GrantFor<'GET', '/platform/profile'>>().toBeNever()
|
|
})
|
|
|
|
test('useGrant narrows the grant on status', () => {
|
|
type Result = ReturnType<typeof useGrant<'GET /v1/projects/{ref}/branches'>>
|
|
expectTypeOf<Result>().toEqualTypeOf<GrantResult<'GET /v1/projects/{ref}/branches'>>()
|
|
|
|
function check(result: Result) {
|
|
expectTypeOf(result.grant).toEqualTypeOf<BranchesGrant | undefined>()
|
|
if (result.status === 'granted') {
|
|
expectTypeOf(result.grant).toEqualTypeOf<BranchesGrant>()
|
|
}
|
|
}
|
|
expect(check).toBeDefined()
|
|
})
|
|
})
|