Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Deprecate getAPIKeys from project settings v2, use new api keys endpoint instead (#37300)

Joshen Lim31b8fbe487eb
diff --git a/apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx b/apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx
index 7010e1a8c82..10c0e5df990 100644
--- a/apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx
+++ b/apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx
@@ -1,8 +1,8 @@
import { Key } from 'lucide-react'
import { useMemo } from 'react'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
-import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { Badge, copyToClipboard } from 'ui'
import type { ICommand } from 'ui-patterns/CommandMenu'
import {
@@ -21,14 +21,11 @@ export function useApiKeysCommands() {
const setIsOpen = useSetCommandMenuOpen()
const setPage = useSetPage()
- const project = useSelectedProject()
+ const { data: project } = useSelectedProjectQuery()
const ref = project?.ref || '_'
- const { data: settings } = useProjectSettingsV2Query(
- { projectRef: project?.ref },
- { enabled: !!project }
- )
- const { anonKey, serviceKey } = getAPIKeys(settings)
+ const { data: apiKeys } = useAPIKeysQuery({ projectRef: project?.ref, reveal: true })
+ const { anonKey, serviceKey, publishableKey, allSecretKeys } = getKeys(apiKeys)
const commands = useMemo(
() =>
@@ -42,9 +39,10 @@ export function useApiKeysCommands() {
setIsOpen(false)
},
badge: () => (
- <span className="flex items-center gap-2">
+ <span className="flex items-center gap-x-1">
<Badge>Project: {project?.name}</Badge>
<Badge>Public</Badge>
+ <Badge className="capitalize">{anonKey.type}</Badge>
</span>
),
icon: () => <Key />,
@@ -58,13 +56,47 @@ export function useApiKeysCommands() {
setIsOpen(false)
},
badge: () => (
- <span className="flex items-center gap-2">
+ <span className="flex items-center gap-x-1">
<Badge>Project: {project?.name}</Badge>
<Badge variant="destructive">Secret</Badge>
+ <Badge className="capitalize">{serviceKey.type}</Badge>
+ </span>
+ ),
+ icon: () => <Key />,
+ },
+ project &&
+ publishableKey && {
+ id: 'publishable-key',
+ name: `Copy publishable key`,
+ action: () => {
+ copyToClipboard(publishableKey.api_key ?? '')
+ setIsOpen(false)
+ },
+ badge: () => (
+ <span className="flex items-center gap-x-1">
+ <Badge>Project: {project?.name}</Badge>
+ <Badge className="capitalize">{publishableKey.type}</Badge>
</span>
),
icon: () => <Key />,
},
+ ...(project && allSecretKeys
+ ? allSecretKeys.map((key) => ({
+ id: key.id,
+ name: `Copy secret key (${key.name})`,
+ action: () => {
+ copyToClipboard(key.api_key ?? '')
+ setIsOpen(false)
+ },
+ badge: () => (
+ <span className="flex items-center gap-x-1">
+ <Badge>Project: {project?.name}</Badge>
+ <Badge className="capitalize">{key.type}</Badge>
+ </span>
+ ),
+ icon: () => <Key />,
+ }))
+ : []),
!(anonKey || serviceKey) && {
id: 'api-keys-project-settings',
name: 'See API keys in Project Settings',
diff --git a/apps/studio/components/interfaces/Connect/Connect.tsx b/apps/studio/components/interfaces/Connect/Connect.tsx
index bc1bfbeb6ac..3a68ee63758 100644
--- a/apps/studio/components/interfaces/Connect/Connect.tsx
+++ b/apps/studio/components/interfaces/Connect/Connect.tsx
@@ -7,8 +7,8 @@ import { useMemo, useState } from 'react'
import { DatabaseConnectionString } from 'components/interfaces/Connect/DatabaseConnectionString'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import Panel from 'components/ui/Panel'
-import { useAPIKeysQuery } from 'data/api-keys/api-keys-query'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { PROJECT_STATUS } from 'lib/constants'
@@ -138,21 +138,28 @@ export const Connect = () => {
return []
}
- const { anonKey } = canReadAPIKeys ? getAPIKeys(settings) : { anonKey: null }
- const { data: apiKeys } = useAPIKeysQuery({ projectRef, reveal: false })
+ const { data: apiKeys } = useAPIKeysQuery({ projectRef })
+ const { anonKey, publishableKey } = canReadAPIKeys
+ ? getKeys(apiKeys)
+ : { anonKey: null, publishableKey: null }
const projectKeys = useMemo(() => {
const protocol = settings?.app_config?.protocol ?? 'https'
const endpoint = settings?.app_config?.endpoint ?? ''
const apiHost = canReadAPIKeys ? `${protocol}://${endpoint ?? '-'}` : ''
- const apiUrl = canReadAPIKeys ? apiHost : null
return {
apiUrl: apiHost ?? null,
anonKey: anonKey?.api_key ?? null,
- publishableKey: apiKeys?.find(({ type }) => type === 'publishable')?.api_key ?? null,
+ publishableKey: publishableKey?.api_key ?? null,
}
- }, [apiKeys, anonKey, canReadAPIKeys, settings])
+ }, [
+ settings?.app_config?.protocol,
+ settings?.app_config?.endpoint,
+ canReadAPIKeys,
+ anonKey?.api_key,
+ publishableKey?.api_key,
+ ])
const filePath = getContentFilePath({
connectionObject,
diff --git a/apps/studio/components/interfaces/Database/Hooks/FormContents.tsx b/apps/studio/components/interfaces/Database/Hooks/FormContents.tsx
index 8841de7b993..a1a9dbe3239 100644
--- a/apps/studio/components/interfaces/Database/Hooks/FormContents.tsx
+++ b/apps/studio/components/interfaces/Database/Hooks/FormContents.tsx
@@ -227,8 +227,8 @@ export const FormContents = ({
errors={errors}
httpHeaders={httpHeaders}
httpParameters={httpParameters}
- onAddHeader={(header?: any) => {
- if (header) setHttpHeaders(httpHeaders.concat(header))
+ onAddHeaders={(headers?: any[]) => {
+ if (headers) setHttpHeaders(httpHeaders.concat(headers))
else setHttpHeaders(httpHeaders.concat({ id: uuidv4(), name: '', value: '' }))
}}
onUpdateHeader={(idx, property, value) =>
diff --git a/apps/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx b/apps/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx
index e77c36658d2..ec8cf9e4d75 100644
--- a/apps/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx
+++ b/apps/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx
@@ -5,7 +5,7 @@ import { useParams } from 'common'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { FormSection, FormSectionContent, FormSectionLabel } from 'components/ui/Forms/FormSection'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'
import { uuidv4 } from 'lib/helpers'
import {
@@ -27,7 +27,7 @@ interface HTTPRequestFieldsProps {
errors: any
httpHeaders: HTTPArgument[]
httpParameters: HTTPArgument[]
- onAddHeader: (header?: any) => void
+ onAddHeaders: (headers?: any[]) => void
onUpdateHeader: (idx: number, property: string, value: string) => void
onRemoveHeader: (idx: number) => void
onAddParameter: () => void
@@ -40,21 +40,22 @@ const HTTPRequestFields = ({
errors,
httpHeaders = [],
httpParameters = [],
- onAddHeader,
+ onAddHeaders,
onUpdateHeader,
onRemoveHeader,
onAddParameter,
onUpdateParameter,
onRemoveParameter,
}: HTTPRequestFieldsProps) => {
- const { project: selectedProject } = useProjectContext()
const { ref } = useParams()
- const { data: settings } = useProjectSettingsV2Query({ projectRef: ref })
+ const { project: selectedProject } = useProjectContext()
+
const { data: functions } = useEdgeFunctionsQuery({ projectRef: ref })
+ const { data: apiKeys } = useAPIKeysQuery({ projectRef: ref, reveal: true })
const edgeFunctions = functions ?? []
- const { serviceKey } = getAPIKeys(settings)
- const apiKey = serviceKey?.api_key ?? '[YOUR API KEY]'
+ const { serviceKey, secretKey } = getKeys(apiKeys)
+ const apiKey = secretKey?.api_key ?? serviceKey?.api_key ?? '[YOUR API KEY]'
return (
<>
@@ -159,30 +160,37 @@ const HTTPRequestFields = ({
size="tiny"
icon={<Plus />}
className={cn(type === 'supabase_function' && 'rounded-r-none px-3')}
- onClick={onAddHeader}
+ onClick={() => onAddHeaders()}
>
Add a new header
</Button>
{type === 'supabase_function' && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button type="default" className="rounded-l-none px-[4px] py-[5px]">
- <ChevronDown />
- </Button>
+ <Button
+ type="default"
+ icon={<ChevronDown />}
+ className="rounded-l-none px-[4px] py-[5px]"
+ />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" side="bottom">
<DropdownMenuItem
key="add-auth-header"
- onClick={() =>
- onAddHeader({
- id: uuidv4(),
- name: 'Authorization',
- value: `Bearer ${apiKey}`,
- })
- }
+ onClick={() => {
+ onAddHeaders([
+ {
+ id: uuidv4(),
+ name: 'Authorization',
+ value: `Bearer ${apiKey}`,
+ },
+ ...(serviceKey?.type === 'secret'
+ ? [{ id: uuidv4(), name: 'apikey', value: apiKey }]
+ : []),
+ ])
+ }}
>
<div className="space-y-1">
- <p className="block text-foreground">Add auth header with service key</p>
+ <p className="block text-foreground">Add auth header with secret key</p>
<p className="text-foreground-light">
Required if your edge function enforces JWT verification
</p>
@@ -192,11 +200,13 @@ const HTTPRequestFields = ({
<DropdownMenuItem
key="add-source-header"
onClick={() =>
- onAddHeader({
- id: uuidv4(),
- name: 'x-supabase-webhook-source',
- value: `[Use a secret value]`,
- })
+ onAddHeaders([
+ {
+ id: uuidv4(),
+ name: 'x-supabase-webhook-source',
+ value: `[Use a secret value]`,
+ },
+ ])
}
>
<div className="space-y-1">
diff --git a/apps/studio/components/interfaces/Docs/Authentication.tsx b/apps/studio/components/interfaces/Docs/Authentication.tsx
index f6d24271122..3662e4572f5 100644
--- a/apps/studio/components/interfaces/Docs/Authentication.tsx
+++ b/apps/studio/components/interfaces/Docs/Authentication.tsx
@@ -1,7 +1,8 @@
import Link from 'next/link'
import { useParams } from 'common'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import CodeSnippet from './CodeSnippet'
import Snippets from './Snippets'
@@ -12,9 +13,10 @@ interface AuthenticationProps {
const Authentication = ({ selectedLang, showApiKey }: AuthenticationProps) => {
const { ref: projectRef } = useParams()
+ const { data: apiKeys } = useAPIKeysQuery({ projectRef })
const { data: settings } = useProjectSettingsV2Query({ projectRef })
- const { anonKey, serviceKey } = getAPIKeys(settings)
+ const { anonKey, serviceKey } = getKeys(apiKeys)
const protocol = settings?.app_config?.protocol ?? 'https'
const hostEndpoint = settings?.app_config?.endpoint
const endpoint = `${protocol}://${hostEndpoint ?? ''}`
diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.constants.ts b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.constants.ts
index 5303cc8bc86..41bf5a58644 100644
--- a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.constants.ts
+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.constants.ts
@@ -12,7 +12,7 @@ export const INVOCATION_TABS: InvocationTab[] = [
label: 'cURL',
language: 'bash',
code: (functionUrl, _, apiKey) => `curl -L -X POST '${functionUrl}' \\
- -H 'Authorization: Bearer ${apiKey}' \\
+ -H 'Authorization: Bearer ${apiKey}' \\ ${apiKey.includes('publishable') ? `\n -H 'apikey: ${apiKey}' \\` : ''}
-H 'Content-Type: application/json' \\
--data '{"name":"Functions"}'`,
},
diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
index fdcbd0ed0e4..6358d77eac5 100644
--- a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
@@ -12,7 +12,8 @@ import z from 'zod'
import { useParams } from 'common'
import { ScaffoldSection, ScaffoldSectionTitle } from 'components/layouts/Scaffold'
import AlertError from 'components/ui/AlertError'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'
import { useEdgeFunctionDeleteMutation } from 'data/edge-functions/edge-functions-delete-mutation'
@@ -60,6 +61,7 @@ export const EdgeFunctionDetails = () => {
const [showDeleteModal, setShowDeleteModal] = useState(false)
const canUpdateEdgeFunction = useCheckPermissions(PermissionAction.FUNCTIONS_WRITE, '*')
+ const { data: apiKeys } = useAPIKeysQuery({ projectRef })
const { data: settings } = useProjectSettingsV2Query({ projectRef })
const { data: customDomainData } = useCustomDomainsQuery({ projectRef })
const {
@@ -86,8 +88,8 @@ export const EdgeFunctionDetails = () => {
defaultValues: { name: '', verify_jwt: false },
})
- const { anonKey } = getAPIKeys(settings)
- const apiKey = anonKey?.api_key ?? '[YOUR ANON KEY]'
+ const { anonKey, publishableKey } = getKeys(apiKeys)
+ const apiKey = publishableKey?.api_key ?? anonKey?.api_key ?? '[YOUR ANON KEY]'
const protocol = settings?.app_config?.protocol ?? 'https'
const endpoint = settings?.app_config?.endpoint ?? ''
diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx
index 7c65503db22..4e07ccbf571 100644
--- a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx
+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx
@@ -6,9 +6,10 @@ import * as z from 'zod'
import { useParams } from 'common'
import { RoleImpersonationPopover } from 'components/interfaces/RoleImpersonationSelector'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
import { useSessionAccessTokenQuery } from 'data/auth/session-access-token-query'
import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-config-query'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useEdgeFunctionTestMutation } from 'data/edge-functions/edge-function-test-mutation'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
@@ -86,10 +87,11 @@ export const EdgeFunctionTesterSheet = ({ visible, onClose }: EdgeFunctionTester
const [response, setResponse] = useState<ResponseData | null>(null)
const [error, setError] = useState<string | null>(null)
+ const { data: apiKeys } = useAPIKeysQuery({ projectRef })
const { data: config } = useProjectPostgrestConfigQuery({ projectRef })
const { data: settings } = useProjectSettingsV2Query({ projectRef })
const { data: accessToken } = useSessionAccessTokenQuery({ enabled: IS_PLATFORM })
- const { serviceKey } = getAPIKeys(settings)
+ const { serviceKey } = getKeys(apiKeys)
const { mutate: sendEvent } = useSendEventMutation()
const { mutate: testEdgeFunction, isLoading } = useEdgeFunctionTestMutation({
diff --git a/apps/studio/components/interfaces/Functions/TerminalInstructions.tsx b/apps/studio/components/interfaces/Functions/TerminalInstructions.tsx
index fa2b18867df..363fd7c1056 100644
--- a/apps/studio/components/interfaces/Functions/TerminalInstructions.tsx
+++ b/apps/studio/components/interfaces/Functions/TerminalInstructions.tsx
@@ -6,7 +6,8 @@ import { useParams } from 'common'
import CommandRender from 'components/interfaces/Functions/CommandRender'
import { DocsButton } from 'components/ui/DocsButton'
import { useAccessTokensQuery } from 'data/access-tokens/access-tokens-query'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
import {
Button,
@@ -30,11 +31,12 @@ export const TerminalInstructions = forwardRef<
const [showInstructions, setShowInstructions] = useState(!closable)
const { data: tokens } = useAccessTokensQuery()
+ const { data: apiKeys } = useAPIKeysQuery({ projectRef })
const { data: settings } = useProjectSettingsV2Query({ projectRef })
const { data: customDomainData } = useCustomDomainsQuery({ projectRef })
- const { anonKey } = getAPIKeys(settings)
- const apiKey = anonKey?.api_key ?? '[YOUR ANON KEY]'
+ const { anonKey, publishableKey } = getKeys(apiKeys)
+ const apiKey = publishableKey?.api_key ?? anonKey?.api_key ?? '[YOUR ANON KEY]'
const protocol = settings?.app_config?.protocol ?? 'https'
const endpoint = settings?.app_config?.endpoint ?? ''
@@ -74,15 +76,14 @@ export const TerminalInstructions = forwardRef<
comment: 'Deploy your function',
},
{
- command: `curl -L -X POST 'https://${projectRef}.supabase.${restUrlTld}/functions/v1/hello-world' -H 'Authorization: Bearer ${
- apiKey ?? '[YOUR ANON KEY]'
- }' --data '{"name":"Functions"}'`,
+ command: `curl -L -X POST 'https://${projectRef}.supabase.${restUrlTld}/functions/v1/hello-world' -H 'Authorization: Bearer ${apiKey}'${anonKey?.type === 'publishable' ? ` -H 'apikey: ${apiKey}'` : ''} --data '{"name":"Functions"}'`,
description: 'Invokes the hello-world function',
jsx: () => {
return (
<>
<span className="text-brand-600">curl</span> -L -X POST '{functionsEndpoint}
- /hello-world' -H 'Authorization: Bearer [YOUR ANON KEY]'{' '}
+ /hello-world' -H 'Authorization: Bearer [YOUR ANON KEY]' s
+ {anonKey?.type === 'publishable' ? " -H 'apikey: [YOUR ANON KEY]' " : ''}
{`--data '{"name":"Functions"}'`}
</>
)
diff --git a/apps/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx b/apps/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx
index e9f05f5cd25..5c62c1c2a5b 100644
--- a/apps/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx
+++ b/apps/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx
@@ -4,13 +4,13 @@ import { AlertCircle, Loader } from 'lucide-react'
import Link from 'next/link'
import { useState } from 'react'
-import { SimpleCodeBlock } from 'ui'
import { useParams } from 'common'
import Panel from 'components/ui/Panel'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
import { useJwtSecretUpdatingStatusQuery } from 'data/config/jwt-secret-updating-status-query'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { Input } from 'ui'
+import { Input, SimpleCodeBlock } from 'ui'
const generateInitSnippet = (endpoint: string) => ({
js: `
@@ -42,13 +42,13 @@ const APIKeys = () => {
data: settings,
isError: isProjectSettingsError,
isLoading: isProjectSettingsLoading,
- } = useProjectSettingsV2Query({
- projectRef,
- })
+ } = useProjectSettingsV2Query({ projectRef })
+
+ const { data: apiKeys } = useAPIKeysQuery({ projectRef })
+ const { anonKey, serviceKey } = getKeys(apiKeys)
// API keys should not be empty. However it can be populated with a delay on project creation
- const apiKeys = settings?.service_api_keys ?? []
- const isApiKeysEmpty = apiKeys.length === 0
+ const isApiKeysEmpty = !anonKey && !serviceKey
const {
data,
@@ -56,9 +56,7 @@ const APIKeys = () => {
isLoading: isJwtSecretUpdateStatusLoading,
} = useJwtSecretUpdatingStatusQuery(
{ projectRef },
- {
- enabled: !isProjectSettingsLoading && isApiKeysEmpty,
- }
+ { enabled: !isProjectSettingsLoading && isApiKeysEmpty }
)
// Only show JWT loading state if the query is actually enabled
@@ -75,7 +73,6 @@ const APIKeys = () => {
const protocol = settings?.app_config?.protocol ?? 'https'
const endpoint = settings?.app_config?.endpoint
const apiUrl = `${protocol}://${endpoint ?? '-'}`
- const { anonKey } = getAPIKeys(settings)
const clientInitSnippet: any = generateInitSnippet(apiUrl)
const selectedLanguageSnippet = clientInitSnippet[selectedLanguage.key] ?? 'No snippet available'
@@ -144,17 +141,13 @@ const APIKeys = () => {
<div className="space-y-2">
<p className="text-sm">API Key</p>
<div className="flex items-center space-x-1 -ml-1">
- {anonKey?.tags?.split(',').map((x: any, i: number) => (
- <code key={`${x}${i}`} className="text-xs">
- {x}
- </code>
- ))}
- <code className="text-xs">{'public'}</code>
+ <code className="text-xs">{anonKey?.name}</code>
+ <code className="text-xs">public</code>
</div>
</div>
}
copy={canReadAPIKeys && isNotUpdatingJwtSecret}
- reveal={anonKey?.tags !== 'anon' && canReadAPIKeys && isNotUpdatingJwtSecret}
+ reveal={anonKey?.name !== 'anon' && canReadAPIKeys && isNotUpdatingJwtSecret}
value={
!canReadAPIKeys
? 'You need additional permissions to view API keys'
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/HttpHeaderFieldsSection.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/HttpHeaderFieldsSection.tsx
index 1ee72a8896f..536fd890501 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/HttpHeaderFieldsSection.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/HttpHeaderFieldsSection.tsx
@@ -2,7 +2,7 @@ import { ChevronDown, Plus, Trash } from 'lucide-react'
import { useFieldArray } from 'react-hook-form'
import { useParams } from 'common'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
import {
Button,
cn,
@@ -32,9 +32,10 @@ export const HTTPHeaderFieldsSection = ({ variant }: HTTPHeaderFieldsSectionProp
})
const { ref } = useParams()
- const { data: settings } = useProjectSettingsV2Query({ projectRef: ref })
- const { serviceKey } = getAPIKeys(settings)
- const apiKey = serviceKey?.api_key ?? '[YOUR API KEY]'
+ const { data: apiKeys } = useAPIKeysQuery({ projectRef: ref, reveal: true })
+
+ const { serviceKey, secretKey } = getKeys(apiKeys)
+ const apiKey = secretKey?.api_key ?? serviceKey?.api_key ?? '[YOUR API KEY]'
return (
<SheetSection>
@@ -104,15 +105,18 @@ export const HTTPHeaderFieldsSection = ({ variant }: HTTPHeaderFieldsSectionProp
<DropdownMenuContent align="end" side="bottom">
<DropdownMenuItem
key="add-auth-header"
- onClick={() =>
+ onClick={() => {
append({
name: 'Authorization',
value: `Bearer ${apiKey}`,
})
- }
+ if (serviceKey?.type === 'secret') {
+ append({ name: 'apikey', value: apiKey })
+ }
+ }}
>
<div className="space-y-1">
- <p className="block text-foreground">Add auth header with service key</p>
+ <p className="block text-foreground">Add auth header with secret key</p>
<p className="text-foreground-light">
Required if your edge function enforces JWT verification
</p>
diff --git a/apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx b/apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx
index f235358ea38..790babb0bc9 100644
--- a/apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx
+++ b/apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx
@@ -9,9 +9,9 @@ import ExtensionCard from 'components/interfaces/Database/Extensions/ExtensionCa
import GraphiQL from 'components/interfaces/GraphQL/GraphiQL'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { Loading } from 'components/ui/Loading'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
import { useSessionAccessTokenQuery } from 'data/auth/session-access-token-query'
import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-config-query'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
import { API_URL, IS_PLATFORM } from 'lib/constants'
import { getRoleImpersonationJWT } from 'lib/role-impersonation'
@@ -30,9 +30,9 @@ export const GraphiQLTab = () => {
const pgGraphqlExtension = (data ?? []).find((ext) => ext.name === 'pg_graphql')
const { data: accessToken } = useSessionAccessTokenQuery({ enabled: IS_PLATFORM })
- const { data: settings, isFetched } = useProjectSettingsV2Query({ projectRef })
- const { serviceKey } = getAPIKeys(settings)
+ const { data: apiKeys, isFetched } = useAPIKeysQuery({ projectRef, reveal: true })
+ const { serviceKey, secretKey } = getKeys(apiKeys)
const { data: config } = useProjectPostgrestConfigQuery({ projectRef })
const jwtSecret = config?.jwt_secret
@@ -74,7 +74,7 @@ export const GraphiQLTab = () => {
opts?.headers?.['Authorization'] ??
opts?.headers?.['authorization'] ??
userAuthorization ??
- `Bearer ${serviceKey?.api_key}`,
+ `Bearer ${secretKey?.api_key ?? serviceKey?.api_key}`,
},
})
}
diff --git a/apps/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx b/apps/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx
index 9ec3c001396..e8d906fe5da 100644
--- a/apps/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx
+++ b/apps/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx
@@ -1,6 +1,7 @@
import { useParams } from 'common'
import { Button, Input, copyToClipboard } from 'ui'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { Copy } from 'lucide-react'
import { useEffect, useState } from 'react'
@@ -10,6 +11,7 @@ import type { ContentProps } from './Content.types'
const Introduction = ({ showKeys, language, apikey, endpoint }: ContentProps) => {
const { ref } = useParams()
+ const { data: apiKeys } = useAPIKeysQuery({ projectRef: ref })
const { data } = useProjectSettingsV2Query({ projectRef: ref })
const [copied, setCopied] = useState<'anon' | 'service'>()
@@ -18,10 +20,9 @@ const Introduction = ({ showKeys, language, apikey, endpoint }: ContentProps) =>
if (copied !== undefined) setTimeout(() => setCopied(undefined), 2000)
}, [copied])
- const anonApiKey = (data?.service_api_keys ?? []).find((key) => key.tags === 'anon')?.api_key
- const serviceApiKey =
- (data?.service_api_keys ?? []).find((key) => key.tags === 'service_role')?.api_key ??
- 'SUPABASE_CLIENT_SERVICE_KEY'
+ const { anonKey, serviceKey } = getKeys(apiKeys)
+ const anonApiKey = anonKey?.api_key
+ const serviceApiKey = serviceKey?.api_key ?? 'SUPABASE_CLIENT_SERVICE_KEY'
return (
<>
diff --git a/apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx b/apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx
index 936ed8e0b8a..4ec31a5b9d5 100644
--- a/apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx
+++ b/apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx
@@ -2,7 +2,8 @@ import { useState } from 'react'
import { Button, SidePanel } from 'ui'
import { useParams } from 'common'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
import { useAppStateSnapshot } from 'state/app-state'
import {
@@ -44,6 +45,10 @@ const ProjectAPIDocs = () => {
const [showKeys, setShowKeys] = useState(false)
const language = snap.docsLanguage
+ const { data: apiKeys } = useAPIKeysQuery(
+ { projectRef: ref },
+ { enabled: snap.showProjectApiDocs }
+ )
const { data: settings } = useProjectSettingsV2Query(
{ projectRef: ref },
{ enabled: snap.showProjectApiDocs }
@@ -53,7 +58,7 @@ const ProjectAPIDocs = () => {
{ enabled: snap.showProjectApiDocs }
)
- const { anonKey } = getAPIKeys(settings)
+ const { anonKey } = getKeys(apiKeys)
const apikey = showKeys
? anonKey?.api_key ?? 'SUPABASE_CLIENT_ANON_KEY'
: 'SUPABASE_CLIENT_ANON_KEY'
diff --git a/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsx b/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsx
index ddfafe20953..cb6225cca9a 100644
--- a/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsx
+++ b/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsx
@@ -3,8 +3,9 @@ import { toast } from 'sonner'
import { useParams } from 'common'
import { RoleImpersonationPopover } from 'components/interfaces/RoleImpersonationSelector'
+import { InlineLink } from 'components/ui/InlineLink'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-config-query'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { IS_PLATFORM } from 'lib/constants'
@@ -18,10 +19,15 @@ interface RealtimeTokensPopoverProps {
}
export const RealtimeTokensPopover = ({ config, onChangeConfig }: RealtimeTokensPopoverProps) => {
+ const { ref } = useParams()
+ const org = useSelectedOrganization()
const snap = useRoleImpersonationStateSnapshot()
- const { data: settings } = useProjectSettingsV2Query({ projectRef: config.projectRef })
- const { anonKey, serviceKey } = getAPIKeys(settings)
+ const { data: apiKeys } = useAPIKeysQuery({
+ projectRef: config.projectRef,
+ reveal: true,
+ })
+ const { anonKey, serviceKey, publishableKey } = getKeys(apiKeys)
const { data: postgrestConfig } = useProjectPostgrestConfigQuery(
{ projectRef: config.projectRef },
@@ -29,8 +35,6 @@ export const RealtimeTokensPopover = ({ config, onChangeConfig }: RealtimeTokens
)
const jwtSecret = postgrestConfig?.jwt_secret
- const { ref } = useParams()
- const org = useSelectedOrganization()
const { mutate: sendEvent } = useSendEventMutation()
// only send a telemetry event if the user changes the role. Don't send an event during initial render.
@@ -63,7 +67,7 @@ export const RealtimeTokensPopover = ({ config, onChangeConfig }: RealtimeTokens
.then((b) => (bearer = b))
.catch((err) => toast.error(`Failed to get JWT for role: ${err.message}`))
} else {
- token = serviceKey?.api_key
+ token = serviceKey?.api_key ?? publishableKey?.api_key
}
if (token) {
onChangeConfig({ ...config, token, bearer })
@@ -74,5 +78,22 @@ export const RealtimeTokensPopover = ({ config, onChangeConfig }: RealtimeTokens
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [snap.role, anonKey, serviceKey])
- return <RoleImpersonationPopover align="start" variant="connected-on-both" />
+ return (
+ <RoleImpersonationPopover
+ serviceRoleLabel={!serviceKey ? 'anon' : undefined}
+ disabled={!serviceKey}
+ disabledTooltip={
+ !serviceKey ? (
+ <>
+ Role impersonation for the Realtime Inspector is currently unavailable temporarily due
+ to the new API keys. Please re-enable{' '}
+ <InlineLink href={`/project/${ref}/settings/api-keys`}>legacy JWT keys</InlineLink> if
+ you'd like to use role impersonation with the Realtime Inspector.
+ </>
+ ) : undefined
+ }
+ align="start"
+ variant="connected-on-both"
+ />
+ )
}
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx
index adbe74201f6..971d7ee7136 100644
--- a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx
@@ -1,6 +1,7 @@
-import { useState } from 'react'
-import { Button, PopoverContent_Shadcn_, PopoverTrigger_Shadcn_, Popover_Shadcn_, cn } from 'ui'
+import { ReactNode, useState } from 'react'
+import { PopoverContent_Shadcn_, PopoverTrigger_Shadcn_, Popover_Shadcn_, cn } from 'ui'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import type { User } from 'data/auth/users-infinite-query'
import { ChevronDown, User as IconUser } from 'lucide-react'
import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
@@ -12,6 +13,8 @@ export interface RoleImpersonationPopoverProps {
serviceRoleLabel?: string
variant?: 'regular' | 'connected-on-right' | 'connected-on-left' | 'connected-on-both'
align?: 'center' | 'start' | 'end'
+ disabled?: boolean
+ disabledTooltip?: ReactNode
disallowAuthenticatedOption?: boolean
}
@@ -21,6 +24,10 @@ const RoleImpersonationPopover = ({
variant = 'regular',
align = 'end',
disallowAuthenticatedOption = false,
+
+ // [Joshen] We can clean these up once the API keys fix is done
+ disabled = false,
+ disabledTooltip,
}: RoleImpersonationPopoverProps) => {
const state = useRoleImpersonationStateSnapshot()
@@ -31,7 +38,7 @@ const RoleImpersonationPopover = ({
return (
<Popover_Shadcn_ open={isOpen} onOpenChange={setIsOpen}>
<PopoverTrigger_Shadcn_ asChild>
- <Button
+ <ButtonTooltip
size="tiny"
type="default"
className={cn(
@@ -40,6 +47,10 @@ const RoleImpersonationPopover = ({
variant === 'connected-on-left' && 'rounded-l-none border-l-0',
variant === 'connected-on-both' && 'rounded-none border-x-0'
)}
+ disabled={disabled}
+ tooltip={{
+ content: { side: 'bottom', text: disabledTooltip, className: 'text-center w-72' },
+ }}
>
<div className="flex items-center gap-1">
<span className="text-foreground-muted">Role</span>
@@ -58,7 +69,7 @@ const RoleImpersonationPopover = ({
)}
<ChevronDown className="text-muted" strokeWidth={1} size={12} />
</div>
- </Button>
+ </ButtonTooltip>
</PopoverTrigger_Shadcn_>
<PopoverContent_Shadcn_
portal={portal}
diff --git a/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout.tsx b/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout.tsx
index 528108172a4..127b273b0ef 100644
--- a/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout.tsx
+++ b/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout.tsx
@@ -38,8 +38,8 @@ const EdgeFunctionDetailsLayout = ({
children,
}: PropsWithChildren<EdgeFunctionDetailsLayoutProps>) => {
const router = useRouter()
- const { functionSlug, ref } = useParams()
const org = useSelectedOrganization()
+ const { functionSlug, ref } = useParams()
const { mutate: sendEvent } = useSendEventMutation()
const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()
diff --git a/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/SimpleConfigurationDetails.tsx b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/SimpleConfigurationDetails.tsx
index feccb8aa02f..d08489cf2e0 100644
--- a/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/SimpleConfigurationDetails.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/SimpleConfigurationDetails.tsx
@@ -1,6 +1,7 @@
import Link from '@ui/components/Typography/Link'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { ScaffoldSectionDescription, ScaffoldSectionTitle } from 'components/layouts/Scaffold'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { Card } from 'ui'
import { getCatalogURI, getConnectionURL } from '../StorageSettings/StorageSettings.utils'
@@ -19,12 +20,14 @@ const wrapperMeta = {
export const SimpleConfigurationDetails = ({ bucketName }: { bucketName: string }) => {
const { project } = useProjectContext()
+
+ const { data: apiKeys } = useAPIKeysQuery({ projectRef: project?.ref })
const { data: settings } = useProjectSettingsV2Query({ projectRef: project?.ref })
const protocol = settings?.app_config?.protocol ?? 'https'
const endpoint = settings?.app_config?.endpoint
- const serviceApiKey =
- (settings?.service_api_keys ?? []).find((key) => key.tags === 'service_role')?.api_key ??
- 'SUPABASE_CLIENT_SERVICE_KEY'
+
+ const { serviceKey } = getKeys(apiKeys)
+ const serviceApiKey = serviceKey?.api_key ?? 'SUPABASE_CLIENT_SERVICE_KEY'
const values: Record<string, string> = {
vault_token: serviceApiKey,
diff --git a/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx b/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx
index 18aaf4c8c5e..4072f6f2caa 100644
--- a/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx
+++ b/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx
@@ -10,10 +10,10 @@ import { useJwtSecretUpdatingStatusQuery } from 'data/config/jwt-secret-updating
import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useFlag } from 'hooks/ui/useFlag'
+import Link from 'next/link'
import { Input } from 'ui'
import { getLastUsedAPIKeys, useLastUsedAPIKeysLogQuery } from './DisplayApiSettings.utils'
import { ToggleLegacyApiKeysPanel } from './ToggleLegacyApiKeys'
-import Link from 'next/link'
export const DisplayApiSettings = ({
showTitle = true,
@@ -49,6 +49,7 @@ export const DisplayApiSettings = ({
const isNotUpdatingJwtSecret =
jwtSecretUpdateStatus === undefined || jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updated
+
const apiKeys = useMemo(() => settings?.service_api_keys ?? [], [settings])
// api keys should not be empty. However it can be populated with a delay on project creation
const isApiKeysEmpty = apiKeys.length === 0
diff --git a/apps/studio/data/api-keys/api-keys-query.ts b/apps/studio/data/api-keys/api-keys-query.ts
index a78f3c031d1..24911001188 100644
--- a/apps/studio/data/api-keys/api-keys-query.ts
+++ b/apps/studio/data/api-keys/api-keys-query.ts
@@ -2,7 +2,6 @@ import { useQuery, UseQueryOptions } from '@tanstack/react-query'
import { get, handleError } from 'data/fetchers'
import { ResponseError } from 'types'
-import { IS_PLATFORM } from 'lib/constants'
import { apiKeysKeys } from './keys'
type LegacyKeys = {
@@ -46,9 +45,11 @@ type PublishableKeys = {
interface APIKeysVariables {
projectRef?: string
- reveal: boolean
+ reveal?: boolean
}
+type APIKey = LegacyKeys | SecretKeys | PublishableKeys
+
async function getAPIKeys({ projectRef, reveal }: APIKeysVariables, signal?: AbortSignal) {
if (!projectRef) throw new Error('projectRef is required')
@@ -62,20 +63,33 @@ async function getAPIKeys({ projectRef, reveal }: APIKeysVariables, signal?: Abo
}
// [Jonny]: Overriding the types here since some stuff is not actually nullable or optional
- return data as unknown as (LegacyKeys | SecretKeys | PublishableKeys)[]
+ return data as unknown as APIKey[]
}
export type APIKeysData = Awaited<ReturnType<typeof getAPIKeys>>
export const useAPIKeysQuery = <TData = APIKeysData>(
- { projectRef, reveal }: APIKeysVariables,
+ { projectRef, reveal = false }: APIKeysVariables,
{ enabled, ...options }: UseQueryOptions<APIKeysData, ResponseError, TData> = {}
) =>
useQuery<APIKeysData, ResponseError, TData>(
- apiKeysKeys.list(projectRef),
+ apiKeysKeys.list(projectRef, reveal),
({ signal }) => getAPIKeys({ projectRef, reveal }, signal),
{
- enabled: IS_PLATFORM && enabled && !!projectRef,
+ enabled: enabled && !!projectRef,
...options,
}
)
+
+export const getKeys = (apiKeys: APIKey[] = []) => {
+ const anonKey = apiKeys.find((x) => x.name === 'anon')
+ const serviceKey = apiKeys.find((x) => x.name === 'service_role')
+
+ // [Joshen] For now I just want 1 of each, I don't need all
+ const publishableKey = apiKeys.find((x) => x.type === 'publishable')
+ const secretKey = apiKeys.find((x) => x.type === 'secret')
+
+ const allSecretKeys = apiKeys.filter((x) => x.type === 'secret')
+
+ return { anonKey, serviceKey, publishableKey, secretKey, allSecretKeys }
+}
diff --git a/apps/studio/data/api-keys/keys.ts b/apps/studio/data/api-keys/keys.ts
index 84d9c41d1d1..222a51b0b1c 100644
--- a/apps/studio/data/api-keys/keys.ts
+++ b/apps/studio/data/api-keys/keys.ts
@@ -1,5 +1,6 @@
export const apiKeysKeys = {
- list: (projectRef?: string) => ['projects', projectRef, 'api-keys'] as const,
+ list: (projectRef?: string, reveal?: boolean) =>
+ ['projects', projectRef, 'api-keys', reveal] as const,
single: (projectRef?: string, id?: string) => ['projects', projectRef, 'api-keys', id] as const,
status: (projectRef?: string) => ['projects', projectRef, 'api-keys', 'legacy'] as const,
}
diff --git a/apps/studio/data/config/project-settings-v2-query.ts b/apps/studio/data/config/project-settings-v2-query.ts
index 9b8d65e071d..1827d14be5d 100644
--- a/apps/studio/data/config/project-settings-v2-query.ts
+++ b/apps/studio/data/config/project-settings-v2-query.ts
@@ -62,13 +62,3 @@ export const useProjectSettingsV2Query = <TData = ProjectSettingsData>(
}
)
}
-
-/**
- * @deprecated Use api-keys-query instead!
- */
-export const getAPIKeys = (settings?: ProjectSettings) => {
- const anonKey = (settings?.service_api_keys ?? []).find((x) => x.tags === 'anon')
- const serviceKey = (settings?.service_api_keys ?? []).find((x) => x.tags === 'service_role')
-
- return { anonKey, serviceKey }
-}
diff --git a/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts b/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts
index e82f77ca537..95cac1e501b 100644
--- a/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts
+++ b/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts
@@ -9,6 +9,7 @@ import {
getCatalogURI,
getConnectionURL,
} from 'components/to-be-cleaned/Storage/StorageSettings/StorageSettings.utils'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useProjectStorageConfigQuery } from 'data/config/project-storage-config-query'
import { FDWCreateVariables, useFDWCreateMutation } from 'data/fdw/fdw-create-mutation'
@@ -18,13 +19,15 @@ import { useS3AccessKeyCreateMutation } from './s3-access-key-create-mutation'
export const useIcebergWrapperCreateMutation = () => {
const { project } = useProjectContext()
+
+ const { data: apiKeys } = useAPIKeysQuery({ projectRef: project?.ref })
+ const { serviceKey } = getKeys(apiKeys)
+
const { data: settings } = useProjectSettingsV2Query({ projectRef: project?.ref })
const protocol = settings?.app_config?.protocol ?? 'https'
const endpoint = settings?.app_config?.endpoint
- const serviceApiKey =
- (settings?.service_api_keys ?? []).find((key) => key.tags === 'service_role')?.api_key ??
- 'SUPABASE_CLIENT_SERVICE_KEY'
+ const serviceApiKey = serviceKey?.api_key ?? 'SUPABASE_CLIENT_SERVICE_KEY'
const wrapperMeta = WRAPPERS.find((wrapper) => wrapper.name === 'iceberg_wrapper')
diff --git a/apps/studio/pages/api/v1/projects/[ref]/api-keys.ts b/apps/studio/pages/api/v1/projects/[ref]/api-keys.ts
new file mode 100644
index 00000000000..8a11aa695d6
--- /dev/null
+++ b/apps/studio/pages/api/v1/projects/[ref]/api-keys.ts
@@ -0,0 +1,50 @@
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { components } from 'api-types'
+import apiWrapper from 'lib/api/apiWrapper'
+
+type ProjectAppConfig = components['schemas']['ProjectSettingsResponse']['app_config'] & {
+ protocol?: string
+}
+export type ProjectSettings = components['schemas']['ProjectSettingsResponse'] & {
+ app_config?: ProjectAppConfig
+}
+
+export default (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
+
+async function handler(req: NextApiRequest, res: NextApiResponse) {
+ const { method } = req
+
+ switch (method) {
+ case 'GET':
+ return handleGetAll(req, res)
+ default:
+ res.setHeader('Allow', ['GET'])
+ res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })
+ }
+}
+
+const handleGetAll = async (req: NextApiRequest, res: NextApiResponse) => {
+ const response = [
+ {
+ name: 'anon',
+ api_key: process.env.SUPABASE_ANON_KEY ?? '',
+ id: 'anon',
+ type: 'legacy',
+ hash: '',
+ prefix: '',
+ description: 'Legacy anon API key',
+ },
+ {
+ name: 'service_role',
+ api_key: process.env.SUPABASE_SERVICE_KEY ?? '',
+ id: 'service_role',
+ type: 'legacy',
+ hash: '',
+ prefix: '',
+ description: 'Legacy service_role API key',
+ },
+ ]
+
+ return res.status(200).json(response)
+}
diff --git a/apps/studio/state/storage-explorer.tsx b/apps/studio/state/storage-explorer.tsx
index 4150e63eb4a..373423eb11b 100644
--- a/apps/studio/state/storage-explorer.tsx
+++ b/apps/studio/state/storage-explorer.tsx
@@ -31,8 +31,9 @@ import {
} from 'components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.utils'
import { convertFromBytes } from 'components/to-be-cleaned/Storage/StorageSettings/StorageSettings.utils'
import { InlineLink } from 'components/ui/InlineLink'
+import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
import { configKeys } from 'data/config/keys'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { ProjectStorageConfigResponse } from 'data/config/project-storage-config-query'
import { getQueryClient } from 'data/query-client'
import { deleteBucketObject } from 'data/storage/bucket-object-delete-mutation'
@@ -917,6 +918,20 @@ function createStorageExplorerState({
columnIndex: number
isDrop?: boolean
}) => {
+ if (!state.serviceKey) {
+ toast(
+ <p>
+ Uploading files to Storage through the dashboard is currently unavailable with the new
+ API keys. Please re-enable{' '}
+ <InlineLink href={`/project/${state.projectRef}/settings/api-keys`}>
+ legacy JWT keys
+ </InlineLink>{' '}
+ if you'd like to upload files to Storage through the dashboard.
+ </p>
+ )
+ return
+ }
+
const queryClient = getQueryClient()
const storageConfiguration = queryClient
.getQueryCache()
@@ -1115,6 +1130,7 @@ function createStorageExplorerState({
headers: {
authorization: `Bearer ${state.serviceKey}`,
'x-source': 'supabase-dashboard',
+ ...(state.serviceKey.includes('secret') ? { apikey: state.serviceKey } : {}),
},
uploadDataDuringCreation: uploadDataDuringCreation,
removeFingerprintOnSuccess: true,
@@ -1722,11 +1738,12 @@ export const StorageExplorerStateContextProvider = ({ children }: PropsWithChild
const [state, setState] = useState(() => createStorageExplorerState(DEFAULT_STATE_CONFIG))
const stateRef = useLatest(state)
+ const { data: apiKeys } = useAPIKeysQuery({ projectRef: project?.ref, reveal: true })
const { data: settings } = useProjectSettingsV2Query({ projectRef: project?.ref })
- const { serviceKey } = getAPIKeys(settings)
+
+ const { serviceKey } = getKeys(apiKeys)
const protocol = settings?.app_config?.protocol ?? 'https'
const endpoint = settings?.app_config?.endpoint
- const resumableUploadUrl = `${IS_PLATFORM ? 'https' : protocol}://${endpoint}/storage/v1/upload/resumable`
// [Joshen] JFYI opting with the useEffect here as the storage explorer state was being loaded
// before the project details were ready, hence the store kept returning project ref as undefined
@@ -1736,9 +1753,17 @@ export const StorageExplorerStateContextProvider = ({ children }: PropsWithChild
useEffect(() => {
const snap = snapshot(stateRef.current)
const hasDataReady = !!project?.ref
- const isDifferentProject = snap.projectRef !== project?.ref
+ const resumableUploadUrl = `${IS_PLATFORM ? 'https' : protocol}://${endpoint}/storage/v1/upload/resumable`
- if (!isPaused && hasDataReady && isDifferentProject && serviceKey) {
+ const isDifferentProject = snap.projectRef !== project?.ref
+ const isDifferentResumableUploadUrl = snap.resumableUploadUrl !== resumableUploadUrl
+
+ if (
+ !isPaused &&
+ hasDataReady &&
+ (isDifferentProject || isDifferentResumableUploadUrl) &&
+ serviceKey
+ ) {
const clientEndpoint = `${IS_PLATFORM ? 'https' : protocol}://${endpoint}`
const supabaseClient = createClient(clientEndpoint, serviceKey.api_key, {
auth: {
@@ -1764,7 +1789,7 @@ export const StorageExplorerStateContextProvider = ({ children }: PropsWithChild
})
)
}
- }, [project?.ref, stateRef, serviceKey, isPaused])
+ }, [project?.ref, stateRef, serviceKey, isPaused, protocol, endpoint])
return (
<StorageExplorerStateContext.Provider value={state}>