mirror of
https://github.com/supabase/supabase.git
synced 2026-12-06 08:29:01 +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)
276 lines
8.8 KiB
TypeScript
276 lines
8.8 KiB
TypeScript
import dayjs from 'dayjs'
|
|
import { useMemo, useState } from 'react'
|
|
import { toast } from 'sonner'
|
|
import {
|
|
Badge,
|
|
Checkbox,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogSection,
|
|
DialogSectionSeparator,
|
|
DialogTitle,
|
|
Label,
|
|
Select,
|
|
SelectContent,
|
|
SelectItem,
|
|
SelectTrigger,
|
|
SelectValue,
|
|
Textarea,
|
|
} from 'ui'
|
|
|
|
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
|
|
import { Shortcut } from '@/components/ui/Shortcut'
|
|
import { useJWTSigningKeyCreateMutation } from '@/data/jwt-signing-keys/jwt-signing-key-create-mutation'
|
|
import { JWTAlgorithm } from '@/data/jwt-signing-keys/jwt-signing-keys-query'
|
|
import { stringToBase64URL } from '@/lib/base64url'
|
|
import { getWriteGrantToastMessage, getWriteGrantTooltip, useGrant } from '@/lib/grants'
|
|
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
|
|
|
|
const RSA_JWK_REQUIRED_PROPERTIES = ['kty', 'n', 'e', 'p', 'q', 'd', 'dq', 'dp', 'qi']
|
|
const EC_JWK_REQUIRED_PROPERTIES = ['kty', 'crv', 'x', 'y', 'd']
|
|
|
|
export const CreateKeyDialog = ({
|
|
projectRef,
|
|
onClose,
|
|
}: {
|
|
projectRef: string
|
|
onClose: () => void
|
|
}) => {
|
|
const createGrant = useGrant('POST /v1/projects/{ref}/config/auth/signing-keys', { projectRef })
|
|
const createTooltip = getWriteGrantTooltip(createGrant.status, 'create', 'signing keys')
|
|
const [newKeyAlgorithm, setNewKeyAlgorithm] = useState<JWTAlgorithm>('ES256')
|
|
const [isBYOK, setBYOK] = useState(false)
|
|
const [privateKey, setPrivateKey] = useState('')
|
|
const [isBase64, setBase64] = useState(false)
|
|
|
|
const privateKeyMessage = useMemo(() => {
|
|
const plain = privateKey.replace(/\s+/g, '')
|
|
|
|
if (!plain) {
|
|
return null
|
|
}
|
|
|
|
if (newKeyAlgorithm === 'HS256') {
|
|
if (privateKey.length < 16) {
|
|
return 'Secret must be at least 16 letters long'
|
|
}
|
|
|
|
return null
|
|
}
|
|
|
|
let jwk
|
|
try {
|
|
jwk = JSON.parse(privateKey)
|
|
} catch (e: any) {
|
|
return 'Private key is not valid JSON'
|
|
}
|
|
|
|
if (typeof jwk !== 'object' || !jwk) {
|
|
return 'Private key must be a JSON object'
|
|
}
|
|
|
|
if (typeof jwk.kty !== 'string' || !jwk.kty) {
|
|
return 'Private key must have a kty property'
|
|
}
|
|
|
|
if (newKeyAlgorithm === 'RS256') {
|
|
if (jwk.kty !== 'RSA') {
|
|
return 'Private key must be of RSA type'
|
|
}
|
|
|
|
if (jwk.e !== 'AQAB') {
|
|
return 'RSA private keys must use the 65537 (AQAB) public exponent'
|
|
}
|
|
|
|
for (let prop of RSA_JWK_REQUIRED_PROPERTIES) {
|
|
if (typeof jwk[prop] !== 'string' || !jwk[prop]) {
|
|
return `Incomplete RSA private key, required properties are: ${RSA_JWK_REQUIRED_PROPERTIES.join(', ')}`
|
|
}
|
|
}
|
|
} else if (newKeyAlgorithm === 'ES256') {
|
|
if (jwk.kty !== 'EC') {
|
|
return 'Private key must be of EC type'
|
|
}
|
|
|
|
if (jwk.crv !== 'P-256') {
|
|
return 'EC private keys must use P-256 curve'
|
|
}
|
|
|
|
for (let prop of EC_JWK_REQUIRED_PROPERTIES) {
|
|
if (typeof jwk[prop] !== 'string' || !jwk[prop]) {
|
|
return `Incomplete EC private key, required properties are: ${EC_JWK_REQUIRED_PROPERTIES.join(', ')}`
|
|
}
|
|
}
|
|
}
|
|
|
|
return null
|
|
}, [privateKey, newKeyAlgorithm])
|
|
|
|
const { mutate, isPending: isPendingMutation } = useJWTSigningKeyCreateMutation({
|
|
onSuccess: () => {
|
|
toast.success('Standby key created successfully')
|
|
onClose()
|
|
},
|
|
onError: (error) => {
|
|
let errorMessage = error.message
|
|
|
|
if (errorMessage.includes('Please wait until')) {
|
|
const dateString = errorMessage
|
|
.replace('Please wait until ', '')
|
|
.replace('before attempting this request again.', '')
|
|
.trim()
|
|
const date = dayjs(dateString)
|
|
|
|
if (date.isValid()) {
|
|
errorMessage = `Please wait for ${date.fromNow(true)} before attempting this request again.`
|
|
}
|
|
}
|
|
toast.error(`Failed to add new standby key: ${errorMessage}`)
|
|
},
|
|
})
|
|
|
|
const handleAddNewStandbyKey = async () => {
|
|
if (!createGrant.grant) {
|
|
toast.error(getWriteGrantToastMessage(createGrant.status, 'create', 'signing keys'))
|
|
return
|
|
}
|
|
mutate({
|
|
projectRef: projectRef!,
|
|
grant: createGrant.grant,
|
|
algorithm: newKeyAlgorithm,
|
|
status: 'standby',
|
|
private_jwk: isBYOK
|
|
? newKeyAlgorithm === 'HS256'
|
|
? {
|
|
kty: 'oct',
|
|
k: isBase64
|
|
? privateKey
|
|
.replace(/\s+/g, '')
|
|
.replace(/\+/g, '-')
|
|
.replace(/\//g, '_')
|
|
.replace(/=/g, '')
|
|
: stringToBase64URL(privateKey),
|
|
}
|
|
: JSON.parse(privateKey)
|
|
: null,
|
|
})
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<DialogHeader>
|
|
<DialogTitle>Create a new Standby Key</DialogTitle>
|
|
</DialogHeader>
|
|
<DialogSectionSeparator />
|
|
<DialogSection className="space-y-4">
|
|
<p className="text-sm text-foreground-light">
|
|
Adds a new JSON Web Token signing key. Once all of your application's components have
|
|
picked it up you can rotate the current key with it.
|
|
<br />
|
|
<br />
|
|
This action does not invalidate existing tokens, so your users remain signed in.
|
|
</p>
|
|
</DialogSection>
|
|
<DialogSectionSeparator />
|
|
<DialogSection className="flex flex-col gap-4">
|
|
<div className="flex flex-col gap-4">
|
|
<Label htmlFor="algorithm">Choose signing algorithm:</Label>
|
|
<Select
|
|
name="algorithm"
|
|
value={newKeyAlgorithm}
|
|
onValueChange={(value: JWTAlgorithm) => setNewKeyAlgorithm(value)}
|
|
>
|
|
<SelectTrigger id="algorithm">
|
|
<SelectValue placeholder="Select algorithm" />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value="ES256">
|
|
<span>ES256 (ECC)</span>
|
|
<Badge variant="success" className="ml-2">
|
|
Recommended
|
|
</Badge>
|
|
</SelectItem>
|
|
<SelectItem value="RS256">RS256 (RSA)</SelectItem>
|
|
<SelectItem value="HS256">HS256 (Shared Secret)</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
<div className="flex flex-col gap-4">
|
|
<Label htmlFor="byok" className="flex items-center gap-x-2">
|
|
<Checkbox id="byok" checked={isBYOK} onCheckedChange={(value) => setBYOK(!!value)} />
|
|
{newKeyAlgorithm === 'HS256' ? (
|
|
<span>Import an existing secret</span>
|
|
) : (
|
|
<span>Import an existing private key</span>
|
|
)}
|
|
</Label>
|
|
{isBYOK && (
|
|
<div className="flex flex-col gap-2">
|
|
<Textarea
|
|
className="font-mono"
|
|
placeholder={
|
|
newKeyAlgorithm === 'HS256'
|
|
? 'Type in your JWT secret'
|
|
: 'Add a private key in JWK (JSON Web Key) format'
|
|
}
|
|
value={privateKey}
|
|
onChange={(e: any) => {
|
|
setPrivateKey(e.target.value)
|
|
}}
|
|
autoComplete="off"
|
|
autoCorrect="off"
|
|
autoCapitalize="off"
|
|
spellCheck="false"
|
|
/>
|
|
{privateKeyMessage && <p className="text-red-900 text-sm">{privateKeyMessage}</p>}
|
|
</div>
|
|
)}
|
|
{isBYOK && newKeyAlgorithm === 'HS256' && (
|
|
<>
|
|
<Label htmlFor="base64" className="flex items-center gap-x-2">
|
|
<Checkbox
|
|
id="base64"
|
|
checked={isBase64}
|
|
onCheckedChange={(value) => setBase64(!!value)}
|
|
/>
|
|
Secret is already Base64 encoded
|
|
</Label>
|
|
</>
|
|
)}
|
|
</div>
|
|
</DialogSection>
|
|
<DialogFooter>
|
|
<Shortcut
|
|
id={SHORTCUT_IDS.JWT_KEYS_SUBMIT_STANDBY}
|
|
onTrigger={handleAddNewStandbyKey}
|
|
options={{
|
|
enabled:
|
|
!!createGrant.grant &&
|
|
!isPendingMutation &&
|
|
!privateKeyMessage &&
|
|
(!isBYOK || privateKey.trim().length > 0),
|
|
}}
|
|
side="top"
|
|
// Hide the shortcut hint while blocked so the permission tooltip shows instead
|
|
tooltipOpen={createTooltip ? false : undefined}
|
|
>
|
|
<ButtonTooltip
|
|
variant="primary"
|
|
onClick={() => handleAddNewStandbyKey()}
|
|
disabled={
|
|
!createGrant.grant ||
|
|
isPendingMutation ||
|
|
!!privateKeyMessage ||
|
|
(isBYOK && privateKey.trim().length === 0)
|
|
}
|
|
loading={isPendingMutation}
|
|
tooltip={{ content: { side: 'top', text: createTooltip } }}
|
|
>
|
|
Create standby key
|
|
</ButtonTooltip>
|
|
</Shortcut>
|
|
</DialogFooter>
|
|
</>
|
|
)
|
|
}
|