Files
supabase/apps/studio/pages/api/parse-query.ts
Joshen Lim 3521ff06e1 Joshen/fe 3778 rls tester to support insert queries (#47554)
## Context

Back to working on the [RLS
Tester](https://github.com/orgs/supabase/discussions/45233), slowly
adding support for mutation queries. First part here will be to add
support for testing `INSERT` based queries (Note that there's no changes
to the sandbox stuff in this PR)

## Changes involved
- If testing an `INSERT` query, we show a big warning first that the
query will be ran on the actual DB
  - Note that we skip the warning if the sandbox is used
<img width="534" height="231" alt="image"
src="https://github.com/user-attachments/assets/ef75a0c9-61e4-49b0-9d78-458e8e5f7f4f"
/>
- If the testing as an anon user + RLS enabled
<img width="601" height="386" alt="image"
src="https://github.com/user-attachments/assets/b21f048d-bac1-4ddd-b84b-c231ae9f9e3e"
/>
- If testing as an auth-ed user + RLS enabled, but the INSERT violates
RLS (conditions don't meet)
<img width="604" height="489" alt="image"
src="https://github.com/user-attachments/assets/41c40486-48d5-4eee-b7cd-8f993edc47be"
/>
- Else if testing as an auth-ed user + RLS enabled and INSERT matches
RLS
<img width="612" height="402" alt="image"
src="https://github.com/user-attachments/assets/41854b40-b351-408b-8d23-cc5e0fa40813"
/>
- Minor cosmetic layout change here
  - Use layout horizontal
- Also added the user ID below the dropdown with click to copy action
for convenience
<img width="615" height="528" alt="image"
src="https://github.com/user-attachments/assets/b9c04395-5435-474a-b3c5-640143faa782"
/>
- Added inline guard againsts some conditions
  - Should not be able to run UPDATE or DELETE queries
<img width="622" height="319" alt="image"
src="https://github.com/user-attachments/assets/351af7c6-8f1e-47ae-8651-3b9b0b512490"
/>
  - Should not be able to run multiple queries
<img width="612" height="317" alt="image"
src="https://github.com/user-attachments/assets/603d9a1f-1d1f-40f2-806d-93aea6b6cf8e"
/>

## To test
- [ ] Verify that the RLS Tester works as expected for an insert query
  - Against actual DB
  - Against sandbox (only available on staging)
- [ ] Verify that inline guards are all working as expected
- Let me know if there's any edge cases I might have missed!





<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* RLS Tester results are now operation-aware (SELECT vs mutations), with
clearer “no rows/all rows” and policy evaluation explanations.
  * Added copy-to-clipboard for the impersonated user ID.
* Query parsing now surfaces richer context, including WHERE clause
details and statement count, and SELECT-only previews.

* **Bug Fixes**
* Improved handling of blocked mutation queries and RLS-related error
messaging.
  * Updated RLS Tester navigation to the correct policies page.
  * Refined sandbox-assisted execution flow and empty/error states.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-07-03 17:58:08 +08:00

131 lines
5.1 KiB
TypeScript

import { parse } from 'libpg-query'
import { NextApiRequest, NextApiResponse } from 'next'
const getOperation = (stmt: Record<string, unknown>) => {
if ('SelectStmt' in stmt) return 'SELECT'
if ('InsertStmt' in stmt) return 'INSERT'
if ('UpdateStmt' in stmt) return 'UPDATE'
if ('DeleteStmt' in stmt) return 'DELETE'
}
const getTablesInQuery = (ast: unknown) => {
const tables: string[] = []
function traverse(node: unknown): void {
if (!node || typeof node !== 'object') return
const obj = node as Record<string, unknown>
if ('RangeVar' in obj) {
const rv = obj.RangeVar as { relname?: string; schemaname?: string }
if (rv.relname) tables.push(rv.schemaname ? `${rv.schemaname}.${rv.relname}` : rv.relname)
}
if ('relation' in obj && obj.relation && typeof obj.relation === 'object') {
const rv = obj.relation as { relname?: string; schemaname?: string }
if (rv.relname) tables.push(rv.schemaname ? `${rv.schemaname}.${rv.relname}` : rv.relname)
}
for (const value of Object.values(obj)) {
Array.isArray(value) ? value.forEach(traverse) : traverse(value)
}
}
traverse(ast)
return [...new Set(tables)].sort((a, b) => a.localeCompare(b))
}
// libpg-query nodes only expose the location of their own leading token (e.g. a BoolExpr's
// location is its "AND"/"OR" operator, not the start of its left operand), and some nodes
// (SortBy) use -1 as an "unset" sentinel. Recursing to the smallest non-negative location in
// a subtree gives the true start of that subtree's text in the original SQL.
const getMinLocation = (node: unknown): number | undefined => {
if (!node || typeof node !== 'object') return undefined
const obj = node as Record<string, unknown>
let min: number | undefined
const consider = (loc: unknown) => {
if (typeof loc === 'number' && loc >= 0 && (min === undefined || loc < min)) min = loc
}
consider(obj.location)
for (const value of Object.values(obj)) {
if (Array.isArray(value)) value.forEach((item) => consider(getMinLocation(item)))
else if (value && typeof value === 'object') consider(getMinLocation(value))
}
return min
}
// Clauses that can immediately follow WHERE in each statement type, paired with the keyword
// that introduces them in the original SQL — used to find where the WHERE condition's text
// ends, since libpg-query has no deparser to do this for us.
const FOLLOWING_CLAUSES: Record<string, [field: string, keyword: RegExp][]> = {
SelectStmt: [
['groupClause', /\bgroup\s+by\b/i],
['havingClause', /\bhaving\b/i],
['windowClause', /\bwindow\b/i],
['sortClause', /\border\s+by\b/i],
['limitOffset', /\boffset\b/i],
['limitCount', /\blimit\b/i],
['lockingClause', /\bfor\b/i],
],
UpdateStmt: [['returningList', /\breturning\b/i]],
DeleteStmt: [['returningList', /\breturning\b/i]],
}
const getWhereClauseText = (sql: string, stmtType: string, stmt: Record<string, unknown>) => {
const start = getMinLocation(stmt.whereClause)
if (start === undefined) return null
const candidateEnds: number[] = []
for (const [field, keyword] of FOLLOWING_CLAUSES[stmtType] ?? []) {
const value = stmt[field]
const node = Array.isArray(value) ? value[0] : value
if (!node) continue
// Bound the keyword search to before the clause's own expression when we know where that
// starts; otherwise (e.g. lockingClause, which carries no location at all) search onward.
const exprStart = getMinLocation(node)
const window =
exprStart !== undefined && exprStart > start ? sql.slice(start, exprStart) : sql.slice(start)
const match = keyword.exec(window)
if (match) candidateEnds.push(start + match.index)
else if (exprStart !== undefined && exprStart > start) candidateEnds.push(exprStart)
}
const end =
candidateEnds.length > 0 ? Math.min(...candidateEnds) : sql.replace(/;\s*$/, '').length
return sql.slice(start, end).trim()
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
res.setHeader('Allow', ['POST'])
return res.status(405).json({ error: `Method ${req.method} Not Allowed` })
}
try {
const { sql } = req.body
if (typeof sql !== 'string' || sql.trim().length === 0) {
return res.status(400).json({ error: 'Missing or invalid "sql" in request body' })
}
const ast = await parse(sql)
const statementCount = ast.stmts?.length ?? 0
const stmt = ast.stmts?.[0]?.stmt as Record<string, unknown> | undefined
const [stmtType, stmtNode] = stmt ? Object.entries(stmt)[0] : []
const tables = getTablesInQuery(ast)
const operation = stmt ? getOperation(stmt) : null
const whereClause =
stmtType && stmtNode
? getWhereClauseText(sql, stmtType, stmtNode as Record<string, unknown>)
: null
return res.status(200).json({ tables, operation, whereClause, statementCount })
} catch (error) {
const message =
(error as { sqlDetails?: { message?: string } })?.sqlDetails?.message ??
(error instanceof Error ? error.message : 'Failed to parse SQL')
return res.status(400).json({ error: message })
}
}