Files
supabase/apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/rotate-key-dialog.tsx
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

316 lines
11 KiB
TypeScript

import { ArrowRightIcon, ExternalLinkIcon, InfoIcon, KeyIcon, TimerIcon } from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'
import {
Badge,
Checkbox,
cn,
DialogDescription,
DialogFooter,
DialogHeader,
DialogSection,
DialogSectionSeparator,
DialogTitle,
Label,
Skeleton,
} from 'ui'
import { algorithmLabels } from '../algorithm-details'
import { statusColors } from '../jwt.constants'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { useEdgeFunctionsQuery } from '@/data/edge-functions/edge-functions-query'
import { useJWTSigningKeyUpdateMutation } from '@/data/jwt-signing-keys/jwt-signing-key-update-mutation'
import { JWTSigningKey } from '@/data/jwt-signing-keys/jwt-signing-keys-query'
import { getWriteGrantToastMessage, getWriteGrantTooltip, useGrant } from '@/lib/grants'
export function RotateKeyDialog({
projectRef,
standbyKey,
inUseKey,
onClose,
}: {
projectRef: string
standbyKey: JWTSigningKey
inUseKey: JWTSigningKey
onClose: () => void
}) {
const [isStandbyUnderstood, setStandbyUnderstood] = useState(false)
const [isPreviouslyUsedUnderstood, setPreviouslyUsedUnderstood] = useState(false)
const [isEdgeFunctionsVerifyJWTUnderstood, setEdgeFunctionsVerifyJWTUnderstood] = useState(false)
const updateGrant = useGrant('PATCH /v1/projects/{ref}/config/auth/signing-keys/{id}', {
projectRef,
})
const { data: edgeFunctions, isPending: isLoadingEdgeFunctions } = useEdgeFunctionsQuery({
projectRef,
})
const { mutate, isPending: isPendingMutation } = useJWTSigningKeyUpdateMutation({
onSuccess: () => {
toast.success('Signing key rotated successfully')
onClose()
},
onError: (error) => {
toast.error(`Failed to rotate signing key: ${error.message}`)
},
})
const verifyJWTEdgeFunctions = edgeFunctions?.filter(({ verify_jwt }) => verify_jwt) ?? []
return (
<>
<DialogHeader>
<DialogTitle>Rotate JWT signing key</DialogTitle>
<DialogDescription>
Change the key used by Supabase Auth to create new JSON Web Tokens. Non-expired tokens
remain <span className="text-primary">valid and accepted</span>!
</DialogDescription>
</DialogHeader>
<DialogSectionSeparator />
<DialogSection className="bg">
<div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-x-4 gap-y-2">
<Badge
className={cn(
statusColors['standby'],
'px-4 py-1 gap-2 flex flex-row items-center uppercase'
)}
>
<TimerIcon size={14} />
Standby key
</Badge>
<div>
<ArrowRightIcon className="size-4 text-foreground-light" />
</div>
<div>
<Badge
className={cn(
statusColors['in_use'],
'px-4 py-1 gap-2 flex flex-row items-center uppercase'
)}
>
<KeyIcon size={14} />
Current key
</Badge>
</div>
<div className="text-xs text-foreground-light font-mono text-center">
{algorithmLabels[standbyKey.algorithm]}
</div>
<div />
<div />
<div className="col-span-3" />
<Badge
className={cn(
statusColors['in_use'],
'px-4 py-1 gap-2 flex flex-row items-center uppercase'
)}
>
<KeyIcon size={14} />
Current key
</Badge>
<div>
<ArrowRightIcon className="h-4 w-4 text-foreground-light" />
</div>
<Badge
className={cn(
statusColors['previously_used'],
'px-4 py-1 gap-2 flex flex-row items-center uppercase'
)}
>
<TimerIcon size={14} />
Previous key
</Badge>
<div />
<div />
<div className="text-xs text-foreground-light font-mono text-center">
{algorithmLabels[inUseKey.algorithm]}
</div>
</div>
</DialogSection>
<DialogSectionSeparator />
<DialogSection className="flex flex-col gap-4">
{isLoadingEdgeFunctions ? (
<>
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-full" />
</>
) : (
<>
<div className="text-sm">To proceed please confirm:</div>
<Label
htmlFor="understands-standby"
className="flex items-start gap-4 text-sm leading-none"
>
<Checkbox
id="understands-standby"
className="mt-0.5"
checked={isStandbyUnderstood}
onCheckedChange={(value) => setStandbyUnderstood(!!value)}
/>
<p className="text-sm text-foreground-light">
All of my application's components have picked up the standby key.
</p>
<ButtonTooltip
icon={<InfoIcon />}
className="px-1.5 py-2 mt-0.5"
tooltip={{
content: {
className: 'max-w-[320px] p-4',
text: (
<p>
If your application verifies JWTs on its own in backend servers, functions,
lambdas or other such components, ensure that they've picked up and are
verifying tokens against the standby key.
<br />
<br />
Recommendation: Periodically fetch the public keys from the project's{' '}
<code>jwks.json</code> endpoint.
</p>
),
},
}}
/>
</Label>
<Label
htmlFor="understands-previously-used"
className="flex items-start gap-4 text-sm leading-none"
>
<Checkbox
className="mt-0.5"
id="understands-previously-used"
checked={isPreviouslyUsedUnderstood}
onCheckedChange={(value) => setPreviouslyUsedUnderstood(!!value)}
/>
<p className="text-sm text-foreground-light">
To invalidate non-expired JWTs I need to explicitly revoke the currently used key.
</p>
<ButtonTooltip
icon={<InfoIcon />}
className="px-1.5 py-2 mt-0.5"
tooltip={{
content: {
className: 'max-w-[320px] p-4',
text: (
<p>
Rotating the signing key only changes what key is used by Supabase Auth to
issue <em className="text-primary not-italic">new tokens</em>
.<br />
<br />
To prevent users from being prematurely signed out, you have to manually
revoke the current in use key after rotation.
<br />
<br />
Recommendation: If your JWT expiry time is 1 hour, wait at least 1 hour and
15 minutes before revoking the key.
</p>
),
},
}}
/>
</Label>
{verifyJWTEdgeFunctions.length > 0 && (
<Label htmlFor="edge-functions-verify-jwt" className="flex gap-4 text-sm">
<Checkbox
id="edge-functions-verify-jwt"
className="mt-0.5"
checked={isEdgeFunctionsVerifyJWTUnderstood}
onCheckedChange={(value) => setEdgeFunctionsVerifyJWTUnderstood(!!value)}
/>
<p className="text-sm text-foreground-light">
The following Edge Functions may stop functioning for signed-in users as they
verify the legacy JWT secret:{' '}
{verifyJWTEdgeFunctions
.map(({ name }) => (
<a
key={name}
className=""
href={`../../functions/${name}/details`}
target="_blank"
title={name}
>
<ExternalLinkIcon className="size-3 inline-block" /> <code>{name}</code>
</a>
))
.reduce<React.ReactNode[]>(
(arr, v) => (arr.length > 0 ? [...arr, ', ', v] : [v]),
[]
)}
</p>
<ButtonTooltip
variant="default"
icon={<InfoIcon />}
className="px-1.5 py-2 mt-0.5"
tooltip={{
content: {
className: 'max-w-[320px] p-4',
text: (
<p>
Some of your Edge Functions are set up to require a JWT in the{' '}
<code>Authorization</code> header signed with the{' '}
<em className="text-primary not-italic">legacy JWT secret</em>. Rotation
causes{' '}
<em className="text-primary not-italic">
invocations by signed-in users
</em>{' '}
to fail with HTTP 401 Unauthorized, as the JWT no longer meets this
requirement.
<br />
<br />
Recommendation: Change all of your Edge Functions to no longer verify JWT
and implement the verification logic in the function's code yourself by
using the Supabase client library or any other library for working with
JWT.
</p>
),
},
}}
/>
</Label>
)}
</>
)}
</DialogSection>
<DialogFooter>
<ButtonTooltip
variant="primary"
onClick={() => {
if (!updateGrant.grant) {
toast.error(getWriteGrantToastMessage(updateGrant.status, 'rotate', 'signing keys'))
return
}
mutate({
projectRef,
grant: updateGrant.grant,
keyId: standbyKey.id,
status: 'in_use',
})
}}
disabled={
!updateGrant.grant ||
isLoadingEdgeFunctions ||
!isPreviouslyUsedUnderstood ||
!isStandbyUnderstood ||
(!!verifyJWTEdgeFunctions.length && !isEdgeFunctionsVerifyJWTUnderstood)
}
loading={isPendingMutation}
tooltip={{
content: {
side: 'top',
text: getWriteGrantTooltip(updateGrant.status, 'rotate', 'signing keys'),
},
}}
>
Rotate signing key
</ButtonTooltip>
</DialogFooter>
</>
)
}