Skip to content

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

feat: user impersonation (#18945)

Alaister Younge6006b96533c
diff --git a/apps/studio/components/grid/SupabaseGrid.tsx b/apps/studio/components/grid/SupabaseGrid.tsx
index 8650c1d7632..23bd7149728 100644
--- a/apps/studio/components/grid/SupabaseGrid.tsx
+++ b/apps/studio/components/grid/SupabaseGrid.tsx
@@ -7,6 +7,7 @@ import { createPortal } from 'react-dom'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { useTableRowsQuery } from 'data/table-rows/table-rows-query'
import { useUrlState } from 'hooks'
+import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import {
cleanupProps,
@@ -66,6 +67,8 @@ const SupabaseGridLayout = forwardRef<SupabaseGridRef, SupabaseGridProps>(
const sorts = formatSortURLParams(sort as string[])
const filters = formatFilterURLParams(filter as string[])
+ const roleImpersonationState = useRoleImpersonationStateSnapshot()
+
const { project } = useProjectContext()
const { data, error, isSuccess, isError, isLoading, isRefetching } = useTableRowsQuery(
{
@@ -77,6 +80,7 @@ const SupabaseGridLayout = forwardRef<SupabaseGridRef, SupabaseGridProps>(
filters,
page: snap.page,
limit: snap.rowsPerPage,
+ impersonatedRole: roleImpersonationState.role,
},
{
keepPreviousData: true,
diff --git a/apps/studio/components/grid/components/footer/pagination/Pagination.tsx b/apps/studio/components/grid/components/footer/pagination/Pagination.tsx
index 0bf53e4b552..5d9de68d070 100644
--- a/apps/studio/components/grid/components/footer/pagination/Pagination.tsx
+++ b/apps/studio/components/grid/components/footer/pagination/Pagination.tsx
@@ -6,6 +6,7 @@ import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectConte
import ConfirmationModal from 'components/ui/ConfirmationModal'
import { useTableRowsCountQuery } from 'data/table-rows/table-rows-count-query'
import { useUrlState } from 'hooks'
+import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
import { Button, IconArrowLeft, IconArrowRight, IconLoader, InputNumber, Modal } from 'ui'
import { useDispatch, useTrackedState } from '../../../store'
import { DropdownControl } from '../../common'
@@ -33,6 +34,9 @@ const Pagination = ({ isLoading: isLoadingRows = false }: PaginationProps) => {
})
const filters = formatFilterURLParams(filter as string[])
const table = state.table ?? undefined
+
+ const roleImpersonationState = useRoleImpersonationStateSnapshot()
+
const { project } = useProjectContext()
const { data, isLoading, isSuccess, isError } = useTableRowsCountQuery(
{
@@ -41,6 +45,7 @@ const Pagination = ({ isLoading: isLoadingRows = false }: PaginationProps) => {
connectionString: project?.connectionString,
table,
filters,
+ impersonatedRole: roleImpersonationState.role,
},
{
keepPreviousData: true,
diff --git a/apps/studio/components/grid/components/header/Header.tsx b/apps/studio/components/grid/components/header/Header.tsx
index a73b6566a1b..0aee780bdf9 100644
--- a/apps/studio/components/grid/components/header/Header.tsx
+++ b/apps/studio/components/grid/components/header/Header.tsx
@@ -24,6 +24,7 @@ import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectConte
import { useTableRowsCountQuery } from 'data/table-rows/table-rows-count-query'
import { useTableRowsQuery } from 'data/table-rows/table-rows-query'
import { useCheckPermissions, useStore, useUrlState } from 'hooks'
+import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import RLSBannerWarning from './RLSBannerWarning'
import RefreshButton from './RefreshButton'
@@ -126,8 +127,12 @@ const DefaultHeader = ({
<div className="flex items-center gap-2">
{canCreateColumns && (
<DropdownMenu>
- <DropdownMenuTrigger className="flex">
- <Button size="tiny" icon={<IconChevronDown size={14} strokeWidth={1.5} />}>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="primary"
+ size="tiny"
+ icon={<IconChevronDown size={14} strokeWidth={1.5} />}
+ >
Insert
</Button>
</DropdownMenuTrigger>
@@ -234,6 +239,8 @@ const RowHeader = ({ table, sorts, filters }: RowHeaderProps) => {
const { project } = useProjectContext()
const snap = useTableEditorStateSnapshot()
+ const roleImpersonationState = useRoleImpersonationStateSnapshot()
+
const [isExporting, setIsExporting] = useState(false)
const { data } = useTableRowsQuery({
@@ -245,6 +252,7 @@ const RowHeader = ({ table, sorts, filters }: RowHeaderProps) => {
filters,
page: snap.page,
limit: snap.rowsPerPage,
+ impersonatedRole: roleImpersonationState.role,
})
const { data: countData } = useTableRowsCountQuery(
@@ -254,6 +262,7 @@ const RowHeader = ({ table, sorts, filters }: RowHeaderProps) => {
connectionString: project?.connectionString,
table,
filters,
+ impersonatedRole: roleImpersonationState.role,
},
{ keepPreviousData: true }
)
diff --git a/apps/studio/components/interfaces/Auth/Users/UserListItem.utils.ts b/apps/studio/components/interfaces/Auth/Users/UserListItem.utils.ts
new file mode 100644
index 00000000000..cf48113df31
--- /dev/null
+++ b/apps/studio/components/interfaces/Auth/Users/UserListItem.utils.ts
@@ -0,0 +1,61 @@
+import { User } from 'data/auth/users-query'
+
+export function getDisplayName(user: User, fallback = '-'): string {
+ const {
+ displayName,
+ display_name,
+ fullName,
+ full_name,
+ familyName,
+ family_name,
+ givenName,
+ given_name,
+ surname,
+ lastName,
+ last_name,
+ firstName,
+ first_name,
+ } = user.raw_user_meta_data ?? {}
+
+ const last = familyName || family_name || surname || lastName || last_name
+ const first = givenName || given_name || firstName || first_name
+
+ return (
+ displayName ||
+ display_name ||
+ fullName ||
+ full_name ||
+ (first && last && `${first} ${last}`) ||
+ fallback
+ )
+}
+
+export function getAvatarUrl(user: User): string | undefined {
+ const {
+ avatarUrl,
+ avatarURL,
+ avatar_url,
+ profileUrl,
+ profileURL,
+ profile_url,
+ profileImage,
+ profile_image,
+ profileImageUrl,
+ profileImageURL,
+ profile_image_url,
+ } = user.raw_user_meta_data ?? {}
+
+ return (
+ avatarUrl ||
+ avatarURL ||
+ avatar_url ||
+ profileImage ||
+ profile_image ||
+ profileUrl ||
+ profileURL ||
+ profile_url ||
+ profileImageUrl ||
+ profileImageURL ||
+ profile_image_url
+ )
+}
diff --git a/apps/studio/components/interfaces/Auth/Users/UsersList.tsx b/apps/studio/components/interfaces/Auth/Users/UsersList.tsx
index dd9e9878bea..f34479d04a5 100644
--- a/apps/studio/components/interfaces/Auth/Users/UsersList.tsx
+++ b/apps/studio/components/interfaces/Auth/Users/UsersList.tsx
@@ -40,6 +40,7 @@ const UsersList = ({
<Table
head={
<>
+ <Table.th>Display Name</Table.th>
<Table.th>Email</Table.th>
<Table.th>Phone</Table.th>
<Table.th className="table-cell">Provider</Table.th>
@@ -55,7 +56,7 @@ const UsersList = ({
<Table.tr>
{/* @ts-ignore */}
<Table.td
- colSpan={7}
+ colSpan={8}
className="h-14 whitespace-nowrap border-t p-4 text-sm leading-5 text-gray-300"
>
<div className="flex items-center space-x-3 opacity-75">
@@ -80,7 +81,7 @@ const UsersList = ({
/>
))}
<Table.tr>
- <Table.td colSpan={7}>
+ <Table.td colSpan={8}>
<UsersPagination total={total} page={page} setPage={setPage} />
</Table.td>
</Table.tr>
diff --git a/apps/studio/components/interfaces/Auth/Users/UsersListItem.tsx b/apps/studio/components/interfaces/Auth/Users/UsersListItem.tsx
index 3f197c44bfd..3a67ff0e552 100644
--- a/apps/studio/components/interfaces/Auth/Users/UsersListItem.tsx
+++ b/apps/studio/components/interfaces/Auth/Users/UsersListItem.tsx
@@ -5,6 +5,7 @@ import Table from 'components/to-be-cleaned/Table'
import { User } from 'data/auth/users-query'
import UserDropdown from './UserDropdown'
import { getDateFromIsoString } from './Users.utils'
+import { getDisplayName } from './UserListItem.utils'
interface UserListItemProps {
user: User
@@ -19,6 +20,9 @@ const UserListItem = ({ user, canRemoveUser, canRemoveMFAFactors }: UserListItem
return (
<Table.tr className="relative" key={user.id}>
+ <Table.td className="whitespace-nowrap">
+ <span className="text-foreground">{getDisplayName(user)}</span>
+ </Table.td>
<Table.td className="whitespace-nowrap">
<div className="flex items-center gap-2">
<span className="text-sm text-foreground">{!user.email ? '-' : user.email}</span>
diff --git a/apps/studio/components/interfaces/GraphQL/GraphiQL.tsx b/apps/studio/components/interfaces/GraphQL/GraphiQL.tsx
index d6e92f003a7..596529bae9a 100644
--- a/apps/studio/components/interfaces/GraphQL/GraphiQL.tsx
+++ b/apps/studio/components/interfaces/GraphQL/GraphiQL.tsx
@@ -31,17 +31,28 @@ import {
useTheme,
} from '@graphiql/react'
import { Fetcher } from '@graphiql/toolkit'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
import clsx from 'clsx'
import { MouseEventHandler, useCallback, useEffect, useState } from 'react'
+
+import { useCheckPermissions, useFlag, useLocalStorage } from 'hooks'
+import {
+ AlertDescription_Shadcn_,
+ AlertTitle_Shadcn_,
+ Alert_Shadcn_,
+ Button,
+ IconAlertTriangle,
+} from 'ui'
+import { RoleImpersonationSelector } from '../RoleImpersonationSelector'
import styles from './graphiql.module.css'
+import { XIcon } from 'lucide-react'
export interface GraphiQLProps {
fetcher: Fetcher
theme?: 'dark' | 'light'
- accessToken?: string
}
-export default function GraphiQL({ fetcher, theme = 'dark', accessToken }: GraphiQLProps) {
+export default function GraphiQL({ fetcher, theme = 'dark' }: GraphiQLProps) {
// Ensure props are correct
if (typeof fetcher !== 'function') {
throw new TypeError(
@@ -50,14 +61,7 @@ export default function GraphiQL({ fetcher, theme = 'dark', accessToken }: Graph
}
return (
- <GraphiQLProvider
- fetcher={fetcher}
- defaultHeaders={
- accessToken !== undefined
- ? JSON.stringify({ Authorization: `Bearer ${accessToken}` })
- : undefined
- }
- >
+ <GraphiQLProvider fetcher={fetcher}>
<GraphiQLInterface theme={theme} />
</GraphiQLProvider>
)
@@ -77,6 +81,14 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
const merge = useMergeQuery()
const prettify = usePrettifyEditors()
+ const roleImpersonationEnabledFlag = useFlag('roleImpersonation')
+ const canReadJWTSecret = useCheckPermissions(PermissionAction.READ, 'field.jwt_secret')
+
+ const [rlsBypassedWarningDismissed, setRlsBypassedWarningDismissed] = useLocalStorage(
+ 'graphiql-rls-bypass-warning-dismissed',
+ false
+ )
+
const { setTheme } = useTheme()
useEffect(() => {
setTheme(theme)
@@ -110,13 +122,11 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
storageKey: 'secondaryEditorFlex',
})
- const [activeSecondaryEditor, setActiveSecondaryEditor] = useState<'variables' | 'headers'>(
- () => {
- return !editorContext.initialVariables && editorContext.initialHeaders
- ? 'headers'
- : 'variables'
- }
- )
+ const [activeSecondaryEditor, setActiveSecondaryEditor] = useState<
+ 'variables' | 'headers' | 'role-impersonation'
+ >(() => {
+ return !editorContext.initialVariables && editorContext.initialHeaders ? 'headers' : 'variables'
+ })
const toolbar = (
<>
@@ -164,7 +174,9 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
if (editorToolsResize.hiddenElement === 'second') {
editorToolsResize.setHiddenElement(null)
}
- setActiveSecondaryEditor(event.currentTarget.dataset.name as 'variables' | 'headers')
+ setActiveSecondaryEditor(
+ event.currentTarget.dataset.name as 'variables' | 'headers' | 'role-impersonation'
+ )
},
[editorToolsResize]
)
@@ -179,7 +191,7 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
<Tooltip label="Add tab">
<UnStyledButton
type="button"
- className="graphiql-tab-add"
+ className="graphiql-tab-add text-sm"
onClick={handleAddTab}
aria-label="Add tab"
>
@@ -280,8 +292,8 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
className={
activeSecondaryEditor === 'variables' &&
editorToolsResize.hiddenElement !== 'second'
- ? 'active'
- : ''
+ ? 'active text-sm'
+ : 'text-sm'
}
onClick={handleToolsTabClick}
data-name="variables"
@@ -294,8 +306,8 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
className={
activeSecondaryEditor === 'headers' &&
editorToolsResize.hiddenElement !== 'second'
- ? 'active'
- : ''
+ ? 'active text-sm'
+ : 'text-sm'
}
onClick={handleToolsTabClick}
data-name="headers"
@@ -303,6 +315,22 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
Headers
</UnStyledButton>
+ {canReadJWTSecret && roleImpersonationEnabledFlag && (
+ <UnStyledButton
+ type="button"
+ className={
+ activeSecondaryEditor === 'role-impersonation' &&
+ editorToolsResize.hiddenElement !== 'second'
+ ? 'active text-sm'
+ : 'text-sm'
+ }
+ onClick={handleToolsTabClick}
+ data-name="role-impersonation"
+ >
+ Role Impersonation
+ </UnStyledButton>
+ )}
+
<Tooltip
label={
editorToolsResize.hiddenElement === 'second'
@@ -318,7 +346,7 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
? 'Show editor tools'
: 'Hide editor tools'
}
- className="graphiql-toggle-editor-tools"
+ className="graphiql-toggle-editor-tools text-sm"
>
{editorToolsResize.hiddenElement === 'second' ? (
<ChevronUpIcon className="graphiql-chevron-icon" aria-hidden="true" />
@@ -341,6 +369,17 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
/>
<HeaderEditor isHidden={activeSecondaryEditor !== 'headers'} />
+
+ {canReadJWTSecret && roleImpersonationEnabledFlag && (
+ <div
+ className={clsx(
+ 'graphiql-editor px-1',
+ activeSecondaryEditor !== 'role-impersonation' && 'hidden'
+ )}
+ >
+ <RoleImpersonationSelector padded={false} />
+ </div>
+ )}
</section>
</div>
</div>
@@ -354,7 +393,7 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
<div ref={editorResize.secondRef}>
<div
className={clsx(
- 'graphiql-response text-sm',
+ 'graphiql-response text-sm relative',
hasSingleTab
? styles.graphiqlResponseSingleTab
: styles.graphiqlResponseMultiTab
@@ -362,6 +401,33 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
>
{executionContext.isFetching ? <Spinner /> : null}
<ResponseEditor />
+
+ {!rlsBypassedWarningDismissed && (
+ <Alert_Shadcn_ variant="warning" className="absolute bottom-[5px] right-[5px]">
+ <IconAlertTriangle strokeWidth={2} />
+ <AlertTitle_Shadcn_ className="leading-5 text-foreground">
+ Please note that queries and mutations run in GraphiQL now use the service
+ role key by default.
+ <br />
+ <span className="text-amber-900">RLS will be bypassed.</span>
+ </AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ {roleImpersonationEnabledFlag
+ ? 'You can send queries as a specific role/user by using the role impersonation tab.'
+ : 'You can send queries as a specific role/user by changing the "Authorization" header.'}
+ </AlertDescription_Shadcn_>
+ <Button
+ type="outline"
+ aria-label="Dismiss"
+ className="absolute top-2 right-2 p-1 !pl-1"
+ onClick={() => {
+ setRlsBypassedWarningDismissed(true)
+ }}
+ >
+ <XIcon width={14} height={14} />
+ </Button>
+ </Alert_Shadcn_>
+ )}
</div>
</div>
</div>
@@ -390,7 +456,7 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
<Tooltip key={plugin.title} label={label}>
<UnStyledButton
type="button"
- className={isVisible ? 'active' : ''}
+ className={isVisible ? 'active text-sm' : 'text-sm'}
onClick={handlePluginClick}
data-index={index}
aria-label={label}
@@ -405,6 +471,7 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {
<Tooltip label="Re-fetch GraphQL schema">
<UnStyledButton
type="button"
+ className="text-sm"
disabled={schemaContext.isFetching}
onClick={handleRefetchSchema}
aria-label="Re-fetch GraphQL schema"
diff --git a/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsx b/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsx
index 509c23b155a..23ca0ce2f3e 100644
--- a/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsx
+++ b/apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover/index.tsx
@@ -1,21 +1,11 @@
-import { PlusCircle } from 'lucide-react'
-import { Dispatch, SetStateAction, useEffect, useState } from 'react'
-import {
- Button,
- IconKey,
- IconUnlock,
- IconUser,
- Input,
- Listbox,
- PopoverContent_Shadcn_,
- PopoverTrigger_Shadcn_,
- Popover_Shadcn_,
-} from 'ui'
+import { Dispatch, SetStateAction, useEffect } from 'react'
-import { useProjectSettingsQuery } from 'data/config/project-settings-query'
-import { DEFAULT_PROJECT_API_SERVICE_ID } from 'lib/constants'
+import { RoleImpersonationPopover } from 'components/interfaces/RoleImpersonationSelector'
+import { useProjectApiQuery } from 'data/config/project-api-query'
+import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-config-query'
+import { getRoleImpersonationJWT } from 'lib/role-impersonation'
+import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
import { RealtimeConfig } from '../useRealtimeMessages'
-import Link from 'next/link'
interface RealtimeTokensPopoverProps {
config: RealtimeConfig
@@ -23,130 +13,38 @@ interface RealtimeTokensPopoverProps {
}
export const RealtimeTokensPopover = ({ config, onChangeConfig }: RealtimeTokensPopoverProps) => {
- const [open, setOpen] = useState(false)
- const [tempConfig, setTempConfig] = useState(config)
+ const { data: settings } = useProjectApiQuery({ projectRef: config.projectRef })
- const { data: settings } = useProjectSettingsQuery({ projectRef: config.projectRef })
+ const apiService = settings?.autoApiService
+ const serviceRoleKey = apiService?.service_api_keys.find((x) => x.name === 'service_role key')
+ ? apiService.serviceApiKey
+ : undefined
- const apiService = (settings?.services ?? []).find(
- (x) => x.app.id == DEFAULT_PROJECT_API_SERVICE_ID
- )
- const apiKeys = apiService?.service_api_keys ?? []
- const selectedToken = apiKeys.find((k) => k.api_key === tempConfig.token)
- const bearerEnabled = selectedToken?.tags === 'anon'
+ const { data: postgrestConfig } = useProjectPostgrestConfigQuery({
+ projectRef: config.projectRef,
+ })
+ const jwtSecret = postgrestConfig?.jwt_secret
- const isService = config.token === apiKeys.find((key) => key.tags === 'service_role')?.api_key
+ const snap = useRoleImpersonationStateSnapshot()
useEffect(() => {
- const anonKey = apiKeys.find((k) => k.tags === 'anon')
- if (anonKey) {
- onChangeConfig({ ...config, token: anonKey.api_key })
+ let token: string | undefined
+
+ if (
+ config.projectRef !== undefined &&
+ jwtSecret !== undefined &&
+ snap.role !== undefined &&
+ snap.role.type === 'postgrest'
+ ) {
+ token = getRoleImpersonationJWT(config.projectRef, jwtSecret, snap.role)
+ } else {
+ token = serviceRoleKey
}
- }, [apiKeys])
- const onOpen = (v: boolean) => {
- // when opening, copy the outside config into the intermediate one
- if (v === true) {
- setTempConfig(config)
+ if (token) {
+ onChangeConfig({ ...config, token })
}
- setOpen(v)
- }
+ }, [config.projectRef, jwtSecret, serviceRoleKey, snap.role])
- const onApply = () => {
- onChangeConfig(tempConfig)
- setOpen(false)
- }
-
- return (
- <Popover_Shadcn_ open={open} onOpenChange={onOpen}>
- <PopoverTrigger_Shadcn_ asChild>
- <Button
- icon={<PlusCircle size={16} />}
- type="dashed"
- className="rounded-full px-1.5 pr-2 !py-1 text-xs"
- size="small"
- >
- {isService
- ? 'Bypassing RLS policies'
- : config.bearer
- ? 'Viewing events as user'
- : 'Test RLS policies'}
- </Button>
- </PopoverTrigger_Shadcn_>
- <PopoverContent_Shadcn_ className="w-[500px] p-0" align="start">
- <div className="border-b border-overlay p-4 flex-grow flex flex-col gap-y-3">
- <p className="text-sm text-foreground">Connection key settings</p>
- <Listbox
- type="select"
- value={tempConfig.token}
- size="small"
- className="w-full"
- onChange={(key) => {
- const selectedToken = apiKeys.find((k) => k.api_key === key)
- if (selectedToken) {
- if (selectedToken.tags === 'anon') {
- setTempConfig({ ...config, token: key, bearer: '' })
- } else {
- setTempConfig({ ...config, token: key, bearer: '' })
- }
- }
- }}
- >
- {apiKeys.map((key) => {
- return (
- <Listbox.Option key={key.tags} label={key.tags} value={key.api_key}>
- <span className="text-foreground">{key.tags}</span>
- </Listbox.Option>
- )
- })}
- </Listbox>
- {selectedToken?.tags === 'service_role' ? (
- <span className="text-sm text-foreground-light">
- The <span className="text-foreground">Service role</span> is a predefined Postgres
- role with elevated privileges. It will bypass all Row Level Security (RLS) policies.
- </span>
- ) : (
- <span className="text-sm text-foreground-light">
- The <span className="text-foreground">anonymous key</span> will respect Row Level
- Security (RLS) policies.
- </span>
- )}
- </div>
- {bearerEnabled && (
- <div className="border-b border-overlay p-4 flex-grow flex flex-col gap-y-2">
- <p className="text-sm text-foreground">Impersonate a user</p>
- <p className="text-sm text-foreground-light">
- Provide a JWT token of a user to receive events from the perspective of the user. This
- respects RLS policies relevant for that particular user.
- </p>
- <Input
- icon={<IconKey />}
- size="small"
- className="flex-grow mt-2"
- placeholder="Enter JWT token of a user"
- defaultValue={tempConfig.bearer || ''}
- onChange={(v) => setTempConfig({ ...tempConfig, bearer: v.target.value })}
- />
- <p className="text-xs text-foreground-light">
- Learn more about JWT tokens in{' '}
- <Link
- className="underline"
- target="_blank"
- rel="noreferrer"
- href="https://supabase.com/docs/learn/auth-deep-dive/auth-deep-dive-jwts"
- >
- our docs
- </Link>
- </p>
- </div>
- )}
- <div className="px-4 py-3 gap-2 flex justify-end">
- <Button type="default" onClick={() => setOpen(false)}>
- Cancel
- </Button>
- <Button onClick={onApply}>Apply</Button>
- </div>
- </PopoverContent_Shadcn_>
- </Popover_Shadcn_>
- )
+ return <RoleImpersonationPopover align="start" />
}
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/Icons.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/Icons.tsx
new file mode 100644
index 00000000000..918edb085f8
--- /dev/null
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/Icons.tsx
@@ -0,0 +1,125 @@
+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/RoleImpersonationPopover.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx
new file mode 100644
index 00000000000..f44e57d001d
--- /dev/null
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx
@@ -0,0 +1,77 @@
+import { useState } from 'react'
+import { Button, PopoverContent_Shadcn_, PopoverTrigger_Shadcn_, Popover_Shadcn_, cn } from 'ui'
+
+import { User } from 'data/auth/users-query'
+import { ChevronDown, User as IconUser } from 'lucide-react'
+import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
+import { getAvatarUrl, getDisplayName } from '../Auth/Users/UserListItem.utils'
+import RoleImpersonationSelector from './RoleImpersonationSelector'
+
+export interface RoleImpersonationPopoverProps {
+ serviceRoleLabel?: string
+ variant?: 'regular' | 'connected-on-right'
+ align?: 'center' | 'start' | 'end'
+}
+
+const RoleImpersonationPopover = ({
+ serviceRoleLabel,
+ variant = 'regular',
+ align = 'end',
+}: RoleImpersonationPopoverProps) => {
+ const state = useRoleImpersonationStateSnapshot()
+
+ const [isOpen, setIsOpen] = useState(false)
+
+ const currentRole = state.role?.role ?? serviceRoleLabel ?? 'service role'
+
+ return (
+ <Popover_Shadcn_ open={isOpen} onOpenChange={setIsOpen} modal={false}>
+ <PopoverTrigger_Shadcn_ asChild>
+ <Button
+ size="tiny"
+ type="default"
+ className={cn(
+ 'h-[26px] pr-3 gap-0',
+ variant === 'connected-on-right' && 'rounded-r-none border-r-0'
+ )}
+ >
+ <div className="flex items-center gap-1">
+ <span className="text-foreground-muted">role</span>
+ <span>{currentRole}</span>
+ {state.role?.type === 'postgrest' && state.role.role === 'authenticated' && (
+ <UserRoleButtonSection user={state.role.user} />
+ )}
+ <ChevronDown className="text-muted" strokeWidth={1} size={12} />
+ </div>
+ </Button>
+ </PopoverTrigger_Shadcn_>
+ <PopoverContent_Shadcn_
+ className="p-0 w-full overflow-hidden bg-overlay"
+ side="bottom"
+ align={align}
+ >
+ <RoleImpersonationSelector serviceRoleLabel={serviceRoleLabel} />
+ </PopoverContent_Shadcn_>
+ </Popover_Shadcn_>
+ )
+}
+
+export default RoleImpersonationPopover
+
+const UserRoleButtonSection = ({ user }: { user: User }) => {
+ const avatarUrl = getAvatarUrl(user)
+ const displayName = getDisplayName(user, user.email ?? user.phone ?? user.id ?? 'Unknown')
+
+ return (
+ <div className="flex gap-1 items-center pl-0.5 pr-1.5 h-[21px] bg-surface-200 rounded-full overflow-hidden">
+ {avatarUrl ? (
+ <img className="rounded-full w-[18px] h-[18px]" src={avatarUrl} alt={displayName} />
+ ) : (
+ <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]">{displayName}</span>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationRadio.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationRadio.tsx
new file mode 100644
index 00000000000..25895706f72
--- /dev/null
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationRadio.tsx
@@ -0,0 +1,70 @@
+import { IconCheck, IconMinus, cn } from 'ui'
+
+export interface RoleImpersonationRadioProps<T extends string> {
+ label?: string
+ value: T
+ isSelected: boolean | 'partially'
+ onSelectedChange: (value: T) => void
+ icon?: React.ReactNode
+}
+
+function RoleImpersonationRadio<T extends string>({
+ label,
+ value,
+ isSelected,
+ onSelectedChange,
+ icon,
+}: RoleImpersonationRadioProps<T>) {
+ return (
+ <label
+ className={cn(
+ 'border border-default rounded-md bg-surface-200 hover:bg-overlay-hover hover:border-control px-4 py-3 w-44 cursor-pointer transition-colors',
+ isSelected && 'border-stronger 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' && (
+ <IconCheck size={12} strokeWidth="4" className="text-background" />
+ )}
+ {isSelected === 'partially' && (
+ <IconMinus 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} role
+ </span>
+ </label>
+ )
+}
+
+export default RoleImpersonationRadio
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationSelector.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationSelector.tsx
new file mode 100644
index 00000000000..248b2545ada
--- /dev/null
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationSelector.tsx
@@ -0,0 +1,131 @@
+import { useState } from 'react'
+
+import { PostgrestRole } from 'lib/role-impersonation'
+import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
+import { DropdownMenuSeparator, cn } from 'ui'
+import { AnonIcon, AuthenticatedIcon, ServiceRoleIcon } from './Icons'
+import RoleImpersonationRadio from './RoleImpersonationRadio'
+import UserImpersonationSelector from './UserImpersonationSelector'
+
+export interface RoleImpersonationSelectorProps {
+ serviceRoleLabel?: string
+ padded?: boolean
+}
+
+const RoleImpersonationSelector = ({
+ serviceRoleLabel,
+ padded = true,
+}: RoleImpersonationSelectorProps) => {
+ 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 isAuthenticatedOptionFullySelected = Boolean(
+ selectedOption === 'authenticated' &&
+ state.role?.type === 'postgrest' &&
+ state.role.role === 'authenticated' &&
+ state.role.user
+ )
+
+ 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)
+ }
+
+ return (
+ <>
+ <div className={cn('flex flex-col gap-3', padded ? 'p-5' : 'pb-5')}>
+ <h2 className="text-foreground text-base">Database role settings</h2>
+
+ <form
+ onSubmit={(e) => {
+ // don't allow form submission
+ e.preventDefault()
+ }}
+ >
+ <fieldset className="flex gap-3">
+ <RoleImpersonationRadio
+ value="service_role"
+ isSelected={selectedOption === 'service_role'}
+ onSelectedChange={onSelectedChange}
+ label={serviceRoleLabel}
+ icon={<ServiceRoleIcon isSelected={selectedOption === 'service_role'} />}
+ />
+
+ <RoleImpersonationRadio
+ value="anon"
+ isSelected={selectedOption === 'anon'}
+ onSelectedChange={onSelectedChange}
+ icon={<AnonIcon isSelected={selectedOption === 'anon'} />}
+ />
+
+ <RoleImpersonationRadio
+ value="authenticated"
+ isSelected={
+ selectedOption === 'authenticated' &&
+ (isAuthenticatedOptionFullySelected || 'partially')
+ }
+ onSelectedChange={onSelectedChange}
+ icon={<AuthenticatedIcon isSelected={selectedOption === 'authenticated'} />}
+ />
+ </fieldset>
+ </form>
+
+ {selectedOption === 'service_role' && (
+ <p className="text-foreground-light text-sm">
+ The default Postgres/superuser role. This has admin privileges.
+ <br />
+ It will bypass Row Level Security (RLS) policies.
+ </p>
+ )}
+
+ {selectedOption === 'anon' && (
+ <p className="text-foreground-light text-sm">
+ For "anonymous access". This is the role which the API (PostgREST) will use when a user
+ <br />
+ is not logged in. It will respect Row Level Security (RLS) policies.
+ </p>
+ )}
+
+ {selectedOption === 'authenticated' && (
+ <p className="text-foreground-light text-sm">
+ For "authenticated access". This is the role which the API (PostgREST) will use when
+ <br /> a user is logged in. It will respect Row Level Security (RLS) policies.
+ </p>
+ )}
+ </div>
+
+ {selectedOption === 'authenticated' && (
+ <>
+ <DropdownMenuSeparator />
+ <div className={cn('py-5', padded && 'px-5')}>
+ <UserImpersonationSelector />
+ </div>
+ </>
+ )}
+ </>
+ )
+}
+
+export default RoleImpersonationSelector
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx
new file mode 100644
index 00000000000..9f496518209
--- /dev/null
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/UserImpersonationSelector.tsx
@@ -0,0 +1,202 @@
+import { useDebounce } from '@uidotdev/usehooks'
+import { useState } from 'react'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import AlertError from 'components/ui/AlertError'
+import { User, useUsersQuery } from 'data/auth/users-query'
+import { User as IconUser, Loader2, Search, X } from 'lucide-react'
+import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
+import { Button, Input } from 'ui'
+import { getAvatarUrl, getDisplayName } from '../Auth/Users/UserListItem.utils'
+
+const UserImpersonationSelector = () => {
+ const [searchText, setSearchText] = useState('')
+ const debouncedSearchText = useDebounce(searchText, 300)
+
+ const { project } = useProjectContext()
+ const { data, isSuccess, isLoading, isError, error, isFetching, isPreviousData } = useUsersQuery(
+ {
+ projectRef: project?.ref,
+ keywords: debouncedSearchText || undefined,
+ },
+ {
+ keepPreviousData: true,
+ }
+ )
+
+ const isSearching = isPreviousData && isFetching
+
+ const state = useRoleImpersonationStateSnapshot()
+
+ const impersonatingUser =
+ state.role?.type === 'postgrest' && state.role.role === 'authenticated' && state.role.user
+
+ function impersonateUser(user: User) {
+ state.setRole({
+ type: 'postgrest',
+ role: 'authenticated',
+ user,
+ })
+ }
+
+ function stopImpersonating() {
+ state.setRole(undefined)
+ }
+
+ return (
+ <div className="flex flex-col gap-1">
+ <h2 className="text-foreground text-base">
+ {impersonatingUser
+ ? `Impersonating ${getDisplayName(
+ impersonatingUser,
+ impersonatingUser.email ??
+ impersonatingUser.phone ??
+ impersonatingUser.id ??
+ 'Unknown'
+ )}`
+ : 'Impersonate a User'}
+ </h2>
+ <p className="text-sm text-foreground-light max-w-md">
+ {!impersonatingUser
+ ? "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 ? (
+ <div className="flex flex-col gap-2 mt-4">
+ <Input
+ className="table-editor-search border-none"
+ icon={
+ isSearching ? (
+ <Loader2
+ className="animate-spin text-foreground-lighter"
+ size={16}
+ strokeWidth={1.5}
+ />
+ ) : (
+ <Search className="text-foreground-lighter" size={16} strokeWidth={1.5} />
+ )
+ }
+ placeholder="Search for a user.."
+ onChange={(e) => setSearchText(e.target.value.trim())}
+ value={searchText}
+ size="small"
+ actions={
+ searchText && (
+ <Button size="tiny" type="text" className="px-1" onClick={() => setSearchText('')}>
+ <X size={12} strokeWidth={2} />
+ </Button>
+ )
+ }
+ />
+
+ {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" />}
+
+ {isSuccess &&
+ (data.users.length > 0 ? (
+ <ul className="divide-y max-h-[192px] overflow-y-scroll" role="list">
+ {data.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>
+ ))}
+ </div>
+ ) : (
+ <UserImpersonatingRow
+ user={impersonatingUser}
+ onClick={stopImpersonating}
+ isImpersonating={true}
+ />
+ )}
+ </div>
+ )
+}
+
+export default UserImpersonationSelector
+
+interface UserRowProps {
+ user: User
+ onClick: (user: User) => void
+ isImpersonating?: boolean
+}
+
+const UserImpersonatingRow = ({ user, onClick, isImpersonating = false }: UserRowProps) => {
+ const avatarUrl = getAvatarUrl(user)
+ const displayName = getDisplayName(user, user.email ?? user.phone ?? user.id ?? 'Unknown')
+
+ return (
+ <div className="flex items-center gap-3 py-2 text-foreground">
+ <div className="flex items-center gap-4 bg-surface-200 pr-5 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>
+ </div>
+
+ <Button
+ type="secondary"
+ onClick={() => {
+ onClick(user)
+ }}
+ >
+ {isImpersonating ? 'Stop Impersonating' : 'Impersonate'}
+ </Button>
+ </div>
+ )
+}
+
+interface UserRowProps {
+ user: User
+ onClick: (user: User) => void
+ isImpersonating?: boolean
+}
+
+const UserRow = ({ user, onClick, isImpersonating = false }: UserRowProps) => {
+ const avatarUrl = getAvatarUrl(user)
+ const displayName = getDisplayName(user, user.email ?? user.phone ?? user.id ?? 'Unknown')
+
+ return (
+ <div className="flex items-center justify-between py-2 text-foreground">
+ <div className="flex items-center gap-4">
+ {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 text-muted flex items-center justify-center text-background">
+ <IconUser size={12} strokeWidth={2} />
+ </div>
+ )}
+
+ <span className="text-sm">{displayName}</span>
+ </div>
+
+ <Button
+ type="secondary"
+ onClick={() => {
+ onClick(user)
+ }}
+ >
+ {isImpersonating ? 'Stop Impersonating' : 'Impersonate'}
+ </Button>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/index.ts b/apps/studio/components/interfaces/RoleImpersonationSelector/index.ts
new file mode 100644
index 00000000000..6441dbb7572
--- /dev/null
+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/index.ts
@@ -0,0 +1,2 @@
+export { default as RoleImpersonationPopover } from './RoleImpersonationPopover'
+export { default as RoleImpersonationSelector } from './RoleImpersonationSelector'
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index 115521bf062..ad1fe27149e 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -44,8 +44,10 @@ import {
import { IS_PLATFORM, OPT_IN_TAGS } from 'lib/constants'
import { uuidv4 } from 'lib/helpers'
import { useProfile } from 'lib/profile'
+import { wrapWithRoleImpersonation } from 'lib/role-impersonation'
import Telemetry from 'lib/telemetry'
import { useAppStateSnapshot } from 'state/app-state'
+import { getImpersonatedRole } from 'state/role-impersonation-state'
import { getSqlEditorStateSnapshot, useSqlEditorStateSnapshot } from 'state/sql-editor'
import { subscriptionHasHipaaAddon } from '../Billing/Subscription/Subscription.utils'
import AISchemaSuggestionPopover from './AISchemaSuggestionPopover'
@@ -311,7 +313,10 @@ const SQLEditor = () => {
execute({
projectRef: project.ref,
connectionString: project.connectionString,
- sql,
+ sql: wrapWithRoleImpersonation(sql, {
+ projectRef: project.ref,
+ role: getImpersonatedRole(),
+ }),
})
}
},
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
index 054a026c3e2..d4c6130beb3 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
@@ -1,14 +1,14 @@
import * as Tooltip from '@radix-ui/react-tooltip'
import { IS_PLATFORM } from 'lib/constants'
import { detectOS } from 'lib/helpers'
-import { Button, IconAlignLeft, IconCommand, IconCornerDownLeft } from 'ui'
+import { Button, IconAlignLeft, IconCommand, IconCornerDownLeft, cn } from 'ui'
+import { RoleImpersonationPopover } from 'components/interfaces/RoleImpersonationSelector'
import DatabaseSelector from 'components/ui/DatabaseSelector'
+import { useFlag } from 'hooks'
import { useState } from 'react'
import FavoriteButton from './FavoriteButton'
import SavingIndicator from './SavingIndicator'
-import { useFlag } from 'hooks'
-import SizeToggleButton from './SizeToggleButton'
export type UtilityActionsProps = {
id: string
@@ -29,6 +29,7 @@ const UtilityActions = ({
}: UtilityActionsProps) => {
const os = detectOS()
const readReplicasEnabled = useFlag('readReplicas')
+ const roleImpersonationEnabledFlag = useFlag('roleImpersonation')
const [selectedDatabaseId, setSelectedDatabaseId] = useState<string>('1')
return (
@@ -73,25 +74,32 @@ const UtilityActions = ({
/>
)}
- <Button
- onClick={() => executeQuery()}
- disabled={isDisabled || isExecuting}
- loading={isExecuting}
- type="default"
- size="tiny"
- iconRight={
- <div className="flex items-center space-x-1">
- {os === 'macos' ? (
- <IconCommand size={10} strokeWidth={1.5} />
- ) : (
- <p className="text-xs text-foreground-light">CTRL</p>
- )}
- <IconCornerDownLeft size={10} strokeWidth={1.5} />
- </div>
- }
- >
- {hasSelection ? 'Run selected' : 'Run'}
- </Button>
+ <div className="flex items-center">
+ {roleImpersonationEnabledFlag && (
+ <RoleImpersonationPopover serviceRoleLabel="postgres" variant="connected-on-right" />
+ )}
+
+ <Button
+ onClick={() => executeQuery()}
+ disabled={isDisabled || isExecuting}
+ loading={isExecuting}
+ type="primary"
+ size="tiny"
+ iconRight={
+ <div className="flex items-center space-x-1">
+ {os === 'macos' ? (
+ <IconCommand size={10} strokeWidth={1.5} />
+ ) : (
+ <p className="text-xs text-foreground-light">CTRL</p>
+ )}
+ <IconCornerDownLeft size={10} strokeWidth={1.5} />
+ </div>
+ }
+ className={cn(roleImpersonationEnabledFlag && 'rounded-l-none')}
+ >
+ {hasSelection ? 'Run selected' : 'Run'}
+ </Button>
+ </div>
</div>
</>
)
diff --git a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx
index b3da42a0d90..f8eeca68fa7 100644
--- a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx
@@ -17,6 +17,7 @@ import { useGetTables } from 'data/tables/tables-query'
import { useStore, useUrlState } from 'hooks'
import { TableLike } from 'hooks/misc/useTable'
import { noop } from 'lib/void'
+import { getImpersonatedRole } from 'state/role-impersonation-state'
import { useTableEditorStateSnapshot } from 'state/table-editor'
export type DeleteConfirmationDialogsProps = {
@@ -207,6 +208,7 @@ const DeleteConfirmationDialogs = ({
projectRef: project.ref,
connectionString: project.connectionString,
table: selectedTable as any,
+ impersonatedRole: getImpersonatedRole(),
})
} else {
deleteAllRows({
@@ -214,6 +216,7 @@ const DeleteConfirmationDialogs = ({
connectionString: project.connectionString,
table: selectedTable as any,
filters,
+ impersonatedRole: getImpersonatedRole(),
})
}
} else {
@@ -222,6 +225,7 @@ const DeleteConfirmationDialogs = ({
connectionString: project.connectionString,
table: selectedTable as any,
rows: selectedRowsToDelete as SupaRow[],
+ impersonatedRole: getImpersonatedRole(),
})
}
}
diff --git a/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx b/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
index ad624ce08fb..095e346ac3d 100644
--- a/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
@@ -9,9 +9,10 @@ import { Button, IconAlertCircle, IconLock, Modal } from 'ui'
import { rlsAcknowledgedKey } from 'components/grid/constants'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import ConfirmationModal from 'components/ui/ConfirmationModal'
-import { useCheckPermissions, useStore, useIsFeatureEnabled } from 'hooks'
import APIDocsButton from 'components/ui/APIDocsButton'
+import ConfirmationModal from 'components/ui/ConfirmationModal'
+import { useCheckPermissions, useFlag, useIsFeatureEnabled, useStore } from 'hooks'
+import { RoleImpersonationPopover } from '../RoleImpersonationSelector'
export interface GridHeaderActionsProps {
table: PostgresTable
@@ -22,6 +23,7 @@ const GridHeaderActions = ({ table }: GridHeaderActionsProps) => {
const { meta, ui } = useStore()
const { project } = useProjectContext()
const realtimeEnabled = useIsFeatureEnabled('realtime:all')
+ const roleImpersonationEnabledFlag = useFlag('roleImpersonation')
const [isTogglingRealtime, setIsTogglingRealtime] = useState(false)
const [showEnableRealtime, setShowEnableRealtime] = useState(false)
@@ -142,6 +144,8 @@ const GridHeaderActions = ({ table }: GridHeaderActionsProps) => {
</Button>
)}
+ {roleImpersonationEnabledFlag && <RoleImpersonationPopover serviceRoleLabel="postgres" />}
+
{realtimeEnabled && (
<Button
type="default"
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx
index d4e213bdc52..c15fc168550 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx
@@ -13,6 +13,7 @@ import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectConte
import { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
import { useTableRowsQuery } from 'data/table-rows/table-rows-query'
import { useTableQuery } from 'data/tables/table-query'
+import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
import ActionBar from '../../ActionBar'
import { useEncryptedColumns } from './ForeignRowSelector.utils'
import Pagination from './Pagination'
@@ -69,6 +70,8 @@ const ForeignRowSelector = ({
const rowsPerPage = 100
const [page, setPage] = useState(1)
+ const roleImpersonationState = useRoleImpersonationStateSnapshot()
+
const { data, isLoading, isSuccess, isError, isRefetching } = useTableRowsQuery(
{
queryKey: [schemaName, tableName],
@@ -79,6 +82,7 @@ const ForeignRowSelector = ({
filters,
page,
limit: rowsPerPage,
+ impersonatedRole: roleImpersonationState.role,
},
{
keepPreviousData: true,
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index 67efcb70759..0169e687c3d 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -14,6 +14,7 @@ import { useTableRowCreateMutation } from 'data/table-rows/table-row-create-muta
import { useTableRowUpdateMutation } from 'data/table-rows/table-row-update-mutation'
import { tableKeys } from 'data/tables/keys'
import { useStore, useUrlState } from 'hooks'
+import { getImpersonatedRole } from 'state/role-impersonation-state'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import { ColumnEditor, RowEditor, SpreadsheetImport, TableEditor } from '.'
import ForeignRowSelector from './RowEditor/ForeignRowSelector/ForeignRowSelector'
@@ -86,6 +87,7 @@ const SidePanelEditor = ({
table: selectedTable as any,
payload,
enumArrayColumns,
+ impersonatedRole: getImpersonatedRole(),
})
onRowCreated(result[0])
} catch (error: any) {
@@ -103,6 +105,7 @@ const SidePanelEditor = ({
configuration,
payload,
enumArrayColumns,
+ impersonatedRole: getImpersonatedRole(),
})
onRowUpdated(result[0], configuration.rowIdx)
} catch (error: any) {
diff --git a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
index c72c8c61c0c..6dbd04568e5 100644
--- a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
@@ -32,6 +32,7 @@ import { TableLike } from 'hooks/misc/useTable'
import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'
import { EMPTY_ARR } from 'lib/void'
import { useAppStateSnapshot } from 'state/app-state'
+import { getImpersonatedRole } from 'state/role-impersonation-state'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import { SchemaView } from 'types'
import GridHeaderActions from './GridHeaderActions'
@@ -294,6 +295,7 @@ const TableGridEditor = ({
configuration,
payload: updatedData,
enumArrayColumns,
+ impersonatedRole: getImpersonatedRole(),
})
}
diff --git a/apps/studio/data/sql/execute-sql-query.ts b/apps/studio/data/sql/execute-sql-query.ts
index 5ca25930731..800df7f4cb3 100644
--- a/apps/studio/data/sql/execute-sql-query.ts
+++ b/apps/studio/data/sql/execute-sql-query.ts
@@ -6,8 +6,14 @@ import {
UseQueryOptions,
} from '@tanstack/react-query'
import md5 from 'blueimp-md5'
-import { post } from 'data/fetchers'
import { useCallback } from 'react'
+
+import { post } from 'data/fetchers'
+import {
+ ROLE_IMPERSONATION_NO_RESULTS,
+ ROLE_IMPERSONATION_SQL_LINE_COUNT,
+} from 'lib/role-impersonation'
+import { getRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
import { sqlKeys } from './keys'
export type Error = { code: number; message: string; requestId: string }
@@ -38,7 +44,9 @@ export async function executeSql(
let headers = new Headers()
if (connectionString) headers.set('x-connection-encrypted', connectionString)
- const { data, error } = await post('/platform/pg-meta/{ref}/query', {
+ const isRoleImpersonationEnabled = getRoleImpersonationStateSnapshot().role?.type === 'postgrest'
+
+ let { data, error } = await post('/platform/pg-meta/{ref}/query', {
signal,
params: {
header: { 'x-connection-encrypted': connectionString ?? '' },
@@ -51,9 +59,47 @@ export async function executeSql(
})
if (error) {
- if (handleError !== undefined) return handleError(error)
+ if (
+ isRoleImpersonationEnabled &&
+ typeof error === 'object' &&
+ error !== null &&
+ 'error' in error &&
+ 'formattedError' in error
+ ) {
+ let updatedError = error as { error: string; formattedError: string }
+
+ const regex = /LINE (\d+):/im
+ const [, lineNumberStr] = regex.exec(updatedError.error) ?? []
+ const lineNumber = Number(lineNumberStr)
+ if (!isNaN(lineNumber)) {
+ updatedError = {
+ ...updatedError,
+ error: updatedError.error.replace(
+ regex,
+ `LINE ${lineNumber - ROLE_IMPERSONATION_SQL_LINE_COUNT}:`
+ ),
+ formattedError: updatedError.formattedError.replace(
+ regex,
+ `LINE ${lineNumber - ROLE_IMPERSONATION_SQL_LINE_COUNT}:`
+ ),
+ }
+ }
+
+ error = updatedError as any
+ }
+
+ if (handleError !== undefined) return handleError(error as any)
else throw error
}
+
+ if (
+ isRoleImpersonationEnabled &&
+ Array.isArray(data) &&
+ data?.[0]?.[ROLE_IMPERSONATION_NO_RESULTS] === 1
+ ) {
+ return { result: [] }
+ }
+
return { result: data }
}
diff --git a/apps/studio/data/table-rows/table-row-create-mutation.ts b/apps/studio/data/table-rows/table-row-create-mutation.ts
index 50a423266c4..17f314cb1cb 100644
--- a/apps/studio/data/table-rows/table-row-create-mutation.ts
+++ b/apps/studio/data/table-rows/table-row-create-mutation.ts
@@ -4,6 +4,7 @@ import { toast } from 'react-hot-toast'
import { Query, SupaTable } from 'components/grid'
import { executeSql } from 'data/sql/execute-sql-query'
import { sqlKeys } from 'data/sql/keys'
+import { ImpersonationRole, wrapWithRoleImpersonation } from 'lib/role-impersonation'
import { ResponseError } from 'types'
export type TableRowCreateVariables = {
@@ -12,6 +13,7 @@ export type TableRowCreateVariables = {
table: SupaTable
payload: any
enumArrayColumns: string[]
+ impersonatedRole?: ImpersonationRole
}
export function getTableRowCreateSql({
@@ -31,9 +33,18 @@ export async function createTableRow({
table,
payload,
enumArrayColumns,
+ impersonatedRole,
}: TableRowCreateVariables) {
- const sql = getTableRowCreateSql({ table, payload, enumArrayColumns })
+ const sql = wrapWithRoleImpersonation(
+ getTableRowCreateSql({ table, payload, enumArrayColumns }),
+ {
+ projectRef,
+ role: impersonatedRole,
+ }
+ )
+
const { result } = await executeSql({ projectRef, connectionString, sql })
+
return result
}
diff --git a/apps/studio/data/table-rows/table-row-delete-all-mutation.ts b/apps/studio/data/table-rows/table-row-delete-all-mutation.ts
index 345c912a6c7..cd6375032b1 100644
--- a/apps/studio/data/table-rows/table-row-delete-all-mutation.ts
+++ b/apps/studio/data/table-rows/table-row-delete-all-mutation.ts
@@ -4,6 +4,7 @@ import { toast } from 'react-hot-toast'
import { Filter, Query, SupaTable } from 'components/grid'
import { executeSql } from 'data/sql/execute-sql-query'
import { sqlKeys } from 'data/sql/keys'
+import { ImpersonationRole, wrapWithRoleImpersonation } from 'lib/role-impersonation'
import { ResponseError } from 'types'
import { formatFilterValue } from './utils'
@@ -12,6 +13,7 @@ export type TableRowDeleteAllVariables = {
connectionString?: string
table: SupaTable
filters: Filter[]
+ impersonatedRole?: ImpersonationRole
}
export function getTableRowDeleteAllSql({
@@ -35,8 +37,12 @@ export async function deleteAllTableRow({
connectionString,
table,
filters,
+ impersonatedRole,
}: TableRowDeleteAllVariables) {
- const sql = getTableRowDeleteAllSql({ table, filters })
+ const sql = wrapWithRoleImpersonation(getTableRowDeleteAllSql({ table, filters }), {
+ projectRef,
+ role: impersonatedRole,
+ })
const { result } = await executeSql({ projectRef, connectionString, sql })
diff --git a/apps/studio/data/table-rows/table-row-delete-mutation.ts b/apps/studio/data/table-rows/table-row-delete-mutation.ts
index 1e6498f359a..17ac21c404b 100644
--- a/apps/studio/data/table-rows/table-row-delete-mutation.ts
+++ b/apps/studio/data/table-rows/table-row-delete-mutation.ts
@@ -1,18 +1,20 @@
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'react-hot-toast'
-import { Query, SupaRow, SupaTable } from 'components/grid'
+import { Query, SupaRow } from 'components/grid'
import { executeSql } from 'data/sql/execute-sql-query'
import { sqlKeys } from 'data/sql/keys'
+import { Table } from 'data/tables/table-query'
+import { ImpersonationRole, wrapWithRoleImpersonation } from 'lib/role-impersonation'
import { ResponseError } from 'types'
import { getPrimaryKeys } from './utils'
-import { Table } from 'data/tables/table-query'
export type TableRowDeleteVariables = {
projectRef: string
connectionString?: string
table: Table
rows: SupaRow[]
+ impersonatedRole?: ImpersonationRole
}
export function getTableRowDeleteSql({
@@ -36,8 +38,12 @@ export async function deleteTableRow({
connectionString,
table,
rows,
+ impersonatedRole,
}: TableRowDeleteVariables) {
- const sql = getTableRowDeleteSql({ table, rows })
+ const sql = wrapWithRoleImpersonation(getTableRowDeleteSql({ table, rows }), {
+ projectRef,
+ role: impersonatedRole,
+ })
const { result } = await executeSql({ projectRef, connectionString, sql })
diff --git a/apps/studio/data/table-rows/table-row-truncate-mutation.ts b/apps/studio/data/table-rows/table-row-truncate-mutation.ts
index a36119cf9c4..fab7bab7308 100644
--- a/apps/studio/data/table-rows/table-row-truncate-mutation.ts
+++ b/apps/studio/data/table-rows/table-row-truncate-mutation.ts
@@ -4,12 +4,14 @@ import { toast } from 'react-hot-toast'
import { Query, SupaTable } from 'components/grid'
import { executeSql } from 'data/sql/execute-sql-query'
import { sqlKeys } from 'data/sql/keys'
+import { ImpersonationRole, wrapWithRoleImpersonation } from 'lib/role-impersonation'
import { ResponseError } from 'types'
export type TableRowTruncateVariables = {
projectRef: string
connectionString?: string
table: SupaTable
+ impersonatedRole?: ImpersonationRole
}
export function getTableRowTruncateSql({ table }: Pick<TableRowTruncateVariables, 'table'>) {
@@ -22,8 +24,12 @@ export async function truncateTableRow({
projectRef,
connectionString,
table,
+ impersonatedRole,
}: TableRowTruncateVariables) {
- const sql = getTableRowTruncateSql({ table })
+ const sql = wrapWithRoleImpersonation(getTableRowTruncateSql({ table }), {
+ projectRef,
+ role: impersonatedRole,
+ })
const { result } = await executeSql({ projectRef, connectionString, sql })
diff --git a/apps/studio/data/table-rows/table-row-update-mutation.ts b/apps/studio/data/table-rows/table-row-update-mutation.ts
index f9dc506f8d9..29ddcf842e3 100644
--- a/apps/studio/data/table-rows/table-row-update-mutation.ts
+++ b/apps/studio/data/table-rows/table-row-update-mutation.ts
@@ -4,6 +4,7 @@ import { toast } from 'react-hot-toast'
import { Query, SupaTable } from 'components/grid'
import { executeSql } from 'data/sql/execute-sql-query'
import { sqlKeys } from 'data/sql/keys'
+import { ImpersonationRole, wrapWithRoleImpersonation } from 'lib/role-impersonation'
import { ResponseError } from 'types'
export type TableRowUpdateVariables = {
@@ -13,6 +14,7 @@ export type TableRowUpdateVariables = {
configuration: { identifiers: any }
payload: any
enumArrayColumns: string[]
+ impersonatedRole?: ImpersonationRole
}
export function getTableRowUpdateSql({
@@ -35,8 +37,15 @@ export async function updateTableRow({
payload,
configuration,
enumArrayColumns,
+ impersonatedRole,
}: TableRowUpdateVariables) {
- const sql = getTableRowUpdateSql({ table, configuration, payload, enumArrayColumns })
+ const sql = wrapWithRoleImpersonation(
+ getTableRowUpdateSql({ table, configuration, payload, enumArrayColumns }),
+ {
+ projectRef,
+ role: impersonatedRole,
+ }
+ )
const { result } = await executeSql({ projectRef, connectionString, sql })
diff --git a/apps/studio/data/table-rows/table-rows-count-query.ts b/apps/studio/data/table-rows/table-rows-count-query.ts
index 396aa2818ee..2f2003dbc38 100644
--- a/apps/studio/data/table-rows/table-rows-count-query.ts
+++ b/apps/studio/data/table-rows/table-rows-count-query.ts
@@ -1,12 +1,15 @@
import { QueryKey, UseQueryOptions } from '@tanstack/react-query'
-import { Filter, Query, SupaTable } from 'components/grid'
import { useCallback } from 'react'
+
+import { Filter, Query, SupaTable } from 'components/grid'
+import { ImpersonationRole, wrapWithRoleImpersonation } from 'lib/role-impersonation'
import { ExecuteSqlData, useExecuteSqlPrefetch, useExecuteSqlQuery } from '../sql/execute-sql-query'
import { formatFilterValue } from './utils'
type GetTableRowsCountArgs = {
table?: SupaTable
filters?: Filter[]
+ impersonatedRole?: ImpersonationRole
}
export const getTableRowsCountSqlQuery = ({ table, filters = [] }: GetTableRowsCountArgs) => {
@@ -43,17 +46,31 @@ export type TableRowsCountData = TableRowsCount
export type TableRowsCountError = unknown
export const useTableRowsCountQuery = <TData extends TableRowsCountData = TableRowsCountData>(
- { projectRef, connectionString, queryKey, table, ...args }: TableRowsCountVariables,
+ {
+ projectRef,
+ connectionString,
+ queryKey,
+ table,
+ impersonatedRole,
+ ...args
+ }: TableRowsCountVariables,
options: UseQueryOptions<ExecuteSqlData, TableRowsCountError, TData> = {}
) =>
useExecuteSqlQuery(
{
projectRef,
connectionString,
- sql: getTableRowsCountSqlQuery({ table, ...args }),
+ sql: wrapWithRoleImpersonation(getTableRowsCountSqlQuery({ table, ...args }), {
+ projectRef: projectRef ?? 'ref',
+ role: impersonatedRole,
+ }),
queryKey: [
...(queryKey ?? []),
- { table: { name: table?.name, schema: table?.schema }, ...args },
+ {
+ table: { name: table?.name, schema: table?.schema },
+ impersonatedRole,
+ ...args,
+ },
],
},
{
diff --git a/apps/studio/data/table-rows/table-rows-query.ts b/apps/studio/data/table-rows/table-rows-query.ts
index edd01930ea6..964aba3389e 100644
--- a/apps/studio/data/table-rows/table-rows-query.ts
+++ b/apps/studio/data/table-rows/table-rows-query.ts
@@ -1,5 +1,6 @@
import { QueryKey, UseQueryOptions } from '@tanstack/react-query'
import { Filter, Query, Sort, SupaRow, SupaTable } from 'components/grid'
+import { ImpersonationRole, wrapWithRoleImpersonation } from 'lib/role-impersonation'
import { useCallback } from 'react'
import {
ExecuteSqlData,
@@ -16,9 +17,11 @@ type GetTableRowsArgs = {
sorts?: Sort[]
limit?: number
page?: number
+ impersonatedRole?: ImpersonationRole
}
// [Joshen] From components/grid/services/row/SqlRowService.ts, we should remove the logic from SqlRowService eventually
+// (currently used in csv export)
export const fetchAllTableRows = async ({
projectRef,
connectionString,
@@ -135,17 +138,24 @@ export type TableRowsData = TableRows
export type TableRowsError = unknown
export const useTableRowsQuery = <TData extends TableRowsData = TableRowsData>(
- { projectRef, connectionString, queryKey, table, ...args }: TableRowsVariables,
+ { projectRef, connectionString, queryKey, table, impersonatedRole, ...args }: TableRowsVariables,
options: UseQueryOptions<ExecuteSqlData, TableRowsError, TData> = {}
) =>
useExecuteSqlQuery(
{
projectRef,
connectionString,
- sql: getTableRowsSqlQuery({ table, ...args }),
+ sql: wrapWithRoleImpersonation(getTableRowsSqlQuery({ table, ...args }), {
+ projectRef: projectRef ?? 'ref',
+ role: impersonatedRole,
+ }),
queryKey: [
...(queryKey ?? []),
- { table: { name: table?.name, schema: table?.schema }, ...args },
+ {
+ table: { name: table?.name, schema: table?.schema },
+ impersonatedRole,
+ ...args,
+ },
],
},
{
diff --git a/apps/studio/lib/role-impersonation.ts b/apps/studio/lib/role-impersonation.ts
new file mode 100644
index 00000000000..e1716782ac9
--- /dev/null
+++ b/apps/studio/lib/role-impersonation.ts
@@ -0,0 +1,128 @@
+import jwt from 'jwt-simple'
+
+import { User } from 'data/auth/users-query'
+import { uuidv4 } from './helpers'
+
+export type PostgrestImpersonationRole =
+ | {
+ type: 'postgrest'
+ role: 'anon'
+ }
+ | {
+ type: 'postgrest'
+ role: 'service_role'
+ }
+ | {
+ type: 'postgrest'
+ role: 'authenticated'
+ user: User
+ }
+
+export type PostgrestRole = PostgrestImpersonationRole['role']
+
+export type CustomImpersonationRole = {
+ type: 'custom'
+ role: string
+}
+
+export type ImpersonationRole = PostgrestImpersonationRole | CustomImpersonationRole
+
+function getPostgrestClaims(projectRef: string, role: PostgrestImpersonationRole) {
+ let expiryDate = new Date()
+ expiryDate.setTime(expiryDate.getTime() + 60 * 60 * 1000) // 1 hour
+
+ const exp = Math.floor(expiryDate.getTime() / 1000)
+ const nowTimestamp = Math.floor(Date.now() / 1000)
+
+ if (role.role === 'authenticated') {
+ const user = role.user
+
+ return {
+ 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,
+ }
+ }
+
+ return {
+ iss: 'supabase',
+ ref: projectRef,
+ role: role.role,
+ iat: nowTimestamp,
+ exp,
+ }
+}
+
+export function getPostgrestRoleImpersonationSql(
+ projectRef: string,
+ role: PostgrestImpersonationRole
+) {
+ const claims = getPostgrestClaims(projectRef, role)
+
+ return /* SQL */ `
+ select set_config('role', '${role.role}', true),
+ set_config('request.jwt.claims', '${JSON.stringify(claims)}', true),
+ set_config('request.method', 'POST', true),
+ set_config('request.path', '/impersonation-example-request-path', true),
+ set_config('request.headers', '{"accept": "*/*"}', true);
+ `.trim()
+}
+
+// Includes getPostgrestRoleImpersonationSql() and wrapWithRoleImpersonation()
+export const ROLE_IMPERSONATION_SQL_LINE_COUNT = 11
+export const ROLE_IMPERSONATION_NO_RESULTS = 'ROLE_IMPERSONATION_NO_RESULTS'
+
+export function getCustomRoleImpersonationSql(roleName: string) {
+ return /* SQL */ `
+ set local role '${roleName}';
+ `
+}
+
+export interface WrapWithRoleImpersonationOptions {
+ projectRef: string
+ role?: ImpersonationRole
+}
+
+export function wrapWithRoleImpersonation(
+ sql: string,
+ { projectRef, role }: WrapWithRoleImpersonationOptions
+) {
+ if (role === undefined) {
+ return sql
+ }
+
+ const impersonationSql =
+ role.type === 'postgrest'
+ ? getPostgrestRoleImpersonationSql(projectRef, role)
+ : getCustomRoleImpersonationSql(role.role)
+
+ return /* SQL */ `
+ ${impersonationSql}
+
+ -- If the users sql returns no rows, pg-meta will
+ -- fallback to returning the result of the impersonation sql.
+ select 1 as "${ROLE_IMPERSONATION_NO_RESULTS}";
+
+ ${sql}
+ `
+}
+
+export function getRoleImpersonationJWT(
+ projectRef: string,
+ jwtSecret: string,
+ role: PostgrestImpersonationRole
+) {
+ const claims = getPostgrestClaims(projectRef, role)
+
+ return jwt.encode(claims, jwtSecret, 'HS256')
+}
diff --git a/apps/studio/package.json b/apps/studio/package.json
index 48981cc7d3a..98b7ef7f6ee 100644
--- a/apps/studio/package.json
+++ b/apps/studio/package.json
@@ -36,6 +36,7 @@
"@supabase/supabase-js": "^2.38.2",
"@tanstack/react-query": "^4.35.7",
"@tanstack/react-query-devtools": "^4.35.7",
+ "@uidotdev/usehooks": "^2.4.1",
"@zip.js/zip.js": "^2.7.29",
"ajv": "^8.6.3",
"awesome-debounce-promise": "^2.1.0",
@@ -54,6 +55,7 @@
"ip-address": "^8.1.0",
"json-logic-js": "^2.0.2",
"jsonrepair": "^3.2.3",
+ "jwt-simple": "^0.5.6",
"lodash": "^4.17.21",
"lottie-light-react": "^2.4.0",
"lucide-react": "^0.167.0",
diff --git a/apps/studio/pages/project/[ref]/api/graphiql.tsx b/apps/studio/pages/project/[ref]/api/graphiql.tsx
index 56ed46bc472..91f44ae921f 100644
--- a/apps/studio/pages/project/[ref]/api/graphiql.tsx
+++ b/apps/studio/pages/project/[ref]/api/graphiql.tsx
@@ -11,8 +11,11 @@ import { DocsLayout } from 'components/layouts'
import Connecting from 'components/ui/Loading/Loading'
import { useSessionAccessTokenQuery } from 'data/auth/session-access-token-query'
import { useProjectApiQuery } from 'data/config/project-api-query'
+import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-config-query'
import { useStore } from 'hooks'
import { API_URL, IS_PLATFORM } from 'lib/constants'
+import { getRoleImpersonationJWT } from 'lib/role-impersonation'
+import { getImpersonatedRole } from 'state/role-impersonation-state'
import { NextPageWithLayout } from 'types'
const GraphiQLPage: NextPageWithLayout = () => {
@@ -28,10 +31,13 @@ const GraphiQLPage: NextPageWithLayout = () => {
const { data: settings, isFetched } = useProjectApiQuery({ projectRef })
const apiService = settings?.autoApiService
- const anonKey = apiService?.service_api_keys.find((x) => x.name === 'anon key')
- ? apiService.defaultApiKey
+ const serviceRoleKey = apiService?.service_api_keys.find((x) => x.name === 'service_role key')
+ ? apiService.serviceApiKey
: undefined
+ const { data: config } = useProjectPostgrestConfigQuery({ projectRef })
+ const jwtSecret = config?.jwt_secret
+
useEffect(() => {
if (ui.selectedProjectRef) {
// Schemas may be needed when enabling the GraphQL extension
@@ -39,24 +45,40 @@ const GraphiQLPage: NextPageWithLayout = () => {
}
}, [ui.selectedProjectRef])
- const graphqlUrl = `${API_URL}/projects/${projectRef}/api/graphql`
-
const fetcher = useMemo(() => {
- const fetcherFn = createGraphiQLFetcher({ url: graphqlUrl, fetch })
+ const fetcherFn = createGraphiQLFetcher({
+ url: `${API_URL}/projects/${projectRef}/api/graphql`,
+ fetch,
+ })
const customFetcher: Fetcher = (graphqlParams, opts) => {
+ let userAuthorization: string | undefined
+
+ const role = getImpersonatedRole()
+ if (
+ projectRef !== undefined &&
+ jwtSecret !== undefined &&
+ role !== undefined &&
+ role.type === 'postgrest'
+ ) {
+ userAuthorization = `Bearer ${getRoleImpersonationJWT(projectRef, jwtSecret, role)}`
+ }
+
return fetcherFn(graphqlParams, {
...opts,
headers: {
...opts?.headers,
Authorization: `Bearer ${accessToken}`,
'x-graphql-authorization':
- opts?.headers?.['Authorization'] ?? opts?.headers?.['authorization'],
+ opts?.headers?.['Authorization'] ??
+ opts?.headers?.['authorization'] ??
+ userAuthorization ??
+ `Bearer ${serviceRoleKey}`,
},
})
}
return customFetcher
- }, [graphqlUrl, accessToken])
+ }, [projectRef, jwtSecret, accessToken, serviceRoleKey])
if ((IS_PLATFORM && !accessToken) || !isFetched || (isExtensionsLoading && !pgGraphqlExtension)) {
return <Connecting />
@@ -80,7 +102,7 @@ const GraphiQLPage: NextPageWithLayout = () => {
)
}
- return <GraphiQL fetcher={fetcher} theme={currentTheme} accessToken={anonKey} />
+ return <GraphiQL fetcher={fetcher} theme={currentTheme} />
}
GraphiQLPage.getLayout = (page) => <DocsLayout title="GraphiQL">{page}</DocsLayout>
diff --git a/apps/studio/state/role-impersonation-state.ts b/apps/studio/state/role-impersonation-state.ts
new file mode 100644
index 00000000000..ddeec9dd83b
--- /dev/null
+++ b/apps/studio/state/role-impersonation-state.ts
@@ -0,0 +1,18 @@
+import { proxy, snapshot, useSnapshot } from 'valtio'
+import { ImpersonationRole } from 'lib/role-impersonation'
+
+export const roleImpersonationState = proxy({
+ role: undefined as ImpersonationRole | undefined,
+ setRole: (role: ImpersonationRole | undefined) => {
+ roleImpersonationState.role = role
+ },
+})
+
+export const getRoleImpersonationStateSnapshot = () => snapshot(roleImpersonationState)
+
+export const useRoleImpersonationStateSnapshot = (options?: Parameters<typeof useSnapshot>[1]) =>
+ useSnapshot(roleImpersonationState, options)
+
+export function getImpersonatedRole() {
+ return getRoleImpersonationStateSnapshot().role
+}
diff --git a/package-lock.json b/package-lock.json
index ad48bd37731..ebf3217813d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -723,6 +723,7 @@
"@supabase/supabase-js": "^2.38.2",
"@tanstack/react-query": "^4.35.7",
"@tanstack/react-query-devtools": "^4.35.7",
+ "@uidotdev/usehooks": "^2.4.1",
"@zip.js/zip.js": "^2.7.29",
"ajv": "^8.6.3",
"awesome-debounce-promise": "^2.1.0",
@@ -741,6 +742,7 @@
"ip-address": "^8.1.0",
"json-logic-js": "^2.0.2",
"jsonrepair": "^3.2.3",
+ "jwt-simple": "^0.5.6",
"lodash": "^4.17.21",
"lottie-light-react": "^2.4.0",
"lucide-react": "^0.167.0",
@@ -11702,6 +11704,18 @@
"url": "https://opencollective.com/typescript-eslint"
}
},
+ "node_modules/@uidotdev/usehooks": {
+ "version": "2.4.1",
+ "resolved": "https://registry.npmjs.org/@uidotdev/usehooks/-/usehooks-2.4.1.tgz",
+ "integrity": "sha512-1I+RwWyS+kdv3Mv0Vmc+p0dPYH0DTRAo04HLyXReYBL9AeseDWUJyi4THuksBJcu9F0Pih69Ak150VDnqbVnXg==",
+ "engines": {
+ "node": ">=16"
+ },
+ "peerDependencies": {
+ "react": ">=18.0.0",
+ "react-dom": ">=18.0.0"
+ }
+ },
"node_modules/@ungap/structured-clone": {
"version": "1.2.0",
"license": "ISC"
@@ -22305,6 +22319,14 @@
"safe-buffer": "^5.0.1"
}
},
+ "node_modules/jwt-simple": {
+ "version": "0.5.6",
+ "resolved": "https://registry.npmjs.org/jwt-simple/-/jwt-simple-0.5.6.tgz",
+ "integrity": "sha512-40aUybvhH9t2h71ncA1/1SbtTNCVZHgsTsTgqPUxGWDmUDrXyDf2wMNQKEbdBjbf4AI+fQhbECNTV6lWxQKUzg==",
+ "engines": {
+ "node": ">= 0.4.0"
+ }
+ },
"node_modules/keyv": {
"version": "4.5.3",
"license": "MIT",