The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
[FE-3544] fix(studio): role impersonation for truncated cell loads (#48215)
Alaister Youngfbf7ce44efe8
diff --git a/apps/studio/components/grid/components/editor/JsonEditor.tsx b/apps/studio/components/grid/components/editor/JsonEditor.tsxindex da56dfba3c3..d560fc82224 100644--- a/apps/studio/components/grid/components/editor/JsonEditor.tsx+++ b/apps/studio/components/grid/components/editor/JsonEditor.tsx@@ -23,6 +23,8 @@ import { isTableLike } from '@/data/table-editor/table-editor-types'import { useGetCellValueMutation } from '@/data/table-rows/get-cell-value-mutation'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'import { prettifyJSON, removeJSONTrailingComma, tryParseJson } from '@/lib/helpers'+import { RoleImpersonationState } from '@/lib/role-impersonation'+import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state'const verifyJSON = (value: string) => {try {@@ -86,6 +88,7 @@ export const JsonEditor = <TRow, TSummaryRow = unknown>({const applyChangesLabel = isQueueOperationsEnabled ? 'Queue changes' : 'Save changes'const { mutate: getCellValue, isPending, isSuccess } = useGetCellValueMutation()+ const roleImpersonationState = useRoleImpersonationStateSnapshot()const loadFullValue = () => {if (selectedTable === undefined || project === undefined || !isTableLike(selectedTable)) return@@ -104,6 +107,7 @@ export const JsonEditor = <TRow, TSummaryRow = unknown>({pkMatch,projectRef: project?.ref,connectionString: project?.connectionString,+ roleImpersonationState: roleImpersonationState as RoleImpersonationState,},{onSuccess: (data) => {diff --git a/apps/studio/components/grid/components/editor/TextEditor.tsx b/apps/studio/components/grid/components/editor/TextEditor.tsxindex f049c1df4a0..c96c96dcf64 100644--- a/apps/studio/components/grid/components/editor/TextEditor.tsx+++ b/apps/studio/components/grid/components/editor/TextEditor.tsx@@ -26,6 +26,8 @@ import { useTableEditorQuery } from '@/data/table-editor/table-editor-query'import { isTableLike } from '@/data/table-editor/table-editor-types'import { useGetCellValueMutation } from '@/data/table-rows/get-cell-value-mutation'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'+import { RoleImpersonationState } from '@/lib/role-impersonation'+import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state'export const TextEditor = <TRow, TSummaryRow = unknown>({row,@@ -58,6 +60,7 @@ export const TextEditor = <TRow, TSummaryRow = unknown>({const applyChangesLabel = isQueueEnabled ? 'Queue changes' : 'Save changes'const { mutate: getCellValue, isPending, isSuccess } = useGetCellValueMutation()+ const roleImpersonationState = useRoleImpersonationStateSnapshot()const isTruncated = isValueTruncated(initialValue)@@ -78,6 +81,7 @@ export const TextEditor = <TRow, TSummaryRow = unknown>({pkMatch,projectRef: project?.ref,connectionString: project?.connectionString,+ roleImpersonationState: roleImpersonationState as RoleImpersonationState,},{ onSuccess: (data) => setValue(data) })diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/index.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/index.tsxindex 23b4f9280ca..4ef81bdee9e 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/index.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/index.tsx@@ -17,6 +17,8 @@ import { isTableLike } from '@/data/table-editor/table-editor-types'import { useGetCellValueMutation } from '@/data/table-rows/get-cell-value-mutation'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'import { minifyJSON, prettifyJSON, removeJSONTrailingComma, tryParseJson } from '@/lib/helpers'+import { RoleImpersonationState } from '@/lib/role-impersonation'+import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state'interface JsonEditProps {row?: { [key: string]: any }@@ -60,6 +62,7 @@ export const JsonEditor = ({const isTruncated = isValueTruncated(jsonString, columnFormat)const { mutate: getCellValue, isPending, isSuccess, reset } = useGetCellValueMutation()+ const roleImpersonationState = useRoleImpersonationStateSnapshot()const validateJSON = useCallback(async (nextValue: string, resolve: () => void) => {@@ -117,6 +120,7 @@ export const JsonEditor = ({pkMatch,projectRef: project?.ref,connectionString: project?.connectionString,+ roleImpersonationState: roleImpersonationState as RoleImpersonationState,},{onSuccess: (data: unknown | undefined) => {diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.test.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.test.tsxnew file mode 100644index 00000000000..c2d776927b4--- /dev/null+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.test.tsx@@ -0,0 +1,147 @@+import { MAX_CHARACTERS } from '@supabase/pg-meta/src/query/table-row-query'+import { fireEvent, screen, waitFor } from '@testing-library/react'+import { mockAnimationsApi } from 'jsdom-testing-mocks'+import { HttpResponse } from 'msw'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { TextEditor } from './TextEditor'+import { ENTITY_TYPE } from '@/data/entity-types/entity-type-constants'+import {+ createRoleImpersonationState,+ RoleImpersonationStateContext,+} from '@/state/role-impersonation-state'+import { customRender } from '@/tests/lib/custom-render'+import { addAPIMock } from '@/tests/lib/msw'++// The table editor reads the table id off the URL params+vi.mock('common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('common')>()+ return {+ ...actual,+ useParams: () => ({ ref: 'default', id: '1' }),+ useFlag: () => false,+ }+})++// CodeEditor wraps Monaco, which can't mount in jsdom+vi.mock('@/components/ui/CodeEditor/CodeEditor', () => ({+ CodeEditor: () => <div data-testid="code-editor" />,+}))++mockAnimationsApi()++// A value that isValueTruncated() recognizes as truncated (ends with "..." and+// is longer than MAX_CHARACTERS), so the "Load full text data" button renders.+const TRUNCATED_VALUE = 'a'.repeat(MAX_CHARACTERS + 1) + '...'+const FULL_VALUE = 'the full untruncated value'++const tableEntity = {+ entity_type: ENTITY_TYPE.TABLE,+ id: 1,+ schema: 'public',+ name: 'profiles',+ primary_keys: [{ name: 'id' }],+ columns: [{ name: 'description', format: 'text' }],+}++describe('RowEditor TextEditor - load full truncated value', () => {+ let cellValueQueries: string[] = []++ beforeEach(() => {+ cellValueQueries = []++ addAPIMock({+ method: 'get',+ path: '/platform/projects/:ref',+ // @ts-expect-error partial project is enough for useSelectedProjectQuery+ response: {+ cloud_provider: 'localhost',+ id: 1,+ inserted_at: '2021-08-02T06:40:40.646Z',+ name: 'Default Project',+ organization_id: 1,+ ref: 'default',+ region: 'local',+ status: 'ACTIVE_HEALTHY',+ },+ })++ // Both the table-editor introspection and getCellValue hit this endpoint.+ // The cell-value query is the one that selects from the user table+ // ("public"."profiles"); the introspection query filters pg_catalog by id.+ addAPIMock({+ method: 'post',+ path: '/platform/pg-meta/:ref/query',+ response: async ({ request }) => {+ const body = (await request.json()) as { query: string }+ const query = body.query++ if (query.includes('profiles')) {+ cellValueQueries.push(query)+ return HttpResponse.json([{ description: FULL_VALUE }])+ }+ // table-editor introspection+ return HttpResponse.json([{ entity: tableEntity }])+ },+ })+ })++ it('wraps the getCellValue SQL with the impersonated role when View as role is active', async () => {+ const roleImpersonationState = createRoleImpersonationState('default', {+ current: async () => {},+ })+ roleImpersonationState.role = { type: 'custom', role: 'test_role' }++ customRender(+ <RoleImpersonationStateContext.Provider value={roleImpersonationState}>+ <TextEditor+ visible+ row={{ id: 1, description: TRUNCATED_VALUE }}+ column="description"+ closePanel={() => {}}+ onSaveField={() => {}}+ />+ </RoleImpersonationStateContext.Provider>+ )++ const loadButton = await screen.findByRole('button', { name: 'Load full text data' })++ // Retry the click: it no-ops until the table-editor introspection resolves+ // and populates selectedTable. Every captured query is role-impersonated,+ // so extra clicks (if any) don't affect the assertion.+ await waitFor(() => {+ fireEvent.click(loadButton)+ expect(cellValueQueries.length).toBeGreaterThan(0)+ })++ expect(cellValueQueries[0]).toContain("set local role 'test_role'")+ })++ it('does not impersonate a role when View as role is inactive', async () => {+ const roleImpersonationState = createRoleImpersonationState('default', {+ current: async () => {},+ })+ // role stays undefined -> runs as the default (postgres) role++ customRender(+ <RoleImpersonationStateContext.Provider value={roleImpersonationState}>+ <TextEditor+ visible+ row={{ id: 1, description: TRUNCATED_VALUE }}+ column="description"+ closePanel={() => {}}+ onSaveField={() => {}}+ />+ </RoleImpersonationStateContext.Provider>+ )++ const loadButton = await screen.findByRole('button', { name: 'Load full text data' })++ await waitFor(() => {+ fireEvent.click(loadButton)+ expect(cellValueQueries.length).toBeGreaterThan(0)+ })++ expect(cellValueQueries[0]).not.toContain('set local role')+ })+})diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsxindex 8a03bca1b88..e1e8de2c8c5 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx@@ -15,6 +15,8 @@ import { useTableEditorQuery } from '@/data/table-editor/table-editor-query'import { isTableLike } from '@/data/table-editor/table-editor-types'import { useGetCellValueMutation } from '@/data/table-rows/get-cell-value-mutation'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'+import { RoleImpersonationState } from '@/lib/role-impersonation'+import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state'interface TextEditorProps {visible: boolean@@ -49,6 +51,7 @@ export const TextEditor = ({const isTruncated = isValueTruncated(value)const { mutate: getCellValue, isPending, isSuccess, reset } = useGetCellValueMutation()+ const roleImpersonationState = useRoleImpersonationStateSnapshot()const loadFullValue = () => {if (@@ -73,6 +76,7 @@ export const TextEditor = ({pkMatch,projectRef: project?.ref,connectionString: project?.connectionString,+ roleImpersonationState: roleImpersonationState as RoleImpersonationState,},{ onSuccess: (data) => setStrValue(data) })