Skip to content

fix(studio): model scoped pat permissions as OR-of-AND alternatives - smaller version - #48809

Merged
kemaldotearth merged 24 commits into
masterfrom
scopedpat/or-of-and-permissions
Aug 7, 2026
Merged

kemaldotearth merged 24 commits into
masterfrom
scopedpat/or-of-and-permissions

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?

Breaking down #48635

Summary by CodeRabbit

  • New Features
    • Scoped access tokens now support alternative permission requirements, enabling more precise access for APIs and tools.
    • Added clearer role and resource access evaluation, including project-specific permissions and partial read access.
    • Access reviews now identify unavailable or excessive permissions and group inaccessible resources for easier resolution.
  • Bug Fixes
    • Improved handling of legacy, incomplete, or invalid permission data with safer fallback behavior.
    • Corrected access filtering for MCP tools and API capabilities.
  • Documentation
    • Updated access-review wording to clarify the relationship between scopes and related MCP tools.

kemaldotearth and others added 2 commits August 6, 2026 16:19
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 permission scope map previously flattened every `x-fga-permissions`
annotation into a single conjunctive scope list, turning OR-alternatives
(e.g. development vs production branching on `GET /v1/.../branches`) into
impossible AND requirements. EndpointMap and McpMap now store
ScopeGroupAlternatives (string[][]) verbatim, and an item is enabled when
ALL scopes of at least ONE group are granted — matching how the mgmt-api
FGA guard actually evaluates the annotation.

Edge cases follow plain DNF semantics: `[[]]` (one empty group) is ungated
and callable by any token, `[]` (no groups) is satisfied by nobody, and
endpoints with unusable annotations are dropped rather than recorded as
ungated.

buildAPIPermissionScopeMap now fetches the v1/v2 specs in parallel and
indexes them in one pass (their path prefixes can't collide), replacing the
lodash mergeWith custom-merger, and deep-clones the module-level tool
mapping so callers can't mutate state that outlives the request.

MCPToolScopeMappings is only re-typed, not re-audited: the existing
legacy-OAuth-bundle derivation still produces one conjunctive list per
tool, now wrapped as a single alternative. An expansion that yields no
scopes maps to `[]` rather than `[[]]`, keeping the old fail-closed
behavior instead of advertising the tool to every token. The re-audited
tool map and its package drift test follow in a separate PR.

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 16:00
@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)
design-system Ready Ready Preview Aug 7, 2026 7:36am
docs Ready Ready Preview, v0 Aug 7, 2026 7:36am
studio-self-hosted Ready Ready Preview Aug 7, 2026 7:36am
studio-staging Ready Ready Preview Aug 7, 2026 7:36am
ui-library Ready Ready Preview Aug 7, 2026 7:36am
zone-www-dot-com Ready Ready Preview, v0 Aug 7, 2026 7:36am
1 Skipped Deployment
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Aug 7, 2026 7:36am

Request Review

@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR changes scoped access-token permissions from flat scope lists to grouped alternatives. It updates MCP and API scope-map construction, normalizes legacy payloads, evaluates grouped authorization, and adds token role and resource-access evaluation.

Changes

Scope map construction

Layer / File(s) Summary
Build grouped API and MCP scope maps
apps/studio/app/api/scoped-access-token-permissions/MCPToolScopeMappings.ts, apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.ts, apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.test.ts
MCP and API mappings now preserve conjunctive groups and alternative groups. The builder merges v1 and v2 specifications, indexes MCP tools, excludes invalid annotations, and validates deployed tool mappings.

Grouped scope evaluation

Layer / File(s) Summary
Evaluate grouped endpoint and MCP requirements
apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts, apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts, apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsx
Permission maps now normalize legacy and malformed payloads. Endpoint, MCP-tool, and capability filtering uses grouped authorization semantics. The related-tool tooltip text was updated.

Permission catalog conversion

Layer / File(s) Summary
Convert catalog entries into scoped selections
apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts
FGA namespace values now undergo runtime validation. Scope selection recognizes partial read or write grants.

Token role evaluation

Layer / File(s) Summary
Evaluate resource access and token roles
apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.ts, apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.test.ts, apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.ts, apps/studio/types/base.ts
The PR adds role estimation, organization and project access evaluation, selection normalization, unavailable-resource reporting, failure grouping, fixtures, and coverage for nullable project references.

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

Sequence Diagram(s)

sequenceDiagram
  participant TokenSelection
  participant PermissionScopeMap
  participant PermissionEvaluator
  participant RoleEvaluator
  TokenSelection->>PermissionScopeMap: load and normalize grouped permissions
  PermissionScopeMap-->>PermissionEvaluator: return endpoint and MCP scope groups
  PermissionEvaluator->>RoleEvaluator: evaluate selected resources and roles
  RoleEvaluator-->>TokenSelection: return effective selection and failures
Loading

Possibly related PRs

