From 9b7cbd180367ef082edfcfdb3ac417e2d5fc7a0f Mon Sep 17 00:00:00 2001 From: Charis <26616127+charislam@users.noreply.github.com> Date: Tue, 3 Nov 2026 09:12:48 -0500 Subject: [PATCH] feat(studio): migrate branches to FGA grants with production/development variants (#52331) ## Problem Branch actions in Studio were guarded by hand-written permission checks (`useAsyncCheckPermissionsV2(FGA_PERMISSIONS.PROJECT.BRANCHING_*)`, plus one legacy `useAsyncCheckPermissions` in `Branch.Commands.tsx`) that weren't tied to the endpoints they protect. Every branches request in `data/branches` was marked `unguarded.migrating`. This is the pilot migration for endpoint-bound FGA grants. Resolves [FE-4693](https://linear.app/supabase/issue/FE-4693/pilot-migrate-branches-to-grants-8-endpoints-createbranchmodal). ## Solution ### Data layer * `data/branches` has no `unguarded.migrating` left (was 10). * The list, detail, and diff queries are now `branchesQueryOptions`, `branchQueryOptions`, and `branchDiffQueryOptions`. They take a grant, use `skipToken` without one, and keep the grant out of the query key. * Mutations take the grant in their variables. The merge mutation also takes `diffGrant`, because it reads the diff before merging. ### Production and development variants The backend doesn't treat development and production branching permissions as interchangeable: * Actions on a single branch (`/v1/branches/{branch_id_or_ref}` and its diff, merge, push, reset, and restore) need the production permission for the default branch and the development permission for preview branches. * Creating a default branch or a branch with data needs production create. To model this, `lib/fga-refinements.ts` gets its first entries: * The 8 single-branch endpoints have `production` and `development` variants. A new `variantRequired` flag makes the fetch wrapper reject a grant without a variant, at compile time and in `assertGrant`. * `POST /v1/projects/{ref}/branches` has a `production` variant. `assertGrant` requires it when the body sets `is_default` or `with_data`. * `useBranchGrant(endpoint, { projectRef, isDefault })` picks the variant from the branch's `is_default`. It stays `loading` until the branch is known. * `GrantForVariants` types a grant for any of an endpoint's variants. ### UI * The old checks are replaced with grants in `CreateBranchButton`, `CreateBranchModal`, `Overview`, `DeleteBranchPanel`, `DeleteBranchModal`, the branches and merge-requests pages, and `Branch.Commands.tsx`. * Grants are evaluated against the parent project, where branch permissions live. The scope is passed explicitly, because `/v1/branches/*` paths don't include the project. * Pages that are mainly about branches show `NoPermission` when the grant is denied and `AlertError` when the permission check fails. Action buttons are disabled with a tooltip. Places that use the branch list incidentally (nav, project home, usage) treat a denied grant as "no branches" instead of loading forever. * "Include data" in `CreateBranchModal` is disabled without production create. It previously failed after submitting. * `OutOfDateNotice`'s "Update branch" is disabled without the push grant. It previously did nothing. * The GitHub integration form blocks saving without the production-branch grant. Previously the connection was saved while the branch request failed, and a repo change deleted the old connection first. ### Where the old checks differed from the backend * **Too strict:** the branches and merge-requests pages required development read, and the create button required development create. The backend accepts development or production for both. * **Wrong for the default branch:** single-branch actions always checked development permissions, or production write for the main branch menu, regardless of which branch was targeted. * **Missing:** reset and "Switch to persistent" in `Overview` had no check. * **Legacy check:** `Branch.Commands.tsx` used the legacy `CREATE preview_branches` check. `BranchingPITRNotice` is unchanged: its check guards a subscription update, not a branches request. ### Other changes * The two new query options use an `eslint-disable` for `@tanstack/query/exhaustive-deps`, because grants stay out of query keys. A separate PR upgrades the plugin and allowlists `grant`, after which these can be removed. * `upsertMigration` in the merge mutation still uses `unguarded.migrating`. It belongs to the database-migrations domain. ## Testing * New component tests for `CreateBranchButton`, `DeleteBranchPanel`, the branches page, and `GitHubIntegrationConnectionForm` cover granted, denied, and error states. * New `useBranchGrant` tests: default vs. preview branch, and loading until the branch is known. * `guarded-fetch.test.ts` covers required variants (types and runtime) and the production variant for default and data branches. * Shared fixtures are in `tests/lib/branch-test-utils.ts`. * Studio typecheck passes, affected suites pass, the ESLint ratchet is stable, and knip is clean. --- .../BranchManagement/CreateBranchModal.tsx | 4 +- .../interfaces/Branching/MergeRequest.tsx | 20 +++++--- .../GitHubIntegrationConnectionForm.test.tsx | 33 ++++++++++++ .../GitHubIntegrationConnectionForm.tsx | 5 ++ .../studio/data/branches/branch-diff-query.ts | 50 ++++++++++++------- .../data/branches/branch-merge-mutation.ts | 19 +++++-- .../hooks/branches/useBranchMergeDiff.ts | 47 +++++++++++------ apps/studio/pages/project/[ref]/merge.tsx | 21 +++++++- 8 files changed, 151 insertions(+), 48 deletions(-) diff --git a/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx b/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx index e4d72526823..239731dba60 100644 --- a/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx +++ b/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx @@ -146,7 +146,7 @@ export const CreateBranchModal = () => { const isError = isErrorAuthorization || isErrorConnections const error = authorizationError || connectionsError - const { data: branches } = useQuery( + const { data: branches, isSuccess: isSuccessBranches } = useQuery( branchesQueryOptions({ projectRef, grant: branchesGrant.grant }) ) const { data: addons, isSuccess: isSuccessAddons } = useProjectAddonsQuery( @@ -572,7 +572,7 @@ export const CreateBranchModal = () => { )} - {githubConnection && ( + {githubConnection && isSuccessBranches && (
diff --git a/apps/studio/components/interfaces/Branching/MergeRequest.tsx b/apps/studio/components/interfaces/Branching/MergeRequest.tsx index 69d78d46331..7898906be05 100644 --- a/apps/studio/components/interfaces/Branching/MergeRequest.tsx +++ b/apps/studio/components/interfaces/Branching/MergeRequest.tsx @@ -117,10 +117,12 @@ export const MergeSubtitle = () => { export const MergeActions = ({ isWorkflowRunning, isSubmitting, + canMerge, onSelectMerge, }: { isWorkflowRunning: boolean isSubmitting: boolean + canMerge: boolean onSelectMerge: () => void }) => { const router = useRouter() @@ -165,6 +167,7 @@ export const MergeActions = ({ hasChanges: combinedHasChanges, } = useBranchMergeDiff({ currentBranchRef: ref, + isCurrentBranchDefault: currentBranch?.is_default, parentProjectRef, currentBranchConnectionString: project?.connectionString || undefined, parentBranchConnectionString: parentProject?.connectionString || undefined, @@ -172,6 +175,7 @@ export const MergeActions = ({ }) const isMergeDisabled = + !canMerge || !combinedHasChanges || isCombinedDiffLoading || isBranchOutOfDateOverall || @@ -192,13 +196,15 @@ export const MergeActions = ({ tooltip={{ content: { side: 'bottom', - text: !combinedHasChanges - ? 'No changes to merge' - : isWorkflowRunning - ? 'Workflow is currently running' - : !!ghConnection && Boolean(mainBranch?.git_branch) - ? 'Deploy to production from GitHub is enabled' - : 'Unable to merge at this time', + text: !canMerge + ? 'You need additional permissions to merge branches' + : !combinedHasChanges + ? 'No changes to merge' + : isWorkflowRunning + ? 'Workflow is currently running' + : !!ghConnection && Boolean(mainBranch?.git_branch) + ? 'Deploy to production from GitHub is enabled' + : 'Unable to merge at this time', }, }} variant="primary" diff --git a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.test.tsx b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.test.tsx index 0c35ff7b567..d72f67e764f 100644 --- a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.test.tsx +++ b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.test.tsx @@ -216,4 +216,37 @@ describe('GitHubIntegrationConnectionForm', () => { expect(await screen.findAllByText('Failed to load branches')).not.toHaveLength(0) expect(saveButton).toHaveAttribute('aria-disabled', 'true') }) + + test('keeps saving blocked while the branch list is still loading', async () => { + mockEndpoints([ + FGA_PERMISSIONS.PROJECT.BRANCHING_PRODUCTION_READ, + FGA_PERMISSIONS.PROJECT.BRANCHING_PRODUCTION_CREATE, + FGA_PERMISSIONS.PROJECT.BRANCHING_PRODUCTION_WRITE, + ]) + let resolveBranches: () => void = () => {} + const branchesLoaded = new Promise((resolve) => { + resolveBranches = resolve + }) + addAPIMock({ + method: 'get', + path: '/v1/projects/:ref/branches', + response: async () => { + await branchesLoaded + return HttpResponse.json<(typeof PRODUCTION_BRANCH)[]>([PRODUCTION_BRANCH]) + }, + }) + + renderForm() + + const workingDirectory = await screen.findByLabelText('Working directory') + await waitFor(() => expect(workingDirectory).toBeEnabled()) + await userEvent.type(workingDirectory, '/app') + const saveButton = await screen.findByRole('button', { name: 'Save changes' }) + expect(saveButton).toBeDisabled() + + resolveBranches() + await editWorkingDirectory() + + await waitFor(() => expect(saveButton).toBeEnabled()) + }) }) diff --git a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx index efefddcab92..4c551e1c977 100644 --- a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx +++ b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx @@ -345,6 +345,11 @@ export const GitHubIntegrationConnectionForm = ({ currentConnection: GitHubConnection ) => { if (!selectedProject?.ref || !selectedOrganization?.id) return + if (!canManageProductionBranch) { + setIsConfirmingBranchChange(false) + toast.error(productionBranchPermissionMessage) + return + } const connectionRequest = updateConnectionSettings({ connectionId: currentConnection.id, diff --git a/apps/studio/data/branches/branch-diff-query.ts b/apps/studio/data/branches/branch-diff-query.ts index 4db21232a05..3191d86cae8 100644 --- a/apps/studio/data/branches/branch-diff-query.ts +++ b/apps/studio/data/branches/branch-diff-query.ts @@ -1,22 +1,32 @@ -import { useQuery } from '@tanstack/react-query' +import { queryOptions, skipToken } from '@tanstack/react-query' import { branchKeys } from './keys' -import { get, handleError, unguarded } from '@/data/fetchers' +import { get, handleError } from '@/data/fetchers' import { IS_PLATFORM } from '@/lib/constants' -import type { ResponseError, UseCustomQueryOptions } from '@/types' +import type { GrantForVariants } from '@/lib/grants' +import type { ResponseError } from '@/types' + +export type BranchDiffGrant = GrantForVariants<'get', '/v1/branches/{branch_id_or_ref}/diff'> export type BranchDiffVariables = { - branchRef: string - projectRef: string + branchRef?: string + projectRef?: string includedSchemas?: string pgdelta?: boolean + grant?: BranchDiffGrant } export async function getBranchDiff({ branchRef, includedSchemas, pgdelta, -}: Pick) { + grant, +}: { + branchRef: string + includedSchemas?: string + pgdelta?: boolean + grant: BranchDiffGrant +}) { const query: { included_schemas?: string; pgdelta?: string } = {} if (includedSchemas) query.included_schemas = includedSchemas if (pgdelta === true) query.pgdelta = 'true' @@ -30,7 +40,7 @@ export async function getBranchDiff({ Accept: 'text/plain', }, parseAs: 'text', - grant: unguarded.migrating, + grant, }) if (error) { @@ -45,18 +55,20 @@ export async function getBranchDiff({ return diffData || '' } -type BranchDiffData = Awaited> +export type BranchDiffData = Awaited> +export type BranchDiffError = ResponseError -export const useBranchDiffQuery = ( - { branchRef, projectRef, includedSchemas, pgdelta }: BranchDiffVariables, - { - enabled = true, - ...options - }: Omit, 'queryKey' | 'queryFn'> = {} -) => - useQuery({ +export const branchDiffQueryOptions = ({ + branchRef, + projectRef, + includedSchemas, + pgdelta, + grant, +}: BranchDiffVariables) => + queryOptions({ queryKey: branchKeys.diff(projectRef, branchRef, pgdelta), - queryFn: () => getBranchDiff({ branchRef, includedSchemas, pgdelta }), - enabled: IS_PLATFORM && enabled && Boolean(branchRef), - ...options, + queryFn: + IS_PLATFORM && branchRef && grant + ? () => getBranchDiff({ branchRef, includedSchemas, pgdelta, grant }) + : skipToken, }) diff --git a/apps/studio/data/branches/branch-merge-mutation.ts b/apps/studio/data/branches/branch-merge-mutation.ts index 5d6f5c30e7b..5f4a52582cc 100644 --- a/apps/studio/data/branches/branch-merge-mutation.ts +++ b/apps/studio/data/branches/branch-merge-mutation.ts @@ -1,13 +1,18 @@ import { useMutation, useQueryClient } from '@tanstack/react-query' import { toast } from 'sonner' -import { getBranchDiff } from './branch-diff-query' +import { getBranchDiff, type BranchDiffGrant } from './branch-diff-query' import { branchKeys } from './keys' import { upsertMigration } from '@/data/database/migration-upsert-mutation' -import { handleError, post, unguarded } from '@/data/fetchers' +import { handleError, post } from '@/data/fetchers' +import type { GrantForVariants } from '@/lib/grants' import type { ResponseError, UseCustomMutationOptions } from '@/types' +export type BranchMergeGrant = GrantForVariants<'post', '/v1/branches/{branch_id_or_ref}/merge'> + export type BranchMergeVariables = { + grant: BranchMergeGrant + diffGrant: BranchDiffGrant branchProjectRef: string baseProjectRef: string migration_version?: string @@ -18,9 +23,15 @@ export async function mergeBranch({ branchProjectRef, migration_version, pgdelta, + grant, + diffGrant, }: BranchMergeVariables) { // Step 1: Get the diff output from the branch - const diffContent = await getBranchDiff({ branchRef: branchProjectRef, pgdelta }) + const diffContent = await getBranchDiff({ + branchRef: branchProjectRef, + pgdelta, + grant: diffGrant, + }) let migrationCreated = false @@ -43,7 +54,7 @@ export async function mergeBranch({ const { data, error } = await post('/v1/branches/{branch_id_or_ref}/merge', { params: { path: { branch_id_or_ref: branchProjectRef } }, body: { migration_version }, - grant: unguarded.migrating, + grant, }) if (error) { diff --git a/apps/studio/hooks/branches/useBranchMergeDiff.ts b/apps/studio/hooks/branches/useBranchMergeDiff.ts index 58f9b026eb3..1b56c8a069f 100644 --- a/apps/studio/hooks/branches/useBranchMergeDiff.ts +++ b/apps/studio/hooks/branches/useBranchMergeDiff.ts @@ -1,12 +1,15 @@ +import { useQuery } from '@tanstack/react-query' import { useMemo } from 'react' +import { useBranchGrant } from './useBranchGrant' import { useEdgeFunctionsDiff, type EdgeFunctionsDiffResult } from './useEdgeFunctionsDiff' import { useIsPgDeltaDiffEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext' -import { useBranchDiffQuery } from '@/data/branches/branch-diff-query' +import { branchDiffQueryOptions } from '@/data/branches/branch-diff-query' import { useMigrationsQuery } from '@/data/database/migrations-query' interface UseBranchMergeDiffProps { currentBranchRef?: string + isCurrentBranchDefault?: boolean parentProjectRef?: string currentBranchConnectionString?: string parentBranchConnectionString?: string @@ -48,6 +51,7 @@ export interface BranchMergeDiffResult { export const useBranchMergeDiff = ({ currentBranchRef, + isCurrentBranchDefault, parentProjectRef, currentBranchConnectionString, parentBranchConnectionString, @@ -55,26 +59,39 @@ export const useBranchMergeDiff = ({ }: UseBranchMergeDiffProps): BranchMergeDiffResult => { const pgDeltaDiffEnabled = useIsPgDeltaDiffEnabled() + const diffGrant = useBranchGrant('GET /v1/branches/{branch_id_or_ref}/diff', { + projectRef: parentProjectRef, + isDefault: isCurrentBranchDefault, + }) + // Get database diff const { data: diffContent, - isPending: isDatabaseDiffLoading, + isPending: isDiffQueryPending, isRefetching: isDatabaseDiffRefetching, - error: databaseDiffError, + error: diffQueryError, refetch: refetchDatabaseDiff, - } = useBranchDiffQuery( - { - branchRef: currentBranchRef || '', - projectRef: parentProjectRef || '', + } = useQuery({ + ...branchDiffQueryOptions({ + branchRef: currentBranchRef, + projectRef: parentProjectRef, pgdelta: pgDeltaDiffEnabled, - }, - { - enabled: !!currentBranchRef && !!parentProjectRef, - refetchOnMount: 'always', - refetchOnWindowFocus: false, - staleTime: 0, - } - ) + grant: diffGrant.grant, + }), + enabled: !!currentBranchRef && !!parentProjectRef, + refetchOnMount: 'always', + refetchOnWindowFocus: false, + staleTime: 0, + }) + + const isDatabaseDiffLoading = + diffGrant.status === 'loading' || (diffGrant.status === 'granted' && isDiffQueryPending) + let databaseDiffError: unknown = diffQueryError + if (diffGrant.status === 'denied') { + databaseDiffError = new Error('You need additional permissions to view branch diffs') + } else if (diffGrant.status === 'error') { + databaseDiffError = diffGrant.error + } // Get migrations for both current branch and main branch const { data: currentBranchMigrations, refetch: refetchCurrentBranchMigrations } = diff --git a/apps/studio/pages/project/[ref]/merge.tsx b/apps/studio/pages/project/[ref]/merge.tsx index 0128c82c221..b134f30e956 100644 --- a/apps/studio/pages/project/[ref]/merge.tsx +++ b/apps/studio/pages/project/[ref]/merge.tsx @@ -87,6 +87,14 @@ const MergePage: NextPageWithLayout = () => { projectRef: parentProjectRef, isDefault: currentBranch?.is_default, }) + const mergeBranchGrant = useBranchGrant('POST /v1/branches/{branch_id_or_ref}/merge', { + projectRef: parentProjectRef, + isDefault: currentBranch?.is_default, + }) + const diffGrant = useBranchGrant('GET /v1/branches/{branch_id_or_ref}/diff', { + projectRef: parentProjectRef, + isDefault: currentBranch?.is_default, + }) const { diffContent, @@ -106,6 +114,7 @@ const MergePage: NextPageWithLayout = () => { modifiedFunctionsCount, } = useBranchMergeDiff({ currentBranchRef: ref, + isCurrentBranchDefault: currentBranch?.is_default, parentProjectRef, currentBranchConnectionString: project?.connectionString || undefined, parentBranchConnectionString: parentProject?.connectionString || undefined, @@ -278,12 +287,21 @@ const MergePage: NextPageWithLayout = () => { } const handleMerge = () => { - if (!ref || !parentProjectRef) return + if ( + !ref || + !parentProjectRef || + mergeBranchGrant.status !== 'granted' || + diffGrant.status !== 'granted' + ) { + return + } setIsSubmitting(true) track('branch_merge_submitted', undefined, { project: parentProjectRef }) mergeBranch({ + grant: mergeBranchGrant.grant, + diffGrant: diffGrant.grant, branchProjectRef: ref, baseProjectRef: parentProjectRef, migration_version: undefined, @@ -380,6 +398,7 @@ const MergePage: NextPageWithLayout = () => { setShowConfirmDialog(true)} /> }