Skip to content

feat(studio): role inference core for scoped pat - #48805

Merged
kemaldotearth merged 1 commit into
masterfrom
scopedpat/roles-core
Aug 6, 2026
Merged

kemaldotearth merged 1 commit into
masterfrom
scopedpat/roles-core

Conversation

@kemaldotearth

@kemaldotearth kemaldotearth commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

I have read the CONTRIBUTING.md file.

YES

What kind of change does this PR introduce?

Logic-only extraction from #48742. Scoped PATs are enforced server-side as the intersection of the token's granted scopes and the owner's live role, re-checked on every request. This lands the pure inference layer that will power advisory (never blocking) UI feedback; no UI consumes it yet.

  • FGA_SCOPE_MINIMUM_ROLE: all 83 permission scopes transcribed from the OpenFGA model's role unions, mapped to the lowest base role that holds them. A drift-guard test pins the key set to the scope ids published in @supabase/shared-types, so upstream additions fail CI here with re-transcription instructions.
  • estimateRoleLevel: derives the user's base role per org (or per project for project-invited members) from the ungated /platform/profile/ permissions rows via four discriminating ABAC probes. Works for every member type with no permission-gated endpoint.
  • computeTokenRoleContext + applySelectionToRoleContext: role resolution (expensive, memoized) is split from selection evaluation (cheap, re-run per permission toggle).

AccessToken.permissions.ts gains only what the roles module needs: the PermissionLevel type and the catalog's level field (decides whether an org or project role governs a resource), plus getEntryScopes, which selectionToScopes now reuses. The UI-only additions from #48742 (risk badge/dot variants, mode labels, the OverallRisk.text -> description rename) are deliberately left out so this PR touches no .tsx.

Summary by CodeRabbit

  • New Features

    • Added role-aware evaluation for scoped access-token permissions.
    • Added support for organization- and project-level permission scoping.
    • Added guidance when selected permissions exceed the current role, including read-only downgrades and inaccessible resources.
    • Added clearer grouping of permission access issues by resource.
  • Tests

    • Added comprehensive coverage for role mapping, permission evaluation, scoping, and failure scenarios.

Logic-only extraction from #48742. Scoped PATs are enforced server-side as
the intersection of the token's granted scopes and the owner's live role,
re-checked on every request. This lands the pure inference layer that will
power advisory (never blocking) UI feedback; no UI consumes it yet.

- FGA_SCOPE_MINIMUM_ROLE: all 83 permission scopes transcribed from the
  OpenFGA model's role unions, mapped to the lowest base role that holds
  them. A drift-guard test pins the key set to the scope ids published in
  @supabase/shared-types, so upstream additions fail CI here with
  re-transcription instructions.
- estimateRoleLevel: derives the user's base role per org (or per project
  for project-invited members) from the ungated /platform/profile/
  permissions rows via four discriminating ABAC probes. Works for every
  member type with no permission-gated endpoint.
- computeTokenRoleContext + applySelectionToRoleContext: role resolution
  (expensive, memoized) is split from selection evaluation (cheap, re-run
  per permission toggle).

AccessToken.permissions.ts gains only what the roles module needs: the
PermissionLevel type and the catalog's `level` field (decides whether an
org or project role governs a resource), plus getEntryScopes, which
selectionToScopes now reuses. The UI-only additions from #48742 (risk
badge/dot variants, mode labels, the OverallRisk.text -> description
rename) are deliberately left out so this PR touches no .tsx.

Co-Authored-By: Wen Bo Xie <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@kemaldotearth
kemaldotearth requested a review from a team as a code owner August 6, 2026 15:14
@vercel

vercel Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
studio-self-hosted Ready Ready Preview Aug 6, 2026 3:18pm
studio-staging Ready Ready Preview Aug 6, 2026 3:18pm
5 Skipped Deployments
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Aug 6, 2026 3:18pm
design-system Skipped Skipped Aug 6, 2026 3:18pm
docs Skipped Skipped v0 Aug 6, 2026 3:18pm
ui-library Skipped Skipped Aug 6, 2026 3:18pm
zone-www-dot-com Skipped Skipped v0 Aug 6, 2026 3:18pm

