mirror of
https://github.com/supabase/supabase.git
synced 2026-12-06 08:29:01 +00:00
## Problem `AlertError` gives users and support no way to correlate a failure with Sentry or platform logs. It also treats every failure the same: a bad table editor filter or an offline browser gets "try refreshing, contact support". On the reporting side, SQL errors were attributed by who wrote the whole statement. That made errors in the user's part of mixed SQL Studio's fault: policy expressions, function bodies, cron schedules, table editor filters and row edits. Marking them as user SQL instead would drop them from Sentry entirely. Part of FE-4772. ## Solution **`AlertError`** - Platform and Studio faults show the request ID, the Sentry event ID (labeled "before sampling", since the event may be sampled out) and a "Copy details" button. - The copied text never includes `formattedError`, metadata, the cause or SQL. - SQL errors copy the SQLSTATE, position and query name instead of the message. - User faults (`isUserError`) show their message with "Please try again. If the issue persists, try refreshing your browser." There is no support link, no IDs and no copy button. - Offline shows only "You may be temporarily offline. Check your internet connection and try again." - Defaults come from `getErrorPresentation`, and props the caller passes still win. The table editor passes a filter-specific description when filters are set. **SQL error classification** - `executeSql` takes an optional `isUserFaultSqlState` predicate for Studio SQL. When it matches, the error is a `StudioSqlError` with reason `user_input` and fault `user`, and is still redacted to SQLSTATE plus query name. - `isUserFaultForValues` (classes 22, 23 and P0, plus 42501 and 57014) is for typed values: table editor filters and row edits, cron name and schedule. - `isUserFaultForSql` (any SQLSTATE except server classes 08, 53, 57 other than 57014, 58 and XX) is for embedded user SQL: policies, functions, the custom access token hook. - `isUserFaultForStatsStatement` is for `pg_stat_statements` text (Query Insights `EXPLAIN`, index advisor). It treats 42P02 (`$1` placeholders) as Studio's fault. - `UserSqlError` is now only SQL the user wrote in full, and it is still never sent. - The policy, function and cron mutation hooks no longer take `sqlOrigin`. **Routing and types** - `ERROR_ROUTING` is one table keyed by tag, then by fault. Its type requires exactly the faults each class can produce. - User faults get `SAMPLE_USER_FAULT` (default 0.01, set with `NEXT_PUBLIC_SENTRY_SAMPLE_RATE_USER_FAULT`) to catch misclassification. - The error class decides privacy (`isNeverReportedError`), separately from the rate. - Sentry events get a `reason` tag. - Each class declares its `reasons`, so a mistyped reason fails typecheck. ## Review instructions 1. Open the table editor, add a filter with a wrong-typed value (text on an integer column). The alert shows the Postgres error, the filter hint, and no support link, IDs or copy button. 2. Make a query fail with a platform error (e.g. block a `/platform/` request in DevTools). The alert shows the request ID, the event ID and "Copy details". Paste the copied text and check it has no SQL or `formattedError`. 3. Go offline in DevTools and trigger a query. Only the offline message shows. 4. Create a policy with an invalid `USING` expression. The toast shows the Postgres error. In Sentry it is a `StudioSqlError` with reason `user_input`, sampled at the user-fault rate. 5. Review `lib/errors/error-routing.ts` and `data/error-classification.ts` for the routing table and the SQLSTATE predicates.
323 lines
11 KiB
TypeScript
323 lines
11 KiB
TypeScript
import { ident, literal, safeSql } from '@supabase/pg-meta/src/pg-format'
|
|
import { useConstant } from 'common'
|
|
import {
|
|
createContext,
|
|
PropsWithChildren,
|
|
useCallback,
|
|
useContext,
|
|
useEffect,
|
|
useRef,
|
|
useState,
|
|
} from 'react'
|
|
import { proxy, snapshot, subscribe, useSnapshot } from 'valtio'
|
|
|
|
import {
|
|
CustomAccessTokenHookDetails,
|
|
useCustomAccessTokenHookDetails,
|
|
} from '../hooks/misc/useCustomAccessTokenHookDetails'
|
|
import { isUserFaultForSql } from '@/data/error-classification'
|
|
import { unguarded } from '@/data/fetchers'
|
|
import { executeSql } from '@/data/sql/execute-sql-mutation'
|
|
import { useLatest } from '@/hooks/misc/useLatest'
|
|
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
|
|
import { getPostgrestClaims, ImpersonationRole } from '@/lib/role-impersonation'
|
|
|
|
type PostgrestClaims = ReturnType<typeof getPostgrestClaims>
|
|
type CustomizeAccessToken = (args: {
|
|
schema: string
|
|
functionName: string
|
|
claims: PostgrestClaims
|
|
}) => Promise<unknown>
|
|
|
|
/** Calls the project's customize-access-token hook, shared by the global context and any
|
|
* per-instance controller so the RPC-calling logic isn't duplicated between them. */
|
|
function useCustomizeAccessToken(
|
|
projectRef: string | undefined,
|
|
connectionString: string | null | undefined
|
|
): CustomizeAccessToken {
|
|
return useCallback(
|
|
async ({ schema, functionName, claims }) => {
|
|
const event = { user_id: claims.sub, claims, authentication_method: 'password' }
|
|
|
|
const result = await executeSql({
|
|
projectRef,
|
|
connectionString,
|
|
// The hook is the user's own function: Studio wrote the call, the user wrote what it runs
|
|
sqlOrigin: 'studio',
|
|
queryName: 'customize-access-token-hook',
|
|
isUserFaultSqlState: isUserFaultForSql,
|
|
sql: safeSql`select ${ident(schema)}.${ident(functionName)}(${literal(JSON.stringify(event))}::jsonb) as event;`,
|
|
queryKey: ['customize-access-token', projectRef],
|
|
grant: unguarded.migrating,
|
|
})
|
|
|
|
return result?.result?.[0]?.event?.claims
|
|
},
|
|
[projectRef, connectionString]
|
|
)
|
|
}
|
|
|
|
/** Computes the claims for a role selection, refining them through the customize-access-token
|
|
* hook when one is configured. Shared by `createRoleImpersonationState` (global context) and
|
|
* `useLocalRoleImpersonationState` (per-instance) so both resolve claims identically. */
|
|
async function resolveRoleClaims(
|
|
projectRef: string,
|
|
role: ImpersonationRole | undefined,
|
|
customAccessTokenHookDetails: CustomAccessTokenHookDetails | undefined,
|
|
customizeAccessToken: CustomizeAccessToken
|
|
): Promise<PostgrestClaims | undefined> {
|
|
let claims = role?.type === 'postgrest' ? getPostgrestClaims(projectRef, role) : undefined
|
|
|
|
if (customAccessTokenHookDetails?.type === 'postgres' && claims !== undefined) {
|
|
const { schema, functionName } = customAccessTokenHookDetails
|
|
const updatedClaims = await customizeAccessToken({ schema, functionName, claims })
|
|
// The hook is an arbitrary user-defined Postgres function — its output can't be
|
|
// statically typed, so we trust it wholesale here rather than partially.
|
|
if (updatedClaims) claims = updatedClaims as PostgrestClaims
|
|
}
|
|
|
|
return claims
|
|
}
|
|
|
|
export function createRoleImpersonationState(
|
|
projectRef: string,
|
|
customizeAccessTokenRef: { current: CustomizeAccessToken }
|
|
) {
|
|
const roleImpersonationState = proxy({
|
|
projectRef,
|
|
role: undefined as ImpersonationRole | undefined,
|
|
claims: undefined as PostgrestClaims | undefined,
|
|
|
|
setRole: async (
|
|
role: ImpersonationRole | undefined,
|
|
customAccessTokenHookDetails?: CustomAccessTokenHookDetails
|
|
) => {
|
|
const claims = await resolveRoleClaims(
|
|
projectRef,
|
|
role,
|
|
customAccessTokenHookDetails,
|
|
customizeAccessTokenRef.current
|
|
)
|
|
|
|
roleImpersonationState.role = role
|
|
if (claims) {
|
|
roleImpersonationState.claims = claims
|
|
}
|
|
},
|
|
})
|
|
|
|
return roleImpersonationState
|
|
}
|
|
|
|
export type RoleImpersonationState = ReturnType<typeof createRoleImpersonationState>
|
|
|
|
export type RoleImpersonationController = Pick<
|
|
RoleImpersonationState,
|
|
'role' | 'claims' | 'setRole'
|
|
>
|
|
|
|
export const RoleImpersonationStateContext = createContext<RoleImpersonationState>(
|
|
createRoleImpersonationState('', { current: async () => undefined })
|
|
)
|
|
|
|
export const RoleImpersonationStateContextProvider = ({ children }: PropsWithChildren) => {
|
|
const { data: project } = useSelectedProjectQuery()
|
|
const customizeAccessToken = useCustomizeAccessToken(project?.ref, project?.connectionString)
|
|
const customizeAccessTokenRef = useLatest(customizeAccessToken)
|
|
|
|
const state = useConstant(() =>
|
|
createRoleImpersonationState(project?.ref ?? '', customizeAccessTokenRef)
|
|
)
|
|
|
|
return (
|
|
<RoleImpersonationStateContext.Provider value={state}>
|
|
{children}
|
|
</RoleImpersonationStateContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function useRoleImpersonationStateSnapshot(options?: Parameters<typeof useSnapshot>[1]) {
|
|
const roleImpersonationState = useContext(RoleImpersonationStateContext)
|
|
|
|
return useSnapshot(roleImpersonationState, options)
|
|
}
|
|
|
|
/**
|
|
* A role impersonation controller scoped to a single component instance instead of the
|
|
* shared project-wide context — for surfaces (e.g. a notebook query cell) that need their
|
|
* own independent "run as" selection rather than sharing the one global impersonation state.
|
|
*
|
|
* [Joshen] FWIW we might deprecate this method after hooking things up E2E since QueryCell's
|
|
* role impersonation likely needs to be persisted also
|
|
*/
|
|
export function useLocalRoleImpersonationState(): RoleImpersonationController {
|
|
const { data: project } = useSelectedProjectQuery()
|
|
const customizeAccessToken = useCustomizeAccessToken(project?.ref, project?.connectionString)
|
|
const customizeAccessTokenRef = useLatest(customizeAccessToken)
|
|
const projectRef = project?.ref ?? ''
|
|
|
|
const [role, setRoleValue] = useState<ImpersonationRole | undefined>(undefined)
|
|
const [claims, setClaims] = useState<PostgrestClaims | undefined>(undefined)
|
|
|
|
const setRole = useCallback(
|
|
async (
|
|
nextRole: ImpersonationRole | undefined,
|
|
customAccessTokenHookDetails?: CustomAccessTokenHookDetails
|
|
) => {
|
|
const nextClaims = await resolveRoleClaims(
|
|
projectRef,
|
|
nextRole,
|
|
customAccessTokenHookDetails,
|
|
customizeAccessTokenRef.current
|
|
)
|
|
|
|
setRoleValue(nextRole)
|
|
if (nextClaims) setClaims(nextClaims)
|
|
},
|
|
[projectRef, customizeAccessTokenRef]
|
|
)
|
|
|
|
return { role, claims, setRole }
|
|
}
|
|
|
|
/**
|
|
* Like `useLocalRoleImpersonationState`, but the role selection is controlled externally
|
|
* (e.g. persisted per query tab) instead of held in local component state — for surfaces
|
|
* where the selection needs to survive beyond this component instance's lifetime. Claims
|
|
* stay local regardless: they're derived, time-bound tokens, so they're recomputed whenever
|
|
* the controlled role changes rather than persisted alongside it.
|
|
*/
|
|
export function useControlledRoleImpersonationState(
|
|
role: ImpersonationRole | undefined,
|
|
onRoleChange: (role: ImpersonationRole | undefined) => void
|
|
): RoleImpersonationController {
|
|
const { data: project } = useSelectedProjectQuery()
|
|
const customizeAccessToken = useCustomizeAccessToken(project?.ref, project?.connectionString)
|
|
|
|
const projectRef = project?.ref ?? ''
|
|
const customizeAccessTokenRef = useLatest(customizeAccessToken)
|
|
const customAccessTokenHookDetails = useCustomAccessTokenHookDetails(project?.ref)
|
|
const customAccessTokenHookDetailsRef = useLatest(customAccessTokenHookDetails)
|
|
const onRoleChangeRef = useLatest(onRoleChange)
|
|
|
|
const [claims, setClaims] = useState<PostgrestClaims | undefined>(undefined)
|
|
|
|
// Guards against re-resolving claims for a role change that `setRole` below just resolved
|
|
// itself — without it, every selection would re-run the (possibly RPC-backed) resolution
|
|
// twice: once eagerly in `setRole`, once again here once `role` updates on the next render.
|
|
const skipNextResolveRef = useRef(false)
|
|
|
|
useEffect(() => {
|
|
if (skipNextResolveRef.current) {
|
|
skipNextResolveRef.current = false
|
|
return
|
|
}
|
|
|
|
let cancelled = false
|
|
|
|
resolveRoleClaims(
|
|
projectRef,
|
|
role,
|
|
customAccessTokenHookDetailsRef.current,
|
|
customizeAccessTokenRef.current
|
|
).then((nextClaims) => {
|
|
if (!cancelled) setClaims(nextClaims)
|
|
})
|
|
|
|
return () => {
|
|
cancelled = true
|
|
}
|
|
// Resolves only when the controlled role identity changes (e.g. switching tabs)
|
|
}, [customAccessTokenHookDetailsRef, customizeAccessTokenRef, projectRef, role])
|
|
|
|
const setRole = useCallback(
|
|
async (
|
|
nextRole: ImpersonationRole | undefined,
|
|
customAccessTokenHookDetails?: CustomAccessTokenHookDetails
|
|
) => {
|
|
// Captured before the await: if the controlling tab changes while this resolution is
|
|
// in flight, `onRoleChangeRef.current` will point at a different tab's callback by the
|
|
// time we get here. Comparing against the captured reference lets us detect that and
|
|
// discard the result instead of writing this role/claims into the wrong tab.
|
|
const onRoleChangeAtCallTime = onRoleChangeRef.current
|
|
|
|
const nextClaims = await resolveRoleClaims(
|
|
projectRef,
|
|
nextRole,
|
|
customAccessTokenHookDetails ?? customAccessTokenHookDetailsRef.current,
|
|
customizeAccessTokenRef.current
|
|
)
|
|
|
|
if (onRoleChangeRef.current !== onRoleChangeAtCallTime) return
|
|
|
|
skipNextResolveRef.current = true
|
|
onRoleChangeAtCallTime(nextRole)
|
|
setClaims(nextClaims)
|
|
},
|
|
[projectRef, customizeAccessTokenRef, customAccessTokenHookDetailsRef, onRoleChangeRef]
|
|
)
|
|
|
|
return { role, claims, setRole }
|
|
}
|
|
|
|
export function useGetImpersonatedRoleState() {
|
|
const roleImpersonationState = useContext(RoleImpersonationStateContext)
|
|
|
|
return useCallback(
|
|
// [Alaister]: typeof roleImpersonationState is needed to avoid readonly type errors everywhere
|
|
() => snapshot(roleImpersonationState) as typeof roleImpersonationState,
|
|
[roleImpersonationState]
|
|
)
|
|
}
|
|
|
|
export function useSubscribeToImpersonatedRole(
|
|
onChange: (role: ImpersonationRole | undefined) => void
|
|
) {
|
|
const roleImpersonationState = useContext(RoleImpersonationStateContext)
|
|
const onChangeRef = useLatest(onChange)
|
|
|
|
useEffect(() => {
|
|
return subscribe(roleImpersonationState, () => {
|
|
onChangeRef.current(snapshot(roleImpersonationState).role)
|
|
})
|
|
}, [roleImpersonationState])
|
|
}
|
|
|
|
export function isRoleImpersonationEnabled(impersonationRole?: ImpersonationRole) {
|
|
return impersonationRole?.type === 'postgrest'
|
|
}
|
|
|
|
export const useIsImpersonatingAnon = () => {
|
|
const state = useRoleImpersonationStateSnapshot()
|
|
return state.role?.type === 'postgrest' && state.role.role === 'anon'
|
|
}
|
|
|
|
export const useImpersonatedUser = () => {
|
|
const state = useRoleImpersonationStateSnapshot()
|
|
return state.role?.type === 'postgrest' &&
|
|
state.role.role === 'authenticated' &&
|
|
state.role.userType === 'native'
|
|
? state.role.user
|
|
: undefined
|
|
}
|
|
|
|
export const useImpersonatedExternalAuth = () => {
|
|
const state = useRoleImpersonationStateSnapshot()
|
|
return state.role?.type === 'postgrest' &&
|
|
state.role.role === 'authenticated' &&
|
|
state.role.userType === 'external' &&
|
|
state.role.externalAuth
|
|
? state.role.externalAuth.sub
|
|
: undefined
|
|
}
|
|
|
|
export const useImpersonatedAAL = () => {
|
|
const state = useRoleImpersonationStateSnapshot()
|
|
return (
|
|
state.role?.type === 'postgrest' &&
|
|
state.role.role === 'authenticated' &&
|
|
state.role.userType === 'external' &&
|
|
state.role.aal
|
|
)
|
|
}
|