Files
supabase/apps/studio/components/interfaces/Linter/GraphqlExposureLintCTA.tsx
Charis c0e92057a6 feat(studio): split SQL errors into user and Studio SQL (#53059)
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.
2026-11-09 09:47:35 -05:00

204 lines
7.0 KiB
TypeScript

import { ident, safeSql } from '@supabase/pg-meta/src/pg-format'
import { useQueryClient } from '@tanstack/react-query'
import { EyeOffIcon, LockIcon } from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'
import { Badge, Button } from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { InlineLink } from '@/components/ui/InlineLink'
import { unguarded } from '@/data/fetchers'
import { lintKeys } from '@/data/lint/keys'
import { Lint } from '@/data/lint/lint-query'
import { useExecuteSqlMutation } from '@/data/sql/execute-sql-mutation'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
const GRAPHQL_EXPOSURE_LINT_NAMES = [
'pg_graphql_anon_table_exposed',
'pg_graphql_authenticated_table_exposed',
] as const
export type GraphqlExposureLintName = (typeof GRAPHQL_EXPOSURE_LINT_NAMES)[number]
export const asGraphqlExposureLint = (
name: string | undefined | null
): GraphqlExposureLintName | null =>
!!name && (GRAPHQL_EXPOSURE_LINT_NAMES as readonly string[]).includes(name)
? (name as GraphqlExposureLintName)
: null
interface GraphqlExposureLintCTAProps {
lintName: GraphqlExposureLintName
projectRef: string
metadata: Lint['metadata']
onAfterAction?: () => void
}
const ROLE_BY_LINT: Record<GraphqlExposureLintName, 'anon' | 'authenticated'> = {
pg_graphql_anon_table_exposed: 'anon',
pg_graphql_authenticated_table_exposed: 'authenticated',
}
const AUDIENCE: Record<GraphqlExposureLintName, { lower: string; upper: string }> = {
pg_graphql_anon_table_exposed: { lower: 'anonymous users', upper: 'Anonymous users' },
pg_graphql_authenticated_table_exposed: { lower: 'signed-in users', upper: 'Signed-in users' },
}
const TRIGGER_LABEL: Record<GraphqlExposureLintName, string> = {
pg_graphql_anon_table_exposed: 'Remove access for anonymous users',
pg_graphql_authenticated_table_exposed: 'Remove access for signed-in users',
}
export const GraphqlExposureLintCTA = ({
lintName,
projectRef,
metadata,
onAfterAction,
}: GraphqlExposureLintCTAProps) => {
const { data: project } = useSelectedProjectQuery()
const queryClient = useQueryClient()
const [showConfirmRevoke, setShowConfirmRevoke] = useState(false)
const schema = metadata?.schema
const name = metadata?.name
const objectType = metadata?.type ?? 'object'
const role = ROLE_BY_LINT[lintName]
const audience = AUDIENCE[lintName]
const canAct = !!schema && !!name
const revokeSql =
schema && name
? safeSql`revoke all on ${ident(schema)}.${ident(name)} from ${ident(role)};`
: undefined
const { mutate: executeSql, isPending: isRevoking } = useExecuteSqlMutation({
onSuccess: async () => {
toast.success(
`Revoked access to ${schema}.${name} from ${role}. ${audience.upper} can no longer query this ${objectType} via GraphQL or Data API.`
)
setShowConfirmRevoke(false)
await queryClient.invalidateQueries({ queryKey: lintKeys.lint(projectRef) })
onAfterAction?.()
},
onError: (error) => {
toast.error(`Failed to revoke access: ${error.message}`)
},
})
const handleRevoke = () => {
if (!revokeSql) return
executeSql({
projectRef,
connectionString: project?.connectionString,
sqlOrigin: 'studio',
queryName: 'graphql-exposure-revoke',
sql: revokeSql,
grant: unguarded.migrating,
})
}
return (
<>
<Button variant="primary" disabled={!canAct} onClick={() => setShowConfirmRevoke(true)}>
{TRIGGER_LABEL[lintName]}
</Button>
<ConfirmationModal
visible={showConfirmRevoke}
size="xlarge"
title={
canAct
? `Remove access to ${schema}.${name} for ${audience.lower}?`
: `Remove access for ${audience.lower}?`
}
confirmLabel="Remove access"
confirmLabelLoading="Removing access..."
cancelLabel="Cancel"
loading={isRevoking}
onCancel={() => setShowConfirmRevoke(false)}
onConfirm={handleRevoke}
>
<div className="text-sm text-foreground mb-6">
<p>This change affects both schema visibility and data access for {audience.lower}.</p>
<p>
Alternatively, you can{' '}
<InlineLink href={`/project/${projectRef}/database/extensions`}>
disable GraphQL
</InlineLink>{' '}
to remove schema visibility.
</p>
</div>
<div className="space-y-5">
<div className="flex gap-3">
<LockIcon
className="text-foreground-light shrink-0 mt-0.5"
size={20}
strokeWidth={1.5}
/>
<div>
<div className="flex items-center gap-2">
<p className="text-sm text-foreground">Data API access removed</p>
<Badge variant="warning">Breaking change</Badge>
</div>
<p className="text-sm text-foreground-light mt-1">
{audience.upper} will no longer be able to read or write to this {objectType} via
Supabase APIs (GraphQL or Data API), even if RLS policies allow it.
</p>
</div>
</div>
<div className="flex gap-3">
<EyeOffIcon
className="text-foreground-light shrink-0 mt-0.5"
size={20}
strokeWidth={1.5}
/>
<div>
<p className="text-sm text-foreground">Schema hidden from GraphQL</p>
<p className="text-sm text-foreground-light mt-1">
This {objectType} will no longer appear in the GraphQL schema. {audience.upper}{' '}
won't be able to discover its name, columns, or relationships.
</p>
</div>
</div>
</div>
<Admonition
type="warning"
title="When to keep access"
description={`If your app needs ${audience.lower} to query this ${objectType}, keep access and ignore this warning. Be aware that this ${objectType}'s schema will remain visible via the GraphQL API.`}
className="mt-6"
/>
<p className="text-sm text-foreground-light mt-6">
The following statement will be executed:
</p>
<pre className="mt-2 px-3 py-2 rounded bg-surface-200 text-xs font-mono whitespace-pre-wrap break-all">
{revokeSql}
</pre>
</ConfirmationModal>
</>
)
}
export const GraphqlExposureCallout = ({ projectRef }: { projectRef: string }) => {
return (
<Admonition
type="default"
title="Why this appears"
description={
<p>
These warnings are triggered by GraphQL exposing your table schemas. If you're not using
GraphQL, disable it from the{' '}
<InlineLink href={`/project/${projectRef}/database/extensions`}>
Database extensions page
</InlineLink>
.
</p>
}
/>
)
}