mirror of
https://github.com/supabase/supabase.git
synced 2026-06-10 21:41:25 +08:00
## Context Resolves FE-3221 Heavily inspired by what @filipecabaco has done previously here: https://github.com/supabase/supabase/pull/45360 This PR explores the use of pglite to set up a sandbox for RLS testing, which will pave the way for testing mutation based queries so to ensure no disruption to the actual database. Sandbox can be set up within the RLS tester panel as such: <img width="500" alt="image" src="https://github.com/user-attachments/assets/0cfdf8e4-dd99-4dee-ac00-39a32b375c07" /> Which the sandbox will mimic the project's database to the bare minimum required - entities from the `public` schema are copied over (types, tables, functions, policies) - `auth` schema is pseudo setup with `SANDBOX_SETUP_STATEMENTS` - Enough to support role impersonation + querying tables with references to the auth schema (e.g users table) - data is seeded up to 100 rows for each table - More info RE limitations in the last section below Once sandbox is ready, you'll see this UI where you can either leave the sandbox, or re-sync the sandbox from the actual database <img width="500" alt="image" src="https://github.com/user-attachments/assets/d07ce55f-5bc8-4722-8ce9-898b9b458f9b" /> Changes are currently feature flagged, so won't be available publicly just yet until things are ironed out and ready ## To test - [ ] Verify that setting up sandbox works - [ ] Verify that you can query your sandbox, and queries do not touch the actual database (can verify that we're not sending HTTP requests to the /query endpoint) - [ ] Verify correctness of RLS tester as well, should match correctness with testing against actual DB - [ ] Verify that re-syncing sandbox picks up changes - Can test by updating your policies that will affect the output of your select query - e.g SELECT for `authenticated`, change from just `true` to `false` - [ ] RLS tester should work as per normal (against actual DB) with the feature flag off with no additional overhead Let me know of any edge cases you might run into while testing ## Known quirks that will be addressed subsequently Leaving these for now just to not bloat this PR further - Pglite schema needs to be re-synced if updating RLS policies while testing, to ensure that pglite gets the updated policies. Will think about how to make this more seamless - Sandbox has its own limitations, will need to add a dialog to inform users how the sandbox works and what limitations to note of - e.g only the auth schema is mimicked - so policies that reference storage helpers won't work (although i think auth is probably the main use case and the rest might be niche) - We can slowly expand tho where required - Eventually we'll also move forward with figuring out testing mutation queries with this sandbox <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * RLS tester gains an isolated Postgres sandbox with schema/seed import, start/refresh/exit controls, and pre-populated auth data. * Sandbox management UI with setup, loading, active, and error states; refresh and destroy actions. * **Bug Fixes** * Role impersonation now keeps the PostgREST role set to anon while the tester sheet is open. * **Chores** * Content Security Policy updated to allow sandbox/connectivity endpoints. * **Style** * Minor sheet styling adjustment (top border). <!-- review_stack_entry_start --> [](https://app.coderabbit.ai/change-stack/supabase/supabase/pull/45839) <!-- review_stack_entry_end --> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
201 lines
6.4 KiB
TypeScript
201 lines
6.4 KiB
TypeScript
import { type SafeSqlFragment, type UntrustedSqlFragment } from '@supabase/pg-meta'
|
|
import { useState } from 'react'
|
|
import { toast } from 'sonner'
|
|
|
|
import { checkIfAppendLimitRequired, suffixWithLimit } from '../../SQLEditor/SQLEditor.utils'
|
|
import { type ParseQueryResults } from './RLSTester.types'
|
|
import { filterTablePolicies } from './useTestQueryRLS.utils'
|
|
import { useParseClientCodeMutation } from '@/data/ai/parse-client-code-mutation'
|
|
import { useDatabasePoliciesQuery } from '@/data/database-policies/database-policies-query'
|
|
import { useCheckTableRLSStatusMutation } from '@/data/database/table-check-rls-mutation'
|
|
import { useParseSQLQueryMutation } from '@/data/misc/parse-query-mutation'
|
|
import { useExecuteSqlMutation } from '@/data/sql/execute-sql-mutation'
|
|
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
|
|
import { wrapWithRoleImpersonation } from '@/lib/role-impersonation'
|
|
import { usePostgresSandbox } from '@/state/postgres-sandbox/sandbox'
|
|
import {
|
|
isRoleImpersonationEnabled,
|
|
useGetImpersonatedRoleState,
|
|
useImpersonatedUser,
|
|
useRoleImpersonationStateSnapshot,
|
|
} from '@/state/role-impersonation-state'
|
|
|
|
const limit = 100
|
|
|
|
/**
|
|
* [Joshen] Testing a SQL query for its RLS access involves 3 async steps
|
|
* 0. (Optional) Inferring client library code to SQL query via the AI Assistant
|
|
* 1. Parsing the provided SQL query to retrieve its operation type + tables involved
|
|
* 2. Checking for tables involved if they've got RLS enabled
|
|
* 3. Actually running the query to retrieve the results
|
|
*
|
|
* Errors should all be handled as part of the UI instead of toasts, hence the empty onError
|
|
* handlers to mute the default error handlers within the react query mutationhooks
|
|
*/
|
|
export const useTestQueryRLS = () => {
|
|
const { data: project } = useSelectedProjectQuery()
|
|
const { role } = useRoleImpersonationStateSnapshot()
|
|
|
|
const { sandbox } = usePostgresSandbox()
|
|
const getImpersonatedRoleState = useGetImpersonatedRoleState()
|
|
const impersonatedRoleState = getImpersonatedRoleState()
|
|
const user = useImpersonatedUser()
|
|
|
|
const [isLoading, setIsLoading] = useState(false)
|
|
const [sandboxError, setSandboxError] = useState<Error>()
|
|
|
|
const { data: policies = [] } = useDatabasePoliciesQuery({
|
|
projectRef: project?.ref,
|
|
connectionString: project?.connectionString,
|
|
})
|
|
|
|
const { mutateAsync: executeSql, error: executeSqlMutationError } = useExecuteSqlMutation({
|
|
onError: () => {},
|
|
})
|
|
const executeSqlError = sandbox ? sandboxError : executeSqlMutationError
|
|
|
|
const {
|
|
mutateAsync: parseClientCode,
|
|
isPending: isInferring,
|
|
error: parseClientCodeError,
|
|
} = useParseClientCodeMutation({
|
|
onError: () => {},
|
|
})
|
|
|
|
const inferSQLFromLib = async (
|
|
value: string,
|
|
onInferSQL: (unchecked_sql: UntrustedSqlFragment) => void
|
|
) => {
|
|
const { unchecked_sql, valid } = await parseClientCode({ code: value })
|
|
if (valid && unchecked_sql != null) {
|
|
onInferSQL(unchecked_sql)
|
|
} else {
|
|
toast.error('Client library code provided is not valid')
|
|
}
|
|
}
|
|
|
|
const { mutateAsync: parseQuery, error: parseQueryError } = useParseSQLQueryMutation({
|
|
onError: () => {},
|
|
})
|
|
|
|
const { mutateAsync: getTableRLSStatus, error: getTableRLSStatusError } =
|
|
useCheckTableRLSStatusMutation({
|
|
onError: () => {},
|
|
})
|
|
|
|
const testQuery = async ({
|
|
value,
|
|
option,
|
|
onExecuteSQL,
|
|
onParseQuery,
|
|
}: {
|
|
value: SafeSqlFragment
|
|
option: 'anon' | 'authenticated'
|
|
onExecuteSQL: ({
|
|
result,
|
|
isAutoLimit,
|
|
}: {
|
|
result: Object[] | null
|
|
isAutoLimit: boolean
|
|
}) => void
|
|
onParseQuery: (results?: ParseQueryResults) => void
|
|
}) => {
|
|
if (!project) return console.error('Project is required')
|
|
|
|
if (option === 'authenticated' && !user) {
|
|
return toast('Select which user to test as before running the query')
|
|
}
|
|
|
|
try {
|
|
setIsLoading(true)
|
|
setSandboxError(undefined)
|
|
|
|
const { appendAutoLimit } = checkIfAppendLimitRequired(value, limit)
|
|
const formattedSql = suffixWithLimit(value, limit)
|
|
const data = await parseQuery({ sql: formattedSql })
|
|
|
|
if (data.operation !== 'SELECT') {
|
|
return toast('Only SELECT statements are supported with the RLS Tester at the moment')
|
|
}
|
|
|
|
const formattedTables = data.tables.map((x) => {
|
|
const [schema, table] = x.includes('.') ? x.split('.') : ['public', x]
|
|
return { schema, table }
|
|
})
|
|
const response = await getTableRLSStatus({
|
|
projectRef: project?.ref,
|
|
connectionString: project?.connectionString,
|
|
tables: formattedTables,
|
|
})
|
|
|
|
const tables = response
|
|
.map(({ table, schema, rls_enabled }) => {
|
|
const tablePolicies = filterTablePolicies({
|
|
policies,
|
|
schema,
|
|
table,
|
|
role: role?.role,
|
|
operation: data.operation,
|
|
})
|
|
return {
|
|
table,
|
|
schema,
|
|
isRLSEnabled: rls_enabled,
|
|
tablePolicies,
|
|
}
|
|
})
|
|
.sort((a, b) => {
|
|
const aFirst = a.isRLSEnabled && a.tablePolicies.length === 0
|
|
const bFirst = b.isRLSEnabled && b.tablePolicies.length === 0
|
|
return Number(bFirst) - Number(aFirst)
|
|
})
|
|
|
|
const autoLimit = appendAutoLimit ? limit : undefined
|
|
const sql = wrapWithRoleImpersonation(formattedSql, impersonatedRoleState)
|
|
|
|
const { result } = sandbox
|
|
? await sandbox.run({ sql }).catch((e) => {
|
|
setSandboxError(e instanceof Error ? e : new Error(String(e)))
|
|
throw e
|
|
})
|
|
: await executeSql({
|
|
sql,
|
|
autoLimit,
|
|
projectRef: project.ref,
|
|
connectionString: project.connectionString,
|
|
isRoleImpersonationEnabled: isRoleImpersonationEnabled(impersonatedRoleState.role),
|
|
isStatementTimeoutDisabled: true,
|
|
handleError: (e) => {
|
|
throw e
|
|
},
|
|
queryKey: ['rls-tester'],
|
|
})
|
|
onExecuteSQL({ result, isAutoLimit: !!autoLimit })
|
|
|
|
onParseQuery({
|
|
tables,
|
|
operation: data.operation,
|
|
role: role?.role,
|
|
user,
|
|
})
|
|
} catch (error) {
|
|
onExecuteSQL({ result: null, isAutoLimit: false })
|
|
onParseQuery(undefined)
|
|
} finally {
|
|
setIsLoading(false)
|
|
}
|
|
}
|
|
|
|
return {
|
|
limit,
|
|
testQuery,
|
|
inferSQLFromLib,
|
|
isLoading,
|
|
isInferring,
|
|
executeSqlError,
|
|
parseQueryError,
|
|
parseClientCodeError,
|
|
getTableRLSStatusError,
|
|
}
|
|
}
|