Skip to content

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

feat(studio): add advisor for public bucket rls (#44438)

kemal.earth83e5ee8c5c2d
diff --git a/apps/studio/components/interfaces/Linter/Linter.utils.tsx b/apps/studio/components/interfaces/Linter/Linter.utils.tsx
index 6cf1078d4f3..1059048e1fb 100644
--- a/apps/studio/components/interfaces/Linter/Linter.utils.tsx
+++ b/apps/studio/components/interfaces/Linter/Linter.utils.tsx
@@ -320,6 +320,18 @@ export const lintInfoMap: LintInfo[] = [
docsLink: `${DOCS_URL}/guides/database/database-linter?lint=0024_permissive_rls_policy`,
category: 'security',
},
+ {
+ name: 'public_bucket_allows_listing',
+ title: 'Public Bucket Allows Listing',
+ icon: <Box className="text-foreground-muted" size={15} strokeWidth={1.5} />,
+ link: ({ projectRef, metadata }) => {
+ const bucketId = (metadata as Record<string, string | undefined> | undefined)?.bucket_id
+ return `/project/${projectRef}/storage/files/buckets/${encodeURIComponent(bucketId ?? metadata?.name ?? '')}`
+ },
+ linkText: 'View bucket',
+ docsLink: `${DOCS_URL}/guides/database/database-linter?lint=0025_public_bucket_allows_listing`,
+ category: 'security',
+ },
]
export const LintCTA = ({
diff --git a/apps/studio/components/interfaces/Storage/PublicBucketWarning.tsx b/apps/studio/components/interfaces/Storage/PublicBucketWarning.tsx
index 872f6366c84..81e3f880bb7 100644
--- a/apps/studio/components/interfaces/Storage/PublicBucketWarning.tsx
+++ b/apps/studio/components/interfaces/Storage/PublicBucketWarning.tsx
@@ -1,6 +1,7 @@
import { ident } from '@supabase/pg-meta/src/pg-format'
import { useMutation, useQueryClient } from '@tanstack/react-query'
-import { useState, type ReactNode } from 'react'
+import { LOCAL_STORAGE_KEYS } from 'common'
+import { useEffect, useState, type ReactNode } from 'react'
import { toast } from 'sonner'
import { Button } from 'ui'
import { Admonition } from 'ui-patterns/admonition'
@@ -12,6 +13,29 @@ import { executeSql } from '@/data/sql/execute-sql-query'
import { storageKeys } from '@/data/storage/keys'
import { usePublicBucketsWithSelectPoliciesQuery } from '@/data/storage/public-buckets-with-select-policies-query'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
+import { useTrack } from '@/lib/telemetry/track'
+
+const DISMISS_DURATION_MS = 14 * 24 * 60 * 60 * 1000 // 14 days
+
+function isDismissed(projectRef: string, bucketId: string): boolean {
+ try {
+ const raw = localStorage.getItem(
+ LOCAL_STORAGE_KEYS.STORAGE_PUBLIC_BUCKET_SELECT_POLICY_WARNING_DISMISSED(projectRef, bucketId)
+ )
+ if (!raw) return false
+ const { dismissedAt } = JSON.parse(raw) as { dismissedAt: string }
+ return Date.now() - new Date(dismissedAt).getTime() < DISMISS_DURATION_MS
+ } catch {
+ return false
+ }
+}
+
+function persistDismiss(projectRef: string, bucketId: string): void {
+ localStorage.setItem(
+ LOCAL_STORAGE_KEYS.STORAGE_PUBLIC_BUCKET_SELECT_POLICY_WARNING_DISMISSED(projectRef, bucketId),
+ JSON.stringify({ dismissedAt: new Date().toISOString() })
+ )
+}
function generatePolicyRemovalSql(policyName: string) {
return `DROP POLICY IF EXISTS ${ident(policyName)} ON storage.objects;`
@@ -32,6 +56,9 @@ export function PublicBucketWarning({ projectRef, bucketId }: PublicBucketWarnin
bucketId,
})
const policyToRemove = data?.[0]
+ const matchingPolicyCount = data?.length ?? 0
+
+ const track = useTrack()
const { mutate: removePolicy, isPending: isRemovingPolicy } = useMutation({
mutationFn: async (policyName: string) => {
@@ -50,8 +77,15 @@ export function PublicBucketWarning({ projectRef, bucketId }: PublicBucketWarnin
queryKey: databasePoliciesKeys.list(projectRef, 'storage'),
}),
])
+ track('storage_public_bucket_select_policy_removed', { bucketId })
setShowModal(false)
- toast.success('Policy removed successfully')
+ toast.success(
+ matchingPolicyCount > 1
+ ? `Policy removed successfully. ${matchingPolicyCount - 1} matching ${
+ matchingPolicyCount - 1 === 1 ? 'policy' : 'policies'
+ } remaining.`
+ : 'Policy removed successfully'
+ )
},
onError: (error) => {
console.error('Failed to remove policy', error)
@@ -60,16 +94,30 @@ export function PublicBucketWarning({ projectRef, bucketId }: PublicBucketWarnin
})
const [showModal, setShowModal] = useState(false)
+ const [dismissed, setDismissed] = useState(() => isDismissed(projectRef, bucketId))
+
+ useEffect(() => {
+ setDismissed(isDismissed(projectRef, bucketId))
+ setShowModal(false)
+ }, [bucketId, projectRef])
+
+ function handleDismiss() {
+ persistDismiss(projectRef, bucketId)
+ track('storage_public_bucket_select_policy_warning_dismiss_button_clicked', { bucketId })
+ setDismissed(true)
+ }
- return policyToRemove ? (
+ return policyToRemove && !dismissed ? (
<PublicBucketWarningView
_tag="policy-to-remove"
policyName={policyToRemove.policyname}
+ policyCount={matchingPolicyCount}
isRemovingPolicy={isRemovingPolicy}
onRemovePolicy={() => removePolicy(policyToRemove.policyname)}
isModalVisible={showModal}
onShowModal={() => setShowModal(true)}
onHideModal={() => setShowModal(false)}
+ onDismiss={handleDismiss}
/>
) : (
<PublicBucketWarningView _tag="no-policy-to-remove" />
@@ -83,11 +131,13 @@ type PublicBucketWarningViewProps_NoPolicyToRemove = {
type PublicBucketWarningViewProps_PolicyToRemove = {
_tag: 'policy-to-remove'
policyName: string
+ policyCount: number
isRemovingPolicy: boolean
onRemovePolicy: () => void
isModalVisible: boolean
onShowModal: () => void
onHideModal: () => void
+ onDismiss: () => void
}
type PublicBucketWarningViewProps =
@@ -99,26 +149,48 @@ function PublicBucketWarningView(props: PublicBucketWarningViewProps): ReactNode
return null
}
- const { policyName, isRemovingPolicy, onRemovePolicy, isModalVisible, onShowModal, onHideModal } =
- props
+ const {
+ policyName,
+ policyCount,
+ isRemovingPolicy,
+ onRemovePolicy,
+ isModalVisible,
+ onShowModal,
+ onHideModal,
+ onDismiss,
+ } = props
+ const hasMultiplePolicies = policyCount > 1
return (
<>
<Admonition
type="warning"
layout="horizontal"
- title="Anyone can list all files in this bucket"
- description="A SELECT policy on storage.objects allows clients to retrieve a full list of files. Public buckets don’t need this and it may expose more data than intended."
+ title="Clients can list all files in this bucket"
+ description={
+ hasMultiplePolicies
+ ? `${policyCount} broad SELECT policies on storage.objects allow clients to retrieve a full list of files. Public buckets don’t need these policies and they may expose more data than intended.`
+ : 'A broad SELECT policy on storage.objects allows clients to retrieve a full list of files. Public buckets don’t need this and it may expose more data than intended.'
+ }
actions={
- <Button type="warning" size="tiny" onClick={onShowModal}>
- Remove policy
- </Button>
+ <div className="flex gap-2">
+ <Button type="default" size="tiny" onClick={onDismiss}>
+ Dismiss
+ </Button>
+ <Button type="warning" size="tiny" onClick={onShowModal}>
+ Remove policy
+ </Button>
+ </div>
}
/>
<ConfirmationModal
visible={isModalVisible}
variant="destructive"
- title="Remove SELECT policy"
+ title={
+ hasMultiplePolicies
+ ? `Remove SELECT policy (1 of ${policyCount})`
+ : 'Remove SELECT policy'
+ }
confirmLabel="Remove policy"
loading={isRemovingPolicy}
onCancel={onHideModal}
@@ -126,8 +198,13 @@ function PublicBucketWarningView(props: PublicBucketWarningViewProps): ReactNode
>
<div className="flex flex-col gap-3">
<p className="text-sm text-foreground-light">
- This will drop the <code>SELECT</code> policy that makes the bucket&apos;s contents
- listable. Object URLs will continue to work.
+ This will drop {hasMultiplePolicies ? 'one' : 'the'} <code>SELECT</code> policy that
+ makes the bucket&apos;s contents listable. Object URLs will continue to work.
+ {hasMultiplePolicies
+ ? ` ${policyCount - 1} matching ${
+ policyCount - 1 === 1 ? 'policy' : 'policies'
+ } will remain after this.`
+ : null}
</p>
<div className="-mx-4 md:-mx-5 -mb-4 border-t">
<CodeBlock
diff --git a/apps/studio/data/storage/public-buckets-with-select-policies-query.ts b/apps/studio/data/storage/public-buckets-with-select-policies-query.ts
index b661ab5052a..fa6cee9c404 100644
--- a/apps/studio/data/storage/public-buckets-with-select-policies-query.ts
+++ b/apps/studio/data/storage/public-buckets-with-select-policies-query.ts
@@ -20,10 +20,11 @@ export type PublicBucketSelectPolicy = {
}
/**
- * For the given public bucket, checks whether any SELECT policy on storage.objects
- * references this bucket's ID in its qual expression. This combination means anyone
- * can enumerate all objects in the bucket, which is usually unintentional — public
- * buckets don't require SELECT policies for object access by URL.
+ * For the given public bucket, checks whether any permissive SELECT or ALL policy
+ * on storage.objects broadly allows listing for API roles. This combination means
+ * clients can enumerate all objects in the bucket, which is usually unintentional.
+ * Public buckets don't require SELECT policies for object access by URL. Policies
+ * with additional object, path, or user constraints are excluded from this warning.
*
* Scoped to a single bucket so the query is a point-lookup rather than a full scan.
*/
@@ -41,10 +42,26 @@ async function getPublicBucketsWithSelectPolicies({
JOIN pg_policies p
ON p.schemaname = 'storage'
AND p.tablename = 'objects'
- AND p.cmd = 'SELECT'
+ AND p.cmd IN ('SELECT', 'ALL')
+ AND p.permissive = 'PERMISSIVE'
+ AND p.roles && ARRAY['public'::name, 'anon'::name, 'authenticated'::name]
WHERE b.public = true
AND b.id = ${literal(bucketId)}
- AND p.qual ~* ('bucket_id\\s*=\\s*' || quote_literal(b.id))
+ AND (
+ p.qual IS NULL
+ OR replace(replace(replace(lower(p.qual), ' ', ''), E'\\n', ''), E'\\t', '')
+ IN ('true', '(true)', '1=1', '(1=1)')
+ OR EXISTS (
+ SELECT 1
+ FROM regexp_match(
+ p.qual,
+ $re$\\A\\s*\\(*\\s*bucket_id\\s*=\\s*('(?:[^']|'')*')(\\s*::\\s*[[:alnum:]_\\.]+)?\\s*\\)*\\s*\\Z$re$,
+ 'i'
+ ) AS bucket_match(matches)
+ WHERE bucket_match.matches[1] = '''' || replace(b.id, '''', '''''') || ''''
+ )
+ )
+ ORDER BY p.policyname
`,
})
diff --git a/packages/common/constants/local-storage.ts b/packages/common/constants/local-storage.ts
index 5195a4af689..dc64600f289 100644
--- a/packages/common/constants/local-storage.ts
+++ b/packages/common/constants/local-storage.ts
@@ -118,6 +118,8 @@ export const LOCAL_STORAGE_KEYS = {
`table-editor-queue-operations-banner-dismissed-${ref}`,
FREE_MICRO_UPGRADE_BANNER_DISMISSED: (ref: string) =>
`free-micro-upgrade-banner-dismissed-${ref}`,
+ STORAGE_PUBLIC_BUCKET_SELECT_POLICY_WARNING_DISMISSED: (ref: string, bucketId: string) =>
+ `storage-public-bucket-select-policy-warning-dismissed-${ref}-${bucketId}`,
PRIVACY_NOTICE_ACKNOWLEDGED: 'privacy-notice-acknowledged-2026-03',
/**
diff --git a/packages/common/telemetry-constants.ts b/packages/common/telemetry-constants.ts
index 0761ce96623..ea9933f2f65 100644
--- a/packages/common/telemetry-constants.ts
+++ b/packages/common/telemetry-constants.ts
@@ -3010,6 +3010,38 @@ export interface StorageExplorerNavigateSubmittedEvent {
groups: TelemetryGroups
}
+/**
+ * User clicked the Remove policy button on the public bucket SELECT policy warning.
+ *
+ * @group Events
+ * @source studio
+ * @page /project/{ref}/storage/files/buckets/{bucketId}
+ */
+export interface StoragePublicBucketSelectPolicyRemovedEvent {
+ action: 'storage_public_bucket_select_policy_removed'
+ properties: {
+ /** The ID of the bucket whose SELECT policy was removed */
+ bucketId: string
+ }
+ groups: TelemetryGroups
+}
+
+/**
+ * User dismissed the public bucket SELECT policy warning banner.
+ *
+ * @group Events
+ * @source studio
+ * @page /project/{ref}/storage/files/buckets/{bucketId}
+ */
+export interface StoragePublicBucketSelectPolicyWarningDismissButtonClickedEvent {
+ action: 'storage_public_bucket_select_policy_warning_dismiss_button_clicked'
+ properties: {
+ /** The ID of the bucket whose warning was dismissed */
+ bucketId: string
+ }
+ groups: TelemetryGroups
+}
+
/**
* User was exposed to the pricing value/flexibility experiment on the /pricing page.
*
@@ -3127,6 +3159,8 @@ export type TelemetryEvent =
| LogExplorerQueryRunButtonClickedEvent
| StorageExplorerNavigateClickedEvent
| StorageExplorerNavigateSubmittedEvent
+ | StoragePublicBucketSelectPolicyRemovedEvent
+ | StoragePublicBucketSelectPolicyWarningDismissButtonClickedEvent
| StudioPricingPlanCtaClickedEvent
| StudioPricingSidePanelOpenedEvent
| ReportsDatabaseGrafanaBannerClickedEvent
diff --git a/packages/pg-meta/src/sql/studio/advisor/lints.ts b/packages/pg-meta/src/sql/studio/advisor/lints.ts
index dbd155ea77f..e7609f6452f 100644
--- a/packages/pg-meta/src/sql/studio/advisor/lints.ts
+++ b/packages/pg-meta/src/sql/studio/advisor/lints.ts
@@ -1408,4 +1408,101 @@ where
order by
schema_name,
table_name,
- policy_name)`.trim()
+ policy_name)
+union all
+(
+with public_buckets as (
+ select
+ (xpath('/row/id/text()', bucket_xml))[1]::text as bucket_id,
+ (xpath('/row/name/text()', bucket_xml))[1]::text as bucket_name
+ from unnest(
+ case when pg_catalog.to_regclass('storage.buckets') is not null
+ then xpath(
+ '/table/row',
+ pg_catalog.query_to_xml(
+ 'select id, name from storage.buckets where public = true order by id',
+ false,
+ false,
+ ''
+ )
+ )
+ else array[]::xml[]
+ end
+ ) as bucket_xml
+),
+matching_policies as (
+ select
+ b.bucket_id,
+ b.bucket_name,
+ p.policyname
+ from
+ public_buckets b
+ join pg_catalog.pg_policies p
+ on p.schemaname = 'storage'
+ and p.tablename = 'objects'
+ and p.cmd in ('SELECT', 'ALL')
+ and p.permissive = 'PERMISSIVE'
+ and p.roles && array['public'::name, 'anon'::name, 'authenticated'::name]
+ where
+ (
+ p.qual is null
+ or replace(replace(replace(lower(p.qual), ' ', ''), E'\n', ''), E'\t', '')
+ in ('true', '(true)', '1=1', '(1=1)')
+ or exists (
+ select
+ 1
+ from
+ pg_catalog.regexp_match(
+ p.qual,
+ $re$\\A\\s*\\(*\\s*bucket_id\\s*=\\s*('(?:[^']|'')*')(\\s*::\\s*[[:alnum:]_\\.]+)?\\s*\\)*\\s*\\Z$re$,
+ 'i'
+ ) as bucket_match(matches)
+ where
+ bucket_match.matches[1] = '''' || replace(b.bucket_id, '''', '''''') || ''''
+ )
+ )
+),
+affected_buckets as (
+ select
+ bucket_id,
+ bucket_name,
+ array_agg(policyname order by policyname) as policy_names,
+ count(*)::int as policy_count
+ from
+ matching_policies
+ group by
+ bucket_id,
+ bucket_name
+)
+select
+ 'public_bucket_allows_listing' as name,
+ 'Public Bucket Allows Listing' as title,
+ 'WARN' as level,
+ 'EXTERNAL' as facing,
+ array['SECURITY'] as categories,
+ 'Detects public storage buckets with a broad SELECT policy on \`storage.objects\`, which allows clients to list all files in the bucket.' as description,
+ format(
+ 'Public bucket \`%s\` has %s broad SELECT %s on \`storage.objects\` (%s), allowing clients to list all files. Public buckets don''t need this for object URL access and it may expose more data than intended.',
+ bucket_name,
+ policy_count,
+ case
+ when policy_count = 1 then 'policy'
+ else 'policies'
+ end,
+ array_to_string(policy_names, ', ')
+ ) as detail,
+ '${docsUrl}/guides/database/database-linter?lint=0025_public_bucket_allows_listing' as remediation,
+ jsonb_build_object(
+ 'schema', 'storage',
+ 'name', bucket_name,
+ 'type', 'bucket',
+ 'bucket_id', bucket_id,
+ 'bucket_name', bucket_name,
+ 'policy_names', policy_names,
+ 'policy_count', policy_count
+ ) as metadata,
+ format('public_bucket_allows_listing_%s', bucket_id) as cache_key
+from
+ affected_buckets
+order by
+ bucket_id)`.trim()