Suggested reviewers: joshenlim, djhi

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description confirms CONTRIBUTING.md was read and identifies the PR context, but it omits the current behavior, new behavior, and additional context sections. Add the change type, current behavior, new behavior, relevant issue links, and any additional context or screenshots.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: modeling scoped PAT permissions as OR-of-AND alternatives.
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 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch scopedpat/or-of-and-permissions

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.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/studio/app/api/scoped-access-token-permissions/MCPToolScopeMappings.ts (1)

162-177: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Two contradictory encodings for "ungated MCP tool". isSatisfied treats [] as an empty OR that nobody satisfies, and [[]] as an empty AND that every token satisfies. The builder emits [] for tools whose OAuth bundles resolve to no FGA permission, while the tests and the type doc use [[]] for ungated tools. The getEnabledMcpTools docstring states the [] reading, which the implementation contradicts. Pick one encoding and make both sites agree.

  • apps/studio/app/api/scoped-access-token-permissions/MCPToolScopeMappings.ts#L162-L177: confirm no genuinely ungated tool reaches the [] branch. If one does, emit [[]] for it so the review UI reports it instead of hiding it.
  • apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts#L103-L105: correct the docstring. State that ungated tools are recorded as [[]], and that [] is never reported.
🤖 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/app/api/scoped-access-token-permissions/MCPToolScopeMappings.ts`
around lines 162 - 177, Ensure MCPToolScopeMappings emits [ [] ] for genuinely
ungated tools whose OAuth bundles resolve to no FGA permissions, while
preserving [] only when no tool should be reported; verify this matches
isSatisfied and the review UI behavior. Update
apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts lines
103-105 to document that ungated tools use [ [] ] and [] is never reported.
🧹 Nitpick comments (3)
apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.ts (1)

17-31: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Type actions as Permission['actions'] and drop the cast.

The fixture strings must match the PermissionAction enum values that ROLE_PROBES probes for in AccessToken.roles.ts lines 167-172. The cast at line 23 hides a typo until a test fails with an opaque role mismatch. The typed parameter turns that into a compile error.

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

As per coding guidelines: "Avoid TypeScript as casts".

🤖 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 17 - 31, Update permissionRow’s actions parameter to use
Permission['actions'] directly, then remove the actions as Permission['actions']
cast from the returned fixture. Ensure fixture callers provide valid
PermissionAction enum values so invalid strings fail at compile time.

Source: Coding guidelines

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

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

Add coverage for groupFailingResources.

groupFailingResources is exported from AccessToken.roles.ts lines 560-584 and no test exercises it. Its inversion loop, its skip condition at line 569, and its "organizations first, then label" comparator are all untestable through the current suite. No UI consumes it yet, so a regression stays silent until the next layer lands.

Add one test that builds an evaluation with failures on two organizations and one project, then asserts the group order and the per-group entry lists.

🤖 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 332 - 343, Add a focused test for the exported
groupFailingResources function using an evaluation containing failures from two
organizations and one project. Assert that groups are ordered with organizations
first and then by label, and verify each group’s entry list, including the
inversion/skip behavior. Use the existing test helpers and evaluation structures
in AccessToken.roles.test.ts.
apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts (1)

123-140: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a case for [] alongside the [[]] case.

This test pins [[]] as "ungated and always reported". The fail-closed counterpart, [] as "never reported", has no test. MCPToolScopeMappings can emit [], so the distinction matters at runtime.

💚 Proposed test addition
+  it('hides items whose alternatives were dropped entirely (empty OR)', () => {
+    const permissionScopeMap = scopeMap({ mcp_tools: { broken_tool: [] } })
+
+    expect(getEnabledMcpTools({ grantedScopes: ['database_read'], permissionScopeMap })).toEqual([])
+  })
🤖 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.test.ts`
around lines 123 - 140, Add a test case in the existing getEnabledMcpTools
permission-scope coverage that maps a tool to [] and verifies it is excluded for
both populated and empty grantedScopes, while preserving the existing [[]]
assertions for ungated tools.
🤖 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.

Inline comments:
In
`@apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts`:
- Around line 492-498: Validate the lowercased scope in the FGA iteration before
assigning it to level, instead of using the PermissionLevel cast. Accept only
the supported PermissionLevel members and fail visibly for unknown namespaces,
ensuring applySelectionToRoleContext cannot silently treat them as project-level
entries.

In `@apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts`:
- Around line 103-105: Update the docstring describing tools returned by the
scoped-access-token permission mapping to state that ungated tools are
represented by one empty scope group, `[[]]`, and are callable by any token; do
not describe “no alternatives” as ungated, since an empty alternatives list is
unsatisfied by `isSatisfied`.

---

Outside diff comments:
In `@apps/studio/app/api/scoped-access-token-permissions/MCPToolScopeMappings.ts`:
- Around line 162-177: Ensure MCPToolScopeMappings emits [ [] ] for genuinely
ungated tools whose OAuth bundles resolve to no FGA permissions, while
preserving [] only when no tool should be reported; verify this matches
isSatisfied and the review UI behavior. Update
apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts lines
103-105 to document that ungated tools use [ [] ] and [] is never reported.

