mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
## 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.
253 lines
8.3 KiB
TypeScript
253 lines
8.3 KiB
TypeScript
import { PermissionAction } from '@supabase/shared-types/out/constants'
|
|
import { screen, waitFor } from '@testing-library/react'
|
|
import userEvent from '@testing-library/user-event'
|
|
import { HttpResponse } from 'msw'
|
|
import { describe, expect, test, vi } from 'vitest'
|
|
|
|
import { GitHubIntegrationConnectionForm } from './GitHubIntegrationConnectionForm'
|
|
import { type components } from '@/data/api'
|
|
import type { GitHubConnection } from '@/data/integrations/integrations.types'
|
|
import { FGA_PERMISSIONS, type FgaPermissions } from '@/hooks/misc/useCheckPermissionsV2'
|
|
import { createMockOrganizationResponse } from '@/tests/helpers'
|
|
import { createTestBranch } from '@/tests/lib/branch-test-utils'
|
|
import { customRender } from '@/tests/lib/custom-render'
|
|
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
|
|
import { mockPermissions } from '@/tests/lib/msw-permissions'
|
|
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
|
|
|
|
type AccessControlPermission = components['schemas']['AccessControlPermission']
|
|
|
|
const ORGANIZATION_SLUG = 'acme'
|
|
const PROJECT_REF = 'project-ref'
|
|
|
|
vi.mock('common', async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import('common')>()
|
|
return {
|
|
...actual,
|
|
useIsLoggedIn: () => true,
|
|
useParams: () => ({ ref: PROJECT_REF }),
|
|
}
|
|
})
|
|
|
|
vi.mock('@/lib/constants', async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import('@/lib/constants')>()
|
|
return { ...actual, IS_PLATFORM: true }
|
|
})
|
|
|
|
const CONNECTION: GitHubConnection = {
|
|
id: 1,
|
|
inserted_at: '2026-01-01T00:00:00.000Z',
|
|
updated_at: '2026-01-01T00:00:00.000Z',
|
|
branch_limit: 50,
|
|
installation_id: 1,
|
|
new_branch_per_pr: true,
|
|
supabase_changes_only: true,
|
|
workdir: 'supabase',
|
|
project: { id: 1, name: 'Production', ref: PROJECT_REF },
|
|
repository: { id: 1, name: 'acme/app' },
|
|
user: null,
|
|
}
|
|
|
|
const CAN_MANAGE_GITHUB_CONNECTIONS_PERMISSION: AccessControlPermission = {
|
|
actions: [PermissionAction.CREATE, PermissionAction.UPDATE],
|
|
condition: null,
|
|
organization_id: null,
|
|
organization_slug: ORGANIZATION_SLUG,
|
|
project_ids: null,
|
|
project_refs: [],
|
|
resources: ['integrations.github_connections'],
|
|
restrictive: false,
|
|
}
|
|
|
|
const PRODUCTION_BRANCH = createTestBranch({
|
|
name: 'main',
|
|
is_default: true,
|
|
git_branch: 'main',
|
|
parent_project_ref: PROJECT_REF,
|
|
project_ref: PROJECT_REF,
|
|
})
|
|
|
|
function mockEndpoints(projectPermissions: FgaPermissions[]) {
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/projects/:ref',
|
|
response: {
|
|
cloud_provider: 'AWS',
|
|
connectionString: null,
|
|
db_host: `db.${PROJECT_REF}.supabase.co`,
|
|
dbVersion: 'supabase-postgres-15.1.0',
|
|
high_availability: false,
|
|
id: 1,
|
|
infra_compute_size: 'micro',
|
|
inserted_at: '2026-01-01T00:00:00.000Z',
|
|
integration_source: null,
|
|
is_branch_enabled: true,
|
|
is_physical_backups_enabled: false,
|
|
name: 'Production',
|
|
organization_id: 1,
|
|
ref: PROJECT_REF,
|
|
region: 'us-east-1',
|
|
restUrl: `https://${PROJECT_REF}.supabase.co`,
|
|
status: 'ACTIVE_HEALTHY',
|
|
subscription_id: 'subscription-1',
|
|
updated_at: '2026-01-01T00:00:00.000Z',
|
|
},
|
|
})
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/integrations/github/authorization',
|
|
response: { id: 1, sender_id: 1, user_id: 1 },
|
|
})
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/organizations',
|
|
response: [createMockOrganizationResponse({ id: 1, slug: ORGANIZATION_SLUG })],
|
|
})
|
|
mockPermissions({
|
|
organizations: [
|
|
{
|
|
slug: ORGANIZATION_SLUG,
|
|
role: 'developer',
|
|
permissions: [],
|
|
projects: [{ ref: PROJECT_REF, role: 'developer', permissions: projectPermissions }],
|
|
},
|
|
],
|
|
})
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/profile/permissions',
|
|
response: () =>
|
|
HttpResponse.json<AccessControlPermission[]>([CAN_MANAGE_GITHUB_CONNECTIONS_PERMISSION]),
|
|
})
|
|
addAPIMock({ method: 'get', path: '/v1/projects/:ref/branches', response: [PRODUCTION_BRANCH] })
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/integrations/github/repositories',
|
|
response: {
|
|
partial_response_due_to_sso: false,
|
|
repositories: [{ id: 1, installation_id: 1, name: 'acme/app', default_branch: 'main' }],
|
|
},
|
|
})
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/organizations/:slug/entitlements',
|
|
response: {
|
|
entitlements: (['integrations.github_connections', 'branching_limit'] as const).map(
|
|
(key) => ({
|
|
config: { enabled: true },
|
|
feature: { key, type: 'boolean' as const },
|
|
hasAccess: true,
|
|
type: 'boolean' as const,
|
|
})
|
|
),
|
|
},
|
|
})
|
|
addAPIMock({ method: 'get', path: '/platform/organizations/:slug/members', response: [] })
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/organizations/:slug/members/invitations',
|
|
response: { invitations: [] },
|
|
})
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/organizations/:slug/roles',
|
|
response: { org_scoped_roles: [], project_scoped_roles: [] },
|
|
})
|
|
}
|
|
|
|
const renderForm = () =>
|
|
customRender(<GitHubIntegrationConnectionForm connection={CONNECTION} />, {
|
|
profileContext: createMockProfileContext(),
|
|
})
|
|
|
|
async function editWorkingDirectory() {
|
|
await waitFor(() => expect(screen.getByLabelText('Production branch name')).toHaveValue('main'))
|
|
await userEvent.type(screen.getByLabelText('Working directory'), '/app')
|
|
}
|
|
|
|
describe('GitHubIntegrationConnectionForm', () => {
|
|
test('blocks saving when the user cannot update the production branch', async () => {
|
|
mockEndpoints([FGA_PERMISSIONS.PROJECT.BRANCHING_DEVELOPMENT_READ])
|
|
|
|
renderForm()
|
|
|
|
await editWorkingDirectory()
|
|
|
|
const saveButton = await screen.findByRole('button', { name: 'Save changes' })
|
|
expect(saveButton).toHaveAttribute('aria-disabled', 'true')
|
|
await userEvent.hover(saveButton)
|
|
expect(
|
|
await screen.findAllByText('You need additional permissions to update the production branch')
|
|
).not.toHaveLength(0)
|
|
})
|
|
|
|
test('allows saving with permission to update the production branch', async () => {
|
|
mockEndpoints([
|
|
FGA_PERMISSIONS.PROJECT.BRANCHING_PRODUCTION_READ,
|
|
FGA_PERMISSIONS.PROJECT.BRANCHING_PRODUCTION_WRITE,
|
|
])
|
|
|
|
renderForm()
|
|
|
|
await editWorkingDirectory()
|
|
|
|
const saveButton = await screen.findByRole('button', { name: 'Save changes' })
|
|
await waitFor(() => expect(saveButton).toBeEnabled())
|
|
})
|
|
|
|
test('blocks saving until the branch list loads, so it never creates a second production branch', async () => {
|
|
mockEndpoints([
|
|
FGA_PERMISSIONS.PROJECT.BRANCHING_PRODUCTION_READ,
|
|
FGA_PERMISSIONS.PROJECT.BRANCHING_PRODUCTION_CREATE,
|
|
FGA_PERMISSIONS.PROJECT.BRANCHING_PRODUCTION_WRITE,
|
|
])
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/v1/projects/:ref/branches',
|
|
response: () =>
|
|
HttpResponse.json<APIErrorBody>({ message: 'Failed to list branches' }, { status: 500 }),
|
|
})
|
|
|
|
renderForm()
|
|
|
|
await userEvent.type(await screen.findByLabelText('Working directory'), '/app')
|
|
const saveButton = await screen.findByRole('button', { name: 'Save changes' })
|
|
await userEvent.hover(saveButton)
|
|
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())
|
|
})
|
|
})
|