Files
supabase/apps/studio/lib/grants.ts
Charis 395a54f2b7 feat(studio): gate jwt signing keys, legacy api keys, and third-party auth on grants (#53241)
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)
2026-11-10 15:30:58 -05:00

260 lines
9.1 KiB
TypeScript

import type { QueryClient } from '@tanstack/react-query'
import { fgaRequirements, type FgaGuardedEndpoint } from 'api-types'
import { useIsLoggedIn } from 'common'
import { useMemo } from 'react'
import { classifyError } from '@/data/error-classification'
import {
permissionsQueryOptionsV2,
usePermissionsQueryV2,
type PermissionsV2Data,
} from '@/data/permissions/permissions-query-v2'
import { prefetchProjectDetail } from '@/data/projects/project-detail-query'
import { doPermissionsCheckV2, usePermissionScopeV2 } from '@/hooks/misc/useCheckPermissionsV2'
import { IS_PLATFORM } from '@/lib/constants'
import type { StudioError } from '@/lib/errors/studio-errors'
import { fgaRefinements, type FgaRefinementMap, type FgaRefinements } from '@/lib/fga-refinements'
export type VariantOf<E extends FgaGuardedEndpoint> = FgaRefinements extends {
readonly [K in E]: { readonly variants: infer Vs }
}
? Extract<keyof Vs, string>
: never
declare const grantBrand: unique symbol
/** Proof that the current user holds the FGA permissions an endpoint (and optional variant) requires. */
export type Grant<E extends FgaGuardedEndpoint, V extends VariantOf<E> = never> = {
readonly endpoint: E
readonly variant: [V] extends [never] ? undefined : V
readonly organizationSlug: string | undefined
/** The ref the grant authorizes (the branch ref for branch projects). */
readonly projectRef: string | null | undefined
/** The ref permissions were evaluated against (the parent project for branch projects). */
readonly permissionsProjectRef: string | null | undefined
// Function type: invariant in E and V. A plain property would be covariant, so `Grant<E, never>` would satisfy `Grant<E, 'write'>`.
readonly [grantBrand]: (_: { e: E; v: V }) => { e: E; v: V }
}
export type GrantResult<E extends FgaGuardedEndpoint, V extends VariantOf<E> = never> =
| { status: 'loading'; grant?: never }
| { status: 'granted'; grant: Grant<E, V> }
| { status: 'denied'; grant?: never }
| { status: 'error'; error: StudioError; grant?: never }
/**
* Tooltip text for a write action that is disabled by its grant, e.g.
* `getWriteGrantTooltip(grant.status, 'create', 'signing keys')`. Returns undefined while the grant
* is loading or granted.
*/
export function getWriteGrantTooltip(
status: GrantResult<FgaGuardedEndpoint, never>['status'],
action: string,
resource: string
) {
if (status === 'denied') return `You need additional permissions to ${action} ${resource}`
if (status === 'error') return `Failed to check permissions to ${action} ${resource}`
return undefined
}
/**
* Toast text for a write action that did nothing because its grant is missing, e.g.
* `toast.error(getWriteGrantToastMessage(grant.status, 'create', 'signing keys'))`. Unlike the
* tooltip, it always returns a message, including while permissions are still loading.
*/
export function getWriteGrantToastMessage(
status: Exclude<GrantResult<FgaGuardedEndpoint, never>['status'], 'granted'>,
action: string,
resource: string
) {
return (
getWriteGrantTooltip(status, action, resource) ??
`Still checking permissions to ${action} ${resource}. Try again in a moment.`
)
}
export type GrantScope = {
organizationSlug?: string
projectRef?: string | null
}
/** `permissionsProjectRef` is the ref permissions are evaluated against: the parent project for branches. */
type ResolvedGrantScope = GrantScope & { permissionsProjectRef: string | null | undefined }
/** The `fgaRequirements` key for a method and path, e.g. `GET /v1/projects/{ref}`. */
export type EndpointKey<M extends string, P extends string> = `${Uppercase<M>} ${P}`
type VariantOfKey<K extends string> = K extends FgaGuardedEndpoint ? VariantOf<K> : never
/** Grant type for an endpoint, or `never` if the endpoint isn't annotated. For xQueryOptions / mutation variables. */
export type GrantFor<
M extends string,
P extends string,
V extends VariantOfKey<EndpointKey<M, P>> = never,
> = EndpointKey<M, P> extends FgaGuardedEndpoint ? Grant<EndpointKey<M, P>, V> : never
type GrantForVariant<E extends FgaGuardedEndpoint, V> = V extends VariantOf<E> ? Grant<E, V> : never
/** A grant for any one of an endpoint's variants, or `never` if the endpoint isn't annotated. */
export type GrantForVariants<M extends string, P extends string> =
EndpointKey<M, P> extends FgaGuardedEndpoint
? GrantForVariant<EndpointKey<M, P>, VariantOf<EndpointKey<M, P>>>
: never
function mintGrant<E extends FgaGuardedEndpoint, V extends VariantOf<E>>(
endpoint: E,
variant: V | undefined,
scope: ResolvedGrantScope
): Grant<E, V> {
// The brand is type-only: this is the one place a grant is created
return {
endpoint,
variant,
organizationSlug: scope.organizationSlug,
projectRef: scope.projectRef,
permissionsProjectRef: scope.permissionsProjectRef,
} as unknown as Grant<E, V>
}
/**
* Pure check of `permissions` against the endpoint's requirements (and the variant's, if given),
* evaluated against `permissionsProjectRef`. The minted grant records both refs.
*/
export function getGrant<E extends FgaGuardedEndpoint, const V extends VariantOf<E> = never>(
permissions: PermissionsV2Data | undefined,
endpoint: E,
scope: ResolvedGrantScope,
opts?: { variant?: V }
): { status: 'granted'; grant: Grant<E, V> } | { status: 'denied' } {
const variant = opts?.variant
if (!IS_PLATFORM) return { status: 'granted', grant: mintGrant(endpoint, variant, scope) }
const passesBase = doPermissionsCheckV2(
permissions,
fgaRequirements[endpoint],
scope.organizationSlug,
scope.permissionsProjectRef
)
if (!passesBase) return { status: 'denied' }
if (variant !== undefined) {
const refinements: FgaRefinementMap = fgaRefinements
const requires = refinements[endpoint]?.variants[variant]?.requires
if (
!requires ||
!doPermissionsCheckV2(
permissions,
requires,
scope.organizationSlug,
scope.permissionsProjectRef
)
) {
return { status: 'denied' }
}
}
return { status: 'granted', grant: mintGrant(endpoint, variant, scope) }
}
/**
* Mints a grant for the current user, resolving organization and project from the URL unless
* `scope` overrides them. Self-hosted always grants.
*/
export function useGrant<E extends FgaGuardedEndpoint, const V extends VariantOf<E> = never>(
endpoint: E,
scope: GrantScope,
opts?: { variant?: V }
): GrantResult<E, V> {
const variant = opts?.variant
const isLoggedIn = useIsLoggedIn()
const {
data: permissions,
error: permissionsError,
isPending: isLoadingPermissions,
} = usePermissionsQueryV2()
const {
organizationSlug,
projectRef,
permissionsProjectRef,
isLoading: isLoadingScope,
error: scopeError,
} = usePermissionScopeV2({ ...scope, enabled: IS_PLATFORM && isLoggedIn })
return useMemo((): GrantResult<E, V> => {
if (!IS_PLATFORM)
return getGrant(
permissions,
endpoint,
{ organizationSlug, projectRef, permissionsProjectRef: projectRef },
{ variant }
)
if (!isLoggedIn) return { status: 'loading' }
if (permissionsError) return { status: 'error', error: permissionsError }
if (scopeError) return { status: 'error', error: scopeError }
if (isLoadingPermissions || isLoadingScope) return { status: 'loading' }
return getGrant(
permissions,
endpoint,
{ organizationSlug, projectRef, permissionsProjectRef },
{ variant }
)
}, [
endpoint,
variant,
permissions,
permissionsError,
scopeError,
isLoggedIn,
isLoadingPermissions,
isLoadingScope,
organizationSlug,
projectRef,
permissionsProjectRef,
])
}
async function resolveGrantScope(
queryClient: QueryClient,
scope: GrantScope & { permissionsProjectRef?: string | null }
): Promise<ResolvedGrantScope> {
const { permissionsProjectRef, projectRef } = scope
if (permissionsProjectRef !== undefined) return { ...scope, permissionsProjectRef }
if (!IS_PLATFORM || typeof projectRef !== 'string') {
return { ...scope, permissionsProjectRef: projectRef }
}
const project = await prefetchProjectDetail(queryClient, { ref: projectRef })
return { ...scope, permissionsProjectRef: project.parent_project_ref ?? projectRef }
}
/**
* Imperative counterpart of `useGrant` for prefetching and callbacks. Reuses fresh cached
* permissions and project details, fetching them otherwise. Pass `permissionsProjectRef` to skip
* resolving a branch's parent project.
*/
export async function ensureGrant<
E extends FgaGuardedEndpoint,
const V extends VariantOf<E> = never,
>(
queryClient: QueryClient,
endpoint: E,
scope: GrantScope & { permissionsProjectRef?: string | null },
opts?: { variant?: V }
): Promise<
| { status: 'granted'; grant: Grant<E, V> }
| { status: 'denied' }
| { status: 'error'; error: StudioError }
> {
try {
const [permissions, resolvedScope] = await Promise.all([
IS_PLATFORM ? queryClient.fetchQuery(permissionsQueryOptionsV2()) : undefined,
resolveGrantScope(queryClient, scope),
])
return getGrant(permissions, endpoint, resolvedScope, opts)
} catch (error) {
return { status: 'error', error: classifyError(error) }
}
}