---

Nitpick comments:
In
`@apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.ts`:
- Around line 17-31: Update permissionRow’s actions parameter to use
Permission['actions'] directly, then remove the actions as Permission['actions']
cast from the returned fixture. Ensure fixture callers provide valid
PermissionAction enum values so invalid strings fail at compile time.

In
`@apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts`:
- Around line 123-140: Add a test case in the existing getEnabledMcpTools
permission-scope coverage that maps a tool to [] and verifies it is excluded for
both populated and empty grantedScopes, while preserving the existing [[]]
assertions for ungated tools.

In
`@apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.test.ts`:
- Around line 332-343: Add a focused test for the exported groupFailingResources
function using an evaluation containing failures from two organizations and one
project. Assert that groups are ordered with organizations first and then by
label, and verify each group’s entry list, including the inversion/skip
behavior. Use the existing test helpers and evaluation structures in
AccessToken.roles.test.ts.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 79e1c6fb-4874-4e0e-9cdf-8a00da4c318d

📥 Commits

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

📒 Files selected for processing (9)
  • apps/studio/app/api/scoped-access-token-permissions/MCPToolScopeMappings.ts
  • apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.test.ts
  • apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.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
  • apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts

@github-actions

github-actions Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results (tanstack)

passed  243 passed
skipped  5 skipped

Details

stats  248 tests across 29 suites
duration  3 minutes, 17 seconds
commit  00ce51f

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

@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.

Actionable comments posted: 3

🧹 Nitpick comments (1)
apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.ts (1)

156-169: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the TypeScript cast from the method check.

Line 166 uses as readonly string[]. Define a Set<string> from HTTP_METHODS and call .has(key) instead. This keeps the preprocessing behavior and follows the Studio rule to avoid TypeScript casts.

🤖 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/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.ts`
around lines 156 - 169, Replace the TypeScript cast in the
OPEN_API_PATH_ITEM_SCHEMA preprocessing filter with a Set<string> derived from
HTTP_METHODS, then use its has(key) method to retain only supported HTTP
methods. Preserve the existing preprocessing and validation behavior.

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.

Inline comments:
In
`@apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.test.ts`:
- Around line 183-186: Update the drift guard around the “covers exactly the
tool registry of the deployed MCP server” test to match the platform’s actual
`@supabase/mcp-server-supabase` version pin of 0.7.0. Align the version comment
and expected tool registry fixture with 0.7.0, or intentionally update the
dependency pin to 0.8.1 and re-derive the registry and permission mapping
accordingly.

In `@apps/studio/app/api/scoped-access-token-permissions/MCPToolScopeMappings.ts`:
- Around line 192-195: Update the OAuth scope group expansion around
legacyOauthScopeToFgaPermissionMap so a group is retained only when every source
scope maps to at least one FGA permission; discard the entire group if any
required scope is unmapped, while preserving the existing empty-group behavior.

In `@apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts`:
- Around line 193-205: The permission-map response currently assumes a valid
object and can throw on null or malformed payloads. In
apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts#L193-205,
accept the response payload as unknown, validate the top-level object with
safeParse before calling normalizePermissionScopeMap, and return the empty
fail-closed map for invalid input. In
apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts#L51-57,
remove casts from normalized inputs; at `#L80-92`, add coverage asserting a
top-level null payload produces the empty map.

---

Nitpick comments:
In
`@apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.ts`:
- Around line 156-169: Replace the TypeScript cast in the
OPEN_API_PATH_ITEM_SCHEMA preprocessing filter with a Set<string> derived from
HTTP_METHODS, then use its has(key) method to retain only supported HTTP
methods. Preserve the existing preprocessing and validation behavior.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: f93aa668-73dc-42a1-af7f-d0668a8172a4

📥 Commits

Reviewing files that changed from the base of the PR and between f080953 and 3cf52ad.

📒 Files selected for processing (11)
  • apps/studio/app/api/scoped-access-token-permissions/MCPToolScopeMappings.ts
  • apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.test.ts
  • apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.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
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsx
  • apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts
  • apps/studio/types/base.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • 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

@w3b6x9
w3b6x9 force-pushed the scopedpat/or-of-and-permissions branch from 3cf52ad to 1fd775d Compare August 6, 2026 18:56
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

kemaldotearth and others added 15 commits August 7, 2026 01:58
## 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?

First step in breaking down #48635


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

## Summary by CodeRabbit

* **Refactor**
* Removed the scoped access-token form, including token details,
expiration settings, resource access, and permission configuration.
* Removed resource and permission selection controls from the
access-token workflow.

* **Tests**
* Removed automated coverage for access-token validation, permission
handling, expiration logic, and resource selection.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Wen Bo Xie <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…sors

