mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 15:39:13 +00:00
create-pull-request/patch
10
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
115a2ffeef |
feat(studio): gate database functions, triggers, and webhooks on sql grants (#53269)
Resolves FE-4744. Part of the grants rollout; builds on the read/write SQL variants from #53185. ## What - **Data layer:** the database functions, triggers, database webhooks, and event triggers queries now take a `read` grant (exposed as `queryOptions` factories). All 8 create/update/delete mutations take a `write` grant and mark their SQL with `asWriteSql`. - **Guards:** the hand-written FGA checks in the functions, triggers, event triggers, and database webhooks lists, the functions page, the triggers layout/route, and the webhooks integration tab now derive from grants, with denied and error states. - **Other consumers** updated to pass grants: `CreateFunction`, `TriggerSheet`, `EditHookPanel`, `DeleteHookModal`, `ChooseFunctionForm`, `FunctionSelector`, `AutoEnableRLSNotice`, and SQL editor definition/autocomplete hooks. ## Behavior changes - **Webhooks integration tab:** was gated on `database_webhooks_config_read`; now gated on `database_read`, which is what the backend checks for the pg-meta query it uses. Both permissions are granted to the same built-in roles, so there is no change for built-in roles. A permissions-load failure now shows an error alert instead of the content. - **`AutoEnableRLSNotice`:** hidden unless the user has read access, since it can't tell whether the trigger already exists without it. ## Out of scope - User-authored SQL execution in `QueryEditor` / `useSqlEditorExecution` stays `unguarded.migrating` (FE-4750). ## Testing - New tests: query factories and write mutations (`data/database-sql-grants.test.ts`), webhooks tab granted/denied/error, functions list read/write granted/denied/error. - Typecheck, Prettier, lint ratchet, and Studio vitest suites for affected areas pass. |
||
|
|
254e24b170 |
feat(studio): require grants in fetch wrappers for FGA-annotated endpoints (#52238)
## Problem Resolves FE-4689 and FE-4690. Builds on #52105. Studio's fetch wrappers don't know which FGA permissions an endpoint requires, so a UI guard and the request it protects can drift apart. This makes the `grant` minted by `useGrant`/`getGrant`/`ensureGrant` part of the request itself: calling an annotated endpoint without a matching grant is a compile error. ## Solution ### What changed - **Fetch wrappers** (`data/fetchers.ts`, `data/guarded-fetch.ts`): `get`/`post`/`put`/`patch`/`del` keep their names, so no imports change. - The `grant` option is required for endpoints annotated with `x-fga-permissions`, and forbidden for unannotated ones. - It accepts a `Grant` for that exact endpoint (or one of its variants) or `unguarded`. - The wrapper strips the grant before calling openapi-fetch. - `head`/`trace`/`options` are unchanged. - **Owned params**: refinements can declare query params the wrapper sets from the grant's variant (`ownedQuery`). These params are removed from the init type (`Omit<Query, Owned> & { [K in Owned]?: never }`), so callers can't pass them. Nothing uses this yet: the api-keys `reveal` variant is the first. - **`assertGrant`** runs in development only and throws `GrantAssertionError`. It checks: - the endpoint; - a missing grant; - the variant against `when(init)` predicates; - the path `ref` against the grant's project, also accepting the parent project ref for a grant minted on a branch; - the path `slug` against the grant's organization. - **Escape hatches**: - `unguarded.migrating` for unmigrated call sites. - `unguarded.byDesign('reason')` for calls that intentionally skip the check. - **Grants** now record `permissionsProjectRef`, the ref permissions were evaluated against. It's required once the scope is resolved. - **Readable errors**: a missing or wrong grant reports the caller's own init type plus the expected `grant` type, instead of openapi-fetch's full options type. Under `noErrorTruncation`, the old message was tens of KB per call site. - **`executeSql`** now requires a grant for `POST /platform/pg-meta/{ref}/query`, so every caller counts as unmigrated. - **Codemod**: added `grant: unguarded.migrating` at every existing call site that hits an annotated endpoint, including all `executeSql` callers. No behavior change. A follow-up lint rule ratchets the count down. - **Dependencies**: adds `openapi-typescript-helpers` (the version openapi-fetch already uses) for the helper types. Only openapi-fetch's unexported `InitParam` is copied locally. ### Type-level notes - The grant is checked in the parameter type rather than in `Init`'s constraint. That way `Init` is still inferred from the argument, which keeps both the return type and the error message tied to the caller's code. - The grant is replaced rather than intersected. Intersecting a wrong grant with the expected one can reduce the init type to `never`, which then accepts the call. - `NoInfer<Path>` stops a grant's endpoint from becoming an inference candidate for the path. ## Review instructions ### Tests - `data/guarded-fetch.test.ts`: - Type equality with the raw client: required params and body, template-literal paths, `parseAs`, `signal`/`headers`, optional-init endpoints, and `unguarded`. An openapi-fetch upgrade that breaks the local `InitParam` copy fails typecheck. - Negative type cases: - a missing or `undefined` grant; - a missing init on an annotated endpoint; - a grant for a different path or method; - any grant or `unguarded` on an unannotated endpoint; - a forged grant; - params and body still checked; - an unknown path. - `guardMethod` and `assertGrant` runtime behavior, including branch-parent refs and org slugs. - Variant and owned-param tests are deferred to the api-keys (`reveal`) and pg-meta (`read`/`write`) PRs, since no refinements exist yet. 1. Run `pnpm typecheck` and confirm Studio passes. Then remove a `grant: unguarded.migrating` and check that the error is short and names the expected grant. 2. Run `pnpm test:studio`. 3. Skim the codemod commit: it only adds `grant: unguarded.migrating` and the `unguarded` import. ## Checklist Check all before review: - [ ] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) |
||
|
|
71d58cba7f |
Joshenlim/fe 4401 re sql editor silently points to the primary instead of (#50513)
## Context Fixes the following 2 issues with the database selection in the SQL Editor - An errant `useEffect` was resetting the `selectedDatabaseId` back to the primary every time the `databases` list from `useReadReplicasQuery` changed reference (not just on first load). - `QuerySourceMenu` kept showing "Read Replica" even after selection had reverted - Was using local storage value as the `identifier` for `DatabaseParametersSubMenu`, when it should use the valtio store as the source of truth <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Improvements** - The SQL Editor now remembers the last selected database between sessions. - Your saved database selection is restored when available; otherwise, the project’s primary database is selected automatically. - Query source settings now stay synchronized with the database currently selected in the SQL Editor. - **Bug Fixes** - Background database refreshes no longer unexpectedly reset your selected read replica to the primary database. - Database selection now waits for saved preferences to load, preventing a brief incorrect selection. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
4c8ed105d2 |
feat(studio): logs SQL execution wiring + source-aware run gestures (#48414)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Feature (SQL editor: execution wiring for logs-source snippets). Part of the stacked SQL-editor "Database vs Logs" query-source series. ## What is the current behavior? The SQL editor only ever runs queries against the user's Postgres database. There is no execution path for a logs (`log_sql`) snippet, and the run-button telemetry event carries no backend discriminator. ## What is the new behavior? - `useRunSource(id)` derives the run backend from the snippet type; a `log_sql` snippet resolves to `{ type: 'logs', dateRange }`, pairing the run with its session time range (default: last hour). - `useLogsSqlExecution` runs a promoted `SafeLogSqlFragment` against the analytics OTEL (ClickHouse) endpoint with the resolved time range as `iso_timestamp_start`/`iso_timestamp_end` request params. The endpoint is **pinned to OTEL** — a snippet's dialect must not flip with org migration. - The run gestures (toolbar button and Cmd+Enter) branch on the source and promote with the matching `acceptUntrusted*` right at the user action, preserving the auditable promotion-at-gesture boundary. pg intellisense is gated off for logs snippets. - The `sql_editor_query_run_button_clicked` telemetry event gains a required `{ source: 'database' | 'logs' }` property, fired from both execution paths. - Capability guard: a `log_sql` snippet is reachable by direct URL regardless of the (later) entry-point flag gating, so `executeLogsQuery` short-circuits when `otelLegacyLogs` is off — recording a clear "not available yet" result message instead of firing a request that would only return an opaque backend error on a non-ClickHouse project. This is a guard on the gesture, not endpoint selection. - Tests: `useRunSource` routing, `useLogsSqlExecution` endpoint/range/structured-error/capability-guard, and a reusable `flags` option on `renderSqlEditorHook`. No UI entry points are added — the feature runs dark until the flag-gated creation/nav PRs later in the stack. ## Additional context Stacked on the query-source series; base branch is `master` now that PR 4 (log date range domain + session state, #48401) is merged. Follow-ups in the stack add the toolbar/creation UI (with a run-affordance gate on `otelLegacyLogs`), nav section, AI dialect support, and reports guard. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added support for running log queries directly from the SQL editor. * Log query results, errors, and time ranges are now handled within the editor session. * Added automatic selection between database and log query execution, including support for custom date ranges. * SQL assistance is disabled while editing log queries where database definitions do not apply. * **Tests** * Added coverage for log query execution, date ranges, feature availability, and execution source selection. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
3d83e026f9 |
refactor(sql-editor): finish EditorController/DiffController port (Step 2) (#48166)
## Summary Step 2 of the SQL Editor testability plan. `SQLEditorContext` already wrapped the Monaco refs and exposed a few semantic imperative helpers (`getEditorSql`, `clearHighlights`, `applyErrorHighlight`, `refocusEditor`, …). This finishes that abstraction so no hook or controller touches `editorRef.current`/`diffEditorRef.current` directly anymore — they only call the port. The port is what will let Step 3's test harness inject a real in-memory editor adapter instead of mocking Monaco; production wires it to the real Monaco refs, unchanged. - Extends the context value with two semantic controllers, backed by the existing refs: - `editor: EditorController` — `isReady`, `getValue`, `getSelectionStartLine`, `getSql` (today's `getEditorSql`), `replaceAll` (wraps the repeated `executeEdits(...)` pattern), `focus`, `revealLineInCenter`, `highlightErrorLine` (today's `applyErrorHighlight`), `clearHighlights`. - `diff: DiffController` — `isMounted`, `getModifiedValue`, `setDiff` (the diff-sync effect body), `attach` (today's `handleDiffEditorMount`). - Migrates every touch point off raw refs onto the port: `useSqlEditorExecution`, `usePrettifyQuery`, `useSqlEditorShortcuts`, `SQLEditorControllers`' `readEditorSql`, and `useSqlEditorAi`'s `acceptAiHandler`/`drainDiffRequest`/`handleDiffEditorMount`/diff-sync effect. - `SQLEditorEditorPanel.tsx` is intentionally left untouched — it wires the raw refs into the real Monaco/DiffEditor React components for rendering, which isn't decision logic to abstract. Behavior-preserving. ## Test plan - [x] `pnpm --filter studio typecheck` - [x] `pnpm test:studio -- SQLEditor` (265 tests passing) - [x] `pnpm --filter studio run lint:ratchet` |
||
|
|
1c827c5cbb |
refactor(sql-editor): extract title-gen/execute-params + merge auto-limit functions (#48013)
## Summary Part 2/6 of the SQL Editor testability follow-up, stacked on #47980 (the analyzeQueryIssues/resolveConnectionString PR). - Extracts `shouldAutoGenerateTitle` and `buildExecuteParams` out of `useSqlEditorExecution`'s inline logic into `SQLEditor.utils.ts`. - Merges `checkIfAppendLimitRequired` and `suffixWithLimit` into a single `applyAutoLimit` function — the two were only ever called together and re-parsed the same query twice at every call site. `applyAutoLimit` only accepts `SafeSqlFragment` (never a plain string) and composes the `LIMIT` suffix through `safeSql`/`literal` rather than raw template concatenation, so the only place in the file that reasserts the `SafeSqlFragment` brand on a derived string is the small, dedicated `trimTrailingSemicolons` helper — removing existing terminators can't introduce unsafe content, unlike gluing new text onto the fragment. - Updates the two other `checkIfAppendLimitRequired`/`suffixWithLimit` call sites (`EditorPanel.tsx`, `ReportBlock.tsx`) accordingly; `ReportBlock` now promotes its report SQL once and reuses the result for both its display-only auto-limit hint and its execution, instead of promoting twice. ## Test plan - [x] `pnpm --filter studio typecheck` - [x] `pnpm test:studio -- SQLEditor ReportBlock EditorPanel` (239 tests passing) |
||
|
|
11fb715149 |
refactor(sql-editor): extract query-issue analysis + connection string resolution (#47980)
## Summary Part 1/6 of the SQL Editor testability follow-up (extracting pure decision logic out of the SQL editor hooks so it can be exhaustively unit-tested without mocking). - Extracts `analyzeQueryIssues` and `hasBlockingIssues` out of `useSqlEditorExecution`'s inline destructive-query / warning-modal-gating logic into `SQLEditor.utils.ts`. - Extracts `resolveConnectionString`, deduping the `databases?.find(...)` lookup that was duplicated verbatim in both `useSqlEditorExecution` and `useSqlEditorExplain`. - Behavior-preserving — same runtime logic, now unit-testable in isolation. ## Test plan - [x] `pnpm --filter studio typecheck` - [x] `pnpm test:studio -- SQLEditor.utils` (159 tests passing, includes new exhaustive-permutation cases for the three extracted functions) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved SQL safety checks before execution, including destructive queries, unsafe updates, database-altering commands, and tables missing row-level security. * Correctly recognizes tables protected by active security triggers. * Improved database connection selection for primary and read-replica databases. * Preserved the ability to run queries with force enabled when safety warnings are present. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
b100272376 |
chore(sql-editor): remove Pretty Explain feature (#47981)
Removes the SQL Editor Pretty Explain feature — the Explain tab, the Run EXPLAIN ANALYZE action + shortcut, and its dead plumbing. It's been gated off behind the `DisablePrettyExplainOnSqlEditor` kill switch for weeks with no usage or complaints. `ExplainVisualizer` / `isExplainQuery` are kept — they're used independently by Query Insights, Query Performance, and the EditorPanel quick-runner. Manually-run `EXPLAIN` queries still render as raw rows in the Results tab. Typecheck, lint, and all affected unit tests pass. Closes FE-3930 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Changes** * Removed the SQL editor’s EXPLAIN execution workflow, including its toolbar action, keyboard shortcut, utility tab, and visual query-plan display. * Simplified query execution to focus on standard results and charts. * Improved result clearing when switching databases and refined execution error handling. * Updated SQL editor state and tests to reflect the streamlined experience. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
9e80a159b5 |
refactor(sql-editor): decompose into controller contexts + presentational components (decompose 6/6) (#47938)
## What Final step (**6 of 6**) of the `SQLEditor.tsx` decomposition. Splits the two `ResizablePanel` bodies out of the `SQLEditorContent` monolith into presentational sub-components: - **`SQLEditorPane`** — the editor panel: loading state, `DiffEditor` + diff ask-AI widget, `MonacoEditor` + ask-AI widget. Reads the Monaco refs (`editorRef`/`monacoRef`/`diffEditorRef`) from `SQLEditorContext`, and receives the `diff`/`prompt`/`ai` controllers plus reactive state as props. - **`SQLEditorResults`** — the results panel: loading state + `UtilityPanel`. `SQLEditorContent` is now a composition root: shared-ref provider, hook composition, and the run-query warning modal. ## Result `SQLEditor.tsx` goes from the original **1056-line** monolith down to **259 lines** (≈75% reduction). The remaining size over a bare ~140-line root is the run-query warning modal, kept inline **deliberately**: its handlers hold the `acceptUntrustedSql` promotion, which must stay at the explicit user-action boundary in the root rather than moving into a presentational pane. ## Behavior-preserving The moved JSX is byte-identical aside from prop threading. No logic, effects, dependency arrays, or `eslint-disable`s changed. The two **render-time ref reads** — the editor placeholder (`!promptState.isOpen && !editorRef.current?.getValue()`) and the ask-AI widget gate (`editorRef.current && promptState.isOpen && !isDiffOpen`) — are preserved verbatim in `SQLEditorPane`, which re-renders whenever the `prompt`/`diff` props change, keeping those reads fresh (the guardrail from the plan). Verification (all green): - `SQLEditor.test.tsx` characterization suite — 11/11 pass - `tsc --noEmit` — no new errors - eslint — clean (no new ratchet entries) - prettier — clean ## Stack Builds on decompose 5 (#47935). This is the last PR in the series — the decomposition is complete after this merges. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added a resizable SQL editor layout with run warnings, query results, and an Explain view. * Introduced centralized SQL editor controllers and expanded AI-assisted prompt/diff workflows. * Added keyboard support for running and Explain analysis. * **Bug Fixes** * Restored editor focus after accepting or discarding AI changes. * Improved handling and validation of SQL Explain actions. * Preserved editor scroll position when switching snippets. * **Refactor** * Streamlined the SQLEditor into a composed layout and improved memoization to reduce unnecessary re-renders. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
3fa7f086df |
refactor(sql-editor): extract execution + explain hooks (decompose 4/6) (#47923)
## Summary PR **4 of 6** in the SQLEditor decomposition stack. Extracts the two query-run concerns out of the composition root into cohesive hooks. Behavior-preserving — the characterization suite stays green. ## New hooks - `useSqlEditorExecution` — the execute mutation, the `executeQuery` pipeline (destructive-query gating, lazy title generation, connection resolution), and the `potentialIssues` warning-modal state. - `useSqlEditorExplain` — the execute-explain mutation and the `executeExplainQuery` pipeline. Both pipelines accept an **already-promoted `SafeSqlFragment`**. ## Safe-SQL boundary Per review guidance, `acceptUntrustedSql` promotion stays in the **composition root's** run/explain gesture handlers and warning-modal confirm handlers — as close to the explicit user action as possible, so it's auditable. The hooks never call `acceptUntrustedSql`; they only accept safe SQL. `executeQuery` lists its (now all-stable) dependencies directly rather than suppressing `react-hooks/exhaustive-deps`. ## Verification - `vitest` — 11 characterization tests pass - `pnpm --filter studio typecheck` — clean for SQL editor files - `eslint` / `lint:ratchet` — pass (0 new violations) - `prettier --check` — clean `SQLEditorContent` is down to ~530 lines (from 1056 at the start of the stack). Remaining: PR5 (AI/diff + shortcuts), PR6 (JSX pane split + cleanup). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved SQL query execution safeguards for potentially destructive statements, unsafe updates, and missing row-level security coverage. * Improved EXPLAIN handling, including clearer validation for unsupported multi-statement queries. * Preserved query results, errors, and EXPLAIN output more reliably in the SQL editor. * **Improvements** * Added clearer execution status handling and more consistent editor focus, highlighting, and utility-tab behavior. * Improved connection selection and SQL execution reliability across supported database configurations. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |