The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): role inference core for scoped pat (#48805)
kemal.earth2a3025df25c6
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.ts b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.tsnew file mode 100644index 00000000000..5275f6ace06--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.ts@@ -0,0 +1,62 @@+import type { Permission } from '@/types'++/**+ * Test-only fixtures for the scoped-access-token surfaces.+ *+ * The permission-row builders mirror the shape of /platform/profile/permissions rows for each+ * base role, per the ABAC default_permissions seeds (platform: middleware-db). Roles inherit+ * lower roles' rows. Keep the rows in lockstep with ROLE_PROBES in AccessToken.roles.ts.+ */++/** Satisfies both Studio's `Permission` type and the API's `AccessControlPermission` row shape. */+export type PermissionRowFixture = Permission & {+ organization_id: number | null+ project_ids: number[] | null+}++export const permissionRow = (+ organization_slug: string,+ actions: string[],+ resources: string[],+ project_refs: string[] = []+): PermissionRowFixture => ({+ actions: actions as Permission['actions'],+ condition: null as unknown as Permission['condition'],+ organization_id: null,+ organization_slug,+ project_ids: null,+ resources,+ restrictive: false,+ project_refs,+})++export const memberRows = (slug: string, refs: string[] = []) => [+ permissionRow(slug, ['read:Read'], ['members', 'organizations', 'auth.subject_roles'], refs),+]++export const readonlyRows = (slug: string, refs: string[] = []) => [+ ...memberRows(slug, refs),+ permissionRow(slug, ['analytics:Read', 'tenant:Sql:Read:Select'], ['%'], refs),+]++export const developerRows = (slug: string, refs: string[] = []) => [+ ...readonlyRows(slug, refs),+ permissionRow(+ slug,+ ['functions:Write', 'tenant:Sql:Admin:Write', 'tenant:Sql:Query'],+ ['%'],+ refs+ ),+]++export const administratorRows = (slug: string, refs: string[] = []) => [+ ...developerRows(slug, refs),+ permissionRow(slug, ['write:Create', 'write:Update'], ['projects'], refs),+ permissionRow(slug, ['billing:Write', 'infra:Execute'], ['%'], refs),+]++export const ownerRows = (slug: string, refs: string[] = []) => [+ ...administratorRows(slug, refs),+ permissionRow(slug, ['write:Update'], ['organizations'], refs),+ permissionRow(slug, ['write:Create', 'write:Delete'], ['auth.subject_roles'], refs),+]diff --git a/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.tsindex be204f9d45b..3b94a29c952 100644--- a/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts+++ b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts@@ -447,9 +447,13 @@ const RESOURCE_METADATA_FALLBACK = (: 'Read-only access to this resource.',})+export type PermissionLevel = 'user' | 'organization' | 'project'+export interface PermissionCatalogEntry {/** Derived resource key, e.g. "project:database" */key: string+ /** Which FGA namespace the resource lives in — decides which role (org vs project) governs it. */+ level: PermissionLevelcategory: PermissionCategoryKeyname: stringdescription: string@@ -482,15 +486,16 @@ const getResource = (key: string): string =>const buildCatalog = (): PermissionCatalogEntry[] => {const byResource = new Map<string,- { title: string; readScopes: string[]; writeScopes: string[] }+ { level: PermissionLevel; title: string; readScopes: string[]; writeScopes: string[] }>()for (const [scope, scopePerms] of Object.entries(FGA)) {+ const level = scope.toLowerCase() as PermissionLevelfor (const [permKey, perm] of Object.entries(scopePerms)) {- const resourceKey = `${scope.toLowerCase()}:${getResource(permKey)}`+ const resourceKey = `${level}:${getResource(permKey)}`const action = getAction(permKey)if (!byResource.has(resourceKey)) {- byResource.set(resourceKey, { title: perm.title, readScopes: [], writeScopes: [] })+ byResource.set(resourceKey, { level, title: perm.title, readScopes: [], writeScopes: [] })}const entry = byResource.get(resourceKey)!if (action === 'read') entry.readScopes.push(perm.id)@@ -499,11 +504,12 @@ const buildCatalog = (): PermissionCatalogEntry[] => {}const catalog: PermissionCatalogEntry[] = []- for (const [key, { title, readScopes, writeScopes }] of byResource.entries()) {+ for (const [key, { level, title, readScopes, writeScopes }] of byResource.entries()) {const meta =RESOURCE_METADATA[key] ?? RESOURCE_METADATA_FALLBACK(key, title, writeScopes.length > 0)catalog.push({key,+ level,category: meta.category,name: meta.name,description: meta.description,@@ -541,17 +547,25 @@ export const PERMISSION_CATALOG_BY_CATEGORY: CategoryWithEntries[] = PERMISSION_/** Map of resource key -> selected mode. Absent keys are treated as 'none'. */export type PermissionSelection = Record<string, PermissionMode>+/** FGA scope ids a catalog entry grants at the given mode. */+export const getEntryScopes = (+ entry: PermissionCatalogEntry,+ mode: PermissionMode+): ScopedAccessTokenPermission[] => {+ if (mode === 'none') return []+ if (mode === 'readwrite') return [...entry.readScopes, ...entry.writeScopes]+ return entry.readScopes+}+/** Flattens a selection into the concrete FGA scope ids to send to the API. */export const selectionToScopes = (selection: PermissionSelection): ScopedAccessTokenPermission[] => {const scopes: ScopedAccessTokenPermission[] = []for (const [key, mode] of Object.entries(selection)) {- if (mode === 'none') continueconst entry = CATALOG_BY_KEY.get(key)if (!entry) continue- scopes.push(...entry.readScopes)- if (mode === 'readwrite') scopes.push(...entry.writeScopes)+ scopes.push(...getEntryScopes(entry, mode))}return Array.from(new Set(scopes))}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.test.ts b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.test.tsnew file mode 100644index 00000000000..ab3f229e318--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.test.ts@@ -0,0 +1,343 @@+import { permissions } from '@supabase/shared-types'+import { describe, expect, it } from 'vitest'++import {+ administratorRows,+ developerRows,+ memberRows,+ ownerRows,+ readonlyRows,+ permissionRow as row,+} from './AccessToken.fixtures'+import { getCatalogEntry, type PermissionSelection } from './AccessToken.permissions'+import {+ applySelectionToRoleContext,+ computeTokenRoleContext,+ estimateRoleLevel,+ FGA_SCOPE_MINIMUM_ROLE,+ getIsProjectScopedOnly,+ requiredRoleForEntry,+ type TokenRoleContextArgs,+} from './AccessToken.roles'++type EvaluateTokenAccessArgs = TokenRoleContextArgs & { selection: PermissionSelection }++/** Composes the two production entry points the way `useTokenAccessEvaluation` does. */+const evaluateTokenAccess = ({ selection, ...contextArgs }: EvaluateTokenAccessArgs) =>+ applySelectionToRoleContext(computeTokenRoleContext(contextArgs), selection)++const ORG = { slug: 'acme' }+const OTHER_ORG = { slug: 'globex' }+const PROJECT = { ref: 'abcdefghij1234567890', organization_slug: 'acme' }+const OTHER_PROJECT = { ref: 'klmnopqrst1234567890', organization_slug: 'acme' }++const baseArgs: Omit<EvaluateTokenAccessArgs, 'permissions'> = {+ selection: {},+ resourceAccess: 'organization',+ organizationSlugs: [ORG.slug],+ projectRefs: [],+ organizations: [ORG, OTHER_ORG],+ projects: [PROJECT, OTHER_PROJECT],+}++describe('FGA_SCOPE_MINIMUM_ROLE', () => {+ it('covers exactly the scope ids published in @supabase/shared-types', () => {+ const publishedIds = Object.values(permissions.FgaPermissions)+ .flatMap((group) => Object.values(group))+ .map((permission) => permission.id)+ .sort()+ const mappedIds = Object.keys(FGA_SCOPE_MINIMUM_ROLE).sort()+ // If this fails, a scope was added/removed upstream: re-transcribe the role unions from the+ // OpenFGA model (platform: openfga/model/supabase.fga) into FGA_SCOPE_MINIMUM_ROLE.+ expect(mappedIds).toEqual(publishedIds)+ })+})++describe('estimateRoleLevel', () => {+ it('identifies each base role from its permission rows', () => {+ expect(estimateRoleLevel(ownerRows(ORG.slug), ORG.slug)).toBe('owner')+ expect(estimateRoleLevel(administratorRows(ORG.slug), ORG.slug)).toBe('administrator')+ expect(estimateRoleLevel(developerRows(ORG.slug), ORG.slug)).toBe('developer')+ expect(estimateRoleLevel(readonlyRows(ORG.slug), ORG.slug)).toBe('readonly')+ expect(estimateRoleLevel(memberRows(ORG.slug), ORG.slug)).toBe('member')+ expect(estimateRoleLevel([], ORG.slug)).toBe('none')+ })++ it('scopes the estimate to the queried organization', () => {+ const rows = [...ownerRows(ORG.slug), ...readonlyRows(OTHER_ORG.slug)]+ expect(estimateRoleLevel(rows, ORG.slug)).toBe('owner')+ expect(estimateRoleLevel(rows, OTHER_ORG.slug)).toBe('readonly')+ })++ it('resolves project-scoped roles only for their projects', () => {+ const rows = developerRows(ORG.slug, [PROJECT.ref])+ expect(estimateRoleLevel(rows, ORG.slug, PROJECT.ref)).toBe('developer')+ // Org-level (no project) the same user is only a member.+ expect(estimateRoleLevel(rows, ORG.slug)).toBe('member')+ })+})++describe('project-scoped membership helpers', () => {+ it('detects project-scoped-only membership', () => {+ expect(getIsProjectScopedOnly(developerRows(ORG.slug, [PROJECT.ref]), ORG.slug)).toBe(true)+ expect(getIsProjectScopedOnly(developerRows(ORG.slug), ORG.slug)).toBe(false)+ expect(getIsProjectScopedOnly([], ORG.slug)).toBe(false)+ })+})++describe('requiredRoleForEntry', () => {+ it('maps read and readwrite modes to the FGA role unions', () => {+ const database = getCatalogEntry('project:database')!+ expect(requiredRoleForEntry(database, 'read')).toBe('readonly')+ expect(requiredRoleForEntry(database, 'readwrite')).toBe('developer')++ const members = getCatalogEntry('organization:members')!+ expect(requiredRoleForEntry(members, 'read')).toBe('readonly')+ expect(requiredRoleForEntry(members, 'readwrite')).toBe('administrator')++ const orgAdmin = getCatalogEntry('organization:admin')!+ expect(requiredRoleForEntry(orgAdmin, 'readwrite')).toBe('owner')+ })++ it('takes the strictest scope when readwrite spans multiple write scopes', () => {+ // branching_production_write is developer, but create/delete require administrator.+ const branching = getCatalogEntry('project:branching_production')!+ expect(requiredRoleForEntry(branching, 'readwrite')).toBe('administrator')+ })+})++describe('evaluateTokenAccess', () => {+ it('is unknown while permissions are loading', () => {+ const result = evaluateTokenAccess({+ ...baseArgs,+ selection: { 'project:database': 'readwrite' },+ permissions: undefined,+ })+ expect(result.status).toBe('unknown')+ expect(result.exceedingEntryKeys).toEqual([])+ expect(result.entries['project:database'].status).toBe('unknown')+ })++ it('passes everything the user’s role covers', () => {+ const result = evaluateTokenAccess({+ ...baseArgs,+ selection: { 'project:database': 'readwrite', 'organization:members': 'readwrite' },+ permissions: administratorRows(ORG.slug),+ })+ expect(result.status).toBe('evaluated')+ expect(result.exceedingEntryKeys).toEqual([])+ expect(result.effectiveSelection).toEqual({+ 'project:database': 'readwrite',+ 'organization:members': 'readwrite',+ })+ })++ it('flags selections above the user’s role and downgrades the effective mode', () => {+ const result = evaluateTokenAccess({+ ...baseArgs,+ selection: {+ 'project:database': 'readwrite', // requires developer+ 'project:advisors': 'read', // requires readonly+ },+ permissions: readonlyRows(ORG.slug),+ })+ expect(result.exceedingEntryKeys).toEqual(['project:database'])+ expect(result.entries['project:database']).toMatchObject({+ status: 'exceeds-role',+ effectiveMode: 'read',+ requiredRole: 'developer',+ })+ expect(result.effectiveSelection).toEqual({+ 'project:database': 'read',+ 'project:advisors': 'read',+ })+ })++ it('drops entries whose read mode already exceeds the role', () => {+ const result = evaluateTokenAccess({+ ...baseArgs,+ selection: { 'project:api_gateway_keys': 'read' }, // read requires developer+ permissions: readonlyRows(ORG.slug),+ })+ expect(result.entries['project:api_gateway_keys']).toMatchObject({+ status: 'exceeds-role',+ effectiveMode: 'none',+ })+ expect(result.effectiveSelection).toEqual({})+ })++ it('uses the weakest role across multiple bound organizations and names the failing ones', () => {+ const result = evaluateTokenAccess({+ ...baseArgs,+ organizationSlugs: [ORG.slug, OTHER_ORG.slug],+ selection: { 'project:database': 'readwrite' },+ permissions: [...ownerRows(ORG.slug), ...readonlyRows(OTHER_ORG.slug)],+ })+ expect(result.exceedingEntryKeys).toEqual(['project:database'])+ // Only the org where the role is insufficient is called out.+ expect(result.entries['project:database'].failingResources).toEqual([+ {+ type: 'organization',+ id: OTHER_ORG.slug,+ label: OTHER_ORG.slug,+ role: 'readonly',+ projectScopedRoles: undefined,+ },+ ])+ })++ it('evaluates project mode per selected project for project-scoped members', () => {+ const result = evaluateTokenAccess({+ ...baseArgs,+ resourceAccess: 'project',+ projectRefs: [PROJECT.ref],+ selection: { 'project:database': 'readwrite', 'organization:members': 'read' },+ permissions: developerRows(ORG.slug, [PROJECT.ref]),+ })+ // Developer on the bound project: database readwrite is fine.+ expect(result.entries['project:database'].status).toBe('ok')+ // But org-level scopes check the org-wide role, which is only member — and the failure+ // carries their real per-project role so the UI can explain the distinction.+ expect(result.entries['organization:members'].status).toBe('exceeds-role')+ expect(result.entries['organization:members'].failingResources).toEqual([+ {+ type: 'organization',+ id: ORG.slug,+ label: ORG.slug,+ role: 'member',+ projectScopedRoles: [{ label: PROJECT.ref, role: 'developer' }],+ },+ ])+ })++ it('explains org-level failures for members invited only to a project', () => {+ // Read-only on one project, selecting Organization Settings read-write (requires Owner).+ const result = evaluateTokenAccess({+ ...baseArgs,+ resourceAccess: 'project',+ projectRefs: [PROJECT.ref],+ selection: { 'organization:admin': 'readwrite' },+ permissions: readonlyRows(ORG.slug, [PROJECT.ref]),+ organizations: [{ ...ORG, name: 'Acme Corp' }],+ projects: [{ ...PROJECT, name: 'Acme production' }],+ })+ expect(result.entries['organization:admin']).toMatchObject({+ status: 'exceeds-role',+ requiredRole: 'owner',+ failingResources: [+ {+ type: 'organization',+ id: ORG.slug,+ label: 'Acme Corp',+ role: 'member',+ projectScopedRoles: [{ label: 'Acme production', role: 'readonly' }],+ },+ ],+ })+ })++ it('attaches project-scoped detail even when stray org-level rows exist', () => {+ // Real permissions data can include org-level rows (e.g. restrictive rules) alongside a+ // project-scoped role; the per-project detail must still resolve.+ const strayOrgRow = row(ORG.slug, ['read:Read'], ['notifications'])+ const result = evaluateTokenAccess({+ ...baseArgs,+ resourceAccess: 'project',+ projectRefs: [PROJECT.ref],+ selection: { 'organization:admin': 'readwrite' },+ permissions: [...readonlyRows(ORG.slug, [PROJECT.ref]), strayOrgRow],+ projects: [{ ...PROJECT, name: 'Acme production' }],+ })+ expect(result.entries['organization:admin'].failingResources).toEqual([+ {+ type: 'organization',+ id: ORG.slug,+ label: ORG.slug,+ role: 'member',+ projectScopedRoles: [{ label: 'Acme production', role: 'readonly' }],+ },+ ])+ })++ it('does not attach project-scoped detail for organization-wide members', () => {+ const result = evaluateTokenAccess({+ ...baseArgs,+ selection: { 'organization:admin': 'readwrite' },+ permissions: developerRows(ORG.slug),+ })+ expect(result.entries['organization:admin'].failingResources).toEqual([+ {+ type: 'organization',+ id: ORG.slug,+ label: ORG.slug,+ role: 'developer',+ projectScopedRoles: undefined,+ },+ ])+ })++ it('labels failing resources with their display names when provided', () => {+ const result = evaluateTokenAccess({+ ...baseArgs,+ resourceAccess: 'project',+ projectRefs: [PROJECT.ref],+ selection: { 'project:database': 'readwrite' },+ permissions: readonlyRows(ORG.slug),+ projects: [{ ...PROJECT, name: 'Acme production' }],+ })+ expect(result.entries['project:database'].failingResources).toEqual([+ { type: 'project', id: PROJECT.ref, label: 'Acme production', role: 'readonly' },+ ])+ })++ it('reports bound resources the user can no longer access', () => {+ const result = evaluateTokenAccess({+ ...baseArgs,+ organizationSlugs: ['departed-org'],+ selection: { 'project:database': 'read' },+ permissions: readonlyRows(ORG.slug),+ organizations: [ORG],+ })+ expect(result.inaccessibleOrgSlugs).toEqual(['departed-org'])+ expect(result.hasNoAccessibleResource).toBe(true)+ expect(result.entries['project:database'].status).toBe('unknown')+ })++ it('reports partially inaccessible projects while still evaluating the rest', () => {+ const result = evaluateTokenAccess({+ ...baseArgs,+ resourceAccess: 'project',+ projectRefs: [PROJECT.ref, 'gone-project-ref-123'],+ selection: { 'project:database': 'read' },+ permissions: readonlyRows(ORG.slug),+ })+ expect(result.inaccessibleProjectRefs).toEqual(['gone-project-ref-123'])+ expect(result.hasNoAccessibleResource).toBe(false)+ expect(result.entries['project:database'].status).toBe('ok')+ })++ it('is unknown before any resource is selected', () => {+ const result = evaluateTokenAccess({+ ...baseArgs,+ resourceAccess: 'project',+ organizationSlugs: [ORG.slug],+ projectRefs: [],+ selection: { 'project:database': 'readwrite' },+ permissions: readonlyRows(ORG.slug),+ })+ expect(result.status).toBe('unknown')+ expect(result.exceedingEntryKeys).toEqual([])+ })++ it('never flags account-scoped tokens', () => {+ const result = evaluateTokenAccess({+ ...baseArgs,+ resourceAccess: 'account',+ organizationSlugs: [],+ selection: { 'project:database': 'readwrite' },+ permissions: memberRows(ORG.slug),+ })+ expect(result.exceedingEntryKeys).toEqual([])+ expect(result.entries['project:database'].status).toBe('ok')+ })+})diff --git a/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.ts b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.tsnew file mode 100644index 00000000000..c4039ee8bb4--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.ts@@ -0,0 +1,584 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'++import type {+ PermissionCatalogEntry,+ PermissionMode,+ PermissionSelection,+ ResourceAccessMode,+} from './AccessToken.permissions'+import { getCatalogEntry, getEntryScopes } from './AccessToken.permissions'+import { doPermissionsCheck } from '@/hooks/misc/useCheckPermissions'+import type { Permission } from '@/types'++/**+ * Client-side estimation of what a scoped token can actually do, given its owner's current role.+ *+ * Scoped tokens are enforced server-side as the intersection of the token's granted scopes and+ * the owner's live role, re-checked on every request. Nothing here gates anything — these helpers+ * only power advisory UI (warnings in the creation flow, status badges in the token view) so users+ * aren't surprised when an over-provisioned scope returns 403.+ *+ * The minimum-role table below is transcribed from the OpenFGA authorization model+ * (platform: openfga/model/supabase.fga), where every permission is a union of base roles.+ * AccessToken.roles.test.ts asserts the table stays in sync with the scope ids in+ * `@supabase/shared-types` FgaPermissions.+ */++/** Base-role ladder. `member` covers org membership without a base role (e.g. project-scoped users at org level). */+export const TOKEN_ROLE_LEVELS = [+ 'none',+ 'member',+ 'readonly',+ 'developer',+ 'administrator',+ 'owner',+] as const++export type TokenRoleLevel = (typeof TOKEN_ROLE_LEVELS)[number]++const ROLE_RANK = Object.fromEntries(+ TOKEN_ROLE_LEVELS.map((role, index) => [role, index])+) as Record<TokenRoleLevel, number>++export const TOKEN_ROLE_LABEL: Record<TokenRoleLevel, string> = {+ none: 'No role',+ member: 'Member',+ readonly: 'Read-only',+ developer: 'Developer',+ administrator: 'Administrator',+ owner: 'Owner',+}++const rankOf = (role: TokenRoleLevel) => ROLE_RANK[role]++const minRole = (a: TokenRoleLevel, b: TokenRoleLevel): TokenRoleLevel =>+ rankOf(a) <= rankOf(b) ? a : b++const maxRole = (a: TokenRoleLevel, b: TokenRoleLevel): TokenRoleLevel =>+ rankOf(a) >= rankOf(b) ? a : b++/**+ * Lowest base role that holds each FGA permission scope, transcribed from the role unions in the+ * OpenFGA model. Keep in the same order as the model for easy diffing.+ *+ * The drift-guard test only pins the *key set* (scope ids). The role values have no automated+ * guard: if a role union changes in the OpenFGA model (e.g. a `_write` scope moves from developer+ * to administrator), CI stays green and this advisory UI silently gives stale guidance until the+ * value is re-transcribed here. Reviewers of FGA model changes must update this table in the same+ * change.+ */+export const FGA_SCOPE_MINIMUM_ROLE: Record<string, TokenRoleLevel> = {+ // user — available to any authenticated account, no org role required+ organizations_read: 'member',+ organizations_create: 'member',+ projects_read: 'member',+ snippets_read: 'member',++ // organization+ organization_admin_read: 'member',+ organization_admin_write: 'owner',+ organization_projects_read: 'member',+ organization_projects_create: 'administrator',+ members_read: 'readonly',+ members_write: 'administrator',+ platform_webhooks_organization_read: 'member',+ platform_webhooks_organization_write: 'administrator',++ // project+ project_admin_read: 'member',+ project_admin_write: 'administrator',+ action_runs_read: 'readonly',+ action_runs_write: 'developer',+ advisors_read: 'readonly',+ analytics_config_read: 'developer',+ analytics_config_write: 'administrator',+ analytics_logs_read: 'readonly',+ analytics_usage_read: 'readonly',+ api_gateway_keys_read: 'developer',+ api_gateway_keys_write: 'administrator',+ auth_config_read: 'readonly',+ auth_config_write: 'developer',+ auth_signing_keys_read: 'developer',+ auth_signing_keys_write: 'developer',+ backups_read: 'readonly',+ backups_write: 'developer',+ branching_development_create: 'developer',+ branching_development_delete: 'developer',+ branching_development_read: 'readonly',+ branching_development_write: 'developer',+ branching_production_create: 'administrator',+ branching_production_delete: 'administrator',+ branching_production_read: 'readonly',+ branching_production_write: 'developer',+ custom_domain_read: 'readonly',+ custom_domain_write: 'administrator',+ data_api_config_read: 'readonly',+ data_api_config_write: 'administrator',+ database_read: 'readonly',+ database_write: 'developer',+ database_config_read: 'readonly',+ database_config_write: 'administrator',+ database_jit_read: 'readonly',+ database_jit_write: 'administrator',+ database_network_bans_read: 'readonly',+ database_network_bans_write: 'administrator',+ database_network_restrictions_read: 'readonly',+ database_network_restrictions_write: 'administrator',+ database_migrations_read: 'readonly',+ database_migrations_write: 'developer',+ database_pooling_config_read: 'readonly',+ database_pooling_config_write: 'administrator',+ database_readonly_config_read: 'readonly',+ database_readonly_config_write: 'administrator',+ database_ssl_config_read: 'readonly',+ database_ssl_config_write: 'administrator',+ database_webhooks_config_read: 'readonly',+ database_webhooks_config_write: 'developer',+ edge_functions_read: 'readonly',+ edge_functions_write: 'developer',+ edge_functions_secrets_read: 'readonly',+ edge_functions_secrets_write: 'administrator',+ infra_add_ons_read: 'readonly',+ infra_add_ons_write: 'administrator',+ infra_disk_config_read: 'readonly',+ infra_disk_config_write: 'administrator',+ infra_read_replicas_read: 'readonly',+ infra_read_replicas_write: 'administrator',+ project_snippets_read: 'readonly',+ project_snippets_write: 'readonly',+ realtime_config_read: 'readonly',+ realtime_config_write: 'administrator',+ storage_read: 'readonly',+ storage_write: 'developer',+ storage_config_read: 'readonly',+ storage_config_write: 'administrator',+ vanity_subdomain_read: 'administrator',+ vanity_subdomain_write: 'administrator',+ platform_webhooks_projects_read: 'member',+ platform_webhooks_projects_write: 'administrator',+}++/**+ * ABAC checks that identify the user's base role from their own permission rows (the ungated+ * /platform/profile/permissions response). Base roles inherit each other's rows+ * (Owner ⊃ Administrator ⊃ Developer ⊃ Read-only), so the first probe that passes, walking+ * top-down, is the user's level. Each probe is a permission only that role and above holds.+ */+const ROLE_PROBES: { role: TokenRoleLevel; action: string; resource: string }[] = [+ { role: 'owner', action: PermissionAction.UPDATE, resource: 'organizations' },+ { role: 'administrator', action: PermissionAction.CREATE, resource: 'projects' },+ { role: 'developer', action: PermissionAction.FUNCTIONS_WRITE, resource: 'functions' },+ { role: 'readonly', action: PermissionAction.TENANT_SQL_SELECT, resource: 'sql' },+]++/**+ * Estimates the user's base role in an organization (or on a specific project, when the user's+ * access is project-scoped). Custom roles resolve to the nearest base role by capability, which+ * matches how they behave in the FGA model.+ */+export const estimateRoleLevel = (+ permissions: Permission[],+ organizationSlug: string,+ projectRef?: string+): TokenRoleLevel => {+ for (const probe of ROLE_PROBES) {+ if (+ doPermissionsCheck(+ permissions,+ probe.action,+ probe.resource,+ undefined,+ organizationSlug,+ projectRef+ )+ ) {+ return probe.role+ }+ }+ const isMember = permissions.some(+ (permission) => permission.organization_slug === organizationSlug+ )+ return isMember ? 'member' : 'none'+}++/** True when every permission row the user holds in the org is limited to specific projects. */+export const getIsProjectScopedOnly = (+ permissions: Permission[],+ organizationSlug: string+): boolean => {+ const orgRows = permissions.filter(+ (permission) => permission.organization_slug === organizationSlug+ )+ if (orgRows.length === 0) return false+ return orgRows.every(+ (permission) => permission.project_refs !== undefined && permission.project_refs.length > 0+ )+}++/** Lowest role that holds every scope in the list. Unknown scope ids assume `owner` (warn rather than promise). */+const requiredRoleForScopes = (scopeIds: string[]): TokenRoleLevel => {+ let required: TokenRoleLevel = 'member'+ for (const id of scopeIds) {+ required = maxRole(required, FGA_SCOPE_MINIMUM_ROLE[id] ?? 'owner')+ }+ return required+}++/** Lowest role that can exercise a catalog entry at the given mode. */+export const requiredRoleForEntry = (+ entry: PermissionCatalogEntry,+ mode: PermissionMode+): TokenRoleLevel =>+ mode === 'none' ? 'member' : requiredRoleForScopes(getEntryScopes(entry, mode))++export type EntryAccessStatus = 'ok' | 'exceeds-role' | 'unknown'++/** A token-bound resource where the user's current role can't exercise the selected mode. */+export interface FailingResource {+ type: 'organization' | 'project'+ /** Org slug or project ref — unique, unlike `label`. Use for React keys and grouping. */+ id: string+ /** Display name of the org/project, falling back to its slug/ref. */+ label: string+ /** The user's current role on that resource. */+ role: TokenRoleLevel+ /**+ * Set when the user has no organization-level role here but does hold roles on specific+ * projects (they were invited to projects, not the org). Lets the UI say "your role is+ * Read-only on the project X" instead of an opaque org-level pseudo-role.+ */+ projectScopedRoles?: { label: string; role: TokenRoleLevel }[]+}++export interface EntryAccess {+ status: EntryAccessStatus+ /** Highest mode the user's current role can exercise for this entry. */+ effectiveMode: PermissionMode+ /** Lowest role that could exercise the selected mode. */+ requiredRole: TokenRoleLevel+ /** Resources where the selected mode would be denied (empty unless status is 'exceeds-role'). */+ failingResources: FailingResource[]+}++export interface TokenAccessEvaluation {+ /** 'unknown' while the user's permissions are loading (or on self-hosted) — show no warnings. */+ status: 'unknown' | 'evaluated'+ /** Token-bound orgs the user can no longer access. */+ inaccessibleOrgSlugs: string[]+ /** Token-bound projects the user can no longer access. */+ inaccessibleProjectRefs: string[]+ /** True when a resource-scoped token has no bindings left — everything it was bound to was deleted. */+ hasNoBoundResources: boolean+ /** True when the token is bound to resources but the user can access none of them. */+ hasNoAccessibleResource: boolean+ /** Per selected catalog entry key. */+ entries: Record<string, EntryAccess>+ /** Entry keys whose selected mode exceeds the user's current role. */+ exceedingEntryKeys: string[]+ /** Selection reduced to what the user's current role can exercise. */+ effectiveSelection: PermissionSelection+}++export interface TokenRoleContextArgs {+ resourceAccess: ResourceAccessMode+ /** Token-bound org slugs (organization mode), or the parent org (project mode, from the form). */+ organizationSlugs: string[]+ /** Token-bound project refs (project mode). */+ projectRefs: string[]+ /** The user's own ABAC permission rows; undefined while loading. */+ permissions: Permission[] | undefined+ /** Organizations the user can currently access. */+ organizations: { slug: string; name?: string }[]+ /** Projects the user can currently access. */+ projects: { ref: string; organization_slug: string; name?: string }[]+}++/**+ * Selection-independent role resolution for a token's bound resources. Resolving roles walks the+ * user's full permission list several times, so callers should memoize this on its inputs and+ * apply (cheap) selection changes via `applySelectionToRoleContext`.+ */+export interface TokenRoleContext {+ status: 'unknown' | 'evaluated'+ resourceAccess: ResourceAccessMode+ inaccessibleOrgSlugs: string[]+ inaccessibleProjectRefs: string[]+ hasNoBoundResources: boolean+ hasNoAccessibleResource: boolean+ /** Per bound organization (or parent org in project mode). */+ orgLevels: FailingResource[]+ /** Per bound project in project mode; mirrors orgLevels otherwise (org roles cascade). */+ projectLevels: FailingResource[]+ /** Weakest role across orgLevels / projectLevels. */+ orgLevel: TokenRoleLevel+ projectLevel: TokenRoleLevel+}++const UNKNOWN_ENTRY: EntryAccess = {+ status: 'unknown',+ effectiveMode: 'none',+ requiredRole: 'member',+ failingResources: [],+}++const minOver = (levels: FailingResource[]): TokenRoleLevel =>+ levels.length === 0+ ? 'none'+ : levels.reduce<TokenRoleLevel>((lowest, level) => minRole(lowest, level.role), 'owner')++export const computeTokenRoleContext = ({+ resourceAccess,+ organizationSlugs,+ projectRefs,+ permissions,+ organizations,+ projects,+}: TokenRoleContextArgs): TokenRoleContext => {+ const boundResourceIds =+ resourceAccess === 'project'+ ? projectRefs+ : resourceAccess === 'organization'+ ? organizationSlugs+ : []+ const hasNoBoundResources = resourceAccess !== 'account' && boundResourceIds.length === 0++ const unknownContext = (status: TokenRoleContext['status']): TokenRoleContext => ({+ status,+ resourceAccess,+ inaccessibleOrgSlugs: [],+ inaccessibleProjectRefs: [],+ hasNoBoundResources,+ hasNoAccessibleResource: false,+ orgLevels: [],+ projectLevels: [],+ orgLevel: 'none',+ projectLevel: 'none',+ })++ // Nothing to evaluate while permissions load, or until resources are chosen (mid-form state).+ if (permissions === undefined || hasNoBoundResources) return unknownContext('unknown')+ if (resourceAccess === 'account') return unknownContext('evaluated')++ const knownOrgSlugs = new Set(organizations.map((org) => org.slug))+ const projectsByRef = new Map(projects.map((project) => [project.ref, project]))++ const inaccessibleOrgSlugs = organizationSlugs.filter((slug) => !knownOrgSlugs.has(slug))+ // Only meaningful in project mode — the form can carry stale projectRefs after a mode switch.+ const inaccessibleProjectRefs =+ resourceAccess === 'project' ? projectRefs.filter((ref) => !projectsByRef.has(ref)) : []++ const accessibleOrgSlugs = organizationSlugs.filter((slug) => knownOrgSlugs.has(slug))+ const accessibleProjects = projectRefs.flatMap((ref) => projectsByRef.get(ref) ?? [])++ const hasNoAccessibleResource =+ resourceAccess === 'project' ? accessibleProjects.length === 0 : accessibleOrgSlugs.length === 0++ if (hasNoAccessibleResource) {+ return {+ ...unknownContext('evaluated'),+ inaccessibleOrgSlugs,+ inaccessibleProjectRefs,+ hasNoAccessibleResource,+ }+ }++ // Role probes walk every permission row; the same org/project pair is asked for repeatedly+ // (project levels + project-scoped detail), so resolve each pair once.+ const roleCache = new Map<string, TokenRoleLevel>()+ const roleFor = (slug: string, ref?: string): TokenRoleLevel => {+ const cacheKey = `${slug}|${ref ?? ''}`+ const cached = roleCache.get(cacheKey)+ if (cached !== undefined) return cached+ const role = estimateRoleLevel(permissions, slug, ref)+ roleCache.set(cacheKey, role)+ return role+ }++ const organizationsBySlug = new Map(organizations.map((org) => [org.slug, org]))++ // The form passes the parent org even in project mode; the token view may not, so fall back to+ // the bound projects' parent orgs when no org slug was provided.+ const orgSlugsForLevels =+ accessibleOrgSlugs.length > 0+ ? accessibleOrgSlugs+ : Array.from(new Set(accessibleProjects.map((project) => project.organization_slug)))++ // For members without an organization-level role, resolve their per-project roles so org-level+ // failures can explain the distinction (invited to projects, not the org). In project mode only+ // the token-bound projects are relevant; in organization mode (e.g. a token that predates a+ // role change) look at every project they can access in the org.+ const getProjectScopedRoles = (+ slug: string,+ orgRole: TokenRoleLevel+ ): FailingResource['projectScopedRoles'] => {+ if (rankOf(orgRole) >= ROLE_RANK.readonly) return undefined+ const candidates =+ resourceAccess === 'project'+ ? accessibleProjects.filter((project) => project.organization_slug === slug)+ : projects.filter((project) => project.organization_slug === slug)+ const roles = candidates.flatMap((project) => {+ const role = roleFor(slug, project.ref)+ if (rankOf(role) < ROLE_RANK.readonly) return []+ return [{ label: project.name ?? project.ref, role }]+ })+ return roles.length > 0 ? roles : undefined+ }++ const orgLevels: FailingResource[] = orgSlugsForLevels.map((slug) => {+ const role = roleFor(slug)+ return {+ type: 'organization',+ id: slug,+ label: organizationsBySlug.get(slug)?.name ?? slug,+ role,+ projectScopedRoles: getProjectScopedRoles(slug, role),+ }+ })++ const projectLevels: FailingResource[] =+ resourceAccess === 'project'+ ? accessibleProjects.map((project) => ({+ type: 'project' as const,+ id: project.ref,+ label: project.name ?? project.ref,+ role: roleFor(project.organization_slug, project.ref),+ }))+ : orgLevels++ return {+ status: 'evaluated',+ resourceAccess,+ inaccessibleOrgSlugs,+ inaccessibleProjectRefs,+ hasNoBoundResources,+ hasNoAccessibleResource,+ orgLevels,+ projectLevels,+ orgLevel: minOver(orgLevels),+ projectLevel: minOver(projectLevels),+ }+}++/**+ * Applies a scope selection to a resolved role context. Cheap — safe to re-run on every+ * permission toggle. Account-scoped (legacy/user) tokens track the owner's access by definition,+ * so every entry evaluates as 'ok' there.+ */+export const applySelectionToRoleContext = (+ context: TokenRoleContext,+ selection: PermissionSelection+): TokenAccessEvaluation => {+ const base = {+ status: context.status,+ inaccessibleOrgSlugs: context.inaccessibleOrgSlugs,+ inaccessibleProjectRefs: context.inaccessibleProjectRefs,+ hasNoBoundResources: context.hasNoBoundResources,+ hasNoAccessibleResource: context.hasNoAccessibleResource,+ exceedingEntryKeys: [] as string[],+ effectiveSelection: selection,+ }++ const selectedKeys = Object.keys(selection).filter((key) => selection[key] !== 'none')++ // Account-scoped (legacy/user) tokens track the owner's access by definition — every entry is+ // exercisable, so requiredRole/failingResources (only read for 'exceeds-role' entries) stay inert.+ if (context.status === 'evaluated' && context.resourceAccess === 'account') {+ return {+ ...base,+ entries: Object.fromEntries(+ selectedKeys.map((key): [string, EntryAccess] => [+ key,+ {+ status: 'ok',+ effectiveMode: selection[key],+ requiredRole: 'member',+ failingResources: [],+ },+ ])+ ),+ }+ }++ if (context.status === 'unknown' || context.hasNoAccessibleResource) {+ return {+ ...base,+ entries: Object.fromEntries(selectedKeys.map((key) => [key, UNKNOWN_ENTRY])),+ }+ }++ const { orgLevel, projectLevel, orgLevels, projectLevels } = context+ const entries: Record<string, EntryAccess> = {}+ const exceedingEntryKeys: string[] = []+ const effectiveSelection: PermissionSelection = {}++ for (const key of selectedKeys) {+ const mode = selection[key]+ const entry = getCatalogEntry(key)+ if (!entry) continue++ const availableLevel =+ entry.level === 'user' ? 'owner' : entry.level === 'organization' ? orgLevel : projectLevel++ const requiredRole = requiredRoleForEntry(entry, mode)++ let effectiveMode: PermissionMode = 'none'+ if (rankOf(availableLevel) >= rankOf(requiredRole)) {+ effectiveMode = mode+ } else if (+ mode === 'readwrite' &&+ rankOf(availableLevel) >= rankOf(requiredRoleForEntry(entry, 'read'))+ ) {+ effectiveMode = 'read'+ }++ const status: EntryAccessStatus = effectiveMode === mode ? 'ok' : 'exceeds-role'+ const relevantLevels =+ entry.level === 'user' ? [] : entry.level === 'organization' ? orgLevels : projectLevels+ const failingResources =+ status === 'exceeds-role'+ ? relevantLevels.filter((level) => rankOf(level.role) < rankOf(requiredRole))+ : []++ entries[key] = { status, effectiveMode, requiredRole, failingResources }+ if (status === 'exceeds-role') exceedingEntryKeys.push(key)+ if (effectiveMode !== 'none') effectiveSelection[key] = effectiveMode+ }++ return { ...base, entries, exceedingEntryKeys, effectiveSelection }+}++export interface FailingResourceGroup {+ type: 'organization' | 'project'+ resource: FailingResource+ entries: { key: string; name: string; mode: PermissionMode; requiredRole: TokenRoleLevel }[]+}++/**+ * Inverts the evaluation's entry → failingResources mapping into resource → failing entries+ * (organizations first, then alphabetical) for per-resource breakdowns.+ */+export const groupFailingResources = (+ evaluation: TokenAccessEvaluation,+ selection: PermissionSelection+): FailingResourceGroup[] => {+ const groups = new Map<string, FailingResourceGroup>()+ for (const key of evaluation.exceedingEntryKeys) {+ const entryAccess = evaluation.entries[key]+ const entry = getCatalogEntry(key)+ const mode = selection[key]+ if (entryAccess === undefined || entry === undefined || mode === undefined) continue+ for (const resource of entryAccess.failingResources) {+ const groupKey = `${resource.type}:${resource.id}`+ let group = groups.get(groupKey)+ if (group === undefined) {+ group = { type: resource.type, resource, entries: [] }+ groups.set(groupKey, group)+ }+ group.entries.push({ key, name: entry.name, mode, requiredRole: entryAccess.requiredRole })+ }+ }+ return Array.from(groups.values()).sort((a, b) => {+ if (a.type === b.type) return a.resource.label.localeCompare(b.resource.label)+ return a.type === 'organization' ? -1 : 1+ })+}