Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(studio): add Grant type and useGrant/getGrant/ensureGrant (#52105)

Charis1bcc472d647c
diff --git a/apps/studio/data/permissions/permissions-query-v2.ts b/apps/studio/data/permissions/permissions-query-v2.ts
index e423bfa2322..7b95118aab5 100644
--- a/apps/studio/data/permissions/permissions-query-v2.ts
+++ b/apps/studio/data/permissions/permissions-query-v2.ts
@@ -1,4 +1,4 @@
-import { useQuery, type QueryClient } from '@tanstack/react-query'
+import { queryOptions, useQuery, type QueryClient } from '@tanstack/react-query'
import { useIsLoggedIn } from 'common'
import { permissionKeys } from './keys'
@@ -26,15 +26,34 @@ export async function getPermissionsV2(signal?: AbortSignal) {
export type PermissionsV2Data = Awaited<ReturnType<typeof getPermissionsV2>>
export type PermissionsV2Error = ResponseError
+export const permissionsQueryOptionsV2 = () =>
+ queryOptions({
+ queryKey: permissionKeys.listV2(),
+ queryFn: ({ signal }) => getPermissionsV2(signal),
+ enabled: IS_PLATFORM,
+ staleTime: 5 * 60 * 1000,
+ })
+
export const usePermissionsQueryV2 = <TData = PermissionsV2Data>({
enabled = true,
...options
-}: UseCustomQueryOptions<PermissionsV2Data, PermissionsV2Error, TData> = {}) => {
+}: UseCustomQueryOptions<
+ PermissionsV2Data,
+ PermissionsV2Error,
+ TData,
+ ReturnType<typeof permissionKeys.listV2>
+> = {}) => {
const isLoggedIn = useIsLoggedIn()
+ const { queryKey, queryFn } = permissionsQueryOptionsV2()
- return useQuery<PermissionsV2Data, PermissionsV2Error, TData>({
- queryKey: permissionKeys.listV2(),
- queryFn: ({ signal }) => getPermissionsV2(signal),
+ return useQuery<
+ PermissionsV2Data,
+ PermissionsV2Error,
+ TData,
+ ReturnType<typeof permissionKeys.listV2>
+ >({
+ queryKey,
+ queryFn,
...options,
enabled: IS_PLATFORM && enabled && isLoggedIn,
staleTime: 5 * 60 * 1000,
diff --git a/apps/studio/data/projects/project-create-mutation.ts b/apps/studio/data/projects/project-create-mutation.ts
index d7ef928fcc9..ec21c3b04af 100644
--- a/apps/studio/data/projects/project-create-mutation.ts
+++ b/apps/studio/data/projects/project-create-mutation.ts
@@ -1,10 +1,11 @@
-import { useMutation } from '@tanstack/react-query'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { DesiredInstanceSize, PostgresEngine, ReleaseChannel } from './new-project.constants'
import { useInvalidateProjectsInfiniteQuery } from './org-projects-infinite-query'
import type { components } from '@/data/api'
import { handleError, post } from '@/data/fetchers'
+import { invalidatePermissionsQueryV2 } from '@/data/permissions/permissions-query-v2'
import { PROVIDERS } from '@/lib/constants'
import { captureCriticalError } from '@/lib/error-reporting'
import type { ResponseError, UseCustomMutationOptions } from '@/types'
@@ -95,12 +96,13 @@ export const useProjectCreateMutation = ({
UseCustomMutationOptions<ProjectCreateData, ResponseError, ProjectCreateVariables>,
'mutationFn'
> = {}) => {
+ const queryClient = useQueryClient()
const { invalidateProjectsQuery } = useInvalidateProjectsInfiniteQuery()
return useMutation<ProjectCreateData, ResponseError, ProjectCreateVariables>({
mutationFn: (vars) => createProject(vars),
async onSuccess(data, variables, context) {
- await invalidateProjectsQuery()
+ await Promise.all([invalidateProjectsQuery(), invalidatePermissionsQueryV2(queryClient)])
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
diff --git a/apps/studio/hooks/misc/useCheckPermissionsV2.test.ts b/apps/studio/hooks/misc/useCheckPermissionsV2.test.ts
index 33538311540..f4faab137ea 100644
--- a/apps/studio/hooks/misc/useCheckPermissionsV2.test.ts
+++ b/apps/studio/hooks/misc/useCheckPermissionsV2.test.ts
@@ -55,4 +55,51 @@ describe('doPermissionsCheckV2', () => {
it('returns false when organizationSlug is undefined', () => {
expect(doPermissionsCheckV2(permissions(), 'storage_read', undefined)).toBe(false)
})
+
+ describe('requirement groups', () => {
+ it('keeps flat arrays as a single AND group', () => {
+ expect(
+ doPermissionsCheckV2(permissions(), ['storage_read', 'storage_write'], 'org-slug')
+ ).toBe(true)
+ expect(
+ doPermissionsCheckV2(permissions(), ['storage_read', 'custom_domain_write'], 'org-slug')
+ ).toBe(false)
+ })
+
+ it('passes when any group is fully satisfied', () => {
+ const groups = [['custom_domain_write'], ['storage_read', 'storage_write']] as const
+ expect(doPermissionsCheckV2(permissions(), groups, 'org-slug')).toBe(true)
+ })
+
+ it('fails when every group misses a permission', () => {
+ const groups = [
+ ['storage_read', 'custom_domain_write'],
+ ['custom_domain_write', 'storage_write'],
+ ] as const
+ expect(doPermissionsCheckV2(permissions(), groups, 'org-slug')).toBe(false)
+ })
+
+ it('resolves each permission in a group from the project or the org', () => {
+ const data = permissions({
+ role: 'member',
+ permissions: ['storage_read'],
+ projects: [{ ref: 'project-ref', role: 'developer', permissions: ['storage_write'] }],
+ })
+ const groups = [['storage_read', 'storage_write']] as const
+ expect(doPermissionsCheckV2(data, groups, 'org-slug', 'project-ref')).toBe(true)
+ expect(doPermissionsCheckV2(data, groups, 'org-slug', 'other-project')).toBe(false)
+ })
+
+ it('fails closed on an empty group, even next to a satisfied one', () => {
+ expect(doPermissionsCheckV2(permissions(), [[]], 'org-slug')).toBe(false)
+ expect(doPermissionsCheckV2(permissions(), [[], ['storage_read']], 'org-slug')).toBe(true)
+ expect(doPermissionsCheckV2(permissions(), [[], ['custom_domain_write']], 'org-slug')).toBe(
+ false
+ )
+ })
+
+ it('fails closed on an empty list', () => {
+ expect(doPermissionsCheckV2(permissions(), [], 'org-slug')).toBe(false)
+ })
+ })
})
diff --git a/apps/studio/hooks/misc/useCheckPermissionsV2.ts b/apps/studio/hooks/misc/useCheckPermissionsV2.ts
index 5346ac99124..247e8df10e6 100644
--- a/apps/studio/hooks/misc/useCheckPermissionsV2.ts
+++ b/apps/studio/hooks/misc/useCheckPermissionsV2.ts
@@ -23,15 +23,22 @@ export const FGA_PERMISSIONS = Object.fromEntries(
type DeepValue<T> = T extends object ? DeepValue<T[keyof T]> : T
export type FgaPermissions = DeepValue<typeof FGA_PERMISSIONS>
+export type FgaRequirementGroups = readonly (readonly FgaPermissions[])[]
+
/**
- * Checks an FGA permission against the v2 permissions response.
- * Resolution order:
+ * Checks FGA permissions against the v2 permissions response.
+ *
+ * `permission` is a single permission, a list of permissions that are all required (one AND group),
+ * or a list of such lists (OR-of-AND): the check passes if every permission in at least one group
+ * is held. Empty input, including an empty group, never grants.
+ *
+ * Each permission is looked up in this order:
* 1. explicit project scoped role entry for projectRef (if provided)
* 2. org level permissions (org role applies to all projects in the org)
*/
export function doPermissionsCheckV2(
data: PermissionsV2Data | undefined,
- permission: FgaPermissions | FgaPermissions[],
+ permission: FgaPermissions | readonly FgaPermissions[] | FgaRequirementGroups,
organizationSlug?: string,
projectRef?: string | null
): boolean {
@@ -40,81 +47,124 @@ export function doPermissionsCheckV2(
const org = data.organizations.find((o) => o.slug === organizationSlug)
if (!org) return false
- const required = Array.isArray(permission) ? permission : [permission]
- if (required.length === 0) return false // nothing requested: fail closed
+ let groups: FgaRequirementGroups
+ if (typeof permission === 'string') {
+ groups = [[permission]]
+ } else if (permission.every((p): p is FgaPermissions => typeof p === 'string')) {
+ groups = [permission]
+ } else {
+ groups = permission
+ }
const project = projectRef ? org.projects.find((p) => p.ref === projectRef) : undefined
- return required.every(
- (p) => (project?.permissions.includes(p) ?? false) || org.permissions.includes(p)
+ return groups.some(
+ (group) =>
+ group.length > 0 &&
+ group.every((p) => (project?.permissions.includes(p) ?? false) || org.permissions.includes(p))
)
}
-function useGetProjectPermissionsV2(
- permissionsOverride?: PermissionsV2Data,
- organizationSlugOverride?: string,
- projectRefOverride?: string | null,
- enabled = true
-) {
- const {
- data,
- isPending: isLoadingPermissions,
- isSuccess: isSuccessPermissions,
- } = usePermissionsQueryV2({
- enabled: permissionsOverride === undefined && enabled,
- })
- const permissions = permissionsOverride === undefined ? data : permissionsOverride
-
+/**
+ * Resolves the organization and project an FGA check applies to.
+ *
+ * - `organizationSlug` defaults to the selected organization.
+ * - `projectRef` defaults to the URL ref; `null` means an org-level check.
+ * - `permissionsProjectRef` is the ref permissions are evaluated against. For the URL project it
+ * resolves branches to their parent, since FGA tuples are written against the parent project
+ * only. An explicit ref other than the URL ref is used as-is, without fetching its details.
+ */
+export function usePermissionScopeV2({
+ organizationSlug: organizationSlugOverride,
+ projectRef: projectRefOverride,
+ enabled = true,
+}: {
+ organizationSlug?: string
+ projectRef?: string | null
+ enabled?: boolean
+}) {
const getOrganizationDataFromParamsSlug = organizationSlugOverride === undefined && enabled
const {
data: organizationData,
isPending: isLoadingOrganization,
isSuccess: isSuccessOrganization,
+ error: organizationError,
} = useSelectedOrganizationQuery({
enabled: getOrganizationDataFromParamsSlug,
})
- const organization =
- organizationSlugOverride === undefined ? organizationData : { slug: organizationSlugOverride }
- const organizationSlug = organization?.slug
+ const organizationSlug =
+ organizationSlugOverride === undefined ? organizationData?.slug : organizationSlugOverride
const { ref: urlProjectRef } = useParams()
- const getProjectDataFromParamsRef = !!urlProjectRef && projectRefOverride === undefined && enabled
+ const projectRef = projectRefOverride === undefined ? urlProjectRef : projectRefOverride
+
+ const getProjectDataFromParamsRef = !!urlProjectRef && projectRef === urlProjectRef && enabled
const {
data: projectData,
isPending: isLoadingProject,
isSuccess: isSuccessProject,
+ error: projectError,
} = useSelectedProjectQuery({
enabled: getProjectDataFromParamsRef,
})
- const project =
- projectRefOverride === undefined
- ? projectData
- : { ref: projectRefOverride, parent_project_ref: undefined }
// branch projects resolve to their base project ref, since FGA tuples
// are written against the base project only
- const projectRef =
- projectRefOverride === null
- ? null
- : project?.parent_project_ref
- ? project.parent_project_ref
- : project?.ref
+ const permissionsProjectRef =
+ projectRef === urlProjectRef && !!urlProjectRef ? projectData?.parentRef : projectRef
const isLoading =
- isLoadingPermissions ||
(getOrganizationDataFromParamsSlug && isLoadingOrganization) ||
(getProjectDataFromParamsRef && isLoadingProject)
const isSuccess =
- isSuccessPermissions &&
(!getOrganizationDataFromParamsSlug || isSuccessOrganization) &&
(!getProjectDataFromParamsRef || isSuccessProject)
+ const error =
+ (getOrganizationDataFromParamsSlug ? organizationError : null) ??
+ (getProjectDataFromParamsRef ? projectError : null)
return {
- permissions,
organizationSlug,
projectRef,
+ permissionsProjectRef,
isLoading,
isSuccess,
+ error,
+ }
+}
+
+function useGetProjectPermissionsV2(
+ permissionsOverride?: PermissionsV2Data,
+ organizationSlugOverride?: string,
+ projectRefOverride?: string | null,
+ enabled = true
+) {
+ const {
+ data,
+ isPending: isLoadingPermissions,
+ isSuccess: isSuccessPermissions,
+ } = usePermissionsQueryV2({
+ enabled: permissionsOverride === undefined && enabled,
+ })
+ const permissions = permissionsOverride === undefined ? data : permissionsOverride
+
+ const {
+ organizationSlug,
+ permissionsProjectRef: projectRef,
+ isLoading: isLoadingScope,
+ isSuccess: isSuccessScope,
+ } = usePermissionScopeV2({
+ organizationSlug: organizationSlugOverride,
+ projectRef: projectRefOverride,
+ enabled,
+ })
+
+ return {
+ permissions,
+ organizationSlug,
+ projectRef,
+ isLoading: isLoadingPermissions || isLoadingScope,
+ isSuccess: isSuccessPermissions && isSuccessScope,
}
}
diff --git a/apps/studio/lib/fga-refinements.ts b/apps/studio/lib/fga-refinements.ts
new file mode 100644
index 00000000000..3f0cb6bd96f
--- /dev/null
+++ b/apps/studio/lib/fga-refinements.ts
@@ -0,0 +1,18 @@
+import type { FgaGuardedEndpoint, FgaRequirements } from 'api-types'
+
+import type { FgaRequirementGroups } from '@/hooks/misc/useCheckPermissionsV2'
+
+export type FgaRefinement<E extends FgaGuardedEndpoint> = {
+ /** The annotation from `fga-requirements.ts` this refinement was written against. Typecheck fails if the generated annotation changes, so the refinement gets re-reviewed. */
+ base: FgaRequirements[E]
+ /** Named variants. A grant for a variant needs the base requirement AND the variant's `requires`. */
+ variants: { readonly [variant: string]: { readonly requires: FgaRequirementGroups } }
+}
+
+export type FgaRefinementMap = { readonly [E in FgaGuardedEndpoint]?: FgaRefinement<E> }
+
+// Requirements that depend on the request body or params, which the OpenAPI annotation can't express
+// (for example, running a write query through pg-meta, or revealing an API key secret).
+export const fgaRefinements = {} as const satisfies FgaRefinementMap
+
+export type FgaRefinements = typeof fgaRefinements
diff --git a/apps/studio/lib/grants.test.ts b/apps/studio/lib/grants.test.ts
new file mode 100644
index 00000000000..e1692306fd2
--- /dev/null
+++ b/apps/studio/lib/grants.test.ts
@@ -0,0 +1,425 @@
+import { QueryClient } from '@tanstack/react-query'
+import { waitFor } from '@testing-library/react'
+import { platformComponents as components } from 'api-types'
+import { HttpResponse } from 'msw'
+import { beforeEach, describe, expect, expectTypeOf, test, vi } from 'vitest'
+
+import {
+ ensureGrant,
+ getGrant,
+ useGrant,
+ type Grant,
+ type GrantFor,
+ type GrantResult,
+} from './grants'
+import { projectKeys } from '@/data/projects/keys'
+import type { ProjectDetailData } from '@/data/projects/project-detail-query'
+import { createMockOrganizationResponse } from '@/tests/helpers'
+import { customRenderHook } from '@/tests/lib/custom-render'
+import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
+import { createMockProfileContext } from '@/tests/lib/profile-helpers'
+
+type PermissionsV2Response = components['schemas']['UserPermissionsResponse_Output']
+type OrganizationResponse = ReturnType<typeof createMockOrganizationResponse>
+
+const mocks = vi.hoisted((): { isPlatform: boolean; params: { ref?: string } } => ({
+ isPlatform: true,
+ params: { ref: 'default' },
+}))
+
+vi.mock('common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('common')>()
+ return {
+ ...actual,
+ useParams: () => mocks.params,
+ useIsLoggedIn: () => true,
+ }
+})
+
+vi.mock('@/lib/constants', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>()
+ return {
+ ...actual,
+ get IS_PLATFORM() {
+ return mocks.isPlatform
+ },
+ }
+})
+
+const ORG_SLUG = 'test-org'
+const BRANCHES = 'GET /v1/projects/{ref}/branches'
+const DELETE_BRANCH = 'DELETE /v1/branches/{branch_id_or_ref}'
+const PROFILE_CONTEXT = createMockProfileContext()
+
+function permissionsFor(
+ org: Partial<PermissionsV2Response['organizations'][number]> = {}
+): PermissionsV2Response {
+ return {
+ organizations: [{ slug: ORG_SLUG, role: 'developer', permissions: [], projects: [], ...org }],
+ }
+}
+
+function mockPermissions(response: PermissionsV2Response) {
+ addAPIMock({
+ method: 'get',
+ path: '/platform/profile/permissions/v2',
+ response: () => HttpResponse.json<PermissionsV2Response>(response),
+ })
+}
+
+function mockOrganizations(details: Partial<OrganizationResponse> = {}) {
+ addAPIMock({
+ method: 'get',
+ path: '/platform/organizations',
+ response: () =>
+ HttpResponse.json<OrganizationResponse[]>([
+ createMockOrganizationResponse({ id: 1, slug: ORG_SLUG, ...details }),
+ ]),
+ })
+}
+
+const BRANCH_PROJECT: ProjectDetailData = {
+ cloud_provider: 'AWS',
+ connectionString: 'postgresql://postgres:[email protected]:5432/postgres',
+ db_host: 'db.branch-ref.supabase.co',
+ dbVersion: 'supabase-postgres-15.1.0',
+ high_availability: false,
+ id: 2,
+ infra_compute_size: 'micro',
+ inserted_at: '2026-01-01T00:00:00.000Z',
+ integration_source: null,
+ is_branch_enabled: false,
+ is_physical_backups_enabled: false,
+ name: 'Branch',
+ organization_id: 1,
+ parent_project_ref: 'parent-ref',
+ ref: 'branch-ref',
+ region: 'us-east-1',
+ restUrl: 'https://branch-ref.supabase.co',
+ status: 'ACTIVE_HEALTHY',
+ subscription_id: 'subscription-1',
+ updated_at: '2026-01-01T00:00:00.000Z',
+}
+
+function mockProjectDetail() {
+ addAPIMock({
+ method: 'get',
+ path: '/platform/projects/:ref',
+ response: ({ params }) =>
+ HttpResponse.json<ProjectDetailData>(
+ params.ref === BRANCH_PROJECT.ref
+ ? BRANCH_PROJECT
+ : { ...BRANCH_PROJECT, ref: String(params.ref), parent_project_ref: undefined }
+ ),
+ })
+}
+
+beforeEach(() => {
+ mocks.isPlatform = true
+ mocks.params = { ref: 'default' }
+})
+
+describe('getGrant', () => {
+ const scope = { organizationSlug: ORG_SLUG, projectRef: 'proj' }
+
+ test('mints from any satisfied group of an OR-of-AND requirement', () => {
+ const dev = permissionsFor({ permissions: ['branching_development_read'] })
+ const prod = permissionsFor({ permissions: ['branching_production_read'] })
+
+ expect(getGrant(dev, BRANCHES, scope).status).toBe('granted')
+ expect(getGrant(prod, BRANCHES, scope).status).toBe('granted')
+ })
+
+ test('records the endpoint and scope on the grant', () => {
+ const result = getGrant(
+ permissionsFor({ permissions: ['branching_production_read'] }),
+ BRANCHES,
+ scope
+ )
+
+ expect(result).toEqual({
+ status: 'granted',
+ grant: {
+ endpoint: BRANCHES,
+ variant: undefined,
+ organizationSlug: ORG_SLUG,
+ projectRef: 'proj',
+ },
+ })
+ })
+
+ test('denies when no group is satisfied or permissions are missing', () => {
+ expect(getGrant(permissionsFor(), BRANCHES, scope)).toEqual({ status: 'denied' })
+ expect(getGrant(undefined, BRANCHES, scope)).toEqual({ status: 'denied' })
+ expect(
+ getGrant(permissionsFor({ permissions: ['branching_production_read'] }), BRANCHES, {
+ ...scope,
+ organizationSlug: 'other-org',
+ })
+ ).toEqual({ status: 'denied' })
+ })
+
+ test('evaluates against permissionsProjectRef but records the branch ref', () => {
+ const data = permissionsFor({
+ role: 'member',
+ projects: [
+ { ref: 'parent-ref', role: 'developer', permissions: ['branching_production_read'] },
+ ],
+ })
+
+ const result = getGrant(data, BRANCHES, {
+ ...scope,
+ projectRef: 'branch-ref',
+ permissionsProjectRef: 'parent-ref',
+ })
+ expect(result.status).toBe('granted')
+ if (result.status === 'granted') expect(result.grant.projectRef).toBe('branch-ref')
+
+ expect(getGrant(data, BRANCHES, { ...scope, projectRef: 'branch-ref' }).status).toBe('denied')
+ })
+
+ test('supports an explicit project scope for endpoints without the project in the path', () => {
+ const data = permissionsFor({
+ role: 'member',
+ projects: [{ ref: 'proj', role: 'developer', permissions: ['branching_development_delete'] }],
+ })
+
+ expect(getGrant(data, DELETE_BRANCH, scope).status).toBe('granted')
+ expect(getGrant(data, DELETE_BRANCH, { ...scope, projectRef: 'other' }).status).toBe('denied')
+ })
+
+ test('mints without permission data when self-hosted', () => {
+ mocks.isPlatform = false
+
+ expect(getGrant(undefined, BRANCHES, { projectRef: 'proj' }).status).toBe('granted')
+ })
+
+ test('denies an unknown variant at runtime', () => {
+ const data = permissionsFor({ permissions: ['branching_production_read'] })
+
+ const result = getGrant(data, BRANCHES, scope, { variant: 'write' as never })
+ expect(result).toEqual({ status: 'denied' })
+ })
+})
+
+describe('useGrant', () => {
+ test('moves from loading to granted', async () => {
+ mockPermissions(permissionsFor({ permissions: ['branching_production_read'] }))
+
+ const { result } = customRenderHook(
+ () => useGrant(BRANCHES, { organizationSlug: ORG_SLUG, projectRef: 'proj' }),
+ { profileContext: PROFILE_CONTEXT }
+ )
+
+ expect(result.current.status).toBe('loading')
+ await waitFor(() => expect(result.current.status).toBe('granted'))
+ expect(result.current.grant).toEqual({
+ endpoint: BRANCHES,
+ variant: undefined,
+ organizationSlug: ORG_SLUG,
+ projectRef: 'proj',
+ })
+ })
+
+ test('denies when the permissions are missing', async () => {
+ mockPermissions(permissionsFor())
+
+ const { result } = customRenderHook(
+ () => useGrant(BRANCHES, { organizationSlug: ORG_SLUG, projectRef: 'proj' }),
+ { profileContext: PROFILE_CONTEXT }
+ )
+
+ await waitFor(() => expect(result.current.status).toBe('denied'))
+ expect(result.current.grant).toBeUndefined()
+ })
+
+ test('reports an error when the permissions request fails', async () => {
+ addAPIMock({
+ method: 'get',
+ path: '/platform/profile/permissions/v2',
+ response: () => HttpResponse.json<APIErrorBody>({ message: 'Boom' }, { status: 500 }),
+ })
+
+ const { result } = customRenderHook(
+ () => useGrant(BRANCHES, { organizationSlug: ORG_SLUG, projectRef: 'proj' }),
+ { profileContext: PROFILE_CONTEXT }
+ )
+
+ await waitFor(() => expect(result.current.status).toBe('error'))
+ expect(result.current).toMatchObject({ error: { message: 'Boom' } })
+ })
+
+ test('grants immediately when self-hosted', () => {
+ mocks.isPlatform = false
+
+ const { result } = customRenderHook(() => useGrant(BRANCHES, { projectRef: 'proj' }), {
+ profileContext: PROFILE_CONTEXT,
+ })
+
+ expect(result.current.status).toBe('granted')
+ })
+
+ test('resolves a branch from the URL to its parent but records the branch ref', async () => {
+ mocks.params = { ref: 'branch-ref' }
+ addAPIMock({
+ method: 'get',
+ path: '/platform/projects/:ref',
+ response: () => HttpResponse.json<ProjectDetailData>(BRANCH_PROJECT),
+ })
+ mockOrganizations()
+ mockPermissions(
+ permissionsFor({
+ role: 'member',
+ projects: [
+ { ref: 'parent-ref', role: 'developer', permissions: ['branching_production_read'] },
+ ],
+ })
+ )
+
+ const { result } = customRenderHook(() => useGrant(BRANCHES, {}), {
+ profileContext: PROFILE_CONTEXT,
+ })
+
+ await waitFor(() => expect(result.current.status).toBe('granted'))
+ expect(result.current.grant).toMatchObject({
+ organizationSlug: ORG_SLUG,
+ projectRef: 'branch-ref',
+ })
+ })
+
+ test('returns a stable result across rerenders', async () => {
+ mockPermissions(permissionsFor({ permissions: ['branching_production_read'] }))
+
+ const { result, rerender } = customRenderHook(
+ () => useGrant(BRANCHES, { organizationSlug: ORG_SLUG, projectRef: 'proj' }),
+ { profileContext: PROFILE_CONTEXT }
+ )
+
+ await waitFor(() => expect(result.current.status).toBe('granted'))
+ const first = result.current
+ rerender()
+ expect(result.current).toBe(first)
+ })
+})
+
+describe('ensureGrant', () => {
+ const scope = { organizationSlug: ORG_SLUG, projectRef: 'proj' }
+
+ beforeEach(() => {
+ mockProjectDetail()
+ })
+
+ test('grants when permissions allow', async () => {
+ mockPermissions(permissionsFor({ permissions: ['branching_production_read'] }))
+
+ const result = await ensureGrant(new QueryClient(), BRANCHES, scope)
+
+ expect(result.status).toBe('granted')
+ })
+
+ test('denies when permissions are missing', async () => {
+ mockPermissions(permissionsFor())
+
+ expect(await ensureGrant(new QueryClient(), BRANCHES, scope)).toEqual({ status: 'denied' })
+ })
+
+ test('returns an error when permissions cannot be fetched', async () => {
+ addAPIMock({
+ method: 'get',
+ path: '/platform/profile/permissions/v2',
+ response: () => HttpResponse.json<APIErrorBody>({ message: 'Boom' }, { status: 500 }),
+ })
+
+ const result = await ensureGrant(new QueryClient(), BRANCHES, scope)
+
+ expect(result).toMatchObject({ status: 'error', error: { message: 'Boom' } })
+ })
+
+ test('grants without fetching when self-hosted', async () => {
+ mocks.isPlatform = false
+
+ const result = await ensureGrant(new QueryClient(), BRANCHES, scope)
+
+ expect(result.status).toBe('granted')
+ })
+
+ test('fetches the project detail to resolve the parent ref', async () => {
+ mockPermissions(
+ permissionsFor({
+ role: 'member',
+ projects: [
+ { ref: 'parent-ref', role: 'developer', permissions: ['branching_production_read'] },
+ ],
+ })
+ )
+ const queryClient = new QueryClient()
+
+ const result = await ensureGrant(queryClient, BRANCHES, {
+ organizationSlug: ORG_SLUG,
+ projectRef: 'branch-ref',
+ })
+
+ expect(result.status).toBe('granted')
+ if (result.status === 'granted') expect(result.grant.projectRef).toBe('branch-ref')
+ expect(queryClient.getQueryData(projectKeys.detail('branch-ref'))).toMatchObject({
+ parent_project_ref: 'parent-ref',
+ })
+ })
+
+ test('returns an error when the project detail cannot be fetched', async () => {
+ mockPermissions(permissionsFor({ permissions: ['branching_production_read'] }))
+ addAPIMock({
+ method: 'get',
+ path: '/platform/projects/:ref',
+ response: () => HttpResponse.json<APIErrorBody>({ message: 'Boom' }, { status: 500 }),
+ })
+
+ const result = await ensureGrant(new QueryClient(), BRANCHES, scope)
+
+ expect(result).toMatchObject({ status: 'error', error: { message: 'Boom' } })
+ })
+})
+
+describe('types', () => {
+ type BranchesGrant = Grant<'GET /v1/projects/{ref}/branches'>
+ type CreateBranchGrant = Grant<'POST /v1/projects/{ref}/branches'>
+
+ test('grants are bound to their endpoint', () => {
+ function check(grant: BranchesGrant) {
+ // @ts-expect-error a grant for another endpoint is not interchangeable
+ const other: CreateBranchGrant = grant
+ return other
+ }
+ expect(check).toBeDefined()
+ })
+
+ test('a plain object is not a grant', () => {
+ const plain = {
+ endpoint: 'GET /v1/projects/{ref}/branches' as const,
+ variant: undefined,
+ organizationSlug: 'org',
+ projectRef: 'proj',
+ }
+ // @ts-expect-error the brand can only be minted by getGrant
+ const grant: BranchesGrant = plain
+ expect(grant).toBeDefined()
+ })
+
+ test('GrantFor resolves annotated endpoints and is never otherwise', () => {
+ expectTypeOf<GrantFor<'GET', '/v1/projects/{ref}/branches'>>().toEqualTypeOf<BranchesGrant>()
+ expectTypeOf<GrantFor<'GET', '/platform/profile'>>().toBeNever()
+ })
+
+ test('useGrant narrows the grant on status', () => {
+ type Result = ReturnType<typeof useGrant<'GET /v1/projects/{ref}/branches'>>
+ expectTypeOf<Result>().toEqualTypeOf<GrantResult<'GET /v1/projects/{ref}/branches'>>()
+
+ function check(result: Result) {
+ expectTypeOf(result.grant).toEqualTypeOf<BranchesGrant | undefined>()
+ if (result.status === 'granted') {
+ expectTypeOf(result.grant).toEqualTypeOf<BranchesGrant>()
+ }
+ }
+ expect(check).toBeDefined()
+ })
+})
diff --git a/apps/studio/lib/grants.ts b/apps/studio/lib/grants.ts
new file mode 100644
index 00000000000..dc0c3bbbf23
--- /dev/null
+++ b/apps/studio/lib/grants.ts
@@ -0,0 +1,198 @@
+import type { QueryClient } from '@tanstack/react-query'
+import { fgaRequirements, type FgaGuardedEndpoint } from 'api-types'
+import { useIsLoggedIn } from 'common'
+import { useMemo } from 'react'
+
+import {
+ permissionsQueryOptionsV2,
+ usePermissionsQueryV2,
+ type PermissionsV2Data,
+} from '@/data/permissions/permissions-query-v2'
+import { prefetchProjectDetail } from '@/data/projects/project-detail-query'
+import { doPermissionsCheckV2, usePermissionScopeV2 } from '@/hooks/misc/useCheckPermissionsV2'
+import { IS_PLATFORM } from '@/lib/constants'
+import { fgaRefinements, type FgaRefinementMap, type FgaRefinements } from '@/lib/fga-refinements'
+import { ResponseError } from '@/types'
+
+export type VariantOf<E extends FgaGuardedEndpoint> = FgaRefinements extends {
+ readonly [K in E]: { readonly variants: infer Vs }
+}
+ ? Extract<keyof Vs, string>
+ : never
+
+declare const grantBrand: unique symbol
+
+/** Proof that the current user holds the FGA permissions an endpoint (and optional variant) requires. */
+export type Grant<E extends FgaGuardedEndpoint, V extends VariantOf<E> = never> = {
+ readonly endpoint: E
+ readonly variant: [V] extends [never] ? undefined : V
+ readonly organizationSlug: string | undefined
+ /** The ref the grant authorizes (the branch ref for branch projects). */
+ readonly projectRef: string | null | undefined
+ // Function type: invariant in E and V. A plain property would be covariant, so `Grant<E, never>` would satisfy `Grant<E, 'write'>`.
+ readonly [grantBrand]: (_: { e: E; v: V }) => { e: E; v: V }
+}
+
+export type GrantResult<E extends FgaGuardedEndpoint, V extends VariantOf<E> = never> =
+ | { status: 'loading'; grant?: never }
+ | { status: 'granted'; grant: Grant<E, V> }
+ | { status: 'denied'; grant?: never }
+ | { status: 'error'; error: ResponseError; grant?: never }
+
+export type GrantScope = {
+ organizationSlug?: string
+ projectRef?: string | null
+}
+
+type ResolvedGrantScope = GrantScope & { permissionsProjectRef?: string | null }
+
+type EndpointKey<M extends string, P extends string> = `${Uppercase<M>} ${P}`
+
+type VariantOfKey<K extends string> = K extends FgaGuardedEndpoint ? VariantOf<K> : never
+
+/** Grant type for an endpoint, or `never` if the endpoint isn't annotated. For xQueryOptions / mutation variables. */
+export type GrantFor<
+ M extends string,
+ P extends string,
+ V extends VariantOfKey<EndpointKey<M, P>> = never,
+> = EndpointKey<M, P> extends FgaGuardedEndpoint ? Grant<EndpointKey<M, P>, V> : never
+
+function mintGrant<E extends FgaGuardedEndpoint, V extends VariantOf<E>>(
+ endpoint: E,
+ variant: V | undefined,
+ scope: GrantScope
+): Grant<E, V> {
+ // The brand is type-only: this is the one place a grant is created
+ return {
+ endpoint,
+ variant,
+ organizationSlug: scope.organizationSlug,
+ projectRef: scope.projectRef,
+ } as unknown as Grant<E, V>
+}
+
+/**
+ * Pure check of `permissions` against the endpoint's requirements (and the variant's, if given).
+ * Permissions are evaluated against `permissionsProjectRef` (the parent project for branches),
+ * falling back to `projectRef`; the minted grant records `projectRef`.
+ */
+export function getGrant<E extends FgaGuardedEndpoint, V extends VariantOf<E> = never>(
+ permissions: PermissionsV2Data | undefined,
+ endpoint: E,
+ scope: ResolvedGrantScope,
+ opts?: { variant?: V }
+): { status: 'granted'; grant: Grant<E, V> } | { status: 'denied' } {
+ const variant = opts?.variant
+ if (!IS_PLATFORM) return { status: 'granted', grant: mintGrant(endpoint, variant, scope) }
+
+ const evaluatedProjectRef = scope.permissionsProjectRef ?? scope.projectRef
+ const passesBase = doPermissionsCheckV2(
+ permissions,
+ fgaRequirements[endpoint],
+ scope.organizationSlug,
+ evaluatedProjectRef
+ )
+ if (!passesBase) return { status: 'denied' }
+
+ if (variant !== undefined) {
+ const refinements: FgaRefinementMap = fgaRefinements
+ const requires = refinements[endpoint]?.variants[variant]?.requires
+ if (
+ !requires ||
+ !doPermissionsCheckV2(permissions, requires, scope.organizationSlug, evaluatedProjectRef)
+ ) {
+ return { status: 'denied' }
+ }
+ }
+
+ return { status: 'granted', grant: mintGrant(endpoint, variant, scope) }
+}
+
+/**
+ * Mints a grant for the current user, resolving organization and project from the URL unless
+ * `scope` overrides them. Self-hosted always grants.
+ */
+export function useGrant<E extends FgaGuardedEndpoint, V extends VariantOf<E> = never>(
+ endpoint: E,
+ scope: GrantScope,
+ opts?: { variant?: V }
+): GrantResult<E, V> {
+ const variant = opts?.variant
+ const isLoggedIn = useIsLoggedIn()
+
+ const {
+ data: permissions,
+ error: permissionsError,
+ isPending: isLoadingPermissions,
+ } = usePermissionsQueryV2()
+ const {
+ organizationSlug,
+ projectRef,
+ permissionsProjectRef,
+ isLoading: isLoadingScope,
+ error: scopeError,
+ } = usePermissionScopeV2({ ...scope, enabled: IS_PLATFORM && isLoggedIn })
+
+ return useMemo((): GrantResult<E, V> => {
+ if (!IS_PLATFORM)
+ return getGrant(permissions, endpoint, { organizationSlug, projectRef }, { variant })
+ if (!isLoggedIn) return { status: 'loading' }
+ if (permissionsError) return { status: 'error', error: permissionsError }
+ if (scopeError) return { status: 'error', error: scopeError }
+ if (isLoadingPermissions || isLoadingScope) return { status: 'loading' }
+
+ return getGrant(
+ permissions,
+ endpoint,
+ { organizationSlug, projectRef, permissionsProjectRef },
+ { variant }
+ )
+ }, [
+ endpoint,
+ variant,
+ permissions,
+ permissionsError,
+ scopeError,
+ isLoggedIn,
+ isLoadingPermissions,
+ isLoadingScope,
+ organizationSlug,
+ projectRef,
+ permissionsProjectRef,
+ ])
+}
+
+/**
+ * Imperative counterpart of `useGrant` for prefetching and callbacks. Reuses fresh cached
+ * permissions and project details, fetching them otherwise.
+ */
+export async function ensureGrant<E extends FgaGuardedEndpoint, V extends VariantOf<E> = never>(
+ queryClient: QueryClient,
+ endpoint: E,
+ scope: ResolvedGrantScope,
+ opts?: { variant?: V }
+): Promise<
+ | { status: 'granted'; grant: Grant<E, V> }
+ | { status: 'denied' }
+ | { status: 'error'; error: ResponseError }
+> {
+ if (!IS_PLATFORM) return getGrant(undefined, endpoint, scope, opts)
+
+ try {
+ const permissions = await queryClient.fetchQuery(permissionsQueryOptionsV2())
+
+ let permissionsProjectRef = scope.permissionsProjectRef
+ if (permissionsProjectRef === undefined && typeof scope.projectRef === 'string') {
+ const project = await prefetchProjectDetail(queryClient, { ref: scope.projectRef })
+ permissionsProjectRef = project.parent_project_ref ?? scope.projectRef
+ }
+
+ return getGrant(permissions, endpoint, { ...scope, permissionsProjectRef }, opts)
+ } catch (error) {
+ const responseError =
+ error instanceof ResponseError
+ ? error
+ : new ResponseError(error instanceof Error ? error.message : undefined)
+ return { status: 'error', error: responseError }
+ }
+}
diff --git a/knip.jsonc b/knip.jsonc
index 7a79952a7e0..c853906d8a7 100644
--- a/knip.jsonc
+++ b/knip.jsonc
@@ -60,6 +60,8 @@
// the full set, so some of it is unreferenced by design. execute.ts in
// the same directory is hand-written and is NOT listed here.
"data/graphql/{fragment-masking,gql,graphql}.ts": ["files"],
+ // Grant core; first consumers land with the fetch-wrapper and pilot PRs. Remove once imported.
+ "lib/grants.ts": ["files"],
// CONSTRAINT_TYPE mirrors the complete closed set of Postgres
// `pg_constraint.contype` values (c/f/p/u/t/x). The members we don't
// read are documentation of the valid values, not dead code. Scoped to