Skip to content

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

Prototype: Enhance Supabase Studio User Impersonation with External Auth Support (#32786)

Sanden Gockaecd7b5f4ddf3
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx
index 8c978d87539..e13d5e6c545 100644
--- a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx
@@ -42,7 +42,11 @@ const RoleImpersonationPopover = ({
<span>{currentRole}</span>
{state.role?.type === 'postgrest' && state.role.role === 'authenticated' && (
<>
- <UserRoleButtonSection user={state.role.user} />
+ {state.role.userType === 'native' && state.role.user ? (
+ <UserRoleButtonSection user={state.role.user} />
+ ) : state.role.userType === 'external' && state.role.externalAuth ? (
+ <ExternalAuthButtonSection sub={state.role.externalAuth.sub} />
+ ) : null}
<span className="text-xs text-foreground-lighter font-light">
{state.role.aal === 'aal2' ? 'AAL2' : 'AAL1'}
</span>
@@ -78,3 +82,14 @@ const UserRoleButtonSection = ({ user }: { user: User }) => {
</div>
)
}
+
+const ExternalAuthButtonSection = ({ sub }: { sub: string }) => {
+ return (
+ <div className="flex gap-1 items-center pl-0.5 pr-1.5 h-[21px] bg-surface-200 rounded-full overflow-hidden">
+ <div className="rounded-full w-[18px] h-[18px] bg-surface-100 border flex items-center justify-center text-light">
+ <IconUser size={12} strokeWidth={2} />
+ </div>
+ <span className="truncate max-w-[84px]">{sub}</span>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationSelector.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationSelector.tsx
index 248b2545ada..17b121074ca 100644
--- a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationSelector.tsx
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationSelector.tsx
@@ -33,7 +33,8 @@ const RoleImpersonationSelector = ({
selectedOption === 'authenticated' &&
state.role?.type === 'postgrest' &&
state.role.role === 'authenticated' &&
- state.role.user
+ (('user' in state.role && state.role.user) ||
+ ('externalAuth' in state.role && state.role.externalAuth)) // Check for either auth type
)
function onSelectedChange(value: PostgrestRole) {
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx
index e834e1422e5..1e90c0bc11b 100644
--- a/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx
@@ -1,6 +1,7 @@
import { useDebounce } from '@uidotdev/usehooks'
import { ChevronDown, ExternalLink, User as IconUser, Loader2, Search, X } from 'lucide-react'
import { useMemo, useState } from 'react'
+import { toast } from 'sonner'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import AlertError from 'components/ui/AlertError'
@@ -22,6 +23,9 @@ type AuthenticatorAssuranceLevels = 'aal1' | 'aal2'
const UserImpersonationSelector = () => {
const [searchText, setSearchText] = useState('')
const [aal, setAal] = useState<AuthenticatorAssuranceLevels>('aal1')
+ const [externalUserId, setExternalUserId] = useState('')
+ const [additionalClaims, setAdditionalClaims] = useState('')
+ const [showExternalAuth, setShowExternalAuth] = useState(false)
const state = useRoleImpersonationStateSnapshot()
const debouncedSearchText = useDebounce(searchText, 300)
@@ -41,45 +45,83 @@ const UserImpersonationSelector = () => {
const users = useMemo(() => data?.pages.flatMap((page) => page.result) ?? [], [data?.pages])
const isSearching = isPreviousData && isFetching
const impersonatingUser =
- state.role?.type === 'postgrest' && state.role.role === 'authenticated' && state.role.user
+ state.role?.type === 'postgrest' &&
+ 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?.type === 'postgrest' &&
+ state.role.role === 'authenticated' &&
+ state.role.userType === 'external' &&
+ state.role.externalAuth
function impersonateUser(user: User) {
state.setRole({
type: 'postgrest',
role: 'authenticated',
+ userType: 'native',
user,
aal,
})
}
+ // 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
+ function impersonateExternalUser() {
+ let parsedClaims = {}
+ try {
+ parsedClaims = additionalClaims ? JSON.parse(additionalClaims) : {}
+ } catch (e) {
+ toast.error('Invalid JSON in additional claims')
+ return
+ }
+
+ state.setRole({
+ type: 'postgrest',
+ role: 'authenticated',
+ userType: 'external',
+ externalAuth: {
+ sub: externalUserId,
+ additionalClaims: parsedClaims,
+ },
+ aal,
+ })
+ }
+
function stopImpersonating() {
state.setRole(undefined)
+ setShowExternalAuth(false) // Reset external auth impersonation when stopping impersonation
}
function toggleAalState() {
setAal((prev) => (prev === 'aal2' ? 'aal1' : 'aal2'))
}
+ const displayName = impersonatingUser
+ ? getDisplayName(
+ impersonatingUser,
+ impersonatingUser.email ?? impersonatingUser.phone ?? impersonatingUser.id ?? 'Unknown'
+ )
+ : isExternalAuthImpersonating
+ ? state.role.externalAuth.sub
+ : undefined
+
return (
<div className="flex flex-col gap-1">
<h2 className="text-foreground text-sm">
- {impersonatingUser
- ? `Impersonating ${getDisplayName(
- impersonatingUser,
- impersonatingUser.email ??
- impersonatingUser.phone ??
- impersonatingUser.id ??
- 'Unknown'
- )}`
- : 'Impersonate a User'}
+ {displayName ? `Impersonating ${displayName}` : 'Impersonate a User'}
</h2>
<p className="text-sm text-foreground-light">
- {!impersonatingUser
+ {!impersonatingUser && !isExternalAuthImpersonating
? "Select a user to respect your database's Row-Level Security policies for that particular user."
: "Results will respect your database's Row-Level Security policies for this user."}
</p>
- {!impersonatingUser ? (
+ {/* 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 ? (
<div className="flex flex-col gap-2 mt-2">
<Input
className="table-editor-search border-none"
@@ -120,68 +162,137 @@ const UserImpersonationSelector = () => {
/>
</div>
</CollapsibleTrigger_Shadcn_>
- <CollapsibleContent_Shadcn_ className="mt-1 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="flex flex-col gap-1 max-w-96">
- <p>
- AAL1 verifies users via standard login methods, while AAL2 adds a second
- authentication factor.
- <br />
- If you're not using MFA, you can leave this on AAL1.
- </p>
- <a
- href="/docs/guides/auth/auth-mfa"
- target="_blank"
- rel="noreferrer"
- className="flex items-center gap-x-1 opacity-50 hover:opacity-100 transition"
- >
- Learn more about MFA <ExternalLink size={14} strokeWidth={2} />
- </a>
- </InfoTooltip>
+ <CollapsibleContent_Shadcn_ 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="flex flex-col gap-1 max-w-96">
+ <p>
+ AAL1 verifies users via standard login methods, while AAL2 adds a second
+ authentication factor.
+ <br />
+ If you're not using MFA, you can leave this on AAL1.
+ </p>
+ <a
+ href="/docs/guides/auth/auth-mfa"
+ target="_blank"
+ rel="noreferrer"
+ className="flex items-center gap-x-1 opacity-50 hover:opacity-100 transition"
+ >
+ Learn more about MFA <ExternalLink size={14} strokeWidth={2} />
+ </a>
+ </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>
- <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 className="flex flex-col gap-y-2">
+ <div className="flex items-center gap-x-1">
+ <h3 className="text-sm text-foreground-light">External Auth Impersonation</h3>
+ <InfoTooltip side="top" className="flex flex-col gap-1 max-w-96">
+ <p>
+ Test RLS policies with external auth providers like Clerk or Auth0 by
+ providing a user ID and optional claims.
+ </p>
+ </InfoTooltip>
+ </div>
+
+ <div className="flex flex-row items-center gap-x-2">
+ <Switch checked={showExternalAuth} onCheckedChange={setShowExternalAuth} />
+ <p className="text-xs text-foreground-light">
+ Enable external auth impersonation
+ </p>
+ </div>
+
+ {showExternalAuth && (
+ <div className="flex flex-col gap-y-4 mt-2 border rounded-md p-4 bg-surface-100">
+ <Input
+ className="border-strong"
+ label="External User ID"
+ descriptionText="The user ID from your external auth provider"
+ placeholder="e.g. user_abc123"
+ value={externalUserId}
+ onChange={(e) => setExternalUserId(e.target.value)}
+ size="small"
+ />
+ <Input
+ className="border-strong"
+ label="Additional Claims (JSON)"
+ descriptionText="Optional: Add custom claims like org_id or roles"
+ placeholder='e.g. {"app_metadata": {"org_id": "org_456"}}'
+ value={additionalClaims}
+ onChange={(e) => setAdditionalClaims(e.target.value)}
+ size="small"
+ />
+ <div className="flex items-center justify-between">
+ <div />
+ <Button
+ type="default"
+ disabled={!externalUserId}
+ onClick={impersonateExternalUser}
+ >
+ Impersonate
+ </Button>
+ </div>
+ </div>
+ )}
</div>
</CollapsibleContent_Shadcn_>
</Collapsible_Shadcn_>
- {isLoading && (
- <div className="flex flex-col gap-2 items-center justify-center h-24">
- <Loader2 className="animate-spin" size={24} />
- <span>Loading users...</span>
- </div>
- )}
+ {!showExternalAuth && (
+ <>
+ {isLoading && (
+ <div className="flex flex-col gap-2 items-center justify-center h-24">
+ <Loader2 className="animate-spin" size={24} />
+ <span>Loading users...</span>
+ </div>
+ )}
- {isError && <AlertError error={error} subject="Failed to retrieve users" />}
+ {isError && <AlertError error={error} subject="Failed to retrieve users" />}
- {isSuccess &&
- (users.length > 0 ? (
- <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} />
- </li>
+ {isSuccess &&
+ (users.length > 0 ? (
+ <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} />
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <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>
))}
- </ul>
- ) : (
- <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>
- ))}
+ </>
+ )}
</div>
) : (
- <UserImpersonatingRow
- user={impersonatingUser}
- onClick={stopImpersonating}
- isImpersonating={true}
- aal={aal}
- />
+ <>
+ {impersonatingUser && (
+ <UserImpersonatingRow
+ user={impersonatingUser}
+ onClick={stopImpersonating}
+ isImpersonating={true}
+ aal={aal}
+ />
+ )}
+ {isExternalAuthImpersonating && (
+ <ExternalAuthImpersonatingRow
+ sub={state.role.externalAuth.sub}
+ onClick={stopImpersonating}
+ aal={aal}
+ />
+ )}
+ </>
)}
</div>
)
@@ -189,23 +300,23 @@ const UserImpersonationSelector = () => {
export default UserImpersonationSelector
-interface UserRowProps {
- user: User
- onClick: (user: User) => void
- isImpersonating?: boolean
+// 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
}
-const UserImpersonatingRow = ({
- user,
+const BaseImpersonatingRow = ({
onClick,
- isImpersonating = false,
aal,
-}: UserRowProps & { aal: AuthenticatorAssuranceLevels }) => {
- const avatarUrl = getAvatarUrl(user)
- const displayName =
- getDisplayName(user, user.email ?? user.phone ?? user.id ?? 'Unknown') +
- (user.is_anonymous ? ' (anonymous)' : '')
-
+ displayName,
+ avatarUrl,
+ isImpersonating = 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">
@@ -225,13 +336,47 @@ const UserImpersonatingRow = ({
</span>
</div>
- <Button type="default" onClick={() => onClick(user)}>
+ <Button type="default" onClick={onClick}>
{isImpersonating ? 'Stop Impersonating' : 'Impersonate'}
</Button>
</div>
)
}
+const UserImpersonatingRow = ({
+ user,
+ onClick,
+ isImpersonating = 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}
+ />
+ )
+}
+
+interface ExternalAuthImpersonatingRowProps {
+ sub: string
+ onClick: () => void
+ aal: AuthenticatorAssuranceLevels
+}
+
+const ExternalAuthImpersonatingRow = ({ sub, onClick, aal }: ExternalAuthImpersonatingRowProps) => {
+ return (
+ <BaseImpersonatingRow onClick={onClick} aal={aal} displayName={sub} isImpersonating={true} />
+ )
+}
+
interface UserRowProps {
user: User
onClick: (user: User) => void
diff --git a/apps/studio/lib/role-impersonation.ts b/apps/studio/lib/role-impersonation.ts
index 23f0eeb0c3a..71db4a0d695 100644
--- a/apps/studio/lib/role-impersonation.ts
+++ b/apps/studio/lib/role-impersonation.ts
@@ -13,7 +13,18 @@ type PostgrestImpersonationRole =
| {
type: 'postgrest'
role: 'authenticated'
- user: User
+ userType: 'native'
+ user?: User
+ aal?: 'aal1' | 'aal2'
+ }
+ | {
+ type: 'postgrest'
+ role: 'authenticated'
+ userType: 'external'
+ externalAuth?: {
+ sub: string
+ additionalClaims?: Record<string, any>
+ }
aal?: 'aal1' | 'aal2'
}
@@ -34,23 +45,39 @@ function getPostgrestClaims(projectRef: string, role: PostgrestImpersonationRole
const nowTimestamp = Math.floor(Date.now() / 1000)
if (role.role === 'authenticated') {
- const user = role.user
-
- return {
- aal: role.aal ?? 'aal1',
- amr: [{ method: 'password', timestamp: nowTimestamp }],
- app_metadata: user.raw_app_meta_data,
- aud: 'authenticated',
- email: user.email,
- exp,
- iat: nowTimestamp,
- iss: `https://${projectRef}.supabase.co/auth/v1`,
- phone: user.phone,
- role: user.role ?? role.role,
- session_id: uuidv4(),
- sub: user.id,
- user_metadata: user.raw_user_meta_data,
- is_anonymous: user.is_anonymous,
+ // Supabase native auth case
+ if (role.userType === 'native' && role.user) {
+ const user = role.user
+ return {
+ aal: role.aal ?? 'aal1',
+ amr: [{ method: 'password', timestamp: nowTimestamp }],
+ app_metadata: user.raw_app_meta_data,
+ aud: 'authenticated',
+ email: user.email,
+ exp,
+ iat: nowTimestamp,
+ iss: `https://${projectRef}.supabase.co/auth/v1`,
+ phone: user.phone,
+ role: user.role ?? role.role,
+ session_id: uuidv4(),
+ sub: user.id,
+ user_metadata: user.raw_user_meta_data,
+ is_anonymous: user.is_anonymous,
+ }
+ }
+
+ // External auth case
+ if (role.userType === 'external' && role.externalAuth) {
+ return {
+ aal: role.aal ?? 'aal1',
+ aud: 'authenticated',
+ exp,
+ iat: nowTimestamp,
+ role: 'authenticated',
+ session_id: uuidv4(),
+ sub: role.externalAuth.sub,
+ ...role.externalAuth.additionalClaims,
+ }
}
}