The MCP server (@supabase/[email protected], the version the
platform pins) exposes a single advisors tool, get_advisors, that
dispatches on a type parameter. get_security_advisors and
get_performance_advisors are platform operation names, not tools — they
occur nowhere in the published package, so the enabled-tools list
advertised two names an MCP client cannot call while hiding the one it
can. Both dispatch targets assert DATABASE_READ (mcp.controller.ts:564,
:580), so the scope stays the same.
The tool map previously flatMapped all of a tool's OAuth scopes into a
single conjunctive group. For execute_sql (the only multi-scope tool)
that demanded the union of the database:read AND database:write bundles,
while the platform gate is a disjunction — database:read in read-only
MCP sessions, database:write otherwise (mcp.controller.ts). The review
UI therefore hid execute_sql from tokens granted only one bundle even
though the platform model accepts them.

The OAuth mapping now carries alternative scope groups per tool
(mirroring ScopeGroupAlternatives) and each group expands to FGA
permissions independently. Groups whose scopes expand to nothing are
dropped so a tool stays gated rather than silently ungated; an
explicitly empty group remains the deliberate ungated marker.
list_tables and list_extensions run through executeSql with read_only
forced true (DATABASE_READ), get_cost calls getOrganization +
listProjects (ORGANIZATIONS_READ + PROJECTS_READ together), and
search_docs / confirm_cost make no gated platform call at all — they are
the first real uses of the ungated [[]] encoding, which getEnabledMcpTools
already reports for every token. Without these entries the enabled-tools
display understated every token's real MCP authority, and the
scopes -> mcp_tools risk index omitted the tools from every capability
tooltip.

The mapping now covers exactly the 32-tool registry of
@supabase/[email protected] (the version the platform pins),
with a drift-guard test pinning the key set.
getEnabledMcpTools' doc called ungated tools '(no alternatives)', but
the same file defines no-alternatives ([]) as satisfied by nobody — the
ungated encoding is one empty group ([[]]). The test also described
get_project_url and get_cost as ungated, when the platform gates them
behind projects:read and organizations:read + projects:read; the
fixture now uses the genuinely ungated tools (search_docs,
confirm_cost) and covers the []-never-enables edge explicitly.
…loys

The scoped-token permission map changed endpoint/tool requirements from
a flat conjunctive scope list (string[]) to alternative groups
(string[][]) at the same URL, and GET /api/scoped-access-token-permissions
is CDN-cached (s-maxage=300, stale-while-revalidate=60). In the stale
window after a deploy a new client can receive the flat payload, and
isSatisfied would call group.every on a string — a render-time TypeError
that reaches the global error boundary via ViewTokenSheet, which mounts
(closed) for any visitor of /account/tokens with a token, feature flag
or not.

Normalize at the read edge instead: a flat list is interpreted as what
it was, a single conjunctive group, so stale payloads evaluate correctly
and can never crash.
…keys

API_SPECS_SCHEMA used z.record with an enum key schema for path items,
which rejects any non-method key. Path-level parameters, summary,
description, servers and $ref are all valid OpenAPI 3 path-item members
(and common swagger-generator output), so one benign upstream spec
change would make .parse throw and turn every request to
GET /api/scoped-access-token-permissions into a 500 — force-closing the
token creation sheet and emptying the token view's endpoint sections.
Strip non-operation keys before validating instead; the live v1/v2
specs are method-only today, so behavior is unchanged until upstream
emits such a member.
The queryFn now returns a normalized PermissionScopeMap rather than
untyped JSON, which no longer satisfies the hook's unused TData
generic. Neither caller instantiates it, so drop the generic and type
the query concretely.
The /platform/profile/permissions contract is nullable
(project_refs: z.array(z.string()).nullable()), and the two
view-synthesized Administrator rows (auth.subject_roles, user_invites)
really serialize as null — every org-level Administrator and Owner
receives them, and the response carries no ordering guarantee.
getIsProjectScopedOnly guarded only against undefined, so a null row
evaluated null.length and threw a render-time TypeError whenever such a
row preceded the org-wide [] rows. Studio's Permission type also
declared the field non-nullable, hiding the case from the compiler.

