Repository navigation
feat(studio): role inference core for scoped pat - #48805
Conversation
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]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
5 Skipped Deployments
|
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
📝 WalkthroughWalkthroughThis 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. ChangesAccess token role evaluation
Estimated code review effort: 4 (Complex) | ~45 minutes Suggested reviewers: 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
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning Review ran into problems🔥 ProblemsGit: Failed to clone repository. Please run the 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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (4)
apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.ts (1)
22-31: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReplace the
ascasts with typed literals.The repository guideline asks you to avoid TypeScript
ascasts. Both casts here are avoidable. Type the parameters as the exactPermissionfield types, and setconditionto 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 acceptnull, widenPermissionRowFixturewithcondition: Permission['condition'] | nullinstead of casting.As per coding guidelines: "Avoid TypeScript
ascasts; parse external data with zod usingparseorsafeParse."🤖 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 valueMake the
userlevel 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 theownerrole.♻️ 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 winValidate the FGA namespace instead of casting it to
PermissionLevel.
scope.toLowerCase() as PermissionLevelaccepts any key thatFGAexposes. If@supabase/shared-typesadds a fourth namespace, every resource in it receives an invalidlevel.applySelectionToRoleContextinAccessToken.roles.ts(Line 520) then treats that level asproject, so those entries are gated by the project role instead of the correct role. The scope-id drift test inAccessToken.roles.test.tsdoes 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
ascasts; parse external data with zod usingparseorsafeParse."🤖 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 winAdd coverage for
groupFailingResources.The suite covers
computeTokenRoleContextandapplySelectionToRoleContextwell.groupFailingResourcesis exported fromAccessToken.roles.tsand 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
entriespayload.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
📒 Files selected for processing (4)
apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.tsapps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.tsapps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.test.tsapps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.ts
🎭 Playwright Test Results (next)Details
Flaky testsFeatures › queue-table-operations.spec.ts › Queue Table Operations › pending changes persist when switching between tables Skipped testsFeatures › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled |
## 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]>
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.
AccessToken.permissions.ts gains only what the roles module needs: the PermissionLevel type and the catalog's
levelfield (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
Tests