Repository navigation
Scoped PAT: refactor the scope permission map to be computed from Open API specs - #48182
Conversation
…coped-token-creation-tests
|
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. |
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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 |
🎭 Playwright Test Results (tanstack)Details
Flaky testsFeatures › rls-policies.spec.ts › RLS Policies › Policies Page › should switch between schemas Skipped testsFeatures › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (2)
apps/studio/data/scoped-access-tokens/keys.ts (1)
4-4: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd
as constfor consistency with the other key helpers.The sibling helpers use
as const; without it the key is inferred asstring[]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 winConsider covering the v1+v2 merge path.
This exercises a single spec only; the array-merge dedup issue flagged in
buildAPIPermissionScopeMap.tslives in themergeWithstep and is currently untested. A case merging two specs that share a scope (with the staticmcp_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
⛔ Files ignored due to path filters (1)
apps/studio/routeTree.gen.tsis excluded by!**/routeTree.gen.ts
📒 Files selected for processing (18)
apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.test.tsapps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.tsapps/studio/app/api/scoped-access-token-permissions/mcp_tools_permissions_map.jsonapps/studio/app/api/scoped-access-token-permissions/route.tsapps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.tsapps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.tsxapps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsxapps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionRow.tsxapps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionsAccordion.tsxapps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsxapps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.tsxapps/studio/data/access-tokens/permission-scope-map.tsapps/studio/data/scoped-access-tokens/keys.tsapps/studio/data/scoped-access-tokens/permission-scope-map-query.tsapps/studio/data/scoped-access-tokens/permission-scope-map.jsonapps/studio/lib/hosted-api-allowlist.tsapps/studio/routes/api/scoped-access-token-permissions.tsapps/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
There was a problem hiding this comment.
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. 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:
mcp_toolsarrays in the API response contain every scope twice, e.g."get_advisors": ["advisors_read", "database_read", "advisors_read", "database_read"]. Looks likebuildAPIPermissionScopeMapbuilds the map with the samemcp_tools_permissions_map.jsonfor both v1 and v2 specs, thenmergeWitharray-concat merges the identical MCP maps together. Harmless for the "all scopes granted" check, but worth a dedupe.- Step indicator is stuck on "Step 1 of 2 · Configure" on the review step —
NewScopedTokenForm.tsxhardcodes<StepIndicator step={1} ... label="Configure" />regardless of thestepstate. Pre-existing from an earlier PR in the stack, not introduced here — flagging since I was in there anyway.
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.
ca8ed6a to
452f2d5
Compare
452f2d5 to
bed5eac
Compare
This comment has been minimized.
This comment has been minimized.
|
@coderabbitai review |
✅ Action performedReview finished.
|
| @@ -0,0 +1,174 @@ | |||
| import { constants, permissions } from '@supabase/shared-types' | |||
There was a problem hiding this comment.
This whole file is most probably temporary. Hopefully this will be provided by platform soom
charislam
left a comment
There was a problem hiding this comment.
Looks good! Just minor nits
| // 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 |
| } | ||
| } | ||
|
|
||
| export const buildAPIPermissionScopeMap = async (): Promise<PermissionScopeMap> => { |
There was a problem hiding this comment.
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`, { |
There was a problem hiding this comment.
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.
|
@coderabbitai review |
✅ Action performedReview finished.
|
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
Bug Fixes
Tests