mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
Part of FE-4772. ## Why Errors from the pg-meta query endpoint didn't say who wrote the SQL, so a Sentry issue like SUPABASE-APP-KXE couldn't tell a user's query from one Studio composed. That event came from the assistant's `execute_sql` tool and was captured by the Vercel AI integration on the server, so it skipped `reportStudioError` and had no fault tags. The Postgres message also went to Sentry as-is, and it can contain user SQL and data. ## What - **`sqlOrigin` is required on `executeSql`.** `'user'` covers SQL the user or an AI agent wrote, in whole or in part: SQL editor, editor panel, Explorer, AI `execute_sql` and `run_notebook`, report blocks, Query Insights EXPLAIN, the policy, function, and cron editors, and running a stored cron job. Everything else is `'studio'`. The policy, function, and cron mutation hooks and `useDbQuery` take `sqlOrigin` too. - **`classifySqlResponseError`** turns a 400 from the query endpoint into `UserSqlError` (`user`, `user_sql`) or `StudioSqlError` (`studio`, `studio_sql`). Pattern rules (connection timeouts) and other statuses keep their classes. - **`UserSqlError` never reaches Sentry.** Its routing is `SAMPLE_NEVER`, `alwaysCapture` doesn't override it, and `beforeSend` drops it. - **`StudioSqlError` is redacted.** Error classes can set `sentryMessage`; for `StudioSqlError` it is the SQLSTATE and the query's `queryName`, a static name that `executeSql` requires for Studio SQL. The query key is never reported, since its segments can hold IDs, schemas, and search terms. `applyStudioErrorPolicy` applies it from `beforeSend` on the client and the server, so it holds however the error was captured. The server config gets a `beforeSend` for this. Events get `query_name` and `sql_state` tags and are grouped by both, since every SQL error shares the `executeSql` stack. - **A custom `handleError` gets the classified error**, matching its declared type. The SQL editor, editor panel, and policy editor rethrow it, so their errors are now `UserSqlError` instead of being reported as `UnexpectedError`. The error keeps Postgres's `position` for the editor's line highlight. The error message, `formattedError`, and `position` stay on the error for the UI. The query-performance Sentry context no longer carries the raw error message, which bypassed redaction. ## Known gaps - Index advisor queries run users' query text from `pg_stat_statements` but are marked `'studio'`. Redaction keeps the text out of Sentry, but their failures count as Studio faults. - 5xx responses for user SQL are still `PlatformError` and keep their message. - The self-hosted MCP `executeSql` calls `executeQuery` directly and isn't covered. ## Testing - Unit tests for `classifySqlResponseError`, `applyStudioErrorPolicy`, and the client `beforeSend`. - Full Studio vitest suite passes except `useReportDateRange.test.ts` (169 vs 168 hourly buckets across the DST change), which this PR doesn't touch.
230 lines
7.7 KiB
TypeScript
230 lines
7.7 KiB
TypeScript
import { ident, safeSql } from '@supabase/pg-meta/src/pg-format'
|
||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||
import { LOCAL_STORAGE_KEYS, safeLocalStorage } from 'common'
|
||
import { useEffect, useState, type ReactNode } from 'react'
|
||
import { toast } from 'sonner'
|
||
import { Button } from 'ui'
|
||
import { Admonition } from 'ui-patterns/Admonition'
|
||
import { CodeBlock } from 'ui-patterns/CodeBlock'
|
||
import { ConfirmationModal } from 'ui-patterns/Dialogs/ConfirmationModal'
|
||
|
||
import { databasePoliciesKeys } from '@/data/database-policies/keys'
|
||
import { unguarded } from '@/data/fetchers'
|
||
import { executeSql } from '@/data/sql/execute-sql-mutation'
|
||
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 = safeLocalStorage.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 {
|
||
safeLocalStorage.setItem(
|
||
LOCAL_STORAGE_KEYS.STORAGE_PUBLIC_BUCKET_SELECT_POLICY_WARNING_DISMISSED(projectRef, bucketId),
|
||
JSON.stringify({ dismissedAt: new Date().toISOString() })
|
||
)
|
||
}
|
||
|
||
function generatePolicyRemovalSql(policyName: string) {
|
||
return safeSql`DROP POLICY IF EXISTS ${ident(policyName)} ON storage.objects;`
|
||
}
|
||
|
||
export interface PublicBucketWarningProps {
|
||
projectRef: string
|
||
bucketId: string
|
||
}
|
||
|
||
export function PublicBucketWarning({ projectRef, bucketId }: PublicBucketWarningProps): ReactNode {
|
||
const queryClient = useQueryClient()
|
||
const { data: project } = useSelectedProjectQuery()
|
||
|
||
const { data } = usePublicBucketsWithSelectPoliciesQuery({
|
||
projectRef,
|
||
connectionString: project?.connectionString,
|
||
bucketId,
|
||
})
|
||
const policyToRemove = data?.[0]
|
||
const matchingPolicyCount = data?.length ?? 0
|
||
|
||
const track = useTrack()
|
||
|
||
const { mutate: removePolicy, isPending: isRemovingPolicy } = useMutation({
|
||
mutationFn: async (policyName: string) => {
|
||
await executeSql({
|
||
projectRef,
|
||
connectionString: project?.connectionString,
|
||
sqlOrigin: 'studio',
|
||
queryName: 'public-bucket-policy-remove',
|
||
sql: generatePolicyRemovalSql(policyName),
|
||
grant: unguarded.migrating,
|
||
})
|
||
},
|
||
onSuccess: async () => {
|
||
await Promise.all([
|
||
queryClient.invalidateQueries({
|
||
queryKey: storageKeys.publicBucketsWithSelectPolicies(projectRef, bucketId),
|
||
}),
|
||
queryClient.invalidateQueries({
|
||
queryKey: databasePoliciesKeys.list(projectRef, ['storage']),
|
||
}),
|
||
])
|
||
track('storage_public_bucket_select_policy_removed', { bucketId })
|
||
setShowModal(false)
|
||
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)
|
||
toast.error(`Failed to remove policy: ${error.message}`)
|
||
},
|
||
})
|
||
|
||
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 && !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" />
|
||
)
|
||
}
|
||
|
||
type PublicBucketWarningViewProps_NoPolicyToRemove = {
|
||
_tag: 'no-policy-to-remove'
|
||
}
|
||
|
||
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 =
|
||
| PublicBucketWarningViewProps_NoPolicyToRemove
|
||
| PublicBucketWarningViewProps_PolicyToRemove
|
||
|
||
function PublicBucketWarningView(props: PublicBucketWarningViewProps): ReactNode {
|
||
if (props._tag === 'no-policy-to-remove') {
|
||
return null
|
||
}
|
||
|
||
const {
|
||
policyName,
|
||
policyCount,
|
||
isRemovingPolicy,
|
||
onRemovePolicy,
|
||
isModalVisible,
|
||
onShowModal,
|
||
onHideModal,
|
||
onDismiss,
|
||
} = props
|
||
const hasMultiplePolicies = policyCount > 1
|
||
|
||
return (
|
||
<>
|
||
<Admonition
|
||
type="warning"
|
||
layout="horizontal"
|
||
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={
|
||
<div className="flex gap-2">
|
||
<Button size="tiny" onClick={onDismiss}>
|
||
Dismiss
|
||
</Button>
|
||
<Button variant="warning" size="tiny" onClick={onShowModal}>
|
||
Remove policy
|
||
</Button>
|
||
</div>
|
||
}
|
||
/>
|
||
<ConfirmationModal
|
||
visible={isModalVisible}
|
||
variant="destructive"
|
||
title={
|
||
hasMultiplePolicies
|
||
? `Remove SELECT policy (1 of ${policyCount})`
|
||
: 'Remove SELECT policy'
|
||
}
|
||
confirmLabel="Remove policy"
|
||
loading={isRemovingPolicy}
|
||
onCancel={onHideModal}
|
||
onConfirm={onRemovePolicy}
|
||
>
|
||
<div className="flex flex-col gap-3">
|
||
<p className="text-sm text-foreground-light">
|
||
This will drop {hasMultiplePolicies ? <span>one</span> : <span>the</span>}{' '}
|
||
<code>SELECT</code>
|
||
{
|
||
' policy that makes the bucket’s contents listable. Object URLs will continue to work.'
|
||
}
|
||
{hasMultiplePolicies ? (
|
||
<span>{` ${policyCount - 1} matching ${
|
||
policyCount - 1 === 1 ? 'policy' : 'policies'
|
||
} will remain after this.`}</span>
|
||
) : null}
|
||
</p>
|
||
<div className="-mx-4 md:-mx-5 -mb-4 border-t">
|
||
<CodeBlock
|
||
hideLineNumbers
|
||
language="sql"
|
||
value={generatePolicyRemovalSql(policyName)}
|
||
wrapperClassName="[&_pre]:px-4 [&_pre]:py-3 [&>pre]:rounded-none [&>pre]:border-0 [&_pre>*]:whitespace-pre-wrap!"
|
||
className="[&_code]:text-foreground"
|
||
/>
|
||
</div>
|
||
</div>
|
||
</ConfirmationModal>
|
||
</>
|
||
)
|
||
}
|