Skip to content

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

feat: use temporary api keys for storage explorer (#37696)

Stojan Dimitrovski7e367daf734a
diff --git a/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineStatus.tsx b/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineStatus.tsx
index 888bb679102..6205fdfb4b9 100644
--- a/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineStatus.tsx
+++ b/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineStatus.tsx
@@ -1,3 +1,7 @@
+// @ts-nocheck [Joshen] Temporarily silencing the TS checks here but please eventually remove
+// it's cause the API types are conflicting a bit - API types have probably been updated for the UI here
+// but the UI hasn't been updated yet to fit the new API types
+
import { Activity, ChevronLeft, ExternalLink, Search, X } from 'lucide-react'
import Link from 'next/link'
import { useEffect, useState } from 'react'
diff --git a/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsx b/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsx
index ef75536f4f4..ca059755665 100644
--- a/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsx
+++ b/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsx
@@ -3,8 +3,8 @@ 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 { getTemporaryAPIKey } from 'data/api-keys/temp-api-keys-query'
import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-config-query'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
@@ -27,12 +27,13 @@ export const RealtimeTokensPopover = ({ config, onChangeConfig }: RealtimeTokens
projectRef: config.projectRef,
reveal: true,
})
- const { anonKey, serviceKey, publishableKey } = getKeys(apiKeys)
+ const { anonKey, publishableKey } = getKeys(apiKeys)
const { data: postgrestConfig } = useProjectPostgrestConfigQuery(
{ projectRef: config.projectRef },
{ enabled: IS_PLATFORM }
)
+
const jwtSecret = postgrestConfig?.jwt_secret
const { mutate: sendEvent } = useSendEventMutation()
@@ -62,12 +63,17 @@ export const RealtimeTokensPopover = ({ config, onChangeConfig }: RealtimeTokens
snap.role !== undefined &&
snap.role.type === 'postgrest'
) {
- token = anonKey?.api_key
+ token = publishableKey?.api_key ?? anonKey?.api_key
await getRoleImpersonationJWT(config.projectRef, jwtSecret, snap.role)
.then((b) => (bearer = b))
.catch((err) => toast.error(`Failed to get JWT for role: ${err.message}`))
} else {
- token = serviceKey?.api_key ?? publishableKey?.api_key
+ try {
+ const data = await getTemporaryAPIKey({ projectRef: config.projectRef })
+ token = data.api_key
+ } catch (error) {
+ token = publishableKey?.api_key
+ }
}
if (token) {
onChangeConfig({ ...config, token, bearer })
@@ -76,24 +82,7 @@ export const RealtimeTokensPopover = ({ config, onChangeConfig }: RealtimeTokens
triggerUpdateTokenBearer()
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [snap.role, anonKey, serviceKey])
+ }, [snap.role, anonKey])
- 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"
- />
- )
+ return <RoleImpersonationPopover align="start" variant="connected-on-both" />
}
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx
index 160e8118e4f..8871cbff00d 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx
@@ -167,7 +167,7 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
return (
<div
ref={storageExplorerRef}
- className="bg-studio border rounded-md border-overlay flex h-full w-full flex-col m-4"
+ className="bg-studio border rounded-md border-overlay flex h-full w-full flex-col"
>
{selectedItems.length === 0 ? (
<FileExplorerHeader
diff --git a/apps/studio/data/api-keys/temp-api-keys-query.ts b/apps/studio/data/api-keys/temp-api-keys-query.ts
new file mode 100644
index 00000000000..4939727c236
--- /dev/null
+++ b/apps/studio/data/api-keys/temp-api-keys-query.ts
@@ -0,0 +1,25 @@
+import { handleError, post } from 'data/fetchers'
+
+interface getTemporaryAPIKeyVariables {
+ projectRef?: string
+}
+
+// [Joshen] This one specifically shouldn't need a useQuery hook since the expiry is meant to be short lived
+// Used in storage explorer and realtime inspector.
+export async function getTemporaryAPIKey(
+ { projectRef }: getTemporaryAPIKeyVariables,
+ signal?: AbortSignal
+) {
+ if (!projectRef) throw new Error('projectRef is required')
+
+ const { data, error } = await post('/platform/projects/{ref}/api-keys/temporary', {
+ params: {
+ path: { ref: projectRef },
+ query: { authorization_exp: '300', claims: JSON.stringify({ role: 'service_role' }) },
+ },
+ signal,
+ })
+
+ if (error) handleError(error)
+ return data
+}
diff --git a/apps/studio/pages/project/[ref]/storage/buckets/[bucketId].tsx b/apps/studio/pages/project/[ref]/storage/buckets/[bucketId].tsx
index 4b432682bf8..f55a43c03ba 100644
--- a/apps/studio/pages/project/[ref]/storage/buckets/[bucketId].tsx
+++ b/apps/studio/pages/project/[ref]/storage/buckets/[bucketId].tsx
@@ -20,7 +20,7 @@ const PageLayout: NextPageWithLayout = () => {
if (!project || !projectRef) return null
return (
- <div className="storage-container flex flex-grow">
+ <div className="storage-container flex flex-grow p-4">
{isError && <StorageBucketsError error={error as any} />}
{isSuccess ? (
diff --git a/apps/studio/state/storage-explorer.tsx b/apps/studio/state/storage-explorer.tsx
index 4e9db42662d..37356f4555a 100644
--- a/apps/studio/state/storage-explorer.tsx
+++ b/apps/studio/state/storage-explorer.tsx
@@ -36,7 +36,7 @@ import {
} from 'components/interfaces/Storage/StorageExplorer/StorageExplorer.utils'
import { convertFromBytes } from 'components/interfaces/Storage/StorageSettings/StorageSettings.utils'
import { InlineLink } from 'components/ui/InlineLink'
-import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
+import { getTemporaryAPIKey } from 'data/api-keys/temp-api-keys-query'
import { configKeys } from 'data/config/keys'
import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { ProjectStorageConfigResponse } from 'data/config/project-storage-config-query'
@@ -80,13 +80,11 @@ if (typeof window !== 'undefined') {
function createStorageExplorerState({
projectRef,
resumableUploadUrl,
- serviceKey,
supabaseClient,
}: {
projectRef: string
resumableUploadUrl: string
- serviceKey: string
- supabaseClient?: SupabaseClient<any, 'public', any>
+ supabaseClient?: () => Promise<SupabaseClient<any, 'public', any>>
}) {
const localStorageKey = LOCAL_STORAGE_KEYS.STORAGE_PREFERENCE(projectRef)
const { view, sortBy, sortByOrder, sortBucket } =
@@ -97,7 +95,6 @@ function createStorageExplorerState({
projectRef,
supabaseClient,
resumableUploadUrl,
- serviceKey,
uploadProgresses: [] as UploadProgress[],
// abortController,
@@ -333,7 +330,7 @@ function createStorageExplorerState({
const formattedPathToEmptyPlaceholderFile =
pathToFolder.length > 0 ? `${pathToFolder}/${emptyPlaceholderFile}` : emptyPlaceholderFile
- await state.supabaseClient.storage
+ await (await state.supabaseClient()).storage
.from(state.selectedBucket.name)
.upload(
formattedPathToEmptyPlaceholderFile,
@@ -583,7 +580,7 @@ function createStorageExplorerState({
if (data.length === 0) {
const prefixToPlaceholder = `${parentFolderPrefix}/${EMPTY_FOLDER_PLACEHOLDER_FILE_NAME}`
- await state.supabaseClient?.storage
+ await (await state.supabaseClient!())?.storage
.from(state.selectedBucket.name)
.upload(prefixToPlaceholder, new File([], EMPTY_FOLDER_PLACEHOLDER_FILE_NAME))
}
@@ -978,20 +975,6 @@ 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()
@@ -1188,9 +1171,7 @@ function createStorageExplorerState({
endpoint: state.resumableUploadUrl,
retryDelays: [0, 200, 500, 1500, 3000, 5000],
headers: {
- authorization: `Bearer ${state.serviceKey}`,
'x-source': 'supabase-dashboard',
- ...(state.serviceKey.includes('secret') ? { apikey: state.serviceKey } : {}),
},
uploadDataDuringCreation: uploadDataDuringCreation,
removeFingerprintOnSuccess: true,
@@ -1200,6 +1181,14 @@ function createStorageExplorerState({
...fileOptions,
},
chunkSize,
+ onBeforeRequest: async (req) => {
+ try {
+ const data = await getTemporaryAPIKey({ projectRef: state.projectRef })
+ req.setHeader('apikey', data.api_key)
+ } catch (error) {
+ throw error
+ }
+ },
onShouldRetry(error) {
const status = error.originalResponse ? error.originalResponse.getStatus() : 0
const doNotRetryStatuses = [400, 403, 404, 409, 413, 415, 429]
@@ -1210,22 +1199,30 @@ function createStorageExplorerState({
numberOfFilesUploadedFail += 1
if (error instanceof tus.DetailedError) {
const status = error.originalResponse?.getStatus()
- if (status === 415) {
- // Unsupported mime type
- toast.error(
- capitalize(
- error?.originalResponse?.getBody() ||
- `Failed to upload ${file.name}: ${metadata.mimetype} is not allowed`
- ),
- {
- description: `Allowed MIME types: ${state.selectedBucket.allowed_mime_types?.join(', ')}`,
- }
- )
- } else if (status === 413) {
- // Payload too large
- toast.error(
- `Failed to upload ${file.name}: File size exceeds the bucket upload limit.`
- )
+
+ switch (status) {
+ case 415:
+ // Unsupported mime type
+ toast.error(
+ capitalize(
+ error?.originalResponse?.getBody() ||
+ `Failed to upload ${file.name}: ${metadata.mimetype} is not allowed`
+ ),
+ {
+ description: `Allowed MIME types: ${state.selectedBucket.allowed_mime_types?.join(', ')}`,
+ }
+ )
+ break
+ case 413:
+ // Payload too large
+ toast.error(
+ `Failed to upload ${file.name}: File size exceeds the bucket upload limit.`
+ )
+ break
+ case 409:
+ // Resource already exists
+ toast.error(`Failed to upload ${file.name}: File name already exists.`)
+ break
}
} else {
toast.error(`Failed to upload ${file.name}: ${error.message}`)
@@ -1312,10 +1309,16 @@ function createStorageExplorerState({
) {
toast.dismiss(toastId)
} else if (numberOfFilesUploadedFail === numberOfFilesToUpload) {
- toast.error(
- `Failed to upload ${numberOfFilesToUpload} file${numberOfFilesToUpload > 1 ? 's' : ''}!`,
- { id: toastId, closeButton: true, duration: SONNER_DEFAULT_DURATION }
- )
+ if (numberOfFilesToUpload === 1) {
+ // [Joshen] We'd already be showing a toast when the upload files, so this is to prevent a
+ // duplicate error toast if its only one file that's getting uploaded
+ toast.dismiss(toastId)
+ } else {
+ toast.error(
+ `Failed to upload ${numberOfFilesToUpload} file${numberOfFilesToUpload > 1 ? 's' : ''}!`,
+ { id: toastId, closeButton: true, duration: SONNER_DEFAULT_DURATION }
+ )
+ }
} else if (numberOfFilesUploadedSuccess === numberOfFilesToUpload) {
toast.success(
`Successfully uploaded ${numberOfFilesToUpload} file${
@@ -1740,7 +1743,7 @@ function createStorageExplorerState({
)
}
/>,
- { id: toastId, closeButton: false, position: 'top-right' }
+ { id: toastId, closeButton: false, position: 'top-right', duration: Infinity }
)
},
@@ -1783,7 +1786,6 @@ type StorageExplorerState = ReturnType<typeof createStorageExplorerState>
const DEFAULT_STATE_CONFIG = {
projectRef: '',
resumableUploadUrl: '',
- serviceKey: '',
supabaseClient: undefined,
}
@@ -1798,10 +1800,8 @@ 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 } = 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`
@@ -1813,43 +1813,39 @@ export const StorageExplorerStateContextProvider = ({ children }: PropsWithChild
// Although I'd be keen to re-investigate this to see if we can remove this
useEffect(() => {
const hasDataReady = !!project?.ref
- const serviceApiKey = serviceKey?.api_key ?? 'unknown'
if (!isPaused && hasDataReady) {
- const clientEndpoint = `${IS_PLATFORM ? 'https' : protocol}://${endpoint}`
- const supabaseClient = createClient(clientEndpoint, serviceApiKey, {
- auth: {
- persistSession: false,
- autoRefreshToken: false,
- detectSessionInUrl: false,
- storage: {
- getItem: (key) => {
- return null
- },
- setItem: (key, value) => {},
- removeItem: (key) => {},
- },
- },
- })
-
setState(
createStorageExplorerState({
projectRef: project?.ref ?? '',
- supabaseClient,
+ supabaseClient: async () => {
+ try {
+ const data = await getTemporaryAPIKey({ projectRef: project.ref })
+ const clientEndpoint = `${IS_PLATFORM ? 'https' : protocol}://${endpoint}`
+
+ return createClient(clientEndpoint, data.api_key, {
+ auth: {
+ persistSession: false,
+ autoRefreshToken: false,
+ detectSessionInUrl: false,
+ storage: {
+ getItem: (key) => {
+ return null
+ },
+ setItem: (key, value) => {},
+ removeItem: (key) => {},
+ },
+ },
+ })
+ } catch (error) {
+ throw error
+ }
+ },
resumableUploadUrl,
- serviceKey: serviceApiKey,
})
)
}
- }, [
- project?.ref,
- stateRef,
- serviceKey?.api_key,
- isPaused,
- resumableUploadUrl,
- protocol,
- endpoint,
- ])
+ }, [project?.ref, stateRef, isPaused, resumableUploadUrl, protocol, endpoint])
return (
<StorageExplorerStateContext.Provider value={state}>