Request Review

@supabase

supabase Bot commented Aug 6, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project xguihxuzqibwxjnimxev because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds client-side scoped-token role evaluation for organization and project resources. It extends permission catalog entries with level metadata, adds role-based permission fixtures, computes token role context and effective selections, groups failing resources, and adds comprehensive tests for role, scope, and access cases.

Changes

Access token role evaluation

Layer / File(s) Summary
Permission metadata and role fixtures
apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts, apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.ts, apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.ts, apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.test.ts
PermissionCatalogEntry now includes level, and catalog construction preserves that value. getEntryScopes centralizes mode-to-scope expansion. New fixtures build hierarchical permission rows for token owner roles. The new roles module exports role labels, scope minimum-role data, and evaluation data contracts.
Role inference and resource context
apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.ts, apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.test.ts
The roles module now infers base role levels from permission rows, detects project-only scope, resolves required role per catalog entry, and computes token role context across accessible and inaccessible organizations and projects. Tests cover role mapping, weakest-role resolution, and project-scoped cases.
Selection evaluation and failure grouping
apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.ts, apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.test.ts
applySelectionToRoleContext now evaluates selected modes against resolved roles, keeps unknown and account-scoped cases, downgrades unsupported readwrite selections to read, and returns failing resources. groupFailingResources reorganizes failures by resource and sorts organizations before projects. Tests cover loading, excessive selections, removed entries, inaccessible resources, and no-resource handling.

Estimated code review effort: 4 (Complex) | ~45 minutes

Suggested reviewers: alaister

Sequence Diagram(s)

sequenceDiagram
  participant Selection as Selected permissions
  participant Context as computeTokenRoleContext
  participant Evaluator as applySelectionToRoleContext
  participant Grouper as groupFailingResources

  Selection->>Context: resource bindings and permission rows
  Context-->>Evaluator: TokenRoleContext
  Selection->>Evaluator: selected catalog modes
  Evaluator->>Grouper: failing resources
  Grouper-->>Evaluator: grouped failures
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the role inference core added for scoped personal access tokens.
Description check ✅ Passed The description is detailed, on topic, and explains the change, behavior, scope, and implementation context.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch scopedpat/roles-core

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (4)
apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.ts (1)

22-31: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Replace the as casts with typed literals.

The repository guideline asks you to avoid TypeScript as casts. Both casts here are avoidable. Type the parameters as the exact Permission field types, and set condition to the value the row shape allows.

