Skip to content

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

Fix: Use storage API for downloading files in the Dashboard (#40592)

Ali Waseem3f6f8aa906f6
diff --git a/apps/studio/components/interfaces/Storage/FilesBuckets/BucketTable.tsx b/apps/studio/components/interfaces/Storage/FilesBuckets/BucketTable.tsx
index e218eadc2f0..eb95c29a23a 100644
--- a/apps/studio/components/interfaces/Storage/FilesBuckets/BucketTable.tsx
+++ b/apps/studio/components/interfaces/Storage/FilesBuckets/BucketTable.tsx
@@ -102,6 +102,7 @@ export const BucketTableRow = ({
return (
<BucketTableRow
key={bucket.id}
+ data-bucket-id={bucket.id}
className="relative cursor-pointer h-16 group inset-focus"
onClick={(event) => handleBucketNavigation(bucket.id, event)}
onKeyDown={(event) => {
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx
index f7b45bd74cc..08f0b0cd1a9 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx
@@ -1,19 +1,17 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { Download, Move, Trash2, X } from 'lucide-react'
-import { useParams } from 'common'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import { Button } from 'ui'
-import { downloadFile } from './StorageExplorer.utils'
export const FileExplorerHeaderSelection = () => {
- const { ref: projectRef, bucketId } = useParams()
const { can: canUpdateFiles } = useAsyncCheckPermissions(PermissionAction.STORAGE_WRITE, '*')
const {
selectedItems,
+ downloadFile,
downloadSelectedFiles,
clearSelectedItems,
setSelectedItemsToDelete,
@@ -37,7 +35,7 @@ export const FileExplorerHeaderSelection = () => {
type="primary"
onClick={async () => {
if (selectedItems.length === 1) {
- await downloadFile({ projectRef, bucketId, file: selectedItems[0] })
+ await downloadFile(selectedItems[0])
} else {
await downloadSelectedFiles(selectedItems)
}
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.tsx
index 2db50f2dc88..17192c97ba2 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.tsx
@@ -48,7 +48,7 @@ import {
} from '../Storage.constants'
import { StorageItemWithColumn, type StorageItem } from '../Storage.types'
import { FileExplorerRowEditing } from './FileExplorerRowEditing'
-import { copyPathToFolder, downloadFile } from './StorageExplorer.utils'
+import { copyPathToFolder } from './StorageExplorer.utils'
import { useCopyUrl } from './useCopyUrl'
export const RowIcon = ({
@@ -115,7 +115,7 @@ export const FileExplorerRow = ({
selectedItems = [],
style,
}: FileExplorerRowProps) => {
- const { ref: projectRef, bucketId } = useParams()
+ const { bucketId } = useParams()
const {
selectedBucket,
@@ -128,6 +128,7 @@ export const FileExplorerRow = ({
setSelectedFileCustomExpiry,
setSelectedItems,
setSelectedItemsToDelete,
+ downloadFile,
setSelectedItemToRename,
setSelectedItemsToMove,
openFolder,
@@ -254,13 +255,7 @@ export const FileExplorerRow = ({
{
name: 'Download',
icon: <Download size={14} strokeWidth={1} />,
- onClick: async () => {
- await downloadFile({
- projectRef,
- bucketId,
- file: itemWithColumnIndex,
- })
- },
+ onClick: () => downloadFile(itemWithColumnIndex),
},
{ name: 'Separator', icon: undefined, onClick: undefined },
]
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/ItemContextMenu.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/ItemContextMenu.tsx
index 62ebcaa51a3..2ad5d81009f 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/ItemContextMenu.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/ItemContextMenu.tsx
@@ -8,7 +8,6 @@ import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import { URL_EXPIRY_DURATION } from '../Storage.constants'
import { StorageItemWithColumn } from '../Storage.types'
-import { downloadFile } from './StorageExplorer.utils'
import { useCopyUrl } from './useCopyUrl'
interface ItemContextMenuProps {
@@ -16,7 +15,6 @@ interface ItemContextMenuProps {
}
export const ItemContextMenu = ({ id = '' }: ItemContextMenuProps) => {
- const { ref: projectRef, bucketId } = useParams()
const snap = useStorageExplorerStateSnapshot()
const { setSelectedFileCustomExpiry } = snap
@@ -25,6 +23,7 @@ export const ItemContextMenu = ({ id = '' }: ItemContextMenuProps) => {
setSelectedItemsToDelete,
setSelectedItemToRename,
setSelectedItemsToMove,
+ downloadFile,
} = useStorageExplorerStateSnapshot()
const { onCopyUrl } = useCopyUrl()
const isPublic = selectedBucket.public
@@ -41,7 +40,7 @@ export const ItemContextMenu = ({ id = '' }: ItemContextMenuProps) => {
case 'move':
return setSelectedItemsToMove([item])
case 'download':
- return await downloadFile({ projectRef, bucketId, file: item })
+ return await downloadFile(item)
default:
break
}
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.tsx
index 8305d8f739f..48551d1cc5e 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.tsx
@@ -19,7 +19,6 @@ import {
} from 'ui'
import { URL_EXPIRY_DURATION } from '../Storage.constants'
import { StorageItem } from '../Storage.types'
-import { downloadFile } from './StorageExplorer.utils'
import { useCopyUrl } from './useCopyUrl'
import { useFetchFileUrlQuery } from './useFetchFileUrlQuery'
@@ -116,14 +115,13 @@ const PreviewFile = ({ item }: { item: StorageItem }) => {
}
export const PreviewPane = () => {
- const { ref: projectRef, bucketId } = useParams()
-
const {
selectedBucket,
selectedFilePreview: file,
setSelectedItemsToDelete,
setSelectedFilePreview,
setSelectedFileCustomExpiry,
+ downloadFile,
} = useStorageExplorerStateSnapshot()
const { onCopyUrl } = useCopyUrl()
@@ -204,7 +202,7 @@ export const PreviewPane = () => {
type="default"
icon={<Download />}
disabled={file.isCorrupted}
- onClick={async () => await downloadFile({ projectRef, bucketId, file })}
+ onClick={() => downloadFile(file)}
>
Download
</Button>
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.tsx
index e20a143b53b..bd1af77e8f1 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.tsx
@@ -1,10 +1,9 @@
import { toast } from 'sonner'
-import { downloadBucketObject } from 'data/storage/bucket-object-download-mutation'
import { StorageObject } from 'data/storage/bucket-objects-list-mutation'
-import { SONNER_DEFAULT_DURATION, copyToClipboard } from 'ui'
+import { copyToClipboard } from 'ui'
import { STORAGE_ROW_STATUS, STORAGE_ROW_TYPES } from '../Storage.constants'
-import { StorageItem, StorageItemMetadata, StorageItemWithColumn } from '../Storage.types'
+import { StorageItem, StorageItemMetadata } from '../Storage.types'
type UploadProgress = {
percentage: number
@@ -17,7 +16,10 @@ type UploadProgress = {
const CORRUPTED_THRESHOLD_MS = 15 * 60 * 1000 // 15 minutes
export const EMPTY_FOLDER_PLACEHOLDER_FILE_NAME = '.emptyFolderPlaceholder'
-export const copyPathToFolder = (openedFolders: StorageItem[], item: StorageItemWithColumn) => {
+export const copyPathToFolder = (
+ openedFolders: StorageItem[],
+ item: StorageItem & { columnIndex: number }
+) => {
const folders = openedFolders.slice(0, item.columnIndex).map((folder) => folder.name)
const path = folders.length > 0 ? `${folders.join('/')}/${item.name}` : item.name
copyToClipboard(path)
@@ -38,67 +40,6 @@ export const formatTime = (seconds: number) => {
return `${seconds}s`
}
-export const downloadFile = async ({
- projectRef,
- bucketId,
- file,
- showToast = true,
- returnBlob = false,
-}: {
- projectRef?: string
- bucketId?: string
- file: StorageItemWithColumn
- showToast?: boolean
- returnBlob?: boolean
-}) => {
- if (!projectRef) return toast.error('Failed to download: Project ref is required')
- if (!bucketId) return toast.error('Failed to download: Bucket ID is required')
- if (!file.path) return toast.error('Failed to download: Unable to find path to file')
-
- const fileName: string = file.name
- const fileMimeType = file?.metadata?.mimetype ?? undefined
-
- const toastId = showToast ? toast.loading(`Retrieving ${fileName}...`) : undefined
-
- try {
- const data = await downloadBucketObject({
- projectRef,
- bucketId,
- path: file.path,
- })
-
- const blob = await data.blob()
- const newBlob = new Blob([blob], { type: fileMimeType })
- if (returnBlob) return { name: fileName, blob: newBlob }
-
- const blobUrl = window.URL.createObjectURL(newBlob)
- const link = document.createElement('a')
- link.href = blobUrl
- link.setAttribute('download', `${fileName}`)
- document.body.appendChild(link)
- link.click()
- link.parentNode?.removeChild(link)
- window.URL.revokeObjectURL(blob)
- if (toastId) {
- toast.success(`Downloading ${fileName}`, {
- id: toastId,
- closeButton: true,
- duration: SONNER_DEFAULT_DURATION,
- })
- }
- return true
- } catch (err) {
- if (toastId) {
- toast.error(`Failed to download ${fileName}`, {
- id: toastId,
- closeButton: true,
- duration: SONNER_DEFAULT_DURATION,
- })
- }
- return false
- }
-}
-
export const calculateTotalRemainingTime = (progresses: UploadProgress[]) => {
let totalRemainingTime = 0
let totalRemainingBytes = 0
diff --git a/apps/studio/data/api-keys/temp-api-keys-utils.test.ts b/apps/studio/data/api-keys/temp-api-keys-utils.test.ts
index b4ab3d910e4..79807f4ef1a 100644
--- a/apps/studio/data/api-keys/temp-api-keys-utils.test.ts
+++ b/apps/studio/data/api-keys/temp-api-keys-utils.test.ts
@@ -1,8 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
- createTemporaryUploadKey,
- isTemporaryUploadKeyValid,
- type TemporaryUploadKey,
+ createTemporaryApiKey,
+ isTemporaryApiKeyValid,
+ type TemporaryApiKey,
} from './temp-api-keys-utils'
describe('createTemporaryUploadKey', () => {
@@ -18,7 +18,7 @@ describe('createTemporaryUploadKey', () => {
const apiKey = 'test-api-key-123'
const expiryInSeconds = 3600
- const result = createTemporaryUploadKey(apiKey, expiryInSeconds)
+ const result = createTemporaryApiKey(apiKey, expiryInSeconds)
expect(result.apiKey).toBe(apiKey)
})
@@ -30,7 +30,7 @@ describe('createTemporaryUploadKey', () => {
const apiKey = 'test-api-key-123'
const expiryInSeconds = 3600 // 1 hour
- const result = createTemporaryUploadKey(apiKey, expiryInSeconds)
+ const result = createTemporaryApiKey(apiKey, expiryInSeconds)
expect(result.expiryTime).toBe(now + 3600 * 1000)
})
@@ -42,7 +42,7 @@ describe('createTemporaryUploadKey', () => {
const apiKey = 'test-api-key-123'
const expiryInSeconds = 60 // 1 minute
- const result = createTemporaryUploadKey(apiKey, expiryInSeconds)
+ const result = createTemporaryApiKey(apiKey, expiryInSeconds)
expect(result.expiryTime).toBe(now + 60 * 1000)
})
@@ -53,11 +53,11 @@ describe('createTemporaryUploadKey', () => {
const now1 = 1000000
vi.setSystemTime(now1)
- const result1 = createTemporaryUploadKey(apiKey, expiryInSeconds)
+ const result1 = createTemporaryApiKey(apiKey, expiryInSeconds)
const now2 = 2000000
vi.setSystemTime(now2)
- const result2 = createTemporaryUploadKey(apiKey, expiryInSeconds)
+ const result2 = createTemporaryApiKey(apiKey, expiryInSeconds)
expect(result1.expiryTime).toBe(now1 + expiryInSeconds * 1000)
expect(result2.expiryTime).toBe(now2 + expiryInSeconds * 1000)
@@ -75,13 +75,13 @@ describe('isTemporaryUploadKeyValid', () => {
})
it('should return false for null key', () => {
- const result = isTemporaryUploadKeyValid(null)
+ const result = isTemporaryApiKeyValid(null)
expect(result).toBe(false)
})
it('should return false for undefined key', () => {
- const result = isTemporaryUploadKeyValid(undefined)
+ const result = isTemporaryApiKeyValid(undefined)
expect(result).toBe(false)
})
@@ -90,12 +90,12 @@ describe('isTemporaryUploadKeyValid', () => {
const now = Date.now()
vi.setSystemTime(now)
- const key: TemporaryUploadKey = {
+ const key: TemporaryApiKey = {
apiKey: 'test-key',
expiryTime: now + 120000, // 2 minutes from now
}
- const result = isTemporaryUploadKeyValid(key)
+ const result = isTemporaryApiKeyValid(key)
expect(result).toBe(true)
})
@@ -104,12 +104,12 @@ describe('isTemporaryUploadKeyValid', () => {
const now = Date.now()
vi.setSystemTime(now)
- const key: TemporaryUploadKey = {
+ const key: TemporaryApiKey = {
apiKey: 'test-key',
expiryTime: now + 60000, // Exactly 60 seconds
}
- const result = isTemporaryUploadKeyValid(key)
+ const result = isTemporaryApiKeyValid(key)
expect(result).toBe(false)
})
@@ -118,12 +118,12 @@ describe('isTemporaryUploadKeyValid', () => {
const now = Date.now()
vi.setSystemTime(now)
- const key: TemporaryUploadKey = {
+ const key: TemporaryApiKey = {
apiKey: 'test-key',
expiryTime: now + 30000, // 30 seconds from now
}
- const result = isTemporaryUploadKeyValid(key)
+ const result = isTemporaryApiKeyValid(key)
expect(result).toBe(false)
})
@@ -132,12 +132,12 @@ describe('isTemporaryUploadKeyValid', () => {
const now = Date.now()
vi.setSystemTime(now)
- const key: TemporaryUploadKey = {
+ const key: TemporaryApiKey = {
apiKey: 'test-key',
expiryTime: now - 1000, // 1 second ago
}
- const result = isTemporaryUploadKeyValid(key)
+ const result = isTemporaryApiKeyValid(key)
expect(result).toBe(false)
})
@@ -146,12 +146,12 @@ describe('isTemporaryUploadKeyValid', () => {
const now = Date.now()
vi.setSystemTime(now)
- const key: TemporaryUploadKey = {
+ const key: TemporaryApiKey = {
apiKey: 'test-key',
expiryTime: now - 3600000, // 1 hour ago
}
- const result = isTemporaryUploadKeyValid(key)
+ const result = isTemporaryApiKeyValid(key)
expect(result).toBe(false)
})
@@ -160,12 +160,12 @@ describe('isTemporaryUploadKeyValid', () => {
const now = Date.now()
vi.setSystemTime(now)
- const key: TemporaryUploadKey = {
+ const key: TemporaryApiKey = {
apiKey: 'test-key',
expiryTime: now + 61000, // 61 seconds from now
}
- const result = isTemporaryUploadKeyValid(key)
+ const result = isTemporaryApiKeyValid(key)
expect(result).toBe(true)
})
@@ -174,21 +174,21 @@ describe('isTemporaryUploadKeyValid', () => {
const now = Date.now()
vi.setSystemTime(now)
- const key: TemporaryUploadKey = {
+ const key: TemporaryApiKey = {
apiKey: 'test-key',
expiryTime: now + 120000, // 2 minutes from now
}
// Initially valid
- expect(isTemporaryUploadKeyValid(key)).toBe(true)
+ expect(isTemporaryApiKeyValid(key)).toBe(true)
// Advance time by 59 seconds (should still be valid - 61 seconds remaining)
vi.advanceTimersByTime(59000)
- expect(isTemporaryUploadKeyValid(key)).toBe(true)
+ expect(isTemporaryApiKeyValid(key)).toBe(true)
// Advance time by 2 more seconds (should be invalid - 59 seconds remaining)
vi.advanceTimersByTime(2000)
- expect(isTemporaryUploadKeyValid(key)).toBe(false)
+ expect(isTemporaryApiKeyValid(key)).toBe(false)
})
it('should return true for a key missing apiKey property', () => {
@@ -197,9 +197,9 @@ describe('isTemporaryUploadKeyValid', () => {
const key = {
expiryTime: now + 120000,
- } as TemporaryUploadKey
+ } as TemporaryApiKey
- const result = isTemporaryUploadKeyValid(key)
+ const result = isTemporaryApiKeyValid(key)
// While the key has expiryTime, it's missing apiKey, but since we're checking
// the structure, we expect it to still pass the time check if the expiryTime exists
@@ -211,9 +211,9 @@ describe('isTemporaryUploadKeyValid', () => {
it('should return false for a key missing expiryTime property', () => {
const key = {
apiKey: 'test-key',
- } as TemporaryUploadKey
+ } as TemporaryApiKey
- const result = isTemporaryUploadKeyValid(key)
+ const result = isTemporaryApiKeyValid(key)
// Without expiryTime, the calculation will be NaN and fail the > 60000 check
expect(result).toBe(false)
@@ -233,9 +233,9 @@ describe('integration: createTemporaryUploadKey and isTemporaryUploadKeyValid',
const now = Date.now()
vi.setSystemTime(now)
- const key = createTemporaryUploadKey('test-api-key', 3600)
+ const key = createTemporaryApiKey('test-api-key', 3600)
- expect(isTemporaryUploadKeyValid(key)).toBe(true)
+ expect(isTemporaryApiKeyValid(key)).toBe(true)
})
it('should create a key that becomes invalid after expiry time minus 60 seconds', () => {
@@ -243,18 +243,18 @@ describe('integration: createTemporaryUploadKey and isTemporaryUploadKeyValid',
vi.setSystemTime(now)
const expiryInSeconds = 120 // 2 minutes
- const key = createTemporaryUploadKey('test-api-key', expiryInSeconds)
+ const key = createTemporaryApiKey('test-api-key', expiryInSeconds)
// Initially valid
- expect(isTemporaryUploadKeyValid(key)).toBe(true)
+ expect(isTemporaryApiKeyValid(key)).toBe(true)
// Advance to 59 seconds before expiry (should still be valid - 61 seconds remaining)
vi.advanceTimersByTime((expiryInSeconds - 61) * 1000)
- expect(isTemporaryUploadKeyValid(key)).toBe(true)
+ expect(isTemporaryApiKeyValid(key)).toBe(true)
// Advance to 60 seconds before expiry (should be invalid - 60 seconds remaining)
vi.advanceTimersByTime(1000)
- expect(isTemporaryUploadKeyValid(key)).toBe(false)
+ expect(isTemporaryApiKeyValid(key)).toBe(false)
})
it('should handle very short expiry durations', () => {
@@ -262,10 +262,10 @@ describe('integration: createTemporaryUploadKey and isTemporaryUploadKeyValid',
vi.setSystemTime(now)
// Create a key that expires in 30 seconds (less than the 60 second buffer)
- const key = createTemporaryUploadKey('test-api-key', 30)
+ const key = createTemporaryApiKey('test-api-key', 30)
// Should be invalid immediately because it will expire in less than 60 seconds
- expect(isTemporaryUploadKeyValid(key)).toBe(false)
+ expect(isTemporaryApiKeyValid(key)).toBe(false)
})
it('should handle expiry duration of exactly 60 seconds', () => {
@@ -273,10 +273,10 @@ describe('integration: createTemporaryUploadKey and isTemporaryUploadKeyValid',
vi.setSystemTime(now)
// Create a key that expires in exactly 60 seconds
- const key = createTemporaryUploadKey('test-api-key', 60)
+ const key = createTemporaryApiKey('test-api-key', 60)
// Should be invalid because it has exactly 60 seconds remaining (not more than 60)
- expect(isTemporaryUploadKeyValid(key)).toBe(false)
+ expect(isTemporaryApiKeyValid(key)).toBe(false)
})
it('should handle expiry duration of 61 seconds', () => {
@@ -284,15 +284,15 @@ describe('integration: createTemporaryUploadKey and isTemporaryUploadKeyValid',
vi.setSystemTime(now)
// Create a key that expires in 61 seconds
- const key = createTemporaryUploadKey('test-api-key', 61)
+ const key = createTemporaryApiKey('test-api-key', 61)
// Should be valid because it has 61 seconds remaining (more than 60)
- expect(isTemporaryUploadKeyValid(key)).toBe(true)
+ expect(isTemporaryApiKeyValid(key)).toBe(true)
// Advance by 1 second
vi.advanceTimersByTime(1000)
// Should now be invalid because it has exactly 60 seconds remaining
- expect(isTemporaryUploadKeyValid(key)).toBe(false)
+ expect(isTemporaryApiKeyValid(key)).toBe(false)
})
})
diff --git a/apps/studio/data/api-keys/temp-api-keys-utils.ts b/apps/studio/data/api-keys/temp-api-keys-utils.ts
index f713d9a83a4..9cb0752b098 100644
--- a/apps/studio/data/api-keys/temp-api-keys-utils.ts
+++ b/apps/studio/data/api-keys/temp-api-keys-utils.ts
@@ -1,24 +1,55 @@
-export interface TemporaryUploadKey {
+import { getTemporaryAPIKey } from './temp-api-keys-query'
+
+type ProjectRef = string
+
+const projectApiKeys = new Map<ProjectRef, Promise<TemporaryApiKey>>()
+
+export interface TemporaryApiKey {
apiKey: string
expiryTime: number
}
-export function createTemporaryUploadKey(
- apiKey: string,
- expiryInSeconds: number
-): TemporaryUploadKey {
+export function createTemporaryApiKey(apiKey: string, expiryInSeconds: number): TemporaryApiKey {
return {
apiKey,
expiryTime: Date.now() + expiryInSeconds * 1000,
}
}
-export function isTemporaryUploadKeyValid(
- key: TemporaryUploadKey | null | undefined
-): key is TemporaryUploadKey {
+export function isTemporaryApiKeyValid(
+ key: TemporaryApiKey | null | undefined
+): key is TemporaryApiKey {
if (!key) return false
const now = Date.now()
const timeRemaining = key.expiryTime - now
return timeRemaining > 60000 // More than 60 seconds remaining
}
+
+const checkOrRefreshTemporaryApiKey = async (
+ projectRef: ProjectRef,
+ existingKey: Promise<TemporaryApiKey> | undefined
+): Promise<TemporaryApiKey> => {
+ const resolvedKey = await existingKey
+ if (isTemporaryApiKeyValid(resolvedKey)) {
+ return resolvedKey
+ }
+
+ const expiryInSeconds = 600
+ const fetchedKey = getTemporaryAPIKey({
+ projectRef,
+ expiry: expiryInSeconds,
+ }).then((data) => createTemporaryApiKey(data.api_key, expiryInSeconds))
+
+ return fetchedKey
+}
+
+// This function should never be marked as async, it should always return a promise.
+export function getOrRefreshTemporaryApiKey(projectRef: ProjectRef): Promise<TemporaryApiKey> {
+ const existingKey = projectApiKeys.get(projectRef)
+ if (!existingKey) {
+ const data = checkOrRefreshTemporaryApiKey(projectRef, undefined)
+ projectApiKeys.set(projectRef, data)
+ }
+ return projectApiKeys.get(projectRef)!
+}
diff --git a/apps/studio/state/storage-explorer.tsx b/apps/studio/state/storage-explorer.tsx
index 1e2a58ee330..e3d2fce57d1 100644
--- a/apps/studio/state/storage-explorer.tsx
+++ b/apps/studio/state/storage-explorer.tsx
@@ -5,7 +5,7 @@ import { toast } from 'sonner'
import * as tus from 'tus-js-client'
import { proxy, useSnapshot } from 'valtio'
-import { createClient, SupabaseClient } from '@supabase/supabase-js'
+import { createClient } from '@supabase/supabase-js'
import { BlobReader, BlobWriter, ZipWriter } from '@zip.js/zip.js'
import { LOCAL_STORAGE_KEYS } from 'common'
import {
@@ -28,7 +28,6 @@ import {
} from 'components/interfaces/Storage/Storage.types'
import {
calculateTotalRemainingTime,
- downloadFile,
EMPTY_FOLDER_PLACEHOLDER_FILE_NAME,
formatFolderItems,
formatTime,
@@ -36,18 +35,12 @@ import {
} from 'components/interfaces/Storage/StorageExplorer/StorageExplorer.utils'
import { convertFromBytes } from 'components/interfaces/Storage/StorageSettings/StorageSettings.utils'
import { InlineLink } from 'components/ui/InlineLink'
-import { getTemporaryAPIKey } from 'data/api-keys/temp-api-keys-query'
-import {
- createTemporaryUploadKey,
- isTemporaryUploadKeyValid,
- type TemporaryUploadKey,
-} from 'data/api-keys/temp-api-keys-utils'
+import { getOrRefreshTemporaryApiKey } from 'data/api-keys/temp-api-keys-utils'
import { configKeys } from 'data/config/keys'
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'
-import { downloadBucketObject } from 'data/storage/bucket-object-download-mutation'
import { listBucketObjects, StorageObject } from 'data/storage/bucket-objects-list-mutation'
import { deleteBucketPrefix } from 'data/storage/bucket-prefix-delete-mutation'
import { Bucket } from 'data/storage/buckets-query'
@@ -87,12 +80,12 @@ function createStorageExplorerState({
projectRef,
connectionString,
resumableUploadUrl,
- supabaseClient,
+ clientEndpoint,
}: {
projectRef: string
connectionString: string
resumableUploadUrl: string
- supabaseClient?: () => Promise<SupabaseClient<any, 'public', any>>
+ clientEndpoint: string
}) {
const localStorageKey = LOCAL_STORAGE_KEYS.STORAGE_PREFERENCE(projectRef)
const { view, sortBy, sortByOrder, sortBucket } =
@@ -102,12 +95,31 @@ function createStorageExplorerState({
const state = proxy({
projectRef,
connectionString,
- supabaseClient,
resumableUploadUrl,
uploadProgresses: [] as UploadProgress[],
- // Temporary API key management for batch uploads
- temporaryUploadKey: undefined as TemporaryUploadKey | undefined,
+ supabaseClient: async () => {
+ try {
+ const { apiKey } = await getOrRefreshTemporaryApiKey(projectRef)
+
+ return createClient(clientEndpoint, apiKey, {
+ auth: {
+ persistSession: false,
+ autoRefreshToken: false,
+ detectSessionInUrl: false,
+ storage: {
+ getItem: (key) => {
+ return null
+ },
+ setItem: (key, value) => {},
+ removeItem: (key) => {},
+ },
+ },
+ })
+ } catch (error) {
+ throw error
+ }
+ },
// abortController,
abortApiCalls: () => {
@@ -123,29 +135,6 @@ function createStorageExplorerState({
state.abortUploadCallbacks[toastId] = []
},
- // Get or refresh the temporary upload key
- getOrRefreshTemporaryUploadKey: async () => {
- if (isTemporaryUploadKeyValid(state.temporaryUploadKey)) {
- return state.temporaryUploadKey.apiKey
- }
-
- // Generate new key with 10 minutes expiry
- const expiryInSeconds = 600
- const data = await getTemporaryAPIKey({
- projectRef: state.projectRef,
- expiry: expiryInSeconds,
- })
-
- state.temporaryUploadKey = createTemporaryUploadKey(data.api_key, expiryInSeconds)
-
- return data.api_key
- },
-
- // Clear the temporary upload key
- clearTemporaryUploadKey: () => {
- state.temporaryUploadKey = undefined
- },
-
columns: [] as StorageColumn[],
popColumn: () => {
state.abortApiCalls()
@@ -829,6 +818,9 @@ function createStorageExplorerState({
{ id: toastId, closeButton: false, position: 'top-right' }
)
+ // Get authenticated Supabase client for Storage API access
+ const client = state.supabaseClient ? await state.supabaseClient() : undefined
+
const promises = files.map((file) => {
const fileMimeType = (file.metadata?.mimetype as string) ?? null
return () => {
@@ -841,18 +833,23 @@ function createStorageExplorerState({
| boolean
>(async (resolve) => {
try {
- const data = await downloadBucketObject({
- projectRef: state.projectRef,
- bucketId: state.selectedBucket.id,
- path: `${file.prefix}/${file.name}`,
- })
+ if (!client) {
+ throw new Error('Supabase client not available')
+ }
+ // Use Storage API directly instead of Management API to avoid throttling
+ const { data, error } = await client.storage
+ .from(state.selectedBucket.id)
+ .download(`${file.prefix}/${file.name}`)
+
+ if (error) throw error
+ if (!data) throw new Error('No data returned from download')
+
progress = progress + 1 / files.length
- const blob = await data.blob()
resolve({
name: file.name,
prefix: file.prefix,
- blob: new Blob([blob], { type: fileMimeType }),
+ blob: new Blob([data], { type: fileMimeType }),
})
} catch (error) {
console.error('Failed to download file', `${file.prefix}/${file.name}`)
@@ -1122,15 +1119,6 @@ function createStorageExplorerState({
.map((folder) => folder.name)
.join('/')
- // Generate temporary API key for the batch upload
- try {
- await state.getOrRefreshTemporaryUploadKey()
- } catch (error) {
- console.error('Failed to get temporary API key:', error)
- toast.error('Failed to initialize upload session. Please try again.')
- return
- }
-
const toastId = state.onUploadProgress()
// Upload files in batches
@@ -1231,7 +1219,7 @@ function createStorageExplorerState({
try {
// Use the shared temporary key for batch uploads
// This checks if the key is still valid and refreshes if needed
- const apiKey = await state.getOrRefreshTemporaryUploadKey()
+ const { apiKey } = await getOrRefreshTemporaryApiKey(state.projectRef)
req.setHeader('apikey', apiKey)
if (!IS_PLATFORM) {
req.setHeader('Authorization', `Bearer ${apiKey}`)
@@ -1395,9 +1383,6 @@ function createStorageExplorerState({
closeButton: true,
duration: SONNER_DEFAULT_DURATION,
})
- } finally {
- // Clear the temporary API key after batch upload completes
- state.clearTemporaryUploadKey()
}
const t2 = new Date()
@@ -1520,6 +1505,85 @@ function createStorageExplorerState({
}
},
+ downloadFile: async (file: StorageItemWithColumn, showToast = true) => {
+ if (!file.path) {
+ toast.error('Failed to download: Unable to find path to file')
+ return false
+ }
+
+ const fileName: string = file.name
+ const fileMimeType = file?.metadata?.mimetype ?? undefined
+
+ const toastId = showToast ? toast.loading(`Retrieving ${fileName}...`) : undefined
+
+ try {
+ const client = state.supabaseClient ? await state.supabaseClient() : undefined
+ if (!client) {
+ throw new Error('Supabase client not available')
+ }
+
+ // Use Storage API directly instead of Management API to avoid throttling
+ const { data, error } = await client.storage
+ .from(state.selectedBucket.id)
+ .download(file.path)
+
+ if (error) throw error
+ if (!data) throw new Error('No data returned from download')
+
+ const newBlob = new Blob([data], { type: fileMimeType })
+ const blobUrl = window.URL.createObjectURL(newBlob)
+ const link = document.createElement('a')
+ link.href = blobUrl
+ link.setAttribute('download', `${fileName}`)
+ document.body.appendChild(link)
+ link.click()
+ link.parentNode?.removeChild(link)
+ window.URL.revokeObjectURL(blobUrl)
+
+ if (toastId) {
+ toast.success(`Downloading ${fileName}`, {
+ id: toastId,
+ closeButton: true,
+ duration: SONNER_DEFAULT_DURATION,
+ })
+ }
+ return true
+ } catch (err) {
+ if (toastId) {
+ toast.error(`Failed to download ${fileName}`, {
+ id: toastId,
+ closeButton: true,
+ duration: SONNER_DEFAULT_DURATION,
+ })
+ }
+ return false
+ }
+ },
+
+ downloadFileAsBlob: async (file: StorageItemWithColumn) => {
+ if (!file.path) return false
+
+ try {
+ const client = state.supabaseClient ? await state.supabaseClient() : undefined
+ if (!client) {
+ throw new Error('Supabase client not available')
+ }
+
+ const { data, error } = await client.storage
+ .from(state.selectedBucket.id)
+ .download(file.path)
+
+ if (error) throw error
+ if (!data) throw new Error('No data returned from download')
+
+ const fileMimeType = file?.metadata?.mimetype ?? undefined
+ return { name: file.name, blob: new Blob([data], { type: fileMimeType }) }
+ } catch (err) {
+ console.error('Failed to download file', file.path)
+ return false
+ }
+ },
+
downloadSelectedFiles: async (files: StorageItemWithColumn[]) => {
const lowestColumnIndex = Math.min(...files.map((file) => file.columnIndex))
@@ -1534,7 +1598,6 @@ function createStorageExplorerState({
})
let progress = 0
- const returnBlob = true
const toastId = toast.loading(
`Downloading ${files.length} file${files.length > 1 ? 's' : ''}...`
)
@@ -1542,12 +1605,7 @@ function createStorageExplorerState({
const promises = formattedFilesWithPrefix.map((file) => {
return () => {
return new Promise<{ name: string; blob: Blob } | boolean>(async (resolve) => {
- const data = await downloadFile({
- projectRef: state.projectRef,
- bucketId: state.selectedBucket.id,
- file,
- returnBlob,
- })
+ const data = await state.downloadFileAsBlob(file)
progress = progress + 1 / formattedFilesWithPrefix.length
if (isObject(data)) {
resolve({ ...data, name: file.formattedPathToFile })
@@ -1557,7 +1615,8 @@ function createStorageExplorerState({
}
})
- const batchedPromises = chunk(promises, 10)
+ // Increase batch size to 50 since Storage API doesn't throttle like Management API
+ const batchedPromises = chunk(promises, 50)
const downloadedFiles = await batchedPromises.reduce(async (previousPromise, nextBatch) => {
const previousResults = await previousPromise
const batchResults = await Promise.allSettled(nextBatch.map((batch) => batch()))
@@ -1826,7 +1885,7 @@ const DEFAULT_STATE_CONFIG = {
projectRef: '',
connectionString: '',
resumableUploadUrl: '',
- supabaseClient: undefined,
+ clientEndpoint: '',
}
const StorageExplorerStateContext = createContext<StorageExplorerState>(
@@ -1847,6 +1906,7 @@ export const StorageExplorerStateContextProvider = ({ children }: PropsWithChild
const protocol = settings?.app_config?.protocol ?? 'https'
const endpoint = settings?.app_config?.endpoint
const resumableUploadUrl = `${IS_PLATFORM ? 'https' : protocol}://${endpoint}/storage/v1/upload/resumable`
+ const clientEndpoint = `${IS_PLATFORM ? 'https' : protocol}://${endpoint}`
// [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
@@ -1862,30 +1922,8 @@ export const StorageExplorerStateContextProvider = ({ children }: PropsWithChild
createStorageExplorerState({
projectRef: project?.ref ?? '',
connectionString: project.connectionString ?? '',
- 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,
+ clientEndpoint,
})
)
}
diff --git a/e2e/studio/features/files/test-file.txt b/e2e/studio/features/files/test-file.txt
new file mode 100644
index 00000000000..eba8160d606
--- /dev/null
+++ b/e2e/studio/features/files/test-file.txt
@@ -0,0 +1,3 @@
+This is a test file for e2e storage testing.
+It contains some sample content to verify file uploads work correctly.
+
diff --git a/e2e/studio/features/home.spec.ts b/e2e/studio/features/home.spec.ts
index ad753f8c78b..19568dbff80 100644
--- a/e2e/studio/features/home.spec.ts
+++ b/e2e/studio/features/home.spec.ts
@@ -1,6 +1,6 @@
import { expect } from '@playwright/test'
-import { test } from '../utils/test'
-import { toUrl } from '../utils/to-url'
+import { test } from '../utils/test.js'
+import { toUrl } from '../utils/to-url.js'
test.describe('Project', async () => {
test('Can navigate to project home page', async ({ page, ref }) => {
diff --git a/e2e/studio/features/logs.spec.ts b/e2e/studio/features/logs.spec.ts
index 87cc79c1882..dc33eed1573 100644
--- a/e2e/studio/features/logs.spec.ts
+++ b/e2e/studio/features/logs.spec.ts
@@ -1,6 +1,6 @@
import { expect } from '@playwright/test'
-import { test } from '../utils/test'
-import { toUrl } from '../utils/to-url'
+import { test } from '../utils/test.js'
+import { toUrl } from '../utils/to-url.js'
const LOGS_PAGES = [
{ label: 'API Gateway', route: 'edge-logs' },
{ label: 'Postgres', route: 'postgres-logs' },
diff --git a/e2e/studio/features/storage.spec.ts b/e2e/studio/features/storage.spec.ts
new file mode 100644
index 00000000000..66933bd65d6
--- /dev/null
+++ b/e2e/studio/features/storage.spec.ts
@@ -0,0 +1,253 @@
+import { expect } from '@playwright/test'
+import path from 'path'
+import { test } from '../utils/test.js'
+import { waitForApiResponse } from '../utils/wait-for-response.js'
+import {
+ createBucket,
+ createFolder,
+ deleteAllBuckets,
+ deleteBucket,
+ deleteItem,
+ dismissToastsIfAny,
+ downloadFile,
+ navigateToBucket,
+ renameItem,
+ uploadFile,
+} from '../utils/storage-helpers.js'
+
+const bucketNamePrefix = 'pw_bucket'
+
+test.describe.serial('Storage', () => {
+ test.beforeEach(async ({ page, ref }) => {
+ await deleteAllBuckets(page, ref)
+ })
+
+ test('can navigate to storage page', async ({ page, ref }) => {
+ await expect(
+ page.getByRole('button', { name: 'New bucket' }),
+ 'New bucket button should be visible'
+ ).toBeVisible()
+
+ // Verify we're on the storage files page
+ await expect(page).toHaveURL(new RegExp(`/project/${ref}/storage/files`))
+ })
+
+ test('can create a private bucket', async ({ page, ref }) => {
+ const bucketName = `${bucketNamePrefix}_private`
+
+ await createBucket(page, ref, bucketName, false)
+
+ // Verify it's marked as private (no "Public" badge should be visible)
+ const bucketRow = page.getByRole('row').filter({ hasText: bucketName })
+ await expect(bucketRow, 'Bucket row should be visible').toBeVisible()
+ await expect(
+ bucketRow.getByText('Public'),
+ 'Private bucket should not have Public badge'
+ ).not.toBeVisible()
+ })
+
+ test('can create a public bucket', async ({ page, ref }) => {
+ const bucketName = `${bucketNamePrefix}_public`
+
+ await createBucket(page, ref, bucketName, true)
+
+ // Verify it's marked as public - wait for the badge to appear
+ const bucketRow = page.getByRole('row').filter({ hasText: bucketName })
+ await expect(bucketRow, 'Bucket row should be visible').toBeVisible()
+
+ // The Public badge should be visible within the bucket row
+ await expect(
+ bucketRow.getByText('Public', { exact: true }),
+ 'Bucket should be marked as Public'
+ ).toBeVisible({ timeout: 10000 })
+ })
+
+ test('can edit bucket settings', async ({ page, ref }) => {
+ const bucketName = `${bucketNamePrefix}_edit`
+
+ // Create a private bucket
+ await createBucket(page, ref, bucketName, false)
+
+ // Navigate to the bucket
+ await navigateToBucket(page, ref, bucketName)
+
+ // Open edit bucket dropdown
+ await page.getByRole('button', { name: 'Edit bucket' }).click()
+ await page.getByRole('menuitem', { name: 'Bucket settings' }).click()
+
+ // Toggle public setting
+ const publicToggle = page.getByRole('switch', { name: 'Public bucket' })
+ await expect(publicToggle, 'Public toggle should be visible').toBeVisible()
+ await publicToggle.click()
+
+ // Save changes
+ const apiPromise = waitForApiResponse(page, 'storage', ref, `buckets/${bucketName}`, {
+ method: 'PATCH',
+ })
+ await page.getByRole('button', { name: 'Save' }).click()
+ await apiPromise
+
+ // Verify the bucket is now public
+ await expect(
+ page.getByText('Public').first(),
+ 'Bucket should now be marked as Public'
+ ).toBeVisible({ timeout: 10_000 })
+ })
+
+ test('can delete a bucket', async ({ page, ref }) => {
+ const bucketName = `${bucketNamePrefix}_delete`
+
+ // Create a bucket
+ await createBucket(page, ref, bucketName, false)
+
+ // Delete it
+ await deleteBucket(page, ref, bucketName)
+
+ // Verify it's gone
+ await expect(
+ page.getByRole('row').filter({ hasText: bucketName }),
+ 'Bucket should not be visible after deletion'
+ ).not.toBeVisible()
+ })
+
+ test('can search for buckets', async ({ page, ref }) => {
+ const bucketName1 = `${bucketNamePrefix}_search_1`
+ const bucketName2 = `${bucketNamePrefix}_search_2`
+
+ // Create two buckets
+ await createBucket(page, ref, bucketName1, false)
+ await dismissToastsIfAny(page)
+ await createBucket(page, ref, bucketName2, false)
+
+ // Search for first bucket
+ const searchInput = page.getByPlaceholder('Search for a bucket')
+ await searchInput.fill('search_1')
+
+ // Verify only first bucket is visible
+ await expect(
+ page.getByRole('row').filter({ hasText: bucketName1 }),
+ 'First bucket should be visible in search results'
+ ).toBeVisible()
+ await expect(
+ page.getByRole('row').filter({ hasText: bucketName2 }),
+ 'Second bucket should not be visible in search results'
+ ).not.toBeVisible()
+
+ // Clear search
+ await searchInput.clear()
+
+ // Verify both buckets are visible
+ await expect(
+ page.getByRole('row').filter({ hasText: bucketName1 }),
+ 'First bucket should be visible after clearing search'
+ ).toBeVisible()
+ await expect(
+ page.getByRole('row').filter({ hasText: bucketName2 }),
+ 'Second bucket should be visible after clearing search'
+ ).toBeVisible()
+ })
+
+ test('can upload a file', async ({ page, ref }) => {
+ const bucketName = `${bucketNamePrefix}_upload`
+ const fileName = 'test-file.txt'
+
+ // Create a bucket and navigate to it
+ await createBucket(page, ref, bucketName, false)
+ await navigateToBucket(page, ref, bucketName)
+
+ // Upload a file
+ const filePath = path.join(import.meta.dirname, 'files', fileName)
+ await uploadFile(page, filePath, fileName)
+
+ // Clean up
+ await deleteBucket(page, ref, bucketName)
+ })
+
+ test('can create a folder', async ({ page, ref }) => {
+ const bucketName = `${bucketNamePrefix}_folder`
+ const folderName = 'test_folder'
+
+ // Create a bucket and navigate to it
+ await createBucket(page, ref, bucketName, false)
+ await navigateToBucket(page, ref, bucketName)
+
+ // Create a folder
+ await createFolder(page, folderName)
+ })
+
+ test('can rename a file', async ({ page, ref }) => {
+ const bucketName = `${bucketNamePrefix}_rename_file`
+ const fileName = 'test-file.txt'
+ const newFileName = 'renamed-file.txt'
+
+ // Create a bucket, navigate to it, and upload a file
+ await createBucket(page, ref, bucketName, false)
+ await navigateToBucket(page, ref, bucketName)
+
+ const filePath = path.join(import.meta.dirname, 'files', fileName)
+ await uploadFile(page, filePath, fileName)
+
+ // Rename the file
+ await renameItem(page, fileName, newFileName)
+
+ // Clean up
+ await deleteBucket(page, ref, bucketName)
+ })
+
+ test('can rename a folder', async ({ page, ref }) => {
+ const bucketName = `${bucketNamePrefix}_rename_folder`
+ const folderName = 'old_folder'
+ const newFolderName = 'new_folder'
+
+ // Create a bucket, navigate to it, and create a folder
+ await createBucket(page, ref, bucketName, false)
+ await navigateToBucket(page, ref, bucketName)
+ await createFolder(page, folderName)
+
+ // Rename the folder
+ await renameItem(page, folderName, newFolderName)
+ })
+
+ test('can delete a file', async ({ page, ref }) => {
+ const bucketName = `${bucketNamePrefix}_delete_file`
+ const fileName = 'test-file.txt'
+
+ // Create a bucket, navigate to it, and upload a file
+ await createBucket(page, ref, bucketName, false)
+ await navigateToBucket(page, ref, bucketName)
+
+ const filePath = path.join(import.meta.dirname, 'files', fileName)
+ await uploadFile(page, filePath, fileName)
+
+ // Delete the file
+ await deleteItem(page, fileName)
+ })
+
+ test('can delete a folder', async ({ page, ref }) => {
+ const bucketName = `${bucketNamePrefix}_delete_folder`
+ const folderName = 'test_folder'
+
+ // Create a bucket, navigate to it, and create a folder
+ await createBucket(page, ref, bucketName, false)
+ await navigateToBucket(page, ref, bucketName)
+ await createFolder(page, folderName)
+
+ // Delete the folder
+ await deleteItem(page, folderName)
+ })
+
+ test('can download a file', async ({ page, ref }) => {
+ const bucketName = `${bucketNamePrefix}_download`
+ const fileName = 'test-file.txt'
+
+ // Create a bucket, navigate to it, and upload a file
+ await createBucket(page, ref, bucketName, false)
+ await navigateToBucket(page, ref, bucketName)
+
+ const filePath = path.join(import.meta.dirname, 'files', fileName)
+ await uploadFile(page, filePath, fileName)
+
+ // Download the file
+ await downloadFile(page, fileName)
+ })
+})
diff --git a/e2e/studio/utils/storage-helpers.ts b/e2e/studio/utils/storage-helpers.ts
new file mode 100644
index 00000000000..21e25f06aaa
--- /dev/null
+++ b/e2e/studio/utils/storage-helpers.ts
@@ -0,0 +1,278 @@
+import { expect, Page } from '@playwright/test'
+import { waitForApiResponse } from './wait-for-response'
+import { toUrl } from './to-url'
+
+/**
+ * Dismisses any visible toast notifications
+ */
+export const dismissToastsIfAny = async (page: Page) => {
+ const closeButtons = page.getByRole('button', { name: 'Close toast' })
+ const count = await closeButtons.count()
+ for (let i = 0; i < count; i++) {
+ await closeButtons.nth(i).click()
+ }
+}
+
+/**
+ * Navigates to a the storage home view
+ * @param page - Playwright page instance
+ * @param ref - Project reference
+ */
+export const navigateToStorageFiles = async (page: Page, ref: string) => {
+ await page.goto(toUrl(`/project/${ref}/storage/files`))
+ await page.waitForLoadState('networkidle')
+}
+
+/**
+ * Creates a new storage bucket
+ * @param page - Playwright page instance
+ * @param ref - Project reference
+ * @param bucketName - Name of the bucket to create
+ * @param isPublic - Whether the bucket should be public (default: false)
+ */
+export const createBucket = async (
+ page: Page,
+ ref: string,
+ bucketName: string,
+ isPublic: boolean = false
+) => {
+ await navigateToStorageFiles(page, ref)
+ // Check if bucket already exists
+ const bucketRow = page.getByRole('row').filter({ hasText: bucketName })
+ if ((await bucketRow.count()) > 0) return
+
+ // Dismiss any toasts that might block the button
+ await dismissToastsIfAny(page)
+
+ // Click "New bucket" button
+ const newBucketBtn = page.getByRole('button', { name: 'New bucket' })
+ await expect(newBucketBtn, 'New bucket button should be visible').toBeVisible()
+ await newBucketBtn.click()
+
+ // Fill in bucket name
+ const nameInput = page.getByRole('textbox', { name: 'Bucket name' })
+ await expect(nameInput, 'Bucket name input should be visible').toBeVisible()
+ await nameInput.fill(bucketName)
+
+ // Toggle public setting if needed
+ if (isPublic) {
+ const publicToggle = page.getByRole('switch', { name: 'Public bucket' })
+ await publicToggle.click()
+ }
+
+ // Wait for bucket creation API call and click create button
+ const apiPromise = waitForApiResponse(page, 'storage', ref, 'bucket', { method: 'POST' })
+ await page.getByRole('button', { name: 'Create' }).click()
+ await apiPromise
+
+ // Verify bucket was created - bucket appears in table row
+ await expect(
+ page.getByRole('row').filter({ hasText: bucketName }),
+ `Bucket ${bucketName} should be visible after creation`
+ ).toBeVisible({ timeout: 15_000 })
+}
+
+/**
+ * Deletes a storage bucket
+ * @param page - Playwright page instance
+ * @param ref - Project reference
+ * @param bucketName - Name of the bucket to delete
+ */
+export const deleteBucket = async (page: Page, ref: string, bucketName: string) => {
+ // Check if bucket exists
+ const bucketRow = page.getByRole('row').filter({ hasText: bucketName })
+ if ((await bucketRow.count()) === 0) return
+
+ // Navigate to the bucket first
+ await bucketRow.click()
+ await page.waitForURL(new RegExp(`/storage/files/buckets/${bucketName}`))
+
+ // Click "Edit bucket" dropdown
+ await page.getByRole('button', { name: 'Edit bucket' }).click()
+
+ // Click "Delete bucket" option from dropdown
+ await page.getByRole('menuitem', { name: 'Delete bucket' }).click()
+
+ // Type bucket name in the confirmation textbox (placeholder: "Type bucket name")
+ const confirmInput = page.getByPlaceholder('Type bucket name')
+ await expect(confirmInput, 'Confirmation input should be visible').toBeVisible()
+ await confirmInput.fill(bucketName)
+
+ // Wait for API call and click Delete bucket button
+ const apiPromise = waitForApiResponse(page, 'storage', ref, `buckets/${bucketName}`, {
+ method: 'DELETE',
+ })
+ await page.getByRole('button', { name: 'Delete bucket' }).click()
+ await apiPromise
+
+ // Verify bucket was deleted - should redirect to files page
+ await expect(page, 'Should redirect to storage files page after deletion').toHaveURL(
+ new RegExp(`/storage/files$`)
+ )
+
+ // Verify bucket is no longer in the list
+ await expect(
+ page.getByRole('row').filter({ hasText: bucketName }),
+ `Bucket ${bucketName} should not be visible after deletion`
+ ).not.toBeVisible()
+}
+
+/**
+ * Navigates to a specific bucket
+ * @param page - Playwright page instance
+ * @param ref - Project reference
+ * @param bucketName - Name of the bucket to navigate to
+ */
+export const navigateToBucket = async (page: Page, ref: string, bucketName: string) => {
+ // Click on the bucket row to navigate
+ const bucketRow = page.getByRole('row').filter({ hasText: bucketName })
+ await expect(bucketRow, `Bucket row for ${bucketName} should be visible`).toBeVisible()
+ await bucketRow.click()
+
+ // Wait for navigation to complete
+ await page.waitForURL(new RegExp(`/storage/files/buckets/${encodeURIComponent(bucketName)}`))
+
+ // Verify we're in the bucket by checking the breadcrumb or "Edit bucket" button
+ await expect(
+ page.getByRole('button', { name: 'Edit bucket' }),
+ `Should be in bucket ${bucketName}`
+ ).toBeVisible({ timeout: 10_000 })
+}
+
+/**
+ * Creates a new folder in the current bucket
+ * @param page - Playwright page instance
+ * @param folderName - Name of the folder to create
+ */
+export const createFolder = async (page: Page, folderName: string) => {
+ // Click "Create folder" button
+ const createFolderBtn = page.getByRole('button', { name: 'Create folder' })
+ await expect(createFolderBtn, 'Create folder button should be visible').toBeVisible()
+ await createFolderBtn.click()
+
+ // A textbox with "Untitled folder" appears - type the new name
+ const nameInput = page.getByRole('textbox')
+ await expect(nameInput, 'Folder name input should be visible').toBeVisible()
+ await nameInput.fill(folderName)
+ await nameInput.press('Enter')
+
+ // Wait for folder to appear in the list
+ await expect(
+ page.getByTitle(folderName),
+ `Folder ${folderName} should be visible after creation`
+ ).toBeVisible({ timeout: 10_000 })
+}
+
+/**
+ * Uploads a file to the current folder
+ * @param page - Playwright page instance
+ * @param filePath - Absolute path to the file to upload
+ * @param fileName - Expected file name (for verification)
+ */
+export const uploadFile = async (page: Page, filePath: string, fileName: string) => {
+ // Find the hidden file input and upload the file
+ const fileInput = page.locator('input[type="file"]')
+ await fileInput.setInputFiles(filePath)
+
+ // Wait for upload to complete - file should appear in the explorer
+ await page.waitForTimeout(2000) // Allow time for upload to process
+
+ // Verify file appears in the explorer by title
+ await expect(
+ page.getByTitle(fileName),
+ `File ${fileName} should be visible in explorer after upload`
+ ).toBeVisible({ timeout: 15_000 })
+}
+
+/**
+ * Deletes a file or folder from the current location
+ * @param page - Playwright page instance
+ * @param itemName - Name of the file or folder to delete
+ */
+export const deleteItem = async (page: Page, itemName: string) => {
+ // Right-click on the item to open context menu
+ const item = page.getByTitle(itemName)
+ await expect(item, `Item ${itemName} should be visible`).toBeVisible()
+ await item.click({ button: 'right' })
+
+ // Click delete option from context menu
+ await page.getByRole('menuitem', { name: 'Delete' }).click()
+
+ // Confirm deletion in the modal
+ await page.getByRole('button', { name: 'Submit' }).click()
+
+ // Wait for deletion to complete
+ await page.waitForTimeout(1000)
+ await expect(
+ page.getByTitle(itemName),
+ `Item ${itemName} should not be visible after deletion`
+ ).not.toBeVisible({ timeout: 10_000 })
+}
+
+/**
+ * Renames a file or folder
+ * @param page - Playwright page instance
+ * @param oldName - Current name of the item
+ * @param newName - New name for the item
+ */
+export const renameItem = async (page: Page, oldName: string, newName: string) => {
+ // Right-click on the item to open context menu
+ const item = page.getByTitle(oldName)
+ await expect(item, `Item ${oldName} should be visible`).toBeVisible()
+ await item.click({ button: 'right' })
+
+ // Click rename option from context menu
+ await page.getByRole('menuitem', { name: 'Rename' }).click()
+
+ // A textbox appears - clear and type new name
+ const nameInput = page.getByRole('textbox')
+ await nameInput.fill(newName)
+ await nameInput.press('Enter')
+
+ // Wait for rename to complete
+ await page.waitForTimeout(1000)
+
+ // Verify item was renamed
+ await expect(page.getByTitle(newName), `Item should be renamed to ${newName}`).toBeVisible({
+ timeout: 10_000,
+ })
+ await expect(
+ page.getByTitle(oldName),
+ `Old name ${oldName} should not be visible after rename`
+ ).not.toBeVisible()
+}
+
+/**
+ * Downloads a file and returns the download object
+ * @param page - Playwright page instance
+ * @param fileName - Name of the file to download
+ */
+export const downloadFile = async (page: Page, fileName: string) => {
+ // Right-click on the file to open context menu
+ const file = page.getByTitle(fileName)
+ await expect(file, `File ${fileName} should be visible`).toBeVisible()
+ await file.click({ button: 'right' })
+
+ // Click download option from context menu
+ const downloadPromise = page.waitForEvent('download')
+ await page.getByRole('menuitem', { name: 'Download' }).click()
+
+ // Wait for and return the download
+ const download = await downloadPromise
+ expect(download.suggestedFilename()).toContain(fileName)
+}
+
+export const deleteAllBuckets = async (page: Page, ref: string) => {
+ await navigateToStorageFiles(page, ref)
+
+ // Find all bucket rows and collect their IDs
+ const bucketRows = await page.locator('[data-bucket-id]').all()
+ const bucketIds = await Promise.all(bucketRows.map((row) => row.getAttribute('data-bucket-id')))
+
+ // Delete each bucket
+ for (const bucketId of bucketIds) {
+ if (bucketId) {
+ await deleteBucket(page, ref, bucketId)
+ }
+ }
+}