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<M, P>` 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.
This commit is contained in:
Charis authored and GitHub committed 2026-11-03 09:12:48 -05:00
1 parent 29638836ab
commit 9b7cbd1803
8 files changed
+151 -48

No files matched your search

@@ -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 = () => {
</div>
)}
{githubConnection && (
{githubConnection && isSuccessBranches && (
<div className="flex flex-row gap-4">
<div>
<figure className="w-10 h-10 rounded-md bg-info-200 border border-info-400 flex items-center justify-center">
@@ -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"
@@ -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<void>((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())
})
})
@@ -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,
+31 -19
View File
@@ -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<BranchDiffVariables, 'branchRef' | 'includedSchemas' | 'pgdelta'>) {
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<ReturnType<typeof getBranchDiff>>
export type BranchDiffData = Awaited<ReturnType<typeof getBranchDiff>>
export type BranchDiffError = ResponseError
export const useBranchDiffQuery = (
{ branchRef, projectRef, includedSchemas, pgdelta }: BranchDiffVariables,
{
enabled = true,
...options
}: Omit<UseCustomQueryOptions<BranchDiffData, ResponseError>, 'queryKey' | 'queryFn'> = {}
) =>
useQuery<BranchDiffData, ResponseError>({
export const branchDiffQueryOptions = ({
branchRef,
projectRef,
includedSchemas,
pgdelta,
grant,
}: BranchDiffVariables) =>
queryOptions<BranchDiffData, BranchDiffError>({
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,
})
@@ -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) {
@@ -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 } =
+20 -1
View File
@@ -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 = () => {
<MergeActions
isWorkflowRunning={isWorkflowRunning}
isSubmitting={isMerging || isSubmitting}
canMerge={mergeBranchGrant.status === 'granted' && diffGrant.status === 'granted'}
onSelectMerge={() => setShowConfirmDialog(true)}
/>
}