♻️ Proposed refactor
 export const permissionRow = (
   organization_slug: string,
-  actions: string[],
+  actions: Permission['actions'],
   resources: string[],
   project_refs: string[] = []
 ): PermissionRowFixture => ({
-  actions: actions as Permission['actions'],
-  condition: null as unknown as Permission['condition'],
+  actions,
+  condition: null,
   organization_id: null,

If Permission['condition'] does not accept null, widen PermissionRowFixture with condition: Permission['condition'] | null instead of casting.

As per coding guidelines: "Avoid TypeScript as casts; parse external data with zod using parse or safeParse."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.ts`
around lines 22 - 31, Remove the `as` casts in the `PermissionRowFixture`
factory by typing its `actions` and `condition` parameters with the
corresponding `Permission` field types. Set `condition` directly to the
row-supported value; if `Permission['condition']` excludes null, update
`PermissionRowFixture` to allow `Permission['condition'] | null` instead of
using a cast.

Source: Coding guidelines

apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.ts (1)

519-520: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Make the user level short-circuit explicit.

entry.level === 'user' maps to 'owner', the top of the ladder, so the comparison at Line 525 always passes. The intent is "no organization role is required", but the code states the opposite of that intent. A reader can conclude that user-level scopes need the owner role.

♻️ Proposed refactor
-    const availableLevel =
-      entry.level === 'user' ? 'owner' : entry.level === 'organization' ? orgLevel : projectLevel
+    // User-level scopes need no org/project role, so treat them as always satisfied by using the
+    // top of the role ladder as the available level.
+    const availableLevel: TokenRoleLevel =
+      entry.level === 'user'
+        ? TOKEN_ROLE_LEVELS[TOKEN_ROLE_LEVELS.length - 1]
+        : entry.level === 'organization'
+          ? orgLevel
+          : projectLevel
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.ts`
around lines 519 - 520, Update the available-level logic around entry.level so
the user-level case explicitly short-circuits organization-role checks instead
of assigning the misleading owner level. Preserve orgLevel and projectLevel
behavior for organization and project entries, and ensure user-level scopes
require no organization role.
apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts (1)

492-498: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Validate the FGA namespace instead of casting it to PermissionLevel.

scope.toLowerCase() as PermissionLevel accepts any key that FGA exposes. If @supabase/shared-types adds a fourth namespace, every resource in it receives an invalid level. applySelectionToRoleContext in AccessToken.roles.ts (Line 520) then treats that level as project, so those entries are gated by the project role instead of the correct role. The scope-id drift test in AccessToken.roles.test.ts does not cover namespace keys, so CI stays green.

Narrow the value explicitly and fail loudly on an unknown namespace.

♻️ Proposed refactor
+const PERMISSION_LEVELS = ['user', 'organization', 'project'] as const
+
+const toPermissionLevel = (scope: string): PermissionLevel => {
+  const level = scope.toLowerCase()
+  const match = PERMISSION_LEVELS.find((candidate) => candidate === level)
+  if (match === undefined) throw new Error(`Unknown FGA namespace: ${scope}`)
+  return match
+}
+
 const buildCatalog = (): PermissionCatalogEntry[] => {
   const byResource = new Map<
     string,
     { level: PermissionLevel; title: string; readScopes: string[]; writeScopes: string[] }
   >()
 
   for (const [scope, scopePerms] of Object.entries(FGA)) {
-    const level = scope.toLowerCase() as PermissionLevel
+    const level = toPermissionLevel(scope)

As per coding guidelines: "Avoid TypeScript as casts; parse external data with zod using parse or safeParse."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts`
around lines 492 - 498, The FGA namespace conversion in the loop over FGA
currently accepts unknown keys through an unsafe PermissionLevel cast. Validate
scope.toLowerCase() against the supported PermissionLevel values using the
project’s established zod parsing approach, and fail loudly for an unknown
namespace before creating resource entries; preserve the existing handling for
valid namespaces.

Source: Coding guidelines

apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.test.ts (1)

109-343: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for groupFailingResources.

The suite covers computeTokenRoleContext and applySelectionToRoleContext well. groupFailingResources is exported from AccessToken.roles.ts and has no test. Its inversion logic, its skip branch for missing entries (Line 569 there), and its organizations-first sort order are untestable through the current cases.

Add a case that evaluates a selection failing on two resources, then asserts the group order and the per-group entries payload.

I can draft that test case. Do you want me to open a follow-up issue as well?

As per coding guidelines: "Include relevant tests by default; use Vitest and MSW".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.test.ts`
around lines 109 - 343, Add a targeted Vitest case around groupFailingResources
in AccessToken.roles.test.ts, using evaluateTokenAccess to produce failures on
two resources and then asserting the grouped output order and each group’s
entries payload. Cover the missing-entry skip branch and the organizations-first
sort behavior by checking the result from groupFailingResources directly (or via
the exported helper path), while keeping the existing computeTokenRoleContext
and applySelectionToRoleContext coverage unchanged.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.ts`:
- Around line 22-31: Remove the `as` casts in the `PermissionRowFixture` factory
by typing its `actions` and `condition` parameters with the corresponding
`Permission` field types. Set `condition` directly to the row-supported value;
if `Permission['condition']` excludes null, update `PermissionRowFixture` to
allow `Permission['condition'] | null` instead of using a cast.

In
`@apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts`:
- Around line 492-498: The FGA namespace conversion in the loop over FGA
currently accepts unknown keys through an unsafe PermissionLevel cast. Validate
scope.toLowerCase() against the supported PermissionLevel values using the
project’s established zod parsing approach, and fail loudly for an unknown
namespace before creating resource entries; preserve the existing handling for
valid namespaces.

In
`@apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.test.ts`:
- Around line 109-343: Add a targeted Vitest case around groupFailingResources
in AccessToken.roles.test.ts, using evaluateTokenAccess to produce failures on
two resources and then asserting the grouped output order and each group’s
entries payload. Cover the missing-entry skip branch and the organizations-first
sort behavior by checking the result from groupFailingResources directly (or via
the exported helper path), while keeping the existing computeTokenRoleContext
and applySelectionToRoleContext coverage unchanged.

In `@apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.ts`:
- Around line 519-520: Update the available-level logic around entry.level so
the user-level case explicitly short-circuits organization-role checks instead
of assigning the misleading owner level. Preserve orgLevel and projectLevel
behavior for organization and project entries, and ensure user-level scopes
require no organization role.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: e90db0bc-9f11-428d-bac3-4d87f7d3f8cf

📥 Commits

Reviewing files that changed from the base of the PR and between 1ff84a2 and ce6bfe3.

📒 Files selected for processing (4)
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.test.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.ts

@github-actions

github-actions Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results (next)

passed  242 passed
flaky  1 flaky
skipped  5 skipped

Details

stats  248 tests across 29 suites
duration  6 minutes, 2 seconds
commit  ce6bfe3

Flaky tests

Features › queue-table-operations.spec.ts › Queue Table Operations › pending changes persist when switching between tables

Skipped tests

Features › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled
Features › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected
Features › sql-editor.spec.ts › SQL Editor › share with team works as expected
Features › sql-editor.spec.ts › SQL Editor › folders works as expected
Features › sql-editor.spec.ts › SQL Editor › other SQL snippets actions work as expected

@kemaldotearth
kemaldotearth merged commit 2a3025d into master Aug 6, 2026
39 checks passed
@kemaldotearth
kemaldotearth deleted the scopedpat/roles-core branch August 6, 2026 16:31
kemaldotearth added a commit that referenced this pull request Aug 7, 2026
## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

## What kind of change does this PR introduce?

Extracts the token view sheet slice of #48742
(w3b6x9/scoped-pat-access-feedback, commit 56ef87a). The role-evaluation
logic (estimateRoleLevel, computeTokenRoleContext,
applySelectionToRoleContext, groupFailingResources) already landed on
master via #48805 and #48809 — this PR only wires the view sheet up to
it:

- Bindings whose project/org was deleted (FGA bindings erased) render a
"resources no longer exist" state; bindings the user can no longer reach
render an anonymous count with a "No longer accessible" badge and a
"removed from" admonition.
- Accessible resources list their name plus ref/slug; capabilities show
"Exceeds your role" pills and the risk badge reflects what the owner's
current role actually allows.
- Header split into separate "Access control" and "API docs" buttons.
- Everything recomputes from live org/project/permission queries (no
stored state) and degrades to no warnings while loading or on
self-hosted.

Also gives DocsButton an optional `label` prop (defaults preserve
existing behavior for every other consumer) so the two header buttons
can carry distinct text.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Enhanced access-token details with permission categories, risk
summaries, endpoint, and MCP information.
  * Added warnings for permissions exceeding the token’s role.
* Clearly identifies inaccessible, deleted, or unavailable organizations
and projects.
  * Added resource details and remediation guidance for unusable tokens.
  * Documentation links can now display custom labels.

* **Bug Fixes**
* Improved access evaluation when organization or project data is
incomplete or access has changed.
  * Deferred resource loading until token details are opened.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Sonnet 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants