Skip to content

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

joshenlim/fe 4176 add role impersonation to explorerquerysourcemenu (#49101)

Joshen Lim097a10566362
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerQuerySourceMenu.tsx b/apps/studio/components/interfaces/Explorer/ExplorerQuerySourceMenu.tsx
index 85d1094c37d..fb46469c4a6 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerQuerySourceMenu.tsx
+++ b/apps/studio/components/interfaces/Explorer/ExplorerQuerySourceMenu.tsx
@@ -10,6 +10,7 @@ import {
} from 'ui'
import { RowLimitSubMenu } from '../SQLEditor/UtilityPanel/QuerySourceMenu/RowLimitSubMenu'
+import { RunAsSubMenu } from '../SQLEditor/UtilityPanel/QuerySourceMenu/RunAsSubMenu'
import { DatabaseParametersSubMenu } from '@/components/interfaces/QuerySources/DatabaseParametersSubMenu'
import { LogsCustomRangeDialog } from '@/components/interfaces/QuerySources/LogsCustomRangeDialog'
import { LogsTimeRangeSubMenu } from '@/components/interfaces/QuerySources/LogsTimeRangeSubMenu'
@@ -22,10 +23,12 @@ import {
QUERY_SOURCES,
type QuerySourceBinding,
} from '@/data/query-sources/query-source-registry'
+import { type RoleImpersonationController } from '@/state/role-impersonation-state'
export type ExplorerQuerySourceMenuProps = {
rowLimit?: number
onRowLimitChange?: (val: number) => void
+ roleImpersonationState?: RoleImpersonationController
source: QuerySourceBinding
onSourceChange: (source: QuerySourceBinding) => void
}
@@ -42,6 +45,7 @@ export type ExplorerQuerySourceMenuProps = {
export const ExplorerQuerySourceMenu = ({
rowLimit = 100,
onRowLimitChange,
+ roleImpersonationState,
source,
onSourceChange,
}: ExplorerQuerySourceMenuProps) => {
@@ -109,6 +113,9 @@ export const ExplorerQuerySourceMenu = ({
onSourceChange({ _tag: 'database', database_identifier })
}
/>
+ {roleImpersonationState !== undefined && (
+ <RunAsSubMenu controlled state={roleImpersonationState} />
+ )}
{onRowLimitChange !== undefined && (
<RowLimitSubMenu
value={rowLimit}
diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
index a58d8445433..80adb841a03 100644
--- a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
@@ -21,6 +21,7 @@ import {
} from '@/data/content/notebooks/notebook-schema'
import { type QuerySourceBinding } from '@/data/query-sources/query-source-registry'
import { useCurrentNotebook, useNotebooksStateSnapshot } from '@/state/notebooks/notebooks-state'
+import { useLocalRoleImpersonationState } from '@/state/role-impersonation-state'
interface QueryCellProps {
cell: Snapshot<QueryCellSchema>
@@ -33,6 +34,7 @@ export const QueryCell = ({ cell }: QueryCellProps) => {
const [sql, setSql] = useState<string>(cell.unchecked_sql)
const [result, setResult] = useState<QueryResult>()
+ const roleImpersonationState = useLocalRoleImpersonationState()
const title = cell.title ?? 'Untitled query'
@@ -95,6 +97,7 @@ export const QueryCell = ({ cell }: QueryCellProps) => {
title={title}
query={toQueryModel(cell, sql)}
result={result}
+ roleImpersonationState={roleImpersonationState}
display={getCellDisplay(cell)}
onTitleChange={handleTitleChange}
onSqlChange={setSql}
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor.tsx
index a9116d848e5..1259b8714eb 100644
--- a/apps/studio/components/interfaces/Explorer/QueryEditor.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryEditor.tsx
@@ -45,6 +45,11 @@ import { useExecuteSqlMutation } from '@/data/sql/execute-sql-mutation'
import { applyAutoLimit } from '@/data/sql/utils'
import { useLatest } from '@/hooks/misc/useLatest'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
+import { wrapWithRoleImpersonation } from '@/lib/role-impersonation'
+import {
+ isRoleImpersonationEnabled,
+ type RoleImpersonationController,
+} from '@/state/role-impersonation-state'
/**
* The query this editor is showing, tagged by backend. The tag correlates the SQL's
@@ -69,6 +74,7 @@ export type QueryEditorProps = {
title: string
query: ExplorerQueryModel
result?: QueryResult
+ roleImpersonationState?: RoleImpersonationController
display?: QueryDisplay
toolbarActions?: ReactNode
onTitleChange: (title: string) => void
@@ -91,6 +97,7 @@ export const QueryEditor = ({
title,
query,
result,
+ roleImpersonationState,
display,
toolbarActions,
onTitleChange,
@@ -185,10 +192,11 @@ export const QueryEditor = ({
executeSql({
projectRef: project.ref,
connectionString,
- sql: limitedSql.sql,
+ sql: wrapWithRoleImpersonation(limitedSql.sql, roleImpersonationState),
autoLimit: limitedSql.appendAutoLimit ? rowLimit : undefined,
contextualInvalidation: true,
isStatementTimeoutDisabled: true,
+ isRoleImpersonationEnabled: isRoleImpersonationEnabled(roleImpersonationState?.role),
})
}
@@ -209,6 +217,7 @@ export const QueryEditor = ({
onSourceChange={onSourceChange}
rowLimit={rowLimit}
onRowLimitChange={onRowLimitChange}
+ roleImpersonationState={roleImpersonationState}
/>
)}
{display && onDisplayChange && (
diff --git a/apps/studio/components/interfaces/Explorer/QueryTab.tsx b/apps/studio/components/interfaces/Explorer/QueryTab.tsx
index 365dad0600d..ee94abf4ea8 100644
--- a/apps/studio/components/interfaces/Explorer/QueryTab.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryTab.tsx
@@ -8,6 +8,7 @@ import { QueryEditor, type ExplorerQueryModel } from './QueryEditor'
import { type QueryResult } from './types'
import { toQuerySourceBinding } from '@/data/query-sources/query-source-registry'
import { explorerQueryState, useExplorerQueryStateSnapshot } from '@/state/explorer-query'
+import { useLocalRoleImpersonationState } from '@/state/role-impersonation-state'
import { createTabId, TabsStateContext } from '@/state/tabs'
/** Query-tab lifecycle adapter around the shared QueryEditor. */
@@ -16,6 +17,7 @@ export const QueryTab = () => {
const router = useRouter()
const tabs = useContext(TabsStateContext)
const querySnap = useExplorerQueryStateSnapshot()
+ const roleImpersonationState = useLocalRoleImpersonationState()
const [rowLimit, setRowLimit] = useState<number>(100)
const [restoredQueryKey, setRestoredQueryKey] = useState<string>()
@@ -92,6 +94,7 @@ export const QueryTab = () => {
title={draft.name}
query={query}
result={result}
+ roleImpersonationState={roleImpersonationState}
onTitleChange={(value) => {
const name = value.trim() || 'Untitled query'
explorerQueryState.updateDraft({ id, name })
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx
index 01ce9af2de2..f649e93c9ae 100644
--- a/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx
@@ -34,12 +34,12 @@ import { useCustomAccessTokenHookDetails } from '@/hooks/misc/useCustomAccessTok
import { useLocalStorage } from '@/hooks/misc/useLocalStorage'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { DOCS_URL } from '@/lib/constants'
-import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state'
+import { type RoleImpersonationController } from '@/state/role-impersonation-state'
import type { ResponseError } from '@/types'
type AuthenticatorAssuranceLevels = 'aal1' | 'aal2'
-export const UserImpersonationSelector = () => {
+export const UserImpersonationSelector = ({ state }: { state: RoleImpersonationController }) => {
const [searchText, setSearchText] = useState('')
const [aal, setAal] = useState<AuthenticatorAssuranceLevels>('aal1')
const [externalUserId, setExternalUserId] = useState('')
@@ -53,7 +53,6 @@ export const UserImpersonationSelector = () => {
[]
)
- const state = useRoleImpersonationStateSnapshot()
const debouncedSearchText = useDebounce(searchText, 300)
const { data: project } = useSelectedProjectQuery()
@@ -179,7 +178,7 @@ export const UserImpersonationSelector = () => {
impersonatingUser.email ?? impersonatingUser.phone ?? impersonatingUser.id ?? 'Unknown'
)
: isExternalAuthImpersonating
- ? state.role.externalAuth.sub
+ ? isExternalAuthImpersonating.sub
: undefined
// Clear all search history
@@ -210,7 +209,7 @@ export const UserImpersonationSelector = () => {
)}
{isExternalAuthImpersonating && (
<ExternalAuthImpersonatingRow
- sub={state.role.externalAuth.sub}
+ sub={isExternalAuthImpersonating.sub}
onClick={stopImpersonating}
aal={aal}
isLoading={isImpersonateLoading}
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsx
index 4a9c1ee64de..634648b3d15 100644
--- a/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsx
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsx
@@ -7,7 +7,10 @@ import { UserImpersonationSelector } from './UserImpersonationSelector'
import { DocsButton } from '@/components/ui/DocsButton'
import { DOCS_URL } from '@/lib/constants'
import { PostgrestRole } from '@/lib/role-impersonation'
-import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state'
+import {
+ useRoleImpersonationStateSnapshot,
+ type RoleImpersonationController,
+} from '@/state/role-impersonation-state'
export interface RoleImpersonationSelectorProps {
header?: string
@@ -17,25 +20,38 @@ export interface RoleImpersonationSelectorProps {
orientation?: 'horizontal' | 'vertical'
}
-export const RoleImpersonationSelector = ({
- header = 'Impersonate a database role',
+/**
+ * Tightly coupled with the global role impersonation store
+ * Use RoleImpersonationSelectorInterface to control the logic externally
+ */
+export const RoleImpersonationSelector = (props: RoleImpersonationSelectorProps) => {
+ // valtio's Snapshot<> type is deep-readonly (incl. nested arrays), which isn't
+ // structurally assignable to RoleImpersonationController's plain array fields — same
+ // rationale as the cast in useGetImpersonatedRoleState.
+ const state = useRoleImpersonationStateSnapshot() as unknown as RoleImpersonationController
+
+ return <RoleImpersonationSelectorInterface {...props} state={state} />
+}
+
+type RoleImpersonationSelectorInterfaceProps = RoleImpersonationSelectorProps & {
+ state: RoleImpersonationController
+}
+
+export const RoleImpersonationSelectorInterface = ({
+ state,
+ orientation,
serviceRoleLabel = 'Postgres',
disallowAuthenticatedOption = false,
- orientation = 'horizontal',
-}: RoleImpersonationSelectorProps) => {
+ header = 'Impersonate a database role',
+}: RoleImpersonationSelectorInterfaceProps) => {
const isVertical = orientation === 'vertical'
- const state = useRoleImpersonationStateSnapshot()
-
- const [selectedOption, setSelectedOption] = useState<PostgrestRole | undefined>(() => {
- if (
- state.role?.type === 'postgrest' &&
- (state.role.role === 'anon' || state.role.role === 'authenticated')
- ) {
- return state.role.role
- }
- return 'service_role'
- })
+ const [selectedOption, setSelectedOption] = useState<PostgrestRole>(() =>
+ state.role?.type === 'postgrest' &&
+ (state.role.role === 'anon' || state.role.role === 'authenticated')
+ ? state.role.role
+ : 'service_role'
+ )
const isAuthenticatedOptionFullySelected = Boolean(
selectedOption === 'authenticated' &&
@@ -155,7 +171,7 @@ export const RoleImpersonationSelector = ({
{selectedOption === 'authenticated' && (
<CardContent className="p-0">
- <UserImpersonationSelector />
+ <UserImpersonationSelector state={state} />
</CardContent>
)}
</Card>
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/RunAsSubMenu.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/RunAsSubMenu.tsx
index a44a95d2d60..1f2b714a315 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/RunAsSubMenu.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/RunAsSubMenu.tsx
@@ -1,12 +1,25 @@
import { DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger } from 'ui'
-import { RoleImpersonationSelector } from '@/components/interfaces/RoleImpersonationSelector'
-import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state'
+import { RoleImpersonationSelectorInterface } from '@/components/interfaces/RoleImpersonationSelector'
+import {
+ useRoleImpersonationStateSnapshot,
+ type RoleImpersonationController,
+} from '@/state/role-impersonation-state'
const SERVICE_ROLE_LABEL = 'postgres'
-export const RunAsSubMenu = () => {
- const state = useRoleImpersonationStateSnapshot()
+type RunAsSubMenuProps =
+ | {
+ controlled?: false
+ }
+ | {
+ controlled: true
+ state: RoleImpersonationController
+ }
+
+export const RunAsSubMenu = (props: RunAsSubMenuProps) => {
+ const globalState = useRoleImpersonationStateSnapshot() as unknown as RoleImpersonationController
+ const state = props.controlled ? props.state : globalState
const currentRole = state.role?.role ?? SERVICE_ROLE_LABEL
return (
@@ -20,10 +33,11 @@ export const RunAsSubMenu = () => {
{/* Stops propagation so the authenticated-user search input isn't swallowed by the
dropdown's typeahead. */}
<DropdownMenuSubContent className="w-80 p-0" onKeyDown={(e) => e.stopPropagation()}>
- <RoleImpersonationSelector
+ <RoleImpersonationSelectorInterface
+ orientation="vertical"
header="Run SQL query as a role"
serviceRoleLabel={SERVICE_ROLE_LABEL}
- orientation="vertical"
+ state={state}
/>
</DropdownMenuSubContent>
</DropdownMenuSub>
diff --git a/apps/studio/state/role-impersonation-state.tsx b/apps/studio/state/role-impersonation-state.tsx
index a45590be82e..e1ba37494ff 100644
--- a/apps/studio/state/role-impersonation-state.tsx
+++ b/apps/studio/state/role-impersonation-state.tsx
@@ -1,6 +1,13 @@
import { ident, literal, safeSql } from '@supabase/pg-meta/src/pg-format'
import { useConstant } from 'common'
-import { createContext, PropsWithChildren, useCallback, useContext, useEffect } from 'react'
+import {
+ createContext,
+ PropsWithChildren,
+ useCallback,
+ useContext,
+ useEffect,
+ useState,
+} from 'react'
import { proxy, snapshot, subscribe, useSnapshot } from 'valtio'
import { CustomAccessTokenHookDetails } from '../hooks/misc/useCustomAccessTokenHookDetails'
@@ -9,38 +16,77 @@ import { useLatest } from '@/hooks/misc/useLatest'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { getPostgrestClaims, ImpersonationRole } from '@/lib/role-impersonation'
-export function createRoleImpersonationState(
+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,
+ sql: safeSql`select ${ident(schema)}.${ident(functionName)}(${literal(JSON.stringify(event))}::jsonb) as event;`,
+ queryKey: ['customize-access-token', projectRef],
+ })
+
+ 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,
- customizeAccessTokenRef: {
- current: (args: {
- schema: string
- functionName: string
- claims: ReturnType<typeof getPostgrestClaims>
- }) => Promise<any>
+ 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 ReturnType<typeof getPostgrestClaims> | undefined,
+ claims: undefined as PostgrestClaims | undefined,
setRole: async (
role: ImpersonationRole | undefined,
customAccessTokenHookDetails?: CustomAccessTokenHookDetails
) => {
- let claims = role?.type === 'postgrest' ? getPostgrestClaims(projectRef, role) : undefined
-
- if (customAccessTokenHookDetails?.type === 'postgres' && claims !== undefined) {
- const { schema, functionName } = customAccessTokenHookDetails
- const updatedClaims = await customizeAccessTokenRef.current({
- schema,
- functionName,
- claims,
- })
- if (updatedClaims) {
- claims = updatedClaims
- }
- }
+ const claims = await resolveRoleClaims(
+ projectRef,
+ role,
+ customAccessTokenHookDetails,
+ customizeAccessTokenRef.current
+ )
roleImpersonationState.role = role
if (claims) {
@@ -54,33 +100,24 @@ export function createRoleImpersonationState(
export type RoleImpersonationState = ReturnType<typeof createRoleImpersonationState>
+/**
+ * The subset of `RoleImpersonationState` a role-picker UI needs: the current selection, its
+ * resolved claims, and the setter. Satisfied by both the shared project-wide context (via
+ * `useRoleImpersonationStateSnapshot`) and `useLocalRoleImpersonationState`, so role-picking
+ * components can work against either without knowing which one they got.
+ */
+export type RoleImpersonationController = Pick<
+ RoleImpersonationState,
+ 'role' | 'claims' | 'setRole'
+>
+
export const RoleImpersonationStateContext = createContext<RoleImpersonationState>(
- createRoleImpersonationState('', { current: async () => {} })
+ createRoleImpersonationState('', { current: async () => undefined })
)
export const RoleImpersonationStateContextProvider = ({ children }: PropsWithChildren) => {
const { data: project } = useSelectedProjectQuery()
- async function customizeAccessToken({
- schema,
- functionName,
- claims,
- }: {
- schema: string
- functionName: string
- claims: ReturnType<typeof getPostgrestClaims>
- }) {
- const event = { user_id: claims.sub, claims, authentication_method: 'password' }
-
- const result = await executeSql({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- sql: safeSql`select ${ident(schema)}.${ident(functionName)}(${literal(JSON.stringify(event))}::jsonb) as event;`,
- queryKey: ['customize-access-token', project?.ref],
- })
-
- return result?.result?.[0]?.event?.claims
- }
-
+ const customizeAccessToken = useCustomizeAccessToken(project?.ref, project?.connectionString)
const customizeAccessTokenRef = useLatest(customizeAccessToken)
const state = useConstant(() =>
@@ -100,6 +137,41 @@ export function useRoleImpersonationStateSnapshot(options?: Parameters<typeof us
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.
+ */
+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 }
+}
+
export function useGetImpersonatedRoleState() {
const roleImpersonationState = useContext(RoleImpersonationStateContext)