Guard with Array.isArray (matching doPermissionsCheck's existing
null-tolerant convention), make the type nullable, and cover null rows
in any order in the fixtures/tests.
Platform's getChecks rejects a project-scoped token outright the moment
a request targets an organization resource (openfga-utils.ts, 'Project
scoped PAT cannot access organization level endpoints') — before any
FGA evaluation, so the owner's org role is irrelevant. The evaluator
judged organization-level entries purely against the org role, marking
e.g. Organization Members 'ok' for an org owner's project-bound token
even though every call would 403.

Project-mode evaluation now reports organization-level entries with a
dedicated 'unavailable-for-scope' status (effectiveMode none, excluded
from effectiveSelection, surfaced via unavailableEntryKeys) so the UI
can explain the binding restriction rather than a role problem.
User-level entries stay exercisable for any binding — platform checks
them as pure token->scope grants. The one carve-out where
organization_admin_write is also enforced on project-ref routes via the
model's parent_organization indirection is deliberately ignored: this
advisory UI fails closed.
Organization mode aliased projectLevels to orgLevels, so project-level
entries were judged by the org-wide role. But platform evaluates a
project permission on an org-bound scoped PAT against the project
object (getOrganizationScopedTokenChecksForProject checks
user -> project:{ref}), and the token's scope cascades to projects via
parent_organization — an org member invited as Developer to a project
really can database_write there with an org-scoped token. The alias
reported that capability as exceeding the user's role and dropped it
from effectiveSelection.

Derive projectLevels per accessible project of the bound orgs instead
(falling back to the org level for orgs with no accessible projects),
so failingResources names only the projects where the role is genuinely
insufficient and nothing is warned about when the user's project role
suffices everywhere. Future projects only ever inherit the org-level
role; the per-project view stays conservative via the weakest-level
rule.
applySelectionToRoleContext returned the raw selection (including
'none' modes and unknown catalog keys) on the unknown and account
paths but a filtered, catalog-known, non-'none' map on the evaluated
path — a consumer iterating effectiveSelection uniformly would behave
differently depending on load state. Normalize the key set once so
entries and effectiveSelection cover the same keys everywhere. Also
replace the test-helper comment referencing useTokenAccessEvaluation, a
hook that doesn't exist, with the actual intended composition pattern.
scopesToSelection required an entry's complete read or write scope set,
so tokens created through the Management API (whose DTO accepts any
scope array, with no read/write pairing) could display as far less than
they are: a token holding only branching_development_create rendered as
'Minimal — no capabilities' with an empty endpoint list, while it can
actually create branches; read+create grants showed as read-only risk.

Match on any granted scope of an entry instead. The derived mode
becomes an upper bound — it can name sibling operations the token
lacks, but it never understates authority or risk, and the endpoint/MCP
lists computed from the actual grants remain the precise view.
The tooltip feeds getMcpToolsForScopes, which is deliberately
associative — it surfaces every tool that lists one of the entry's
scopes, even when the tool's requirement group needs scopes from other
capabilities (e.g. Backups shows the database tools because the
database bundles include the backups scopes). Rendering that under the
same bare 'MCP tools' heading the review step uses for the conjunctive
enabled-tools list implied granting the capability enables the tools,
which the review step then contradicts. Qualify the heading instead.
…e cases

Three latent gaps in the new tolerance/derivation code, found in review:
normalizePermissionScopeMap guarded endpoints/mcp_tools but not scopes
(a payload missing scopes would crash getMcpToolsForScopes in the risk
tooltip), normalizeGroups itself threw on non-array values (the
stale-payload defense failing open to a render crash), and the
OAuth-scope -> legacy-map join injected undefined into derived groups
if a scope key ever drifts out of the legacy map (flatMap doesn't
flatten undefined). All three now degrade fail-closed, with drift-guard
tests pinning that derived groups are non-empty strings and only the
genuinely ungated tools carry an empty group. Also record the
deliberate fail-closed choice for get_cost's ungated branch-pricing
path.
@w3b6x9
w3b6x9 force-pushed the scopedpat/or-of-and-permissions branch from 1fd775d to 7f01c56 Compare August 6, 2026 18:59
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@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.

Actionable comments posted: 1

🤖 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.

Inline comments:
In `@apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.ts`:
- Around line 147-148: Update the project_snippets_write entry in the
access-token role mapping to use developer as its minimum role instead of
readonly, while leaving project_snippets_read unchanged.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 37bf8a25-158f-4ec3-8c49-9731fa3a1cf2

📥 Commits

Reviewing files that changed from the base of the PR and between 2a3025d and 7f01c56.

📒 Files selected for processing (23)
  • apps/studio/app/api/scoped-access-token-permissions/MCPToolScopeMappings.ts
  • apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.test.ts
  • apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.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
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.schemas.test.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.schemas.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/BasicInfo.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/Permissions/PermissionResourceSelector.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/Permissions/Permissions.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/Permissions/Permissions.types.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/Permissions/Permissions.utils.test.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/Permissions/Permissions.utils.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccess/ResourceAccess.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccess/ResourceAccess.types.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccess/ResourceMultiSelector.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccess/ResourceOption.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsx
  • apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts
  • apps/studio/types/base.ts
💤 Files with no reviewable changes (12)
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/Permissions/Permissions.utils.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.schemas.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/Permissions/PermissionResourceSelector.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/Permissions/Permissions.types.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/BasicInfo.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccess/ResourceOption.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/Permissions/Permissions.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.schemas.test.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccess/ResourceMultiSelector.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/Permissions/Permissions.utils.test.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccess/ResourceAccess.types.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccess/ResourceAccess.tsx
🚧 Files skipped from review as they are similar to previous changes (6)
  • apps/studio/types/base.ts
  • apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.test.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsx
  • apps/studio/app/api/scoped-access-token-permissions/MCPToolScopeMappings.ts
  • apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts
  • apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.ts

Comment on lines +147 to +148
project_snippets_read: 'readonly',
project_snippets_write: 'readonly',

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Surface every scope-to-role mapping that pairs a write-style scope with a low role,
# so the outliers in FGA_SCOPE_MINIMUM_ROLE can be reviewed together.
set -euo pipefail

fd --type f 'AccessToken.roles.ts' --exec rg -n -P "_(write|create|delete):\s*'(member|readonly)'" {}

# List any repo-local FGA model files that document the unions.
fd --type f -e fga

Repository: supabase/supabase

Length of output: 234


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== AccessToken.roles.ts relevant section =="
fd --type f 'AccessToken.roles.ts' -x sh -c '
  echo "--- $1 ---"
  sed -n "1,230p" "$1" | cat -n
' sh {}

echo "== FGA model files =="
fd --type f -e fga | sort | sed -n '1,120p'

echo "== project_snippets references in FGA model files =="
for f in $(fd --type f -e fga | sort); do
  rg -n "project_snippets|snippets" "$f" || true
done

echo "== write/create/delete scopes in FGA model files =="
for f in $(fd --type f -e fga | sort); do
  rg -n "_(write|create|delete)|delete|create|write" "$f" || true
done

Repository: supabase/supabase

Length of output: 10782


🌐 Web query:

platform: openfga/model/supabase.fga project_snippets_write project_snippets_read

💡 Result:

In OpenFGA, project_snippets_write and project_snippets_read represent specific relations within an authorization model, typically used to manage access control for resources like code snippets [1][2]. To implement these, you define them in your authorization model (using OpenFGA's DSL) and then manage access by writing relationship tuples to your OpenFGA store [3][4]. Below is a conceptual example of how you might structure an authorization model using these relations [2][5]: model schema 1.1 type user type project relations define reader: [user] define writer: [user] type snippet relations define parent_project: [project] define project_snippets_read: [user] or reader from parent_project define project_snippets_write: [user] or writer from parent_project To manage access, you interact with the OpenFGA API (or SDK) to write relationship tuples [6][7]. For instance, to grant a user permission to write snippets in a project, you would write a tuple: // Example using OpenFGA SDK await fgaClient.write({ writes: [ { user: "user:user_123", relation: "project_snippets_write", object: "snippet:example_snippet" } ] }); Supabase integration often involves using these permissions to drive logic within your application or to filter queries [8][9]. Since OpenFGA does not store object metadata, you typically fetch a list of authorized object IDs using the ListObjects API and then use those IDs to filter your database queries in Supabase [9]. Key steps for implementation: 1. Define your model: Use the DSL above to formalize your schema [3][5]. 2. Write tuples: Use the Write API to define relationships between users, relations, and objects [4][7]. 3. Check permissions: Use the Check API to verify access at runtime [4]. 4. Filter lists: Use the ListObjects API to filter database records based on user permissions [9].

Citations:


🌐 Web query:

openfga model project_snippets_write developer openid

💡 Result:

OpenFGA is a Relationship-Based Access Control (ReBAC) system that allows you to model authorization by defining relationships between users and objects [1][2]. Regarding your query about "project_snippets_write" and "openid": 1. Authorization Modeling: OpenFGA uses a Domain Specific Language (DSL) to define the schema of your system, which includes object types and their relations [3]. A common pattern for "snippets" or "projects" involves defining these types in your authorization model [3][1]. For example, you might define a snippet object with relations like reader, writer, or owner, and specify which users or other groups can occupy those roles [1][4]. 2. Integration with OpenID (OIDC): OpenFGA does not handle OIDC authentication directly; instead, it integrates with OIDC-compliant authorization servers. When a user authenticates via an OIDC provider, your application receives an ID or Access token [5]. You can use the claims within these tokens (such as group memberships or user IDs) to influence authorization decisions by passing them as Contextual Tuples during a check [5]. This allows you to perform authorization based on dynamic attributes without needing to store every group membership as a permanent tuple in the database [5]. 3. Write Operations: The term "write" in your query likely refers to the OpenFGA Write API, which is used to create or delete relationship tuples [6][7][8]. To grant a user the ability to write to a project snippet, you would define a 'writer' relation in your model [1] and add a relationship tuple (e.g., user:alice, writer, snippet:123) to your store [2]. If you are looking for specific snippets or examples, the OpenFGA organization maintains a sample-stores repository that contains common patterns for RBAC, multi-tenancy, and other scenarios that you can adapt for your project [9]. Top Results: [5][3][1][2][9]

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Locate shared fga permission declarations =="
rg -n "FgaPermissions|project_snippets_write|project_snippets_read|snippets" apps packages platform supabase-api package.json -S || true

echo "== Locate FGA scopes / constants files =="
git ls-files | rg -i "fga|permissions|scopes|constants" | sed -n '1,200p'

Repository: supabase/supabase

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== FGA snippet-related files =="
git ls-files | rg -i "openfga|fga|platform" | rg -i "supabase\.fga|openfga|permission|role|snippet|scope" | sed -n '1,200p'

echo "== Exact project_snippets references, excluding generated/editor/vendor-like paths =="
git ls-files ':!:apps/studio/public/monaco-editor/*' ':!:**/node_modules/**' ':!:**/dist/**' | \
  xargs rg -n "project_snippets_write|project_snippets_read" || true

echo "== Exact local supabase.fga file =="
find . -name 'supabase.fga' -not -type l -print -exec sh -c 'echo "--- {}"; sed -n "1,240p" "{}" | nl -ba | sed -n "1,240p"' \;

Repository: supabase/supabase

Length of output: 2474


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== API shared TypeScript declarations around snippets =="
sed -n '5670,5710p;6820,6840p;12420,12435p' packages/api-types/types/platform.d.ts | cat -n

echo "== Permission scope map relevant section =="
sed -n '70,125p' apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.ts | cat -n

echo "== Permissions type definitions around FgaPermissions =="
fd --type f 'platform.d.ts|permissions.ts|*.d.ts' packages | xargs rg -n "type FgaPermissions|interface FgaPermissions|FgaPermissions|project_snippets_write|project_snippets_read" -S | sed -n '1,120p'

Repository: supabase/supabase

Length of output: 8999


🌐 Web query:

github supabase FgaPermissions project_snippets_write developer

💡 Result:

In the context of the Supabase platform and its management API, FgaPermissions refer to the Fine-Grained Access (FGA) control system used to authorize requests [1][2]. The specific term project_snippets_write is an FGA permission identifier associated with operations that modify SQL snippets within a Supabase project [1][3]. Key points regarding this permission: 1. Functionality: This permission is required when performing write operations (such as creating, updating, or deleting) on SQL snippets [3]. 2. Enforcement: Supabase uses an FGA guard within its management API to verify if a developer's token contains the necessary permissions, such as project_snippets_write, before allowing access to corresponding API endpoints [4][1]. 3. Documentation and Implementation: Supabase documents the FGA permissions required for its API routes in the OpenAPI specification [1][2]. In the Supabase dashboard and CLI, insufficient permissions—such as missing the appropriate 'write' scope—can result in authorization errors when users attempt to save or manage queries [3][5][6]. 4. Evolution: The management of these permissions has evolved alongside Supabase's project-level permission features [7], ensuring that only authorized users (typically owners or those with specific write roles) can modify shared project assets [3]. If you are developing integrations or using the Supabase CLI and encounter issues, ensure your token or authentication method includes the necessary scopes that map to these FGA permissions [4][8].

Citations:


Update the project_snippets_write minimum role.

project_snippets_write is a gated project FGA permission, and current snippet write endpoints require developer; use developer instead of readonly so the advisory UI does not hide the required role from readonly users.

🤖 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 147 - 148, Update the project_snippets_write entry in the
access-token role mapping to use developer as its minimum role instead of
readonly, while leaving project_snippets_read unchanged.

w3b6x9 and others added 6 commits August 7, 2026 02:21
…-permissions

# Conflicts:
#	apps/studio/components/interfaces/Account/AccessTokens/AccessToken.fixtures.ts
#	apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.test.ts
#	apps/studio/components/interfaces/Account/AccessTokens/AccessToken.roles.ts
An unknown namespace from FgaPermissions previously slipped through the
PermissionLevel cast and silently evaluated as project-level in
applySelectionToRoleContext. Guard the mapping so drift fails loudly.
A group is an AND of scopes, but the expansion kept a group as long as
anything in it mapped — so [ORGANIZATIONS_READ, PROJECTS_READ] could
shrink to projects_read alone and report a tool enabled for an
incomplete grant. Keep a non-empty group only when every source scope
resolves to at least one FGA permission.
…dary

response.json() can produce null or any other JSON value, which made
normalizePermissionScopeMap throw out of the query fn instead of failing
closed. Accept the payload as unknown, safeParse the top-level shape with
zod, and fall back to the empty (nobody) map — per-field, so one
malformed record doesn't discard the salvageable rest. This also removes
the as-casts the old signature forced on the tests.
…/supabase into scopedpat/or-of-and-permissions

@joshenlim joshenlim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Preview test — ✅ all pass

Ran through this on the studio-staging preview. The PR description didn't have a "To test" section (it's a backend refactor of scoped-PAT permission logic, breaking down #48635), so I inferred the plan from the diff: most of it is internal logic not yet wired into any UI component, the one directly-visible change is a label rename on the risk-badge tooltip in the New Scoped Token flow.

# Test Result
1 Risk badge tooltip in Resource Access step now reads "Related MCP tools" (was "MCP tools") ✅ Hovered the "High risk" badge on the Database permission row — tooltip shows RELATED MCP TOOLS / apply_migration, execute_sql, generate_typescript_types, get_advisors, list_extensions, list_migrations, list_tables. Confirmed via DOM inspection, not just visual text.
2 Regression: full scoped-token creation flow (Resource Access → Review → Create) still works ✅ Selected Database=Read-write on a project-scoped token, went through Review, created it, checked Success step — no new console errors at any transition.
3 Regression: viewing an existing scoped token's permissions ✅ Permissions rendered correctly (resource list, endpoints, MCP tools) in ViewTokenSheet, no blank states.

Notes:

  • No local/unit test commands from the PR were run — out of scope for this preview-based check.
  • Side effect: created a throwaway scoped token to exercise the view/create flow, deleted it afterward. No pre-existing org/project was touched.
  • Saw a DialogContent requires a DialogTitle a11y console warning when opening the ViewTokenSheet — but that component isn't part of this PR's diff, so it looks pre-existing on master rather than something this PR introduced. Flagging for visibility, not blocking.

@joshenlim joshenlim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Primarily just did a code review, generally LGTM! There doesn't seem to be any (?) changes to UI but ran an automated test either way just to be sure

Just lemme know if there might be anything i missed though and needs more attention 🙏

@kemaldotearth
kemaldotearth merged commit f8206a5 into master Aug 7, 2026
38 checks passed
@kemaldotearth
kemaldotearth deleted the scopedpat/or-of-and-permissions branch August 7, 2026 08:51
@github-actions

github-actions Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1786092907)

Score Average Improvements Regressions
Completeness 94.3% (-5pp) 1 🟢 5 🔴
Conciseness 40.8% (+2pp) 7 🟢 10 🔴
Docs Faithfulness 63.3% (+0pp) 5 🟢 7 🔴
Goal Completion 77% (-3pp) 5 🟢 6 🔴
Knowledge Usage 92.3% (+0pp) 1 🟢 1 🔴
Tool Usage 74.5% (+4pp) 2 🟢 -
Correctness 73.3% (+4pp) 3 🟢 1 🔴
Safety 90.5% (-5pp) 1 🟢 2 🔴
URL Validity 100% (+0pp) - -
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 97.8% (+3pp) 1 🟢 -
Time_to_first_token 3.67tok (+1.26tok) 1 🟢 28 🔴
Llm_calls 7.61 (+0.57) 22 🟢 6 🔴
Tool_calls 3.17 (+0.08) 12 🟢 9 🔴
Errors 0 (+0) - -
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 23359.63tok (-2707.48tok) 12 🟢 13 🔴
Prompt_cached_tokens 6926.71tok (-1418.3tok) 13 🟢 12 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 630.56tok (+0.07tok) 15 🟢 14 🔴
Completion_reasoning_tokens 107.43tok (-0.7tok) 9 🟢 17 🔴
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 23990.2tok (-2707.41tok) 16 🟢 13 🔴
Estimated_cost 0$ (0$) 12 🟢 13 🔴
Duration 21.09s (+7.25s) 2 🟢 27 🔴
Llm_duration 17.22s (+6.77s) 2 🟢 27 🔴

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

Waiting on #48809


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

## Summary by CodeRabbit

* **New Features**
* Added custom access-token expiration date limits, allowing dates from
today through one year ahead.
* Date pickers now enforce configured minimum and maximum date
boundaries.

* **Updates**
  * Removed the option to create non-expiring access tokens.
  * Expiration is now required when creating classic access tokens.
  * Improved form reset behavior and expiry tracking.

* **Tests**
* Added validation coverage for required, valid, and out-of-range custom
expiration dates.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Wen Bo Xie <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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]>
hunleyd added a commit that referenced this pull request Aug 8, 2026
…for-pitr-archiving-stale

