Skip to content

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

refine role impersonation popover (#49467)

Saxon Fletcher9718eea593aa
diff --git a/apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx b/apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx
index b5a29d8f9e9..b40f791e27a 100644
--- a/apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx
+++ b/apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx
@@ -31,7 +31,7 @@ import { useGetImpersonatedRoleState } from '@/state/role-impersonation-state'
const ROLE_IMPERSONATION_PLUGIN: GraphiQLPlugin = {
title: 'Role Impersonation',
icon: () => <IconUser />,
- content: () => <RoleImpersonationSelector orientation="vertical" />,
+ content: () => <RoleImpersonationSelector />,
}
/**
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/Icons.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/Icons.tsx
deleted file mode 100644
index 918edb085f8..00000000000
--- a/apps/studio/components/interfaces/RoleImpersonationSelector/Icons.tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-import { useTheme } from 'next-themes'
-
-export interface IconProps {
- isSelected?: boolean
-}
-
-export const ServiceRoleIcon = ({ isSelected = false }: IconProps) => {
- const { resolvedTheme } = useTheme()
-
- return (
- <svg width="53" height="17" fill="none" xmlns="http://www.w3.org/2000/svg">
- <g opacity={isSelected ? '1' : '.5'}>
- <rect
- x="37.161"
- y=".53"
- width="15"
- height="15"
- rx="5.5"
- stroke={resolvedTheme === 'light' ? '#11181C' : '#EDEDED'}
- />
- <path d="M1 10.53h32.214" stroke="#33A7E9" strokeLinecap="round" strokeDasharray="2 2" />
- <rect
- x="15.964"
- y=".53"
- width="9"
- height="15"
- rx="4.5"
- stroke={resolvedTheme === 'light' ? '#7E868C' : '#7E7E7E'}
- />
- <path d="M1 5.53h32.214" stroke="#33A7E9" strokeLinecap="round" strokeDasharray="2 2" />
- </g>
- </svg>
- )
-}
-
-export const AnonIcon = ({ isSelected = false }: IconProps) => {
- const { resolvedTheme } = useTheme()
-
- return (
- <svg width="53" height="17" fill="none" xmlns="http://www.w3.org/2000/svg">
- <g opacity={isSelected ? '1' : '.5'}>
- <path
- d="M1 4.994a.5.5 0 0 0 0 1v-1Zm16.218 1h.5v-1h-.5v1ZM1 5.994h1.014v-1H1v1Zm3.04 0h2.028v-1H4.041v1Zm4.056 0h2.027v-1H8.096v1Zm4.054 0h2.027v-1H12.15v1Zm4.055 0h1.013v-1h-1.013v1Z"
- fill={resolvedTheme === 'light' ? '#7E868C' : '#7E7E7E'}
- />
- <path
- d="m15.92 12.56 9.04-9.04"
- stroke={resolvedTheme === 'light' ? '#11181C' : '#EDEDED'}
- />
- <rect
- x="15.964"
- y=".494"
- width="9"
- height="15"
- rx="4.5"
- stroke={resolvedTheme === 'light' ? '#11181C' : '#EDEDED'}
- />
- <rect
- x="37.161"
- y=".744"
- width="15"
- height="15"
- rx="5.5"
- stroke={resolvedTheme === 'light' ? '#11181C' : '#EDEDED'}
- />
- <path d="M1 10.494h32.214" stroke="#33A7E9" strokeLinecap="round" strokeDasharray="2 2" />
- <path
- d="M15.96 7.562 22.568.956M19.049 14.885l5.957-5.958"
- stroke={resolvedTheme === 'light' ? '#11181C' : '#EDEDED'}
- />
- </g>
- </svg>
- )
-}
-
-export const AuthenticatedIcon = ({ isSelected = false }: IconProps) => {
- const { resolvedTheme } = useTheme()
-
- return (
- <svg width="68" height="17" fill="none" xmlns="http://www.w3.org/2000/svg">
- <g opacity={isSelected ? '1' : '.5'}>
- <path
- d="M15.63 5.156a.5.5 0 1 0 0 1v-1Zm16.218 1h.5v-1h-.5v1Zm-16.218 0h1.013v-1H15.63v1Zm3.04 0h2.028v-1h-2.027v1Zm4.055 0h2.028v-1h-2.028v1Zm4.055 0h2.027v-1H26.78v1Zm4.055 0h1.013v-1h-1.013v1Z"
- fill={resolvedTheme === 'light' ? '#7E868C' : '#7E7E7E'}
- />
- <path
- d="m30.55 12.722 9.04-9.04"
- stroke={resolvedTheme === 'light' ? '#11181C' : '#EDEDED'}
- />
- <rect
- x="30.594"
- y=".656"
- width="9"
- height="15"
- rx="4.5"
- stroke={resolvedTheme === 'light' ? '#11181C' : '#EDEDED'}
- />
- <rect
- x="51.791"
- y=".906"
- width="15"
- height="15"
- rx="5.5"
- stroke={resolvedTheme === 'light' ? '#11181C' : '#EDEDED'}
- />
- <path
- d="M15.63 10.656h32.214"
- stroke="#33A7E9"
- strokeLinecap="round"
- strokeDasharray="2 2"
- />
- <path
- d="m30.59 7.724 6.607-6.606M33.679 15.047l5.957-5.958"
- stroke={resolvedTheme === 'light' ? '#11181C' : '#EDEDED'}
- />
- <path
- d="M12.666 14.281v-1.333A2.667 2.667 0 0 0 10 10.28H6a2.667 2.667 0 0 0-2.667 2.667v1.333M8 7.615A2.667 2.667 0 1 0 8 2.28a2.667 2.667 0 0 0 0 5.334Z"
- stroke={resolvedTheme === 'light' ? '#11181C' : '#EDEDED'}
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- </g>
- </svg>
- )
-}
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationRadio.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationRadio.tsx
deleted file mode 100644
index 74f182e7dc6..00000000000
--- a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationRadio.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import { Check, Minus } from 'lucide-react'
-import { cn } from 'ui'
-
-export interface RoleImpersonationRadioProps<T extends string> {
- label?: string
- description?: string
- value: T
- isSelected: boolean | 'partially'
- onSelectedChange: (value: T) => void
- icon?: React.ReactNode
- fullWidth?: boolean
-}
-
-export function RoleImpersonationRadio<T extends string>({
- label,
- description,
- value,
- isSelected,
- onSelectedChange,
- icon,
- fullWidth = false,
-}: RoleImpersonationRadioProps<T>) {
- return (
- <label
- className={cn(
- 'border border-default rounded-md bg-surface-200 hover:bg-overlay-hover hover:border-control-hover px-4 py-3 cursor-pointer transition-colors',
- fullWidth ? 'w-full' : 'w-44',
- isSelected && 'border-control-hover hover:border-control-hover bg-surface-300'
- )}
- tabIndex={0}
- onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- onSelectedChange(value)
- }
- }}
- htmlFor={`role-${value}`}
- >
- <div className="flex justify-between items-center mb-2">
- {icon && <div>{icon}</div>}
-
- {isSelected && (
- <div className="flex items-center justify-center p-0.5 bg-foreground text-background rounded-full">
- {typeof isSelected === 'boolean' && (
- <Check size={12} strokeWidth="4" className="text-background" />
- )}
- {isSelected === 'partially' && (
- <Minus size={12} strokeWidth="4" className="text-background" />
- )}
- </div>
- )}
- </div>
-
- <input
- id={`role-${value}`}
- type="radio"
- name="role"
- value={value}
- checked={Boolean(isSelected)}
- onChange={(e) => {
- onSelectedChange(e.target.value as T)
- }}
- className="invisible h-0 w-0 border-0"
- />
- <span
- className={cn(
- 'text-sm text-foreground-light whitespace-nowrap select-none transition-colors',
- isSelected && 'text-foreground'
- )}
- >
- {label ?? value}
- </span>
-
- {description && <p className="text-foreground-lighter text-xs">{description}</p>}
- </label>
- )
-}
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationSelector.utils.ts b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationSelector.utils.ts
new file mode 100644
index 00000000000..92b8c46f92e
--- /dev/null
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationSelector.utils.ts
@@ -0,0 +1,25 @@
+import type { ImpersonationRole, PostgrestRole } from '@/lib/role-impersonation'
+
+export function getSelectedRoleOption(role: ImpersonationRole | undefined): PostgrestRole {
+ if (role?.type === 'postgrest' && (role.role === 'anon' || role.role === 'authenticated')) {
+ return role.role
+ }
+
+ return 'service_role'
+}
+
+type RoleSelectionUpdate =
+ | { shouldSetRole: false }
+ | { shouldSetRole: true; role: ImpersonationRole | undefined }
+
+export function getRoleSelectionUpdate(value: PostgrestRole): RoleSelectionUpdate {
+ if (value === 'service_role') {
+ return { shouldSetRole: true, role: undefined }
+ }
+
+ if (value === 'anon') {
+ return { shouldSetRole: true, role: { type: 'postgrest', role: 'anon' } }
+ }
+
+ return { shouldSetRole: false }
+}
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx
index f649e93c9ae..b4ec509cb6c 100644
--- a/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx
@@ -1,62 +1,75 @@
import { keepPreviousData } from '@tanstack/react-query'
import { useDebounce } from '@uidotdev/usehooks'
-import { LOCAL_STORAGE_KEYS, useParams } from 'common'
-import { ChevronDown, User as IconUser, Loader2, Search, X } from 'lucide-react'
+import { ChevronsUpDown, User as IconUser, Loader2, X } from 'lucide-react'
import { useMemo, useState } from 'react'
import { toast } from 'sonner'
import {
Button,
cn,
- Collapsible,
- CollapsibleContent,
- CollapsibleTrigger,
- DropdownMenuSeparator,
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
Input,
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupInput,
- ScrollArea,
- Switch,
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ ToggleGroup,
+ ToggleGroupItem,
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { InfoTooltip } from 'ui-patterns/info-tooltip'
-import { getAvatarUrl, getDisplayName } from '../Auth/Users/Users.utils'
+import { getDisplayName } from '../Auth/Users/Users.utils'
import { AlertError } from '@/components/ui/AlertError'
import { InlineLink } from '@/components/ui/InlineLink'
import { User, useUsersInfiniteQuery } from '@/data/auth/users-infinite-query'
import { useCustomAccessTokenHookDetails } from '@/hooks/misc/useCustomAccessTokenHookDetails'
-import { useLocalStorage } from '@/hooks/misc/useLocalStorage'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { DOCS_URL } from '@/lib/constants'
-import { type RoleImpersonationController } from '@/state/role-impersonation-state'
+import type { RoleImpersonationController } from '@/state/role-impersonation-state'
import type { ResponseError } from '@/types'
type AuthenticatorAssuranceLevels = 'aal1' | 'aal2'
+type UserSource = 'user' | 'external'
-export const UserImpersonationSelector = ({ state }: { state: RoleImpersonationController }) => {
+type UserImpersonationSelectorProps = {
+ state: RoleImpersonationController
+ disabled?: boolean
+ onUserImpersonationCleared?: () => void
+}
+
+export const UserImpersonationSelector = ({
+ state,
+ disabled = false,
+ onUserImpersonationCleared,
+}: UserImpersonationSelectorProps) => {
const [searchText, setSearchText] = useState('')
- const [aal, setAal] = useState<AuthenticatorAssuranceLevels>('aal1')
+ const [aal, setAal] = useState<AuthenticatorAssuranceLevels>(() =>
+ state.role?.type === 'postgrest' && state.role.role === 'authenticated'
+ ? (state.role.aal ?? 'aal1')
+ : 'aal1'
+ )
const [externalUserId, setExternalUserId] = useState('')
const [additionalClaims, setAdditionalClaims] = useState('')
-
- const { id: tableId } = useParams()
- const [selectedTab, setSelectedTab] = useState<'user' | 'external'>('user')
-
- const [previousSearches, setPreviousSearches] = useLocalStorage<User[]>(
- LOCAL_STORAGE_KEYS.USER_IMPERSONATION_SELECTOR_PREVIOUS_SEARCHES(tableId!),
- []
+ const [isUserComboboxOpen, setIsUserComboboxOpen] = useState(false)
+ const [selectedSource, setSelectedSource] = useState<UserSource>(() =>
+ state.role?.type === 'postgrest' &&
+ state.role.role === 'authenticated' &&
+ state.role.userType === 'external'
+ ? 'external'
+ : 'user'
)
+ const [isImpersonateLoading, setIsImpersonateLoading] = useState(false)
const debouncedSearchText = useDebounce(searchText, 300)
-
const { data: project } = useSelectedProjectQuery()
-
const {
data,
isSuccess,
@@ -71,10 +84,9 @@ export const UserImpersonationSelector = ({ state }: { state: RoleImpersonationC
connectionString: project?.connectionString,
keywords: debouncedSearchText.trim().toLocaleLowerCase(),
},
- {
- placeholderData: keepPreviousData,
- }
+ { placeholderData: keepPreviousData }
)
+
const users = useMemo(() => data?.pages.flatMap((page) => page.result) ?? [], [data?.pages])
const isSearching = isPlaceholderData && isFetching
const impersonatingUser =
@@ -82,29 +94,26 @@ export const UserImpersonationSelector = ({ state }: { state: RoleImpersonationC
state.role.role === 'authenticated' &&
state.role.userType === 'native' &&
state.role.user
-
- // Check if we're currently impersonating an external auth user (e.g. OAuth, SAML)
- // This is used to show the correct UI state and impersonation details
- const isExternalAuthImpersonating =
+ ? state.role.user
+ : undefined
+ const impersonatingExternalUser =
state.role?.type === 'postgrest' &&
state.role.role === 'authenticated' &&
state.role.userType === 'external' &&
state.role.externalAuth
-
+ ? state.role.externalAuth
+ : undefined
+ const displayName = impersonatingUser
+ ? getDisplayName(
+ impersonatingUser,
+ impersonatingUser.email ?? impersonatingUser.phone ?? impersonatingUser.id ?? 'Unknown'
+ )
+ : impersonatingExternalUser?.sub
+ const isUserSelected = Boolean(displayName)
const customAccessTokenHookDetails = useCustomAccessTokenHookDetails(project?.ref)
- const [isImpersonateLoading, setIsImpersonateLoading] = useState(false)
-
async function impersonateUser(user: User) {
setIsImpersonateLoading(true)
- setPreviousSearches((prev) => {
- // Remove if already present
- const filtered = prev.filter((u) => u.id !== user.id)
- // Add new user to the start of the list (last used first)
- const updated = [user, ...filtered]
- // Keep only the last 6
- return updated.slice(0, 5)
- })
if (customAccessTokenHookDetails?.type === 'https') {
toast.info(
@@ -125,459 +134,363 @@ export const UserImpersonationSelector = ({ state }: { state: RoleImpersonationC
)
} catch (error) {
toast.error(`Failed to impersonate user: ${(error as ResponseError).message}`)
+ } finally {
+ setIsImpersonateLoading(false)
}
-
- setIsImpersonateLoading(false)
}
- // Impersonates an external auth user (e.g. OAuth, SAML) by setting the sub and any additional claims
- // This allows testing RLS policies for external auth users without needing to set up the full OAuth/SAML flow
async function impersonateExternalUser() {
setIsImpersonateLoading(true)
let parsedClaims = {}
try {
parsedClaims = additionalClaims ? JSON.parse(additionalClaims) : {}
- } catch (e) {
+ } catch {
toast.error('Invalid JSON in additional claims')
setIsImpersonateLoading(false)
return
}
+
try {
await state.setRole(
{
type: 'postgrest',
role: 'authenticated',
userType: 'external',
- externalAuth: {
- sub: externalUserId,
- additionalClaims: parsedClaims,
- },
+ externalAuth: { sub: externalUserId, additionalClaims: parsedClaims },
aal,
},
customAccessTokenHookDetails
)
} catch (error) {
toast.error(`Failed to impersonate user: ${(error as ResponseError).message}`)
+ } finally {
+ setIsImpersonateLoading(false)
}
-
- setIsImpersonateLoading(false)
}
- function stopImpersonating() {
- state.setRole(undefined)
- }
+ async function changeSelectedSource(value: UserSource) {
+ if (!isUserSelected) {
+ setSelectedSource(value)
+ return
+ }
- function toggleAalState() {
- setAal((prev) => (prev === 'aal2' ? 'aal1' : 'aal2'))
+ try {
+ await state.setRole(undefined)
+ setSelectedSource(value)
+ onUserImpersonationCleared?.()
+ } catch (error) {
+ toast.error(`Failed to stop impersonating user: ${(error as ResponseError).message}`)
+ }
}
- const displayName = impersonatingUser
- ? getDisplayName(
- impersonatingUser,
- impersonatingUser.email ?? impersonatingUser.phone ?? impersonatingUser.id ?? 'Unknown'
- )
- : isExternalAuthImpersonating
- ? isExternalAuthImpersonating.sub
- : undefined
+ async function changeAal(value: AuthenticatorAssuranceLevels) {
+ const previousAal = aal
+ setAal(value)
+
+ if (
+ state.role?.type !== 'postgrest' ||
+ state.role.role !== 'authenticated' ||
+ !isUserSelected
+ ) {
+ return
+ }
- // Clear all search history
- function clearSearchHistory() {
- setPreviousSearches([])
+ try {
+ await state.setRole({ ...state.role, aal: value }, customAccessTokenHookDetails)
+ } catch (error) {
+ setAal(previousAal)
+ toast.error(`Failed to update MFA assurance level: ${(error as ResponseError).message}`)
+ }
}
return (
- <>
- <div className="px-5 py-3">
- <p className="text-foreground text-sm">
- {displayName ? `Impersonating ${displayName}` : 'Impersonate a user'}
- </p>
- <p className="text-sm text-foreground-light mb-1">
- {!impersonatingUser && !isExternalAuthImpersonating
- ? "Select a user to respect your database's RLS policies for that particular user."
- : "Results will respect your database's RLS policies for this user."}
- </p>
-
- {impersonatingUser && (
- <UserImpersonatingRow
- user={impersonatingUser}
- onClick={stopImpersonating}
- isImpersonating={true}
- aal={aal}
- isLoading={isImpersonateLoading}
- />
- )}
- {isExternalAuthImpersonating && (
- <ExternalAuthImpersonatingRow
- sub={isExternalAuthImpersonating.sub}
- onClick={stopImpersonating}
- aal={aal}
- isLoading={isImpersonateLoading}
+ <fieldset
+ disabled={disabled}
+ aria-disabled={disabled}
+ className={cn(
+ 'm-0 flex min-w-0 flex-col gap-y-2.5 border-0 p-0 transition-opacity',
+ disabled && 'opacity-40'
+ )}
+ >
+ <FormItemLayout
+ isReactForm={false}
+ layout="horizontal"
+ size="tiny"
+ label={
+ <span className="flex items-center gap-1">
+ Users
+ <InfoTooltip side="left" className="max-w-80">
+ Project users come from Supabase Auth. External users let you test RLS policies with
+ providers such as Clerk or Auth0.
+ </InfoTooltip>
+ </span>
+ }
+ >
+ <ToggleGroup
+ type="single"
+ value={selectedSource}
+ onValueChange={(value) => {
+ if (value === 'user' || value === 'external') void changeSelectedSource(value)
+ }}
+ variant="default"
+ size="tiny"
+ aria-label="User source"
+ className="w-full"
+ >
+ <ToggleGroupItem value="user" className="w-full">
+ Project
+ </ToggleGroupItem>
+ <ToggleGroupItem value="external" className="w-full">
+ External
+ </ToggleGroupItem>
+ </ToggleGroup>
+ </FormItemLayout>
+
+ <FormItemLayout
+ id="run-as-user"
+ isReactForm={false}
+ layout="horizontal"
+ size="tiny"
+ label="User"
+ >
+ <ImpersonationControl
+ selectedSource={selectedSource}
+ displayName={displayName}
+ isImpersonateLoading={isImpersonateLoading}
+ stopImpersonating={async () => {
+ await state.setRole(undefined)
+ onUserImpersonationCleared?.()
+ }}
+ isUserComboboxOpen={isUserComboboxOpen}
+ setIsUserComboboxOpen={setIsUserComboboxOpen}
+ searchText={searchText}
+ setSearchText={setSearchText}
+ isLoading={isLoading}
+ isSearching={isSearching}
+ isError={isError}
+ error={error}
+ isSuccess={isSuccess}
+ users={users}
+ impersonateUser={impersonateUser}
+ externalUserId={externalUserId}
+ setExternalUserId={setExternalUserId}
+ impersonateExternalUser={impersonateExternalUser}
+ />
+ </FormItemLayout>
+
+ {selectedSource === 'external' && !isUserSelected && (
+ <FormItemLayout
+ id="run-as-user-claims"
+ isReactForm={false}
+ layout="horizontal"
+ size="tiny"
+ label="Claims"
+ >
+ <Input
+ id="run-as-user-claims"
+ size="tiny"
+ placeholder='e.g. {"app_metadata": {"org_id": "org_456"}}'
+ value={additionalClaims}
+ onChange={(event) => setAdditionalClaims(event.target.value)}
/>
- )}
-
- {!impersonatingUser && !isExternalAuthImpersonating && (
- <Tabs value={selectedTab} onValueChange={(value: any) => setSelectedTab(value)}>
- <TabsList className="gap-x-3">
- <TabsTrigger value="user">Project user</TabsTrigger>
- <TabsTrigger value="external" className="gap-x-1.5">
- External user
- <InfoTooltip side="bottom" className="flex flex-col gap-1 max-w-96">
- Test RLS policies with external auth providers like Clerk or Auth0 by providing a
- user ID and optional claims.
- </InfoTooltip>
- </TabsTrigger>
- </TabsList>
-
- <TabsContent value="user">
- <div className="flex flex-col gap-y-2">
- <InputGroup>
- <InputGroupInput
- size="tiny"
- className="pr-10 border-none"
- placeholder="Search by id, email, phone, or name..."
- onChange={(e) => setSearchText(e.target.value)}
- value={searchText}
- />
- <InputGroupAddon>
- {isSearching ? (
- <Loader2
- className="animate-spin text-foreground-lighter"
- size={16}
- strokeWidth={1.5}
- />
- ) : (
- <Search className="text-foreground-lighter" size={16} strokeWidth={1.5} />
- )}
- </InputGroupAddon>
- <InputGroupAddon align="inline-end">
- {searchText && (
- <InputGroupButton
- size="tiny"
- variant="text"
- onClick={() => setSearchText('')}
- >
- <span className="sr-only">Clear search</span>
- <X size={12} />
- </InputGroupButton>
- )}
- </InputGroupAddon>
- </InputGroup>
- {isLoading && (
- <div className="flex flex-col gap-2 items-center justify-center h-24">
- <Loader2 className="animate-spin" size={24} />
- <span className="text-foreground-light">Loading users...</span>
- </div>
- )}
-
- {isError && <AlertError error={error} subject="Failed to retrieve users" />}
-
- {isSuccess &&
- (users.length > 0 ? (
- <div>
- <ul className="divide-y max-h-[150px] overflow-y-scroll" role="list">
- {users.map((user) => (
- <li key={user.id} role="listitem">
- <UserRow
- user={user}
- onClick={impersonateUser}
- isLoading={isImpersonateLoading}
- />
- </li>
- ))}
- </ul>
- </div>
- ) : (
- <div className="flex flex-col gap-2 items-center justify-center h-24">
- <p className="text-foreground-light text-xs" role="status">
- No users found
- </p>
- </div>
- ))}
-
- <>
- {previousSearches.length > 0 && (
- <div>
- {previousSearches.length > 0 ? (
- <>
- <Collapsible className="relative">
- <CollapsibleTrigger className="group font-normal p-0 [&[data-state=open]>div>svg]:-rotate-180!">
- <div className="flex items-center gap-x-1 w-full">
- <p className="text-xs text-foreground-light group-hover:text-foreground transition">
- Recents
- </p>
- <ChevronDown
- className="transition-transform duration-200"
- strokeWidth={1.5}
- size={14}
- />
- </div>
- </CollapsibleTrigger>
-
- <CollapsibleContent className="mt-1 flex flex-col gap-y-4">
- <Button
- size="tiny"
- variant="text"
- className="absolute right-0 top-0 py-2 hover:bg-muted flex items-center text"
- onClick={clearSearchHistory}
- >
- <span className="flex items-center">Clear</span>
- </Button>
- <ScrollArea
- className={cn(previousSearches.length > 3 ? 'h-36' : 'h-auto')}
- >
- <ul className="grid gap-2 ">
- {previousSearches.map((search) => (
- <li key={search.id}>
- <UserRow user={search} onClick={impersonateUser} />
- </li>
- ))}
- </ul>
- </ScrollArea>
- </CollapsibleContent>
- </Collapsible>
- </>
- ) : (
- <div className="p-4 text-center text-muted-foreground">
- No recent searches
- </div>
- )}
- </div>
- )}
- </>
- </div>
- </TabsContent>
-
- <TabsContent value="external">
- <div className="flex flex-col gap-y-4">
- <FormItemLayout
- layout="horizontal"
- label="External User ID"
- description="The user ID from your external auth provider"
- isReactForm={false}
- >
- <Input
- size="small"
- placeholder="e.g. user_abc123"
- value={externalUserId}
- onChange={(e) => setExternalUserId(e.target.value)}
- />
- </FormItemLayout>
- <FormItemLayout
- layout="horizontal"
- label="Additional Claims (JSON)"
- description="Optional: Add custom claims like org_id or roles"
- isReactForm={false}
- >
- <Input
- size="small"
- placeholder='e.g. {"app_metadata": {"org_id": "org_456"}}'
- value={additionalClaims}
- onChange={(e) => setAdditionalClaims(e.target.value)}
- />
- </FormItemLayout>
- <div className="flex items-center justify-end">
- <Button
- variant="default"
- disabled={!externalUserId}
- onClick={impersonateExternalUser}
- >
- Impersonate
- </Button>
- </div>
- </div>
- </TabsContent>
- </Tabs>
- )}
- </div>
-
- {/* Check for both regular user and external auth impersonation since they use different data structures but both need to be handled for displaying impersonation UI */}
- {!impersonatingUser && !isExternalAuthImpersonating ? (
- <>
- <DropdownMenuSeparator className="m-0" />
- <div className="px-5 py-2 flex flex-col gap-2 relative">
- <Collapsible>
- <CollapsibleTrigger className="group font-normal p-0 [&[data-state=open]>div>svg]:-rotate-180!">
- <div className="flex items-center gap-x-1 w-full">
- <p className="text-xs text-foreground-light group-hover:text-foreground transition">
- Advanced options
- </p>
- <ChevronDown
- className="transition-transform duration-200"
- strokeWidth={1.5}
- size={14}
- />
- </div>
- </CollapsibleTrigger>
- <CollapsibleContent className="mt-1 flex flex-col gap-y-4">
- <div className="flex flex-row items-center gap-x-4 text-sm text-foreground-light">
- <div className="flex items-center gap-x-1">
- <h3>MFA assurance level</h3>
- <InfoTooltip side="top" className="max-w-96">
- AAL1 verifies users via standard login methods, while AAL2 adds a second
- authentication factor. If you're not using MFA, you can leave this on AAL1.
- Learn more about MFA{' '}
- <InlineLink href={`${DOCS_URL}/guides/auth/auth-mfa`}>here</InlineLink>.
- </InfoTooltip>
- </div>
-
- <div className="flex flex-row items-center gap-x-2 text-xs font-bold">
- <p className={aal === 'aal1' ? undefined : 'text-foreground-lighter'}>AAL1</p>
- <Switch checked={aal === 'aal2'} onCheckedChange={toggleAalState} />
- <p className={aal === 'aal2' ? undefined : 'text-foreground-lighter'}>AAL2</p>
- </div>
- </div>
- </CollapsibleContent>
- </Collapsible>
- </div>
- </>
- ) : null}
- </>
+ </FormItemLayout>
+ )}
+
+ <FormItemLayout
+ isReactForm={false}
+ layout="horizontal"
+ size="tiny"
+ label={
+ <span className="flex items-center gap-1">
+ MFA level
+ <InfoTooltip side="left" className="max-w-96">
+ AAL1 verifies users via standard login methods, while AAL2 adds a second
+ authentication factor. If you are not using MFA, leave this on AAL1. Learn more in the{' '}
+ <InlineLink href={`${DOCS_URL}/guides/auth/auth-mfa`}>MFA guide</InlineLink>.
+ </InfoTooltip>
+ </span>
+ }
+ >
+ <ToggleGroup
+ type="single"
+ value={aal}
+ onValueChange={(value) => {
+ if (value === 'aal1' || value === 'aal2') void changeAal(value)
+ }}
+ variant="default"
+ size="tiny"
+ aria-label="MFA assurance level"
+ className="w-full"
+ >
+ <ToggleGroupItem value="aal1" className="w-full">
+ AAL1
+ </ToggleGroupItem>
+ <ToggleGroupItem value="aal2" className="w-full">
+ AAL2
+ </ToggleGroupItem>
+ </ToggleGroup>
+ </FormItemLayout>
+ </fieldset>
)
}
-// Base interface for shared impersonation row props to reduce
-// duplication between user and external auth impersonation displays
-interface BaseImpersonatingRowProps {
- onClick: () => void
- aal: AuthenticatorAssuranceLevels
- displayName: string
- avatarUrl?: string
- isImpersonating: boolean
- isLoading?: boolean
+type ImpersonationControlProps = {
+ selectedSource: UserSource
+ displayName?: string
+ isImpersonateLoading: boolean
+ stopImpersonating: () => void
+ isUserComboboxOpen: boolean
+ setIsUserComboboxOpen: (open: boolean) => void
+ searchText: string
+ setSearchText: (value: string) => void
+ isLoading: boolean
+ isSearching: boolean
+ isError: boolean
+ error: ResponseError | null
+ isSuccess: boolean
+ users: User[]
+ impersonateUser: (user: User) => Promise<void>
+ externalUserId: string
+ setExternalUserId: (value: string) => void
+ impersonateExternalUser: () => Promise<void>
}
-const BaseImpersonatingRow = ({
- onClick,
- aal,
+const ImpersonationControl = ({
+ selectedSource,
displayName,
- avatarUrl,
- isImpersonating = false,
- isLoading = false,
-}: BaseImpersonatingRowProps) => {
- return (
- <div className="flex items-center gap-3 py-2 text-foreground">
- <div className="flex items-center gap-4 bg-surface-200 pr-4 pl-0.5 py-0.5 border rounded-full max-w-l">
- {avatarUrl ? (
- <img className="rounded-full w-5 h-5" src={avatarUrl} alt={displayName} />
- ) : (
- <div className="rounded-full w-[21px] h-[21px] bg-surface-300 border border-strong flex items-center justify-center">
- <IconUser size={12} strokeWidth={2} />
- </div>
- )}
-
- <span className="text-sm truncate">
- {displayName}{' '}
- <span className="ml-2 text-foreground-lighter text-xs font-light">
- {aal === 'aal2' ? 'AAL2' : 'AAL1'}
- </span>
- </span>
+ isImpersonateLoading,
+ stopImpersonating,
+ isUserComboboxOpen,
+ setIsUserComboboxOpen,
+ searchText,
+ setSearchText,
+ isLoading,
+ isSearching,
+ isError,
+ error,
+ isSuccess,
+ users,
+ impersonateUser,
+ externalUserId,
+ setExternalUserId,
+ impersonateExternalUser,
+}: ImpersonationControlProps) => {
+ if (displayName) {
+ return (
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="min-w-0 flex-1 truncate text-xs">{displayName}</span>
+ <Button
+ type="button"
+ size="tiny"
+ variant="text"
+ className="px-1"
+ aria-label="Stop impersonating user"
+ icon={<X size={14} />}
+ onClick={stopImpersonating}
+ disabled={isImpersonateLoading}
+ loading={isImpersonateLoading}
+ />
</div>
+ )
+ }
- <Button variant="default" onClick={onClick} disabled={isLoading} loading={isLoading}>
- {isImpersonating ? 'Stop' : 'Impersonate'}
- </Button>
- </div>
- )
-}
-
-const UserImpersonatingRow = ({
- user,
- onClick,
- isImpersonating = false,
- isLoading = false,
- aal,
-}: UserRowProps & { aal: AuthenticatorAssuranceLevels }) => {
- const avatarUrl = getAvatarUrl(user)
- const displayName =
- getDisplayName(user, user.email ?? user.phone ?? user.id ?? 'Unknown') +
- (user.is_anonymous ? ' (anonymous)' : '')
-
- return (
- <BaseImpersonatingRow
- onClick={() => onClick(user)}
- aal={aal}
- displayName={displayName}
- avatarUrl={avatarUrl}
- isImpersonating={isImpersonating}
- isLoading={isLoading}
- />
- )
-}
-
-interface ExternalAuthImpersonatingRowProps {
- sub: string
- onClick: () => void
- aal: AuthenticatorAssuranceLevels
- isLoading?: boolean
-}
-
-const ExternalAuthImpersonatingRow = ({
- sub,
- onClick,
- aal,
- isLoading = false,
-}: ExternalAuthImpersonatingRowProps) => {
- return (
- <BaseImpersonatingRow
- onClick={onClick}
- aal={aal}
- displayName={sub}
- isImpersonating={true}
- isLoading={isLoading}
- />
- )
-}
-
-interface UserRowProps {
- user: User
- onClick: (user: User) => void
- isImpersonating?: boolean
- isLoading?: boolean
-}
-
-const UserRow = ({ user, onClick, isImpersonating = false, isLoading = false }: UserRowProps) => {
- const avatarUrl = getAvatarUrl(user)
- const emailOrPhone = user.email || user.phone
- const displayName = getDisplayName(user, '')
- const isAnonymous = user.is_anonymous
- const showDisplayName = displayName && displayName !== emailOrPhone
+ if (selectedSource === 'external') {
+ return (
+ <InputGroup>
+ <InputGroupInput
+ id="run-as-user"
+ size="tiny"
+ placeholder="External user ID"
+ value={externalUserId}
+ onChange={(event) => setExternalUserId(event.target.value)}
+ />
+ <InputGroupAddon align="inline-end">
+ <InputGroupButton
+ type="button"
+ size="tiny"
+ variant="default"
+ disabled={!externalUserId}
+ onClick={impersonateExternalUser}
+ >
+ Apply
+ </InputGroupButton>
+ </InputGroupAddon>
+ </InputGroup>
+ )
+ }
return (
- <div className="flex items-center justify-between py-1 text-foreground">
- <div className="flex items-center gap-4">
- {avatarUrl ? (
- <img className="rounded-full w-5 h-5" src={avatarUrl} alt={displayName || emailOrPhone} />
- ) : (
- <div className="rounded-full w-[21px] h-[21px] bg-surface-300 border flex items-center justify-center text-foreground-lighter">
- <IconUser size={12} strokeWidth={2} />
- </div>
- )}
-
- <span className="text-sm flex items-center gap-4">
- {emailOrPhone}
- {showDisplayName && (
- <>
- <span className="text-foreground-lighter">
- {displayName}
- {isAnonymous ? ' (anonymous)' : ''}
- </span>
- </>
- )}
- <span className="text-foreground-light bg-surface-200 dark:bg-surface-400 rounded-md px-1 py-0.5 font-mono text-xs">
- {user?.id?.slice(0, 8)}
- </span>
- </span>
- </div>
-
- <Button
- variant="default"
- onClick={() => onClick(user)}
- disabled={isLoading}
- loading={isLoading}
- >
- {isImpersonating ? 'Stop' : 'Impersonate'}
- </Button>
- </div>
+ <Popover open={isUserComboboxOpen} onOpenChange={setIsUserComboboxOpen} modal={false}>
+ <PopoverTrigger asChild>
+ <Button
+ id="run-as-user"
+ type="button"
+ size="tiny"
+ variant="default"
+ role="combobox"
+ aria-label="Find user"
+ aria-expanded={isUserComboboxOpen}
+ className="w-full justify-between"
+ iconRight={<ChevronsUpDown className="shrink-0 text-foreground-muted" size={14} />}
+ >
+ Email, name, or ID
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="p-0" side="bottom" align="start" sameWidthAsTrigger>
+ <Command shouldFilter={false}>
+ <CommandInput
+ placeholder="Email, name, or ID"
+ value={searchText}
+ onValueChange={setSearchText}
+ />
+ <CommandList className="max-h-52">
+ {(isLoading || isSearching) && (
+ <div className="flex items-center justify-center gap-2 px-3 py-2">
+ <Loader2 className="animate-spin" size={14} />
+ <span className="text-xs text-foreground-light">Loading users…</span>
+ </div>
+ )}
+
+ {isError && <AlertError error={error} subject="Failed to retrieve users" />}
+
+ {isSuccess && !isSearching && users.length === 0 && (
+ <CommandEmpty>No users found</CommandEmpty>
+ )}
+
+ {isSuccess && !isSearching && users.length > 0 && (
+ <CommandGroup>
+ {users.map((user) => {
+ const emailOrPhone = user.email || user.phone
+ const userDisplayName = getDisplayName(user, '')
+
+ return (
+ <CommandItem
+ key={user.id}
+ value={user.id}
+ onSelect={() => {
+ void impersonateUser(user)
+ setIsUserComboboxOpen(false)
+ }}
+ className="gap-2"
+ >
+ <IconUser size={14} className="shrink-0 text-foreground-lighter" />
+ <span className="min-w-0 flex-1 truncate">
+ {emailOrPhone || userDisplayName || user.id}
+ </span>
+ {userDisplayName && userDisplayName !== emailOrPhone && (
+ <span className="max-w-24 truncate text-foreground-lighter">
+ {userDisplayName}
+ </span>
+ )}
+ </CommandItem>
+ )
+ })}
+ </CommandGroup>
+ )}
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
)
}
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsx
index 634648b3d15..6ea39c373c4 100644
--- a/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsx
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/index.tsx
@@ -1,12 +1,8 @@
-import { useState } from 'react'
-import { Badge, Card, CardContent, CardHeader, CardTitle, cn } from 'ui'
+import { Check, Database, UserCheck, UserX } from 'lucide-react'
+import { Separator, ToggleGroup, ToggleGroupItem } from 'ui'
-import { AnonIcon, AuthenticatedIcon, ServiceRoleIcon } from './Icons'
-import { RoleImpersonationRadio } from './RoleImpersonationRadio'
import { UserImpersonationSelector } from './UserImpersonationSelector'
-import { DocsButton } from '@/components/ui/DocsButton'
-import { DOCS_URL } from '@/lib/constants'
-import { PostgrestRole } from '@/lib/role-impersonation'
+import { useRoleImpersonationSelection } from './useRoleImpersonationSelection'
import {
useRoleImpersonationStateSnapshot,
type RoleImpersonationController,
@@ -17,17 +13,13 @@ export interface RoleImpersonationSelectorProps {
serviceRoleLabel?: string
disallowAuthenticatedOption?: boolean
title?: string
- orientation?: 'horizontal' | 'vertical'
}
/**
- * Tightly coupled with the global role impersonation store
- * Use RoleImpersonationSelectorInterface to control the logic externally
+ * 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} />
@@ -37,143 +29,97 @@ type RoleImpersonationSelectorInterfaceProps = RoleImpersonationSelectorProps &
state: RoleImpersonationController
}
-export const RoleImpersonationSelectorInterface = ({
- state,
- orientation,
- serviceRoleLabel = 'Postgres',
- disallowAuthenticatedOption = false,
- header = 'Impersonate a database role',
-}: RoleImpersonationSelectorInterfaceProps) => {
- const isVertical = orientation === 'vertical'
-
- 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' &&
- state.role?.type === 'postgrest' &&
- state.role.role === 'authenticated' &&
- (('user' in state.role && state.role.user) ||
- ('externalAuth' in state.role && state.role.externalAuth)) // Check for either auth type
- )
-
- function onSelectedChange(value: PostgrestRole) {
- if (value === 'service_role') {
- // do not set a role for service role
- // as the default role is the "service role"
- state.setRole(undefined)
- }
-
- if (value === 'anon') {
- state.setRole({
- type: 'postgrest',
- role: value,
- })
- }
-
- setSelectedOption(value)
- }
+export const RoleImpersonationSelectorInterface = (
+ props: RoleImpersonationSelectorInterfaceProps
+) => {
+ const { state } = props
+ const serviceRoleLabel = props.serviceRoleLabel ?? 'Postgres'
+ const disallowAuthenticatedOption = props.disallowAuthenticatedOption ?? false
+ const { selectedOption, onSelectedChange, keepAuthenticatedSelected } =
+ useRoleImpersonationSelection(state)
+
+ const roleSummary = {
+ service_role: 'Bypasses RLS and can return all rows.',
+ anon: 'Returns rows available to anonymous users.',
+ authenticated: 'Returns rows available to the selected user.',
+ }[selectedOption]
return (
- <Card className="border-none">
- <CardHeader className="flex-row items-center justify-between py-3 space-y-0">
- <CardTitle>{header}</CardTitle>
- <DocsButton
- href={`${DOCS_URL}/guides/database/postgres/row-level-security#authenticated-and-unauthenticated-roles`}
- />
- </CardHeader>
- <CardContent className="flex flex-col gap-y-4">
- <form
- onSubmit={(e) => {
- // don't allow form submission
- e.preventDefault()
+ <div className="flex w-80 flex-col">
+ <form
+ className="p-3"
+ onSubmit={(event) => {
+ event.preventDefault()
+ }}
+ >
+ <ToggleGroup
+ type="single"
+ orientation="vertical"
+ value={selectedOption}
+ onValueChange={(value) => {
+ if (value === 'service_role' || value === 'anon' || value === 'authenticated') {
+ void onSelectedChange(value)
+ }
}}
+ variant="default"
+ aria-label={props.header ?? props.title ?? 'Run query as role'}
+ className="w-full flex-col items-stretch gap-0.5"
>
- <fieldset className={cn('flex gap-3', isVertical && 'flex-col gap-2')}>
- <RoleImpersonationRadio
- value="service_role"
- isSelected={selectedOption === 'service_role'}
- onSelectedChange={onSelectedChange}
- label={serviceRoleLabel}
- description="Superuser"
- icon={<ServiceRoleIcon isSelected={selectedOption === 'service_role'} />}
- fullWidth={isVertical}
- />
-
- <RoleImpersonationRadio
- value="anon"
- label="Anonymous"
- isSelected={selectedOption === 'anon'}
- onSelectedChange={onSelectedChange}
- description="Not logged in"
- icon={<AnonIcon isSelected={selectedOption === 'anon'} />}
- fullWidth={isVertical}
+ <ToggleGroupItem value="service_role" className="w-full justify-between text-left">
+ <span className="flex min-w-0 items-center gap-3">
+ <Database size={16} strokeWidth={1.5} className="shrink-0" />
+ <span className="flex min-w-0 flex-col items-start">
+ <span>{serviceRoleLabel}</span>
+ <span className="text-xs font-normal text-foreground-lighter">Superuser</span>
+ </span>
+ </span>
+ {selectedOption === 'service_role' && <Check size={14} />}
+ </ToggleGroupItem>
+
+ <ToggleGroupItem value="anon" className="w-full justify-between text-left">
+ <span className="flex min-w-0 items-center gap-3">
+ <UserX size={16} strokeWidth={1.5} className="shrink-0" />
+ <span className="flex min-w-0 flex-col items-start">
+ <span>Anonymous</span>
+ <span className="text-xs font-normal text-foreground-lighter">Not logged in</span>
+ </span>
+ </span>
+ {selectedOption === 'anon' && <Check size={14} />}
+ </ToggleGroupItem>
+
+ {!disallowAuthenticatedOption && (
+ <ToggleGroupItem value="authenticated" className="w-full justify-between text-left">
+ <span className="flex min-w-0 items-center gap-3">
+ <UserCheck size={16} strokeWidth={1.5} className="shrink-0" />
+ <span className="flex min-w-0 flex-col items-start">
+ <span>Authenticated</span>
+ <span className="text-xs font-normal text-foreground-lighter">
+ Logged-in user
+ </span>
+ </span>
+ </span>
+ {selectedOption === 'authenticated' && <Check size={14} />}
+ </ToggleGroupItem>
+ )}
+ </ToggleGroup>
+
+ {!disallowAuthenticatedOption && (
+ <>
+ <Separator className="my-2.5" />
+ <UserImpersonationSelector
+ state={state}
+ disabled={selectedOption !== 'authenticated'}
+ onUserImpersonationCleared={keepAuthenticatedSelected}
/>
-
- {!disallowAuthenticatedOption && (
- <RoleImpersonationRadio
- value="authenticated"
- label="Authenticated"
- isSelected={
- selectedOption === 'authenticated' &&
- (isAuthenticatedOptionFullySelected || 'partially')
- }
- onSelectedChange={onSelectedChange}
- description="Specific logged in user"
- icon={<AuthenticatedIcon isSelected={selectedOption === 'authenticated'} />}
- fullWidth={isVertical}
- />
- )}
- </fieldset>
- </form>
-
- {selectedOption === 'service_role' && (
- <div>
- <p className="text-sm">
- Full admin access
- <Badge className="ml-2">Default</Badge>
- </p>
- <p className="text-foreground-light text-sm">
- The <code className="text-code-inline">postgres</code> role, which bypasses all Row
- Level Security (RLS) policies.
- </p>
- </div>
- )}
-
- {selectedOption === 'anon' && (
- <div>
- <p className="text-sm">For unauthenticated access</p>
- <p className="text-foreground-light text-sm">
- The <code className="text-code-inline">anon</code> role, which the API (PostgREST)
- uses when a user is not logged in.
- <br />
- Row Level Security (RLS) policies apply.
- </p>
- </div>
- )}
-
- {selectedOption === 'authenticated' && (
- <div>
- <p className="text-sm">For authenticated access</p>
- <p className="text-foreground-light text-sm">
- The <code className="text-code-inline">authenticated</code> role, which the API
- (PostgREST) uses when a user is logged in.
- <br />
- Row Level Security (RLS) policies apply.
- </p>
- </div>
+ </>
)}
- </CardContent>
-
- {selectedOption === 'authenticated' && (
- <CardContent className="p-0">
- <UserImpersonationSelector state={state} />
- </CardContent>
- )}
- </Card>
+ </form>
+ <Separator />
+ <footer className="px-3 py-2">
+ <p aria-live="polite" className="text-xs text-foreground-lighter">
+ {roleSummary}
+ </p>
+ </footer>
+ </div>
)
}
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/useRoleImpersonationSelection.ts b/apps/studio/components/interfaces/RoleImpersonationSelector/useRoleImpersonationSelection.ts
new file mode 100644
index 00000000000..49f6dc3260e
--- /dev/null
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/useRoleImpersonationSelection.ts
@@ -0,0 +1,46 @@
+import { useEffect, useState } from 'react'
+import { toast } from 'sonner'
+
+import { getRoleSelectionUpdate, getSelectedRoleOption } from './RoleImpersonationSelector.utils'
+import type { PostgrestRole } from '@/lib/role-impersonation'
+import type { RoleImpersonationController } from '@/state/role-impersonation-state'
+import type { ResponseError } from '@/types'
+
+export const useRoleImpersonationSelection = (state: RoleImpersonationController) => {
+ const [isAuthenticatedPending, setIsAuthenticatedPending] = useState(false)
+
+ useEffect(() => {
+ if (
+ state.role?.type === 'postgrest' &&
+ state.role.role === 'authenticated' &&
+ isAuthenticatedPending
+ ) {
+ setIsAuthenticatedPending(false)
+ }
+ }, [isAuthenticatedPending, state.role])
+
+ const selectedOption = isAuthenticatedPending
+ ? 'authenticated'
+ : getSelectedRoleOption(state.role)
+
+ async function onSelectedChange(value: PostgrestRole) {
+ const update = getRoleSelectionUpdate(value)
+ if (!update.shouldSetRole) {
+ setIsAuthenticatedPending(true)
+ return
+ }
+
+ try {
+ await state.setRole(update.role)
+ setIsAuthenticatedPending(false)
+ } catch (error) {
+ toast.error(`Failed to impersonate user: ${(error as ResponseError).message}`)
+ }
+ }
+
+ function keepAuthenticatedSelected() {
+ setIsAuthenticatedPending(true)
+ }
+
+ return { selectedOption, onSelectedChange, keepAuthenticatedSelected }
+}
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/RunAsSubMenu.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/RunAsSubMenu.tsx
index 1f2b714a315..99ebf6f3789 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/RunAsSubMenu.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/RunAsSubMenu.tsx
@@ -34,7 +34,6 @@ export const RunAsSubMenu = (props: RunAsSubMenuProps) => {
dropdown's typeahead. */}
<DropdownMenuSubContent className="w-80 p-0" onKeyDown={(e) => e.stopPropagation()}>
<RoleImpersonationSelectorInterface
- orientation="vertical"
header="Run SQL query as a role"
serviceRoleLabel={SERVICE_ROLE_LABEL}
state={state}
diff --git a/apps/studio/tests/components/SQLEditor/RoleImpersonationSelector.test.tsx b/apps/studio/tests/components/SQLEditor/RoleImpersonationSelector.test.tsx
new file mode 100644
index 00000000000..1ccca3ca6ab
--- /dev/null
+++ b/apps/studio/tests/components/SQLEditor/RoleImpersonationSelector.test.tsx
@@ -0,0 +1,133 @@
+import { screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { toast } from 'sonner'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { RoleImpersonationSelectorInterface } from '@/components/interfaces/RoleImpersonationSelector'
+import type { ImpersonationRole } from '@/lib/role-impersonation'
+import type { RoleImpersonationController } from '@/state/role-impersonation-state'
+import { customRender } from '@/tests/lib/custom-render'
+
+vi.mock('sonner', () => ({ toast: { error: vi.fn() } }))
+
+vi.mock('@/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector', () => ({
+ UserImpersonationSelector: ({ disabled }: { disabled?: boolean }) => (
+ <fieldset data-testid="user-settings" disabled={disabled}>
+ <button type="button" tabIndex={0}>
+ Project
+ </button>
+ </fieldset>
+ ),
+}))
+
+describe('RoleImpersonationSelectorInterface', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('enables user settings for authenticated queries and summarizes each role', async () => {
+ const user = userEvent.setup()
+ let currentRole: ImpersonationRole | undefined
+ const setRole = vi.fn(async (role: ImpersonationRole | undefined) => {
+ currentRole = role
+ })
+ const state: RoleImpersonationController = {
+ get role() {
+ return currentRole
+ },
+ claims: undefined,
+ setRole,
+ }
+
+ const { rerender } = customRender(<RoleImpersonationSelectorInterface state={state} />)
+
+ expect(screen.queryByText('Role')).not.toBeInTheDocument()
+ for (const option of screen.getAllByRole('radio')) {
+ expect(option).toHaveClass('w-full')
+ expect(option.querySelector('svg')).toBeInTheDocument()
+ }
+ expect(screen.getByRole('radio', { name: 'PostgresSuperuser' })).toBeChecked()
+ expect(screen.getByText('Bypasses RLS and can return all rows.')).toBeVisible()
+ expect(screen.getByTestId('user-settings')).toBeDisabled()
+
+ await user.click(screen.getByRole('radio', { name: 'AuthenticatedLogged-in user' }))
+
+ expect(screen.getByText('Returns rows available to the selected user.')).toBeVisible()
+ expect(screen.getByTestId('user-settings')).not.toBeDisabled()
+
+ await user.click(screen.getByRole('radio', { name: 'AnonymousNot logged in' }))
+ rerender(<RoleImpersonationSelectorInterface state={state} />)
+
+ expect(screen.getByText('Returns rows available to anonymous users.')).toBeVisible()
+ expect(setRole).toHaveBeenCalledWith({ type: 'postgrest', role: 'anon' })
+ expect(screen.getByTestId('user-settings')).toBeDisabled()
+
+ await user.click(screen.getByRole('radio', { name: 'PostgresSuperuser' }))
+ rerender(<RoleImpersonationSelectorInterface state={state} />)
+
+ expect(screen.getByText('Bypasses RLS and can return all rows.')).toBeVisible()
+ expect(setRole).toHaveBeenCalledWith(undefined)
+ })
+
+ it('follows externally cleared role state', () => {
+ let currentRole: ImpersonationRole | undefined = {
+ type: 'postgrest',
+ role: 'authenticated',
+ userType: 'native',
+ }
+ const state: RoleImpersonationController = {
+ get role() {
+ return currentRole
+ },
+ claims: undefined,
+ setRole: vi.fn(),
+ }
+
+ const { rerender } = customRender(<RoleImpersonationSelectorInterface state={state} />)
+
+ expect(screen.getByRole('radio', { name: 'AuthenticatedLogged-in user' })).toBeChecked()
+ expect(screen.getByTestId('user-settings')).not.toBeDisabled()
+
+ currentRole = undefined
+ rerender(<RoleImpersonationSelectorInterface state={state} />)
+
+ expect(screen.getByRole('radio', { name: 'PostgresSuperuser' })).toBeChecked()
+ expect(screen.getByTestId('user-settings')).toBeDisabled()
+ })
+
+ it('allows switching roles while impersonating a user', async () => {
+ const user = userEvent.setup()
+ const setRole = vi.fn().mockResolvedValue(undefined)
+ const state: RoleImpersonationController = {
+ role: {
+ type: 'postgrest',
+ role: 'authenticated',
+ userType: 'external',
+ externalAuth: { sub: 'external-user', additionalClaims: {} },
+ },
+ claims: undefined,
+ setRole,
+ }
+
+ customRender(<RoleImpersonationSelectorInterface state={state} />)
+
+ await user.click(screen.getByRole('radio', { name: 'AnonymousNot logged in' }))
+
+ expect(setRole).toHaveBeenCalledWith({ type: 'postgrest', role: 'anon' })
+ })
+
+ it('keeps the current selection and reports rejected role switches', async () => {
+ const user = userEvent.setup()
+ const state: RoleImpersonationController = {
+ role: undefined,
+ claims: undefined,
+ setRole: vi.fn().mockRejectedValue({ message: 'Role switch failed' }),
+ }
+
+ customRender(<RoleImpersonationSelectorInterface state={state} />)
+ await user.click(screen.getByRole('radio', { name: 'AnonymousNot logged in' }))
+
+ expect(screen.getByRole('radio', { name: 'PostgresSuperuser' })).toBeChecked()
+ expect(toast.error).toHaveBeenCalledWith('Failed to impersonate user: Role switch failed')
+ })
+})
diff --git a/apps/studio/tests/components/SQLEditor/RoleImpersonationSelector.utils.test.ts b/apps/studio/tests/components/SQLEditor/RoleImpersonationSelector.utils.test.ts
new file mode 100644
index 00000000000..ea2abda8b07
--- /dev/null
+++ b/apps/studio/tests/components/SQLEditor/RoleImpersonationSelector.utils.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ getRoleSelectionUpdate,
+ getSelectedRoleOption,
+} from '@/components/interfaces/RoleImpersonationSelector/RoleImpersonationSelector.utils'
+import type { ImpersonationRole, PostgrestRole } from '@/lib/role-impersonation'
+
+describe('getSelectedRoleOption', () => {
+ const cases: Array<{
+ name: string
+ role: ImpersonationRole | undefined
+ expected: PostgrestRole
+ }> = [
+ { name: 'defaults to Postgres when no role is set', role: undefined, expected: 'service_role' },
+ {
+ name: 'maps the service role to Postgres',
+ role: { type: 'postgrest', role: 'service_role' },
+ expected: 'service_role',
+ },
+ {
+ name: 'maps custom roles to Postgres',
+ role: { type: 'custom', role: 'reporter' },
+ expected: 'service_role',
+ },
+ {
+ name: 'preserves the anonymous role',
+ role: { type: 'postgrest', role: 'anon' },
+ expected: 'anon',
+ },
+ {
+ name: 'preserves native authenticated roles',
+ role: {
+ type: 'postgrest',
+ role: 'authenticated',
+ userType: 'native',
+ },
+ expected: 'authenticated',
+ },
+ {
+ name: 'preserves external authenticated roles',
+ role: {
+ type: 'postgrest',
+ role: 'authenticated',
+ userType: 'external',
+ },
+ expected: 'authenticated',
+ },
+ ]
+
+ it.each(cases)('$name', ({ role, expected }) => {
+ expect(getSelectedRoleOption(role)).toBe(expected)
+ })
+})
+
+describe('getRoleSelectionUpdate', () => {
+ it('clears role impersonation for Postgres', () => {
+ expect(getRoleSelectionUpdate('service_role')).toEqual({
+ shouldSetRole: true,
+ role: undefined,
+ })
+ })
+
+ it('sets the anonymous PostgREST role', () => {
+ expect(getRoleSelectionUpdate('anon')).toEqual({
+ shouldSetRole: true,
+ role: { type: 'postgrest', role: 'anon' },
+ })
+ })
+
+ it('waits for a user selection before setting the authenticated role', () => {
+ expect(getRoleSelectionUpdate('authenticated')).toEqual({ shouldSetRole: false })
+ })
+})
diff --git a/apps/studio/tests/components/SQLEditor/UserImpersonationSelector.test.tsx b/apps/studio/tests/components/SQLEditor/UserImpersonationSelector.test.tsx
new file mode 100644
index 00000000000..aad89d6383c
--- /dev/null
+++ b/apps/studio/tests/components/SQLEditor/UserImpersonationSelector.test.tsx
@@ -0,0 +1,151 @@
+import { screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { mockAnimationsApi } from 'jsdom-testing-mocks'
+import { HttpResponse } from 'msw'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { UserImpersonationSelector } from '@/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector'
+import type { AuthConfigResponse } from '@/data/auth/auth-config-query'
+import type { User } from '@/data/auth/users-infinite-query'
+import type { ProjectDetail } from '@/data/projects/project-detail-query'
+import type { RoleImpersonationController } from '@/state/role-impersonation-state'
+import { customRender } from '@/tests/lib/custom-render'
+import { addAPIMock } from '@/tests/lib/msw'
+
+mockAnimationsApi()
+
+const PROJECT: ProjectDetail = {
+ cloud_provider: 'AWS',
+ connectionString: 'postgresql://postgres@localhost:5432/postgres',
+ db_host: 'db.default.supabase.co',
+ high_availability: false,
+ id: 1,
+ inserted_at: '2026-01-01T00:00:00.000Z',
+ integration_source: null,
+ is_branch_enabled: false,
+ is_hibernating: false,
+ is_physical_backups_enabled: false,
+ name: 'Test project',
+ organization_id: 1,
+ ref: 'default',
+ region: 'us-east-1',
+ restUrl: 'https://default.supabase.co/rest/v1',
+ status: 'ACTIVE_HEALTHY',
+ subscription_id: 'subscription-1',
+ updated_at: '2026-01-01T00:00:00.000Z',
+}
+
+const AUTH_CONFIG_WITHOUT_CUSTOM_ACCESS_TOKEN_HOOK = {
+ HOOK_CUSTOM_ACCESS_TOKEN_ENABLED: false,
+ HOOK_CUSTOM_ACCESS_TOKEN_SECRETS: '',
+ HOOK_CUSTOM_ACCESS_TOKEN_URI: '',
+} as unknown as AuthConfigResponse
+
+describe('UserImpersonationSelector', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+
+ addAPIMock({
+ method: 'get',
+ path: '/platform/projects/:ref',
+ response: PROJECT,
+ })
+ addAPIMock({
+ method: 'get',
+ path: '/platform/auth/:ref/config',
+ response: () =>
+ HttpResponse.json<AuthConfigResponse>(AUTH_CONFIG_WITHOUT_CUSTOM_ACCESS_TOKEN_HOOK),
+ })
+ addAPIMock({
+ method: 'post',
+ path: '/platform/pg-meta/:ref/query',
+ response: () => HttpResponse.json<User[]>([]),
+ })
+ })
+
+ it('shows the external claims example and MFA guidance in the shared layout', async () => {
+ const user = userEvent.setup()
+ const state: RoleImpersonationController = {
+ role: {
+ type: 'postgrest',
+ role: 'authenticated',
+ userType: 'native',
+ },
+ claims: undefined,
+ setRole: vi.fn(),
+ }
+
+ customRender(<UserImpersonationSelector state={state} />)
+ await user.click(screen.getByRole('radio', { name: 'External' }))
+
+ expect(
+ screen.getByPlaceholderText('e.g. {"app_metadata": {"org_id": "org_456"}}')
+ ).toBeVisible()
+ expect(screen.getByText('MFA level')).toBeVisible()
+ expect(screen.getByRole('button', { name: 'Users' })).toBeVisible()
+ expect(screen.getByRole('button', { name: 'MFA level' })).toBeVisible()
+ })
+
+ it('clears the selected user when switching user sources', async () => {
+ const user = userEvent.setup()
+ const onUserImpersonationCleared = vi.fn()
+ const state: RoleImpersonationController = {
+ role: {
+ type: 'postgrest',
+ role: 'authenticated',
+ userType: 'external',
+ externalAuth: { sub: 'external-user', additionalClaims: {} },
+ aal: 'aal2',
+ },
+ claims: undefined,
+ setRole: vi.fn().mockResolvedValue(undefined),
+ }
+
+ customRender(
+ <UserImpersonationSelector
+ state={state}
+ onUserImpersonationCleared={onUserImpersonationCleared}
+ />
+ )
+
+ expect(screen.getByRole('radio', { name: 'Project' })).toBeEnabled()
+ expect(screen.getByRole('radio', { name: 'External' })).toBeEnabled()
+ expect(screen.getByRole('button', { name: 'Stop impersonating user' })).toBeEnabled()
+
+ await user.click(screen.getByRole('radio', { name: 'Project' }))
+
+ expect(state.setRole).toHaveBeenCalledWith(undefined)
+ expect(onUserImpersonationCleared).toHaveBeenCalledOnce()
+ })
+
+ it('updates the active impersonation when switching MFA levels', async () => {
+ const user = userEvent.setup()
+ const state: RoleImpersonationController = {
+ role: {
+ type: 'postgrest',
+ role: 'authenticated',
+ userType: 'external',
+ externalAuth: { sub: 'external-user', additionalClaims: {} },
+ aal: 'aal2',
+ },
+ claims: undefined,
+ setRole: vi.fn().mockResolvedValue(undefined),
+ }
+
+ customRender(<UserImpersonationSelector state={state} />)
+
+ expect(screen.getByRole('radio', { name: 'AAL1' })).toBeEnabled()
+ expect(screen.getByRole('radio', { name: 'AAL2' })).toBeEnabled()
+ expect(screen.getByRole('radio', { name: 'AAL2' })).toBeChecked()
+
+ await user.click(screen.getByRole('radio', { name: 'AAL1' }))
+
+ expect(state.setRole).toHaveBeenCalledWith(
+ expect.objectContaining({
+ aal: 'aal1',
+ externalAuth: { sub: 'external-user', additionalClaims: {} },
+ }),
+ undefined
+ )
+ })
+})