Skip to content

Scoped PAT: refactor the scope permission map to be computed from Open API specs - #48182

Merged
djhi merged 32 commits into
scopedpat/root-branchfrom
scopedpat/scope-permissions-api
Jul 30, 2026
Merged

djhi merged 32 commits into
scopedpat/root-branchfrom
scopedpat/scope-permissions-api

Conversation

@djhi

@djhi djhi commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Fifth stacked PR for scoped PAT extracted from the prototype #47783 to ease reviewing.
Previous stacked PR is #47999
Next stacked PR is #48359

This PR refactor how we get the map of which scopes enable which endpoint or mcp tool. Previously it was an hardcoded file. We now compute it from the OpenAPI specs of our API. This ensure the map stays up to date when the API changes.

However, we don't have an always up-to-date equivalent for mcp tools so we duplicated code from platform that map the OAuth scopes they check with the FGA permissions.

Notes

The react-hook-form usage is not great. A follow up PR will fix it

How to test

Summary by CodeRabbit

  • New Features

    • Added dynamic permission mapping for scoped access tokens, covering Management API endpoints and MCP tools.
    • Added a permissions endpoint with hosted-platform support and caching.
    • Updated scoped token creation and review screens to show capabilities based on granted permissions.
    • Added permission-aware risk indicators and tool visibility.
  • Bug Fixes

    • Improved authorization checks so endpoints and tools require all necessary scopes.
  • Tests

    • Added coverage for endpoint, scope, and MCP tool mapping behavior.

@djhi
djhi requested a review from a team as a code owner July 22, 2026 09:47
@vercel

vercel Bot commented Jul 22, 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 Jul 30, 2026 1:29pm
studio-staging Ready Ready Preview Jul 30, 2026 1:29pm
5 Skipped Deployments
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Jul 30, 2026 1:29pm
design-system Skipped Skipped Jul 30, 2026 1:29pm
docs Skipped Skipped Jul 30, 2026 1:29pm
ui-library Skipped Skipped Jul 30, 2026 1:29pm
zone-www-dot-com Skipped Skipped Jul 30, 2026 1:29pm

Request Review

@supabase

supabase Bot commented Jul 22, 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 Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 17f63032-011d-49a5-812e-89f697d68701

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
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.
Description check ⚠️ Warning The description covers the refactor and testing, but it does not follow the required template or include the contributing confirmation section. Rewrite it to match the template, adding the YES/NO CONTRIBUTING confirmation, a change-type section, and explicit current/new behavior headings.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly describes the main change: generating the scoped PAT permission map from OpenAPI specs.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch scopedpat/scope-permissions-api

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.

@github-actions

github-actions Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results (tanstack)

passed  242 passed
flaky  1 flaky
skipped  5 skipped

Details

stats  248 tests across 29 suites
duration  4 minutes, 56 seconds
commit  22805d5

Flaky tests

Features › rls-policies.spec.ts › RLS Policies › Policies Page › should switch between schemas

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: 6

🧹 Nitpick comments (2)
apps/studio/data/scoped-access-tokens/keys.ts (1)

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

Add as const for consistency with the other key helpers.

The sibling helpers use as const; without it the key is inferred as string[] rather than a readonly tuple.