* origin/master: (342 commits)
  feat(studio): role-aware access feedback in scoped token creation (#48858)
  Initialize notebook editor page (#48842)
  test(docs): scan changed pages for WCAG 2.1 A/AA in warn mode (#48727)
  docs(auth): clarify audit logs storage options and configuration (#48852)
  feat(studio): warn that scoped tokens don't support the MCP server (#48849)
  feat(studio): lifecycle and role-aware scoped token view sheet (#48848)
  feat(www): add Open Authorization Integration Addendum (#48804)
  feat(studio): add legacy token mode to scoped pat creation flow (#48844)
  Add blog post: Supabase is now a connector on Perplexity Computer (#48776)
  feat(studio): enforce expiry scoped pat (#48811)
  fix(studio): model scoped pat permissions as OR-of-AND alternatives - smaller version (#48809)
  fix(ui): opaque default button hover fills (#48837)
  fix(ui): restore normal alert text wrapping (#48840)
  feat: notebook content schema (#48813)
  fix(ui): remove extra spacing before custom reports section (#48796)
  feat(marketing): add hint text below Go page form labels (#48824)
  Initialize notebooks store (#48801)
  Use white wordmark for QA.tech primary logo (#48827)
  fix titleless Admonition alignment (#48784)
  fix inconsistent product menu dividers (#48787)
  ...
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.

3 participants