The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
[FE-3096] feat(studio): split edge function secrets into custom and default sections (#45355)
Alaister Young45ffa97240a0
diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/AddNewSecretForm.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/AddNewSecretForm.tsxindex fccd0f829a0..740b5929094 100644--- a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/AddNewSecretForm.tsx+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/AddNewSecretForm.tsx@@ -55,7 +55,7 @@ const removeWrappingQuotes = (str: string): string => {return str}-const AddNewSecretForm = () => {+export const AddNewSecretForm = () => {const { ref: projectRef } = useParams()const [visibleSecrets, setVisibleSecrets] = useState<Set<string>>(new Set())const [duplicateSecretName, setDuplicateSecretName] = useState<string>('')@@ -295,5 +295,3 @@ const AddNewSecretForm = () => {</>)}--export default AddNewSecretFormdiff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/DefaultEdgeFunctionSecrets.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/DefaultEdgeFunctionSecrets.tsxnew file mode 100644index 00000000000..16d1a205c57--- /dev/null+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/DefaultEdgeFunctionSecrets.tsx@@ -0,0 +1,70 @@+import { toast } from 'sonner'+import {+ Badge,+ Card,+ copyToClipboard,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from 'ui'++import type { DefaultEdgeFunctionSecret } from './DefaultEdgeFunctionSecrets.utils'++interface DefaultEdgeFunctionSecretsProps {+ secrets: DefaultEdgeFunctionSecret[]+}++export const DefaultEdgeFunctionSecrets = ({ secrets }: DefaultEdgeFunctionSecretsProps) => {+ return (+ <Card>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Name</TableHead>+ <TableHead>Description</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {secrets.map((secret) => (+ <SecretRow key={secret.name} secret={secret} />+ ))}+ </TableBody>+ </Table>+ </Card>+ )+}++const SecretRow = ({ secret }: { secret: DefaultEdgeFunctionSecret }) => {+ return (+ <TableRow key={secret.name}>+ <TableCell>+ <div className="flex items-center gap-x-2 py-1">+ <Tooltip>+ <TooltipTrigger+ onClick={() => {+ copyToClipboard(secret.name)+ toast.success(`Copied ${secret.name}`)+ }}+ >+ <p className="truncate">+ <code className="text-code-inline">{secret.name}</code>+ </p>+ </TooltipTrigger>+ <TooltipContent side="bottom">Click to copy</TooltipContent>+ </Tooltip>++ {secret.isDeprecated && <Badge variant="warning">Deprecated</Badge>}+ </div>+ </TableCell>+ <TableCell>+ <p className="text-sm text-foreground-light">{secret.description}</p>+ </TableCell>+ </TableRow>+ )+}diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/DefaultEdgeFunctionSecrets.utils.test.ts b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/DefaultEdgeFunctionSecrets.utils.test.tsnew file mode 100644index 00000000000..e16c8d5d2b9--- /dev/null+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/DefaultEdgeFunctionSecrets.utils.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest'++import {+ DEFAULT_EDGE_FUNCTION_SECRETS,+ getVisibleDefaultEdgeFunctionSecrets,+ isInternalEdgeFunctionSecret,+} from './DefaultEdgeFunctionSecrets.utils'++describe('isInternalEdgeFunctionSecret', () => {+ it.each(['SUPABASE_URL', 'SUPABASE_ANON_KEY', 'SUPABASE_THIS_DOES_NOT_EXIST_YET'])(+ 'treats SUPABASE_-prefixed names as internal (%s)',+ (name) => {+ expect(isInternalEdgeFunctionSecret(name)).toBe(true)+ }+ )++ it.each(['SB_REGION', 'SB_EXECUTION_ID', 'DENO_DEPLOYMENT_ID'])(+ 'treats hardcoded default name %s as internal',+ (name) => {+ expect(isInternalEdgeFunctionSecret(name)).toBe(true)+ }+ )++ it.each(['MY_API_KEY', 'STRIPE_SECRET', 'sb_region', 'DENO_OTHER_VAR'])(+ 'treats user-defined name %s as not internal',+ (name) => {+ expect(isInternalEdgeFunctionSecret(name)).toBe(false)+ }+ )+})++describe('getVisibleDefaultEdgeFunctionSecrets', () => {+ const runtimeNames = DEFAULT_EDGE_FUNCTION_SECRETS.filter((secret) => secret.isRuntime).map(+ (secret) => secret.name+ )+ const staticNames = DEFAULT_EDGE_FUNCTION_SECRETS.filter((secret) => !secret.isRuntime).map(+ (secret) => secret.name+ )++ it('always includes runtime secrets', () => {+ const result = getVisibleDefaultEdgeFunctionSecrets(new Set())+ for (const name of runtimeNames) {+ expect(result.map((secret) => secret.name)).toContain(name)+ }+ })++ it('falls back to the full hardcoded list when API returned no static defaults', () => {+ const result = getVisibleDefaultEdgeFunctionSecrets(new Set())+ expect(result.map((secret) => secret.name)).toEqual([...staticNames, ...runtimeNames])+ })++ it('shows only the static defaults present in the API response', () => {+ const apiNames = new Set(['SUPABASE_URL', 'SUPABASE_ANON_KEY', 'MY_USER_SECRET'])+ const result = getVisibleDefaultEdgeFunctionSecrets(apiNames)++ expect(result.map((secret) => secret.name)).toEqual([+ 'SUPABASE_URL',+ 'SUPABASE_ANON_KEY',+ ...runtimeNames,+ ])+ })++ it('does not surface user-defined secret names from the API set', () => {+ const apiNames = new Set(['SUPABASE_URL', 'MY_USER_SECRET'])+ const result = getVisibleDefaultEdgeFunctionSecrets(apiNames)+ expect(result.map((secret) => secret.name)).not.toContain('MY_USER_SECRET')+ })+})diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/DefaultEdgeFunctionSecrets.utils.ts b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/DefaultEdgeFunctionSecrets.utils.tsnew file mode 100644index 00000000000..3dc0ceb16dc--- /dev/null+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/DefaultEdgeFunctionSecrets.utils.ts@@ -0,0 +1,92 @@+export interface DefaultEdgeFunctionSecret {+ name: string+ description: string+ // Runtime secrets are set by the Edge Functions runtime per invocation and+ // are never returned by the secrets API. They should always be shown.+ isRuntime: boolean+ isDeprecated?: boolean+}++export const DEFAULT_EDGE_FUNCTION_SECRETS: DefaultEdgeFunctionSecret[] = [+ {+ name: 'SUPABASE_URL',+ description: 'The API gateway for your Supabase project.',+ isRuntime: false,+ },+ {+ name: 'SUPABASE_DB_URL',+ description:+ 'The direct PostgreSQL connection URL. Should not be shared with anyone, only use it on the server.',+ isRuntime: false,+ },+ {+ name: 'SUPABASE_PUBLISHABLE_KEYS',+ description:+ 'JSON dictionary of publishable API keys. Safe to use in a browser if RLS is enabled.',+ isRuntime: false,+ },+ {+ name: 'SUPABASE_SECRET_KEYS',+ description: 'JSON dictionary of secret API keys. Should never be exposed to a browser.',+ isRuntime: false,+ },+ {+ name: 'SUPABASE_ANON_KEY',+ description:+ 'Legacy anonymous key. Use SUPABASE_PUBLISHABLE_KEYS issued through JWT Signing Keys instead.',+ isRuntime: false,+ isDeprecated: true,+ },+ {+ name: 'SUPABASE_SERVICE_ROLE_KEY',+ description:+ 'Legacy service role key. Use SUPABASE_SECRET_KEYS issued through JWT Signing Keys instead.',+ isRuntime: false,+ isDeprecated: true,+ },+ {+ name: 'SUPABASE_JWKS',+ description: "JSON Web Key Set used to verify JWTs issued by your project's auth server.",+ isRuntime: false,+ },+ {+ name: 'SB_REGION',+ description: 'The region the function was invoked in. Set per request.',+ isRuntime: true,+ },+ {+ name: 'SB_EXECUTION_ID',+ description: 'A unique identifier for each function instance. Set per request.',+ isRuntime: true,+ },+ {+ name: 'DENO_DEPLOYMENT_ID',+ description: 'The version of the function code. Set when the function is deployed.',+ isRuntime: true,+ },+]++const DEFAULT_EDGE_FUNCTION_SECRET_NAMES = new Set(+ DEFAULT_EDGE_FUNCTION_SECRETS.map((secret) => secret.name)+)++// Internal secrets are anything reserved by Supabase that the user can't manage:+// either prefixed with SUPABASE_ (enforced by the API) or in the hardcoded+// list of default secrets above.+export const isInternalEdgeFunctionSecret = (name: string) =>+ /^SUPABASE_/.test(name) || DEFAULT_EDGE_FUNCTION_SECRET_NAMES.has(name)++// Picks the default secrets to display: runtime ones are always shown, static+// SUPABASE_* ones are filtered to those actually present in the API response.+// If the API returned none of the static defaults (brand-new project state),+// fall back to showing the full hardcoded list so the page stays educational.+export const getVisibleDefaultEdgeFunctionSecrets = (apiSecretNames: Set<string>) => {+ const staticDefaults = DEFAULT_EDGE_FUNCTION_SECRETS.filter((secret) => !secret.isRuntime)+ const runtimeDefaults = DEFAULT_EDGE_FUNCTION_SECRETS.filter((secret) => secret.isRuntime)++ const presentStaticDefaults = staticDefaults.filter((secret) => apiSecretNames.has(secret.name))+ const visibleStaticDefaults =+ presentStaticDefaults.length > 0 ? presentStaticDefaults : staticDefaults++ return [...visibleStaticDefaults, ...runtimeDefaults]+}diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecret.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecret.tsxindex 70fbf53cb40..c1faf35d075 100644--- a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecret.tsx+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecret.tsx@@ -1,7 +1,9 @@import { PermissionAction } from '@supabase/shared-types/out/constants'import { Edit2, MoreVertical, Trash } from 'lucide-react'+import { toast } from 'sonner'import {Button,+ copyToClipboard,DropdownMenu,DropdownMenuContent,DropdownMenuItem,@@ -9,6 +11,9 @@ import {DropdownMenuTrigger,TableCell,TableRow,+ Tooltip,+ TooltipContent,+ TooltipTrigger,} from 'ui'import { TimestampInfo } from 'ui-patterns'@@ -24,21 +29,27 @@ interface EdgeFunctionSecretProps {const EdgeFunctionSecret = ({ secret, onSelectEdit, onSelectDelete }: EdgeFunctionSecretProps) => {const { can: canUpdateSecrets } = useAsyncCheckPermissions(PermissionAction.SECRETS_WRITE, '*')- // [Joshen] Following API's validation:- // https://github.com/supabase/platform/blob/develop/api/src/routes/v1/projects/ref/secrets/secrets.controller.ts#L106- const isReservedSecret = !!secret.name.match(/^(SUPABASE_).*/)return (<TableRow><TableCell>- <p className="truncate py-2">{secret.name}</p>+ <Tooltip>+ <TooltipTrigger+ onClick={() => {+ copyToClipboard(secret.name)+ toast.success(`Copied ${secret.name}`)+ }}+ >+ <p className="truncate py-1">+ <code className="text-code-inline">{secret.name}</code>+ </p>+ </TooltipTrigger>+ <TooltipContent side="bottom">Click to copy</TooltipContent>+ </Tooltip></TableCell><TableCell>- <p- className="font-mono text-sm max-w-96 truncate text-foreground-light"- title={secret.value}- >- {secret.value}+ <p className="max-w-96 truncate" title={secret.value}>+ <code className="text-code-inline !text-foreground-light">{secret.value}</code></p></TableCell><TableCell>@@ -70,16 +81,14 @@ const EdgeFunctionSecret = ({ secret, onSelectEdit, onSelectDelete }: EdgeFunctitype="text"icon={<Edit2 size={14} />}className="w-full justify-start group text-inherit"- disabled={!canUpdateSecrets || isReservedSecret}+ disabled={!canUpdateSecrets}onClick={() => onSelectEdit()}tooltip={{content: {side: 'bottom',- text: isReservedSecret- ? 'This is a reserved secret and cannot be changed'- : !canUpdateSecrets- ? 'You need additional permissions to edit edge function secrets'- : undefined,+ text: !canUpdateSecrets+ ? 'You need additional permissions to edit edge function secrets'+ : undefined,},}}>@@ -94,16 +103,14 @@ const EdgeFunctionSecret = ({ secret, onSelectEdit, onSelectDelete }: EdgeFunctitype="text"icon={<Trash size={14} className="group-[&:not(:disabled)]:text-destructive" />}className="w-full justify-start group text-inherit"- disabled={!canUpdateSecrets || isReservedSecret}+ disabled={!canUpdateSecrets}onClick={() => onSelectDelete()}tooltip={{content: {side: 'bottom',- text: isReservedSecret- ? 'This is a reserved secret and cannot be deleted'- : !canUpdateSecrets- ? 'You need additional permissions to delete edge function secrets'- : undefined,+ text: !canUpdateSecrets+ ? 'You need additional permissions to delete edge function secrets'+ : undefined,},}}>diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecrets.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecrets.tsxindex b71dff3ffd7..589f111693b 100644--- a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecrets.tsx+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecrets.tsx@@ -2,19 +2,24 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import { Search } from 'lucide-react'import { parseAsString, useQueryState } from 'nuqs'-import { useEffect, useState } from 'react'+import { useEffect, useMemo, useState } from 'react'import { toast } from 'sonner'import { Badge, Card, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'ui'import { Input } from 'ui-patterns/DataInputs/Input'-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'+import { ConfirmationModal } from 'ui-patterns/Dialogs/ConfirmationModal'import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'-import AddNewSecretForm from './AddNewSecretForm'+import { AddNewSecretForm } from './AddNewSecretForm'+import { DefaultEdgeFunctionSecrets } from './DefaultEdgeFunctionSecrets'+import {+ getVisibleDefaultEdgeFunctionSecrets,+ isInternalEdgeFunctionSecret,+} from './DefaultEdgeFunctionSecrets.utils'import EdgeFunctionSecret from './EdgeFunctionSecret'import { EditSecretSheet } from './EditSecretSheet'-import AlertError from '@/components/ui/AlertError'-import { InlineLink } from '@/components/ui/InlineLink'-import NoPermission from '@/components/ui/NoPermission'+import { AlertError } from '@/components/ui/AlertError'+import { DocsButton } from '@/components/ui/DocsButton'+import { NoPermission } from '@/components/ui/NoPermission'import { useSecretsDeleteMutation } from '@/data/secrets/secrets-delete-mutation'import { useSecretsQuery } from '@/data/secrets/secrets-query'import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'@@ -38,17 +43,33 @@ export const EdgeFunctionSecrets = () => {isError,} = useSecretsQuery({ projectRef: projectRef }, { enabled: canReadSecrets })+ const customSecrets = useMemo(+ () => data.filter((secret) => !isInternalEdgeFunctionSecret(secret.name)),+ [data]+ )++ const visibleDefaultSecrets = useMemo(+ () => getVisibleDefaultEdgeFunctionSecrets(new Set(data.map((secret) => secret.name))),+ [data]+ )+const [selectedIdToEdit, setSelectedIdToEdit] = useQueryState('edit',parseAsString.withOptions({ history: 'push', clearOnDefault: true }))- const selectedSecretToEdit = data.find((secret) => secret.name === selectedIdToEdit)+ const selectedSecretToEdit = useMemo(+ () => customSecrets.find((secret) => secret.name === selectedIdToEdit),+ [customSecrets, selectedIdToEdit]+ )const [selectedIdToDelete, setSelectedIdToDelete] = useQueryState('delete',parseAsString.withOptions({ history: 'push', clearOnDefault: true }))- const selectedSecretToDelete = data.find((secret) => secret.name === selectedIdToDelete)+ const selectedSecretToDelete = useMemo(+ () => customSecrets.find((secret) => secret.name === selectedIdToDelete),+ [customSecrets, selectedIdToDelete]+ )const {mutate: deleteSecret,@@ -61,11 +82,11 @@ export const EdgeFunctionSecrets = () => {},})- const secrets =- searchString.length > 0- ? (data?.filter((secret) => secret.name.toLowerCase().includes(searchString.toLowerCase())) ??- [])- : (data ?? [])+ const filteredCustomSecrets = useMemo(() => {+ if (searchString.length === 0) return customSecrets+ const search = searchString.toLowerCase()+ return customSecrets.filter((secret) => secret.name.toLowerCase().includes(search))+ }, [customSecrets, searchString])const headers = [<TableHead key="secret-name">Name</TableHead>,@@ -109,78 +130,83 @@ export const EdgeFunctionSecrets = () => {{isError && <AlertError error={error} subject="Failed to retrieve project secrets" />}{isSuccess && (- <>- <div className="mb-10">- {!canUpdateSecrets ? (- <NoPermission resourceText="manage this project's edge function secrets" />- ) : (- <AddNewSecretForm />- )}- </div>- {canUpdateSecrets && !canReadSecrets ? (- <NoPermission resourceText="view this project's edge function secrets" />- ) : canReadSecrets ? (- <div className="space-y-4 mt-4">- <div className="flex flex-col md:flex-row md:items-center justify-between gap-2">- <Input- size="small"- className="w-full md:w-80"- placeholder="Search for a secret"- value={searchString}- onChange={(e) => setSearchString(e.target.value)}- icon={<Search />}- />+ <div className="space-y-10">+ {canUpdateSecrets ? (+ <AddNewSecretForm />+ ) : (+ <NoPermission resourceText="manage this project's edge function secrets" />+ )}++ <section className="space-y-4">+ <div className="flex flex-col md:flex-row md:items-center justify-between gap-2">+ <div className="space-y-1">+ <h3 className="text-foreground text-base">Custom secrets</h3>+ <p className="text-sm text-foreground-light">+ Secrets you have defined for this project+ </p></div>+ <Input+ size="small"+ className="w-full md:w-80"+ placeholder="Search for a secret"+ value={searchString}+ onChange={(e) => setSearchString(e.target.value)}+ icon={<Search />}+ />+ </div>- <Card>- <Table>- <TableHeader>- <TableRow>{headers}</TableRow>- </TableHeader>- <TableBody>- {secrets.length > 0 ? (- secrets.map((secret) => (- <EdgeFunctionSecret- key={secret.name}- secret={secret}- onSelectEdit={() => setSelectedIdToEdit(secret.name)}- onSelectDelete={() => setSelectedIdToDelete(secret.name)}- />- ))- ) : secrets.length === 0 && searchString.length > 0 ? (- <TableRow className="[&>td]:hover:bg-inherit">- <TableCell colSpan={headers.length}>- <p className="text-sm text-foreground">No results found</p>- <p className="text-sm text-foreground-light">- Your search for "{searchString}" did not return any results- </p>- </TableCell>- </TableRow>- ) : (- <TableRow className="[&>td]:hover:bg-inherit">- <TableCell colSpan={headers.length}>- <p className="text-sm text-foreground">No secrets created</p>- <p className="text-sm text-foreground-lighter">- This project has no custom secrets yet.{' '}- <code className="text-code-inline !text-foreground-lighter whitespace-nowrap">- SUPABASE_*- </code>{' '}- <InlineLink- href={`${DOCS_URL}/guides/functions/secrets#default-secrets`}- >- default secrets- </InlineLink>{' '}- are still available.- </p>- </TableCell>- </TableRow>- )}- </TableBody>- </Table>- </Card>+ <Card>+ <Table>+ <TableHeader>+ <TableRow>{headers}</TableRow>+ </TableHeader>+ <TableBody>+ {filteredCustomSecrets.length > 0 ? (+ filteredCustomSecrets.map((secret) => (+ <EdgeFunctionSecret+ key={secret.name}+ secret={secret}+ onSelectEdit={() => setSelectedIdToEdit(secret.name)}+ onSelectDelete={() => setSelectedIdToDelete(secret.name)}+ />+ ))+ ) : customSecrets.length === 0 ? (+ <TableRow className="[&>td]:hover:bg-inherit">+ <TableCell colSpan={headers.length}>+ <p className="text-sm text-foreground">No custom secrets created</p>+ <p className="text-sm text-foreground-lighter">+ This project has no custom secrets yet.+ </p>+ </TableCell>+ </TableRow>+ ) : (+ <TableRow className="[&>td]:hover:bg-inherit">+ <TableCell colSpan={headers.length}>+ <p className="text-sm text-foreground">No results found</p>+ <p className="text-sm text-foreground-light">+ Your search for "{searchString}" did not return any results+ </p>+ </TableCell>+ </TableRow>+ )}+ </TableBody>+ </Table>+ </Card>+ </section>++ <section className="space-y-4">+ <div className="flex flex-col md:flex-row md:items-center justify-between gap-2">+ <div className="space-y-1">+ <h3 className="text-foreground text-base">Default secrets</h3>+ <p className="text-sm text-foreground-light">+ Reserved secrets available in every project+ </p>+ </div>+ <DocsButton href={`${DOCS_URL}/guides/functions/secrets#default-secrets`} /></div>- ) : null}- </>+ <DefaultEdgeFunctionSecrets secrets={visibleDefaultSecrets} />+ </section>+ </div>)}</>)}