♻️ Proposed change
-  permissions: () => ['scoped-access-token-permissions'],
+  permissions: () => ['scoped-access-token-permissions'] as const,
🤖 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/data/scoped-access-tokens/keys.ts` at line 4, Update the
permissions key helper to append `as const`, matching the sibling key helpers
and preserving the key as a readonly tuple rather than widening it to string[].
apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.test.ts (1)

29-53: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider covering the v1+v2 merge path.

This exercises a single spec only; the array-merge dedup issue flagged in buildAPIPermissionScopeMap.ts lives in the mergeWith step and is currently untested. A case merging two specs that share a scope (with the static mcp_tools) would guard against duplicate entries.

🤖 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.test.ts`
around lines 29 - 53, Extend the test around getEndpointsAndMCPToolsForAPI to
pass v1 and v2 OpenAPI specs that share a scope, while retaining the static
mcp_tools input. Assert the merged endpoints, permissions, and mcp_tools contain
each shared entry only once, covering the mergeWith path in
buildAPIPermissionScopeMap.
🤖 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.ts`:
- Line 2: Remove the unused ensurePresent import from openai/core.mjs in
buildAPIPermissionScopeMap.ts, leaving the permission-map builder’s remaining
imports and implementation unchanged.
- Around line 16-40: Update mergeArrays used by buildAPIPermissionScopeMap to
concatenate array values while removing duplicate entries, including repeated
MCP tool entries from the shared mcp_tools_permissions_map. Preserve the
existing lodash.mergeWith behavior for non-array values and ensure both
top-level mcp_tools and nested scopes[*].mcp_tools are deduplicated.
- Around line 105-116: Update fetchAPIPermissionScope to throw
InternalServerError on non-OK responses, passing the upstream response.status
and its Retry-After header in details. Preserve the existing successful JSON
response path so route.ts can apply its status mapping and retry handling.

In `@apps/studio/app/api/scoped-access-token-permissions/route.ts`:
- Around line 57-60: Update the error message returned by the scoped token
permission route to include a verb, such as “generate” or “fetch,” so the
message reads grammatically while preserving the existing status code and
headers.

In
`@apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.tsx`:
- Line 54: Update NewScopedTokenForm’s useGetEnabledEndpointsForCapability
handling to distinguish undefined pending/error data from an authoritative empty
permissionScopeMap, showing an unavailable/loading state and preventing token
creation until the map is available. Add Vitest component coverage for both
pending and error query responses using MSW, with unhandled network requests
configured to fail.

In `@apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts`:
- Around line 159-176: Update the non-OK response handling to remove the copied
incident-status wording: change the console.error tag and ResponseError message
to accurately describe the permission-scope-map endpoint, while preserving the
existing status, retry-after parsing, and error propagation.

---

Nitpick comments:
In
`@apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.test.ts`:
- Around line 29-53: Extend the test around getEndpointsAndMCPToolsForAPI to
pass v1 and v2 OpenAPI specs that share a scope, while retaining the static
mcp_tools input. Assert the merged endpoints, permissions, and mcp_tools contain
each shared entry only once, covering the mergeWith path in
buildAPIPermissionScopeMap.

In `@apps/studio/data/scoped-access-tokens/keys.ts`:
- Line 4: Update the permissions key helper to append `as const`, matching the
sibling key helpers and preserving the key as a readonly tuple rather than
widening it to string[].
🪄 Autofix (Beta)

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: 75003e98-531c-4e57-b394-d2b128a3a76a

📥 Commits

Reviewing files that changed from the base of the PR and between cdeba36 and 06ef597.

⛔ Files ignored due to path filters (1)
  • apps/studio/routeTree.gen.ts is excluded by !**/routeTree.gen.ts
📒 Files selected for processing (18)
  • apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.test.ts
  • apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.ts
  • apps/studio/app/api/scoped-access-token-permissions/mcp_tools_permissions_map.json
  • apps/studio/app/api/scoped-access-token-permissions/route.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionRow.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionsAccordion.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.tsx
  • apps/studio/data/access-tokens/permission-scope-map.ts
  • apps/studio/data/scoped-access-tokens/keys.ts
  • apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts
  • apps/studio/data/scoped-access-tokens/permission-scope-map.json
  • apps/studio/lib/hosted-api-allowlist.ts
  • apps/studio/routes/api/scoped-access-token-permissions.ts
  • apps/studio/vite.config.ts
💤 Files with no reviewable changes (2)
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.tsx
  • apps/studio/data/access-tokens/permission-scope-map.ts

@alaister alaister 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 — ⚠️ passes, two minor issues

Ran through the scoped token flow on the studio-staging preview. No "To test" section on the PR, so I tested the flows this refactor touches: the permission map API route, the permissions accordion, the review step, and token create/delete end-to-end.

# Test Result
1 Open scoped token creation sheet ✅ Sheet opens with name, expiry, resource access, and permissions accordion
2 Permission map loads from new API route ✅ GET /dashboard/api/scoped-access-token-permissions → 200 with { scopes, endpoints, mcp_tools }; endpoint lists match what the UI renders. ⚠️ Minor: see note on duplicated mcp_tools arrays below
3 Permissions accordion populates ✅ Expanded Project, Database, and Account & Organization groups — all rows populated with risk markers (High/Medium/Low), no empty groups or stuck loading states
4 Review step renders selected permissions ✅ Selected Advisors·Read + Logs·Read → review listed exactly those capabilities and their endpoints, matching the API response verbatim; unselected scopes correctly absent. Dual-scope MCP enforcement also confirmed: get_advisors correctly hidden since it needs database_read too, while get_logs showed
5 Scoped token end-to-end (my addition) ✅ Created token, value displayed once, appeared in list, deleted cleanly
6 Classic token regression (my addition) ➖ Not testable — the page only offers the scoped flow now ("New tokens are now scoped" banner), no UI path to create a classic token. Assuming that's intentional

Issues found:

  1. mcp_tools arrays in the API response contain every scope twice, e.g. "get_advisors": ["advisors_read", "database_read", "advisors_read", "database_read"]. Looks like buildAPIPermissionScopeMap builds the map with the same mcp_tools_permissions_map.json for both v1 and v2 specs, then mergeWith array-concat merges the identical MCP maps together. Harmless for the "all scopes granted" check, but worth a dedupe.
  2. Step indicator is stuck on "Step 1 of 2 · Configure" on the review step — NewScopedTokenForm.tsx hardcodes <StepIndicator step={1} ... label="Configure" /> regardless of the step state. Pre-existing from an earlier PR in the stack, not introduced here — flagging since I was in there anyway.
test4-step-indicator-bug

Notes:

  • The unit tests in the diff are local-only, out of scope here.
  • Zero new console errors across the whole run.
  • Side effects: created and deleted one throwaway token (alaister-test-scoped-pat-pr48182); nothing else touched.

@djhi djhi changed the title Scoped PAT: refactor the scope permission map to be computed from live Scoped PAT: refactor the scope permission map to be computed from Open API specs Jul 27, 2026
@djhi
djhi changed the base branch from scopedpat/dead-code-cleanup to scopedpat/scoped-token-creation-tests July 27, 2026 13:06
@djhi
djhi force-pushed the scopedpat/scope-permissions-api branch from ca8ed6a to 452f2d5 Compare July 27, 2026 13:15
@djhi
djhi force-pushed the scopedpat/scope-permissions-api branch from 452f2d5 to bed5eac Compare July 27, 2026 14:26
@blacksmith-sh

This comment has been minimized.

Base automatically changed from scopedpat/scoped-token-creation-tests to scopedpat/root-branch July 29, 2026 12:13
@djhi
djhi requested a review from a team as a code owner July 29, 2026 12:13
@djhi

djhi commented Jul 29, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@@ -0,0 +1,174 @@
import { constants, permissions } from '@supabase/shared-types'

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This whole file is most probably temporary. Hopefully this will be provided by platform soom

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

Looks good! Just minor nits

Comment on lines +4 to +5
// We don't have an OpenAPI that describes mcp tools security requirements so
// we have this json file that must be updated when they change

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.

😢

}
}

export const buildAPIPermissionScopeMap = async (): Promise<PermissionScopeMap> => {

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.

Nit: could we mark things that can throw in JSDoc? This can throw because fetchAPIPermissionScope throws by design, but it requires a bit of plumbing to figure that out.

const NEXT_PUBLIC_API_DOMAIN = process.env.NEXT_PUBLIC_API_DOMAIN || 'https://api.supabase.com'

const fetchAPIPermissionScope = async (version: 'v1' | 'v2') => {
const response = await fetch(`${NEXT_PUBLIC_API_DOMAIN}/api/${version}-json`, {

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.

Should the fetch here be wrapped in a catch that produces an InternalServerError? Otherwise we're throwing both wrapped errors and low-level errors from this function.

@djhi

djhi commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@djhi
djhi merged commit 1e26457 into scopedpat/root-branch Jul 30, 2026
27 checks passed
@djhi
djhi deleted the scopedpat/scope-permissions-api branch July 30, 2026 13:42
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.

4 participants