Skip to content

Support creating multiple publishable keys, and deleting publishable keys - #41186

Merged
joshenlim merged 13 commits into
masterfrom
joshen/fe-2200-fix-inconsistencies-in-dashboard-publishable-and-secret-api
Dec 12, 2025
Merged

joshenlim merged 13 commits into
masterfrom
joshen/fe-2200-fix-inconsistencies-in-dashboard-publishable-and-secret-api

Conversation

@joshenlim

@joshenlim joshenlim commented Dec 9, 2025 •

Copy link
Copy Markdown
Member

Pending Infra PR: https://github.com/supabase/platform/pull/28246

Context

Update publishable keys UI to be consistent to that of secret keys. The dashboard implicitly presumes a single publishable key per project, but the API supports multiple, so the changes here are just to support that.

  • Support creating multiple publishable keys
  • Support deleting publishable keys
  • Only show "Create new API keys" CTA if there's no new API keys created (currently checks for if there's at least one publishable API key)
    • Also added empty state to Publishable API key section if there's secret keys
  • Add docs button to new API keys page
  • Do not close "Create new API keys" dialog until all keys are created

Before

image

After

image

Summary by CodeRabbit

  • New Features

    • Docs link added to API Keys settings; toasts displayed on key create/delete.
    • New publishable and secret key creation dialogs with form validation and reset.
  • UI/UX Improvements

    • API keys presented in a table; keys truncated with full value on hover.
    • Optional "Last seen" column, improved loading/deleting states, minor icon styling tweak, clearer permission messaging.
  • Refactor

    • Permission checks standardized to an async permission hook; several components converted to named exports.
  • Removals

    • Deprecated/coming-soon API keys banner removed.

✏️ Tip: You can customize this high-level summary in your review settings.

@joshenlim
joshenlim requested a review from a team as a code owner December 9, 2025 10:36
@vercel

vercel Bot commented Dec 9, 2025 •

Copy link
Copy Markdown

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

Project Deployment Preview Comments Updated (UTC)
studio-self-hosted Ready Ready Preview Comment Dec 12, 2025 6:47am
studio-staging Ready Ready Preview Comment Dec 12, 2025 6:47am
6 Skipped Deployments
Project Deployment Preview Comments Updated (UTC)
studio Ignored Ignored Dec 12, 2025 6:47am
cms Skipped Skipped Dec 12, 2025 6:47am
design-system Skipped Skipped Dec 12, 2025 6:47am
docs Skipped Skipped Dec 12, 2025 6:47am
ui-library Skipped Skipped Dec 12, 2025 6:47am
zone-www-dot-com Skipped Skipped Dec 12, 2025 6:47am

@supabase

supabase Bot commented Dec 9, 2025

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 ↗︎.

@coveralls

coveralls commented Dec 9, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 68.541%. remained the same
when pulling b460652 on joshen/fe-2200-fix-inconsistencies-in-dashboard-publishable-and-secret-api
into 9f3af6e on master.

@github-actions

github-actions Bot commented Dec 9, 2025 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results

passed  65 passed
flaky  2 flaky
skipped  4 skipped

Details

stats  71 tests across 12 suites
duration  10 minutes, 28 seconds
commit  b460652

Flaky tests

Features › auth-users.spec.ts › auth users list refresh › should automatically refresh users list after creating multiple users
Features › database.spec.ts › Database › Schema Visualizer › actions works as expected

Skipped tests

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

@joshenlim joshenlim added the do-not-merge Not ready to be merged yet; pending other dependencies label Dec 9, 2025
@kokoskiwi

Copy link
Copy Markdown

thank you @joshenlim for doing this
im the one who got burned last night

my discord post

make.com is a piece of crap and allows only the usage of supabases's publishable keys. therefore i disabled RLS. now i'm using auth in my app and suddenly had to disclose the publishable key in my front end, almost leaking my user data (i quickly enabled RLS). enabling RLS took down my make automations which took down my ecommerce store. Replacing the "official supabase nodes" with http nodes that use the secret key, will be a long ass task, so my best option is now: get a new publishable key, keep it secret, and make a 2nd supabase project just for auth. (im using the database anyway just for customer data that i never fetch).
for some reason i cant see how to rotate/replace the publishable key. please help me to replace it.
or tell me if its possible to let make.com use the secret keys instead of the publishable key.

@kokoskiwi

Copy link
Copy Markdown

btw you should punish make.com for advertising being "supabase compatible" which is not true. it caught me into this mess.

"You can use the Secret Key which is service_role to bypass RLS." this is not possible on make.com.
That's why i'm here in trouble. They allow only publishable key. This is not publicly disclosed. Users are lured into their platform, thinking they can build backend automations, while in reality, they are just building frontend client shit


const ApiKeyInput = () => {
const { ref: projectRef } = useParams()
{isLoadingApiKeys || isLoadingPermissions ? (

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.

if permissions are denied, I think this will show the generic skeleton loader forever because isLoadingApiKeys will always be true. We may need a separate state for isLoadingPermissions || (canReadApiKeys && isLoadingApiKeys) vs !canReadApiKeys (unless the latter branch is handled somewhere and I missed it)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

oh great catch this!

@blacksmith-sh

This comment has been minimized.

@joshenlim joshenlim removed the do-not-merge Not ready to be merged yet; pending other dependencies label Dec 11, 2025
@coderabbitai

coderabbitai Bot commented Dec 11, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Replaces a dedicated API-keys visibility hook with permission-based gating across many consumers, converts API key dialogs to named, URL/query-state-driven dialogs, switches key creation to async mutations with toasts, refactors publishable keys UI into a table with delete workflow, and applies import/path and small UI tweaks.

Changes

Cohort / File(s) Summary
Dialog components
apps/studio/components/interfaces/APIKeys/CreatePublishableAPIKeyDialog.tsx, apps/studio/components/interfaces/APIKeys/CreateSecretAPIKeyDialog.tsx
Converted to named exports; dialog open/close driven by URL/query-state (useQueryState string values); wired useAPIKeyCreateMutation with mutateAsync; form reset and close on success; updated triggers, labels, icons, and validation.
Creation button
apps/studio/components/interfaces/APIKeys/CreateNewAPIKeysButton.tsx
Switched from mutate to mutateAsync, added toast on success, replaced AlertDialogAction with Button, and handled loading via loading prop.
Publishable / Secret keys pages
apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx, apps/studio/components/interfaces/APIKeys/SecretAPIKeys.tsx
Reworked to use useAsyncCheckPermissions, loads permissions and api keys, renders table-based publishable UI with APIKeyRow, added delete workflow (useAPIKeyDeleteMutation) and toasts; adjusted secret delete query-state key.
Row / pill / delete UI
apps/studio/components/interfaces/APIKeys/APIKeyRow.tsx, apps/studio/components/interfaces/APIKeys/ApiKeyPill.tsx, apps/studio/components/interfaces/APIKeys/APIKeyDeleteDialog.tsx
APIKeyRow: added showLastSeen?: boolean, isLoadingLastSeen?: boolean (defaults) and widened first cell. ApiKeyPill: fixed import path and renders truncated key with title. APIKeyDeleteDialog: removed strokeWidth prop from Trash2 icon.
Visibility hook removal
apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts
Deleted the useApiKeysVisibility hook and its exported ApiKeysVisibilityState interface; removed associated visibility logic.
Widespread permission gating
multiple consumers
apps/studio/components/interfaces/..., apps/studio/components/interfaces/Docs/..., .../Functions/..., .../Storage/..., .../Integrations/..., .../ProjectAPIDocs/..., .../Realtime/..., .../JwtSecrets/..., .../Database/..., .../Home/..., .../UI/ProjectSettings/...
Replaced useApiKeysVisibility usage with useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*') across many files; maps { can: canReadAPIKeys } to gate useAPIKeysQuery and UI.
API/data and import fixes
apps/studio/data/api-keys/api-key-create-mutation.ts, apps/studio/data/api-keys/api-key-id-query.ts, apps/studio/data/api-keys/api-key-id-update-mutation.ts
Simplified APIKeyCreateVariables type to a direct union; fixed relative import paths for apiKeysKeys (./keys).
Layout & misc exports
apps/studio/components/layouts/APIKeys/APIKeysLayout.tsx, apps/studio/components/ui/AlertError.tsx, apps/studio/pages/project/[ref]/settings/api-keys/index.tsx, apps/studio/hooks/analytics/useLogsQuery.tsx
Added DocsButton secondary action to layout; minor whitespace cleanup in AlertError; switched DefaultLayout to a named import; useLogsQuery made a named export (also default-exported).
Illustrations & callouts
apps/studio/components/interfaces/APIKeys/ApiKeysIllustrations.tsx
Removed Github icon export and ApiKeysComingSoonBanner; converted some exported illustrations to internal constants and removed useApiKeysVisibility logic.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant User
    participant UI as Client UI
    participant QueryState as URL Query-State
    participant Perm as Permission Hook
    participant API as Server (queries/mutations)
    participant Toast

    User->>UI: Click "New publishable/secret key"
    UI->>QueryState: set visible = "publishable" / "secret"
    QueryState-->>UI: dialog opens when visible matches
    UI->>Perm: useAsyncCheckPermissions(SECRETS_READ, '*')
    Perm-->>UI: { can: true/false }
    alt can === true
        User->>UI: submit form
        UI->>API: mutateAsync createKey(payload)
        API-->>UI: success (key)
        UI->>Toast: show success toast
        UI->>QueryState: reset visible = ""
        UI->>UI: form.reset()
        UI->>API: invalidate/refetch keys
    else can === false
        UI-->>User: show NoPermission
    end

    User->>UI: Click delete on a key
    UI->>QueryState: set apiKeyToDelete = id
    UI->>UI: open delete dialog
    User->>UI: confirm delete
    UI->>API: mutate deleteKey(id)
    API-->>UI: success
    UI->>Toast: show deletion success
    UI->>API: invalidate/refetch keys
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Areas needing extra attention:
    • Removal of useApiKeysVisibility and ensuring all callers correctly use useAsyncCheckPermissions and adjust destructuring (from { canReadAPIKeys } to { can: canReadAPIKeys }).
    • Dialogs converted to URL/query-state: lifecycle, default/reset behavior, and routing edge-cases.
    • mutate -> mutateAsync conversions: error handling and finally/reset consistency.
    • Type narrowing in api-key-create-mutation and fixed import paths for apiKeysKeys.
    • Publishable keys table and delete workflow correctness (query-state selector, ref usage, toasts).
    • Export changes (named vs default) that may affect imports elsewhere.

Suggested reviewers

  • awaseem
  • ivasilov
  • pamelachia

Poem

🐰 I nibbled at hooks and chased permission light,
Dialogs now live where the URL's bright,
Mutations go async and toasts give a cheer,
Keys sit in a table — delete without fear,
A rabbit's small hop for the deploy tonight 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main changes: supporting creation of multiple publishable keys and deletion of publishable keys, which aligns with the primary objectives of the PR.
Description check ✅ Passed The description exceeds the template requirements by providing context, specific behavioral changes, before/after visuals, and an infra PR reference, making it comprehensive and informative despite not following the exact template structure.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch joshen/fe-2200-fix-inconsistencies-in-dashboard-publishable-and-secret-api

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8d03e04 and b460652.

📒 Files selected for processing (1)
  • apps/studio/components/interfaces/APIKeys/ApiKeysIllustrations.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/studio/components/interfaces/APIKeys/ApiKeysIllustrations.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: test
  • GitHub Check: typecheck
  • GitHub Check: test (1)

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

@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: 4

Caution

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

⚠️ Outside diff range comments (2)
apps/studio/data/api-keys/api-key-create-mutation.ts (1)

25-37: Bug: name on line 32 is not a valid identifier in this scope.

The ternary's else branch spreads name, which is not defined in the function scope. This will cause a runtime error or unintended behavior. Based on the context, this should likely be an empty object since name is already assigned on line 35.

       ...(payload.type === 'secret'
         ? {
             // secret_jwt_template: payload?.secret_jwt_template || null,
             secret_jwt_template: {
               role: 'service_role',
             },
           }
-        : name),
+        : {}),
 
       type: payload.type,
       name: payload.name,
       description: payload.description || null,
apps/studio/components/interfaces/APIKeys/CreateNewAPIKeysButton.tsx (1)

23-42: Sequential create flow looks good, but underlying createAPIKey implementation appears broken for non‑secret keys

The use of mutateAsync here to sequentially create the publishable and secret keys, wrapped in a try/catch/finally with isCreatingKeys and a success toast, matches the requirement to keep the dialog open until both keys are created and to reset state correctly.

However, the referenced implementation of createAPIKey in apps/studio/data/api-keys/api-key-create-mutation.ts currently includes:

body: {
  ...(payload.type === 'secret'
    ? {
        secret_jwt_template: {
          role: 'service_role',
        },
      }
    : name),
  type: payload.type,
  name: payload.name,
  description: payload.description || null,
}

If this is the actual code, name is an undefined identifier and will cause a runtime error whenever you call createAPIKey with type !== 'secret'—which would break the publishable‑key creation path used here.

Consider fixing that spread branch to something like:

-          ...(payload.type === 'secret'
-            ? {
-                secret_jwt_template: {
-                  role: 'service_role',
-                },
-              }
-            : name),
+          ...(payload.type === 'secret'
+            ? {
+                secret_jwt_template: {
+                  role: 'service_role',
+                },
+              }
+            : {}),

so the non‑secret case doesn’t reference an undefined symbol.

🧹 Nitpick comments (3)
apps/studio/components/interfaces/APIKeys/CreatePublishableAPIKeyDialog.tsx (1)

51-59: Use the defaultValues variable in form initialization.

The defaultValues variable is defined on line 51 but not used in the form's defaultValues option. Consider using it to avoid duplication.

  const defaultValues = { name: '', description: '' }

  const form = useForm<z.infer<typeof SCHEMA>>({
    resolver: zodResolver(SCHEMA),
-   defaultValues: {
-     name: '',
-     description: '',
-   },
+   defaultValues,
  })
apps/studio/components/interfaces/APIKeys/CreateNewAPIKeysButton.tsx (1)

45-62: Consider preventing dialog closure while isCreatingKeys is true

Right now the confirm button shows a loading state, but the user can still close the dialog via Cancel or backdrop/Escape while the two createAPIKey calls are in flight. That can leave them without clear feedback that work is still ongoing.

Consider guarding onOpenChange and/or disabling AlertDialogCancel while isCreatingKeys is true so the dialog only closes once the flow has either fully succeeded or failed.

apps/studio/components/interfaces/APIKeys/CreateSecretAPIKeyDialog.tsx (1)

48-64: Query‑param visibility + form reset flow look solid; async on onSubmit is unnecessary

Managing dialog visibility via useQueryState('new', parseAsString...) with the 'secret' sentinel, and wiring open={visible === 'secret'} / onOpenChange keeps this dialog shareable and aligned with the rest of the API keys UI. Reusing defaultValues both for useForm and form.reset after a successful mutation is also clean, and the success toast gives good feedback.

Tiny nit: onSubmit is declared async but only calls createAPIKey via the callback API and doesn’t await anything. You can drop the async keyword to avoid returning an unnecessary Promise from the submit handler:

-  const onSubmit: SubmitHandler<z.infer<typeof SCHEMA>> = async (values) => {
+  const onSubmit: SubmitHandler<z.infer<typeof SCHEMA>> = (values) => {

This is purely stylistic and won’t change behavior.

Also applies to: 68-81, 86-88

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6a6d2cb and 3dccaf3.

📒 Files selected for processing (17)
  • apps/studio/components/interfaces/APIKeys/APIKeyDeleteDialog.tsx (1 hunks)
  • apps/studio/components/interfaces/APIKeys/APIKeyRow.tsx (3 hunks)
  • apps/studio/components/interfaces/APIKeys/ApiKeyPill.tsx (2 hunks)
  • apps/studio/components/interfaces/APIKeys/CreateNewAPIKeysButton.tsx (3 hunks)
  • apps/studio/components/interfaces/APIKeys/CreatePublishableAPIKeyDialog.tsx (3 hunks)
  • apps/studio/components/interfaces/APIKeys/CreateSecretAPIKeyDialog.tsx (3 hunks)
  • apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx (1 hunks)
  • apps/studio/components/interfaces/APIKeys/SecretAPIKeys.tsx (6 hunks)
  • apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts (2 hunks)
  • apps/studio/components/layouts/APIKeys/APIKeysLayout.tsx (2 hunks)
  • apps/studio/components/ui/AlertError.tsx (0 hunks)
  • apps/studio/data/api-keys/api-key-create-mutation.ts (1 hunks)
  • apps/studio/data/api-keys/api-key-id-query.ts (1 hunks)
  • apps/studio/data/api-keys/api-key-id-update-mutation.ts (1 hunks)
  • apps/studio/hooks/analytics/useLogsQuery.tsx (1 hunks)
  • apps/studio/hooks/misc/useQueryStateWithSelect.ts (1 hunks)
  • apps/studio/pages/project/[ref]/settings/api-keys/index.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/studio/components/ui/AlertError.tsx
🧰 Additional context used
🧠 Learnings (14)
📚 Learning: 2025-12-11T02:40:11.135Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T02:40:11.135Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : UI components from packages/ui should be imported with _Shadcn_ suffix where applicable (e.g., Input_Shadcn_)

Applied to files:

  • apps/studio/pages/project/[ref]/settings/api-keys/index.tsx
  • apps/studio/components/interfaces/APIKeys/ApiKeyPill.tsx
  • apps/studio/data/api-keys/api-key-id-update-mutation.ts
  • apps/studio/components/interfaces/APIKeys/CreateSecretAPIKeyDialog.tsx
📚 Learning: 2025-12-11T02:40:11.135Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T02:40:11.135Z
Learning: Applies to apps/studio/pages/**/*.{ts,tsx} : Use PageLayout component for new page structures with props: children, title, subtitle, icon, breadcrumbs, primaryActions, secondaryActions, navigationItems, className, size, isCompact

Applied to files:

  • apps/studio/pages/project/[ref]/settings/api-keys/index.tsx
  • apps/studio/components/layouts/APIKeys/APIKeysLayout.tsx
📚 Learning: 2025-12-11T02:40:11.135Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T02:40:11.135Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Use typography classes from apps/studio/styles/typography.scss instead of hard-coding Tailwind classes (e.g., use 'heading-default' instead of 'text-sm font-medium')

Applied to files:

  • apps/studio/pages/project/[ref]/settings/api-keys/index.tsx
📚 Learning: 2025-12-11T02:40:11.135Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T02:40:11.135Z
Learning: Applies to apps/studio/pages/**/*.{ts,tsx} : Use related layout components (e.g., AuthLayout) when a page is within an existing section

Applied to files:

  • apps/studio/pages/project/[ref]/settings/api-keys/index.tsx
  • apps/studio/components/layouts/APIKeys/APIKeysLayout.tsx
📚 Learning: 2025-12-11T02:40:11.135Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T02:40:11.135Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Use _Shadcn_ form primitives (Form_Shadcn_, FormField_Shadcn_, FormControl_Shadcn_) and prefer FormItemLayout with layout='flex-row-reverse' for form controls

Applied to files:

  • apps/studio/pages/project/[ref]/settings/api-keys/index.tsx
  • apps/studio/components/interfaces/APIKeys/CreateSecretAPIKeyDialog.tsx
  • apps/studio/components/interfaces/APIKeys/CreatePublishableAPIKeyDialog.tsx
📚 Learning: 2025-12-11T02:40:11.135Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T02:40:11.135Z
Learning: Applies to apps/studio/pages/projects/[ref]/**/*.{ts,tsx} : Project-related pages should be organized in apps/studio/pages/projects/[ref]

Applied to files:

  • apps/studio/pages/project/[ref]/settings/api-keys/index.tsx
📚 Learning: 2025-12-11T02:40:11.135Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T02:40:11.135Z
Learning: Read packages/ui/index.tsx file for full list of available components before composing interfaces

Applied to files:

  • apps/studio/pages/project/[ref]/settings/api-keys/index.tsx
  • apps/studio/components/layouts/APIKeys/APIKeysLayout.tsx
📚 Learning: 2025-12-11T02:40:11.135Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T02:40:11.135Z
Learning: Applies to apps/studio/components/interfaces/**/*.{ts,tsx} : Studio-specific components related to individual pages should be placed in apps/studio/components/interfaces

Applied to files:

  • apps/studio/pages/project/[ref]/settings/api-keys/index.tsx
📚 Learning: 2025-12-11T02:40:11.135Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T02:40:11.135Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Use ScaffoldSection, ScaffoldSectionTitle, and ScaffoldSectionDescription for multi-section page layouts

Applied to files:

  • apps/studio/components/layouts/APIKeys/APIKeysLayout.tsx
📚 Learning: 2025-12-11T02:40:11.135Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T02:40:11.135Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Build forms with react-hook-form + zod

Applied to files:

  • apps/studio/components/interfaces/APIKeys/CreateSecretAPIKeyDialog.tsx
  • apps/studio/hooks/misc/useQueryStateWithSelect.ts
  • apps/studio/components/interfaces/APIKeys/CreatePublishableAPIKeyDialog.tsx
📚 Learning: 2025-12-11T02:40:11.135Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T02:40:11.135Z
Learning: Applies to apps/studio/components/interfaces/**/*.{ts,tsx} : Create a new component in apps/studio/components/interfaces for page contents

Applied to files:

  • apps/studio/components/interfaces/APIKeys/CreateSecretAPIKeyDialog.tsx
📚 Learning: 2025-12-11T02:40:11.135Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T02:40:11.135Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : When doing mutations with React Query, always use the mutate function with onSuccess and onError callbacks that include toast.success and toast.error

Applied to files:

  • apps/studio/hooks/misc/useQueryStateWithSelect.ts
  • apps/studio/components/interfaces/APIKeys/SecretAPIKeys.tsx
  • apps/studio/components/interfaces/APIKeys/CreateNewAPIKeysButton.tsx
📚 Learning: 2025-12-11T02:40:11.135Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T02:40:11.135Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Use mutateAsync only when the mutation is part of multiple async actions, wrapped in try/catch blocks with toast.success and toast.error

Applied to files:

  • apps/studio/hooks/misc/useQueryStateWithSelect.ts
  • apps/studio/components/interfaces/APIKeys/SecretAPIKeys.tsx
  • apps/studio/components/interfaces/APIKeys/CreateNewAPIKeysButton.tsx
📚 Learning: 2025-12-11T02:40:11.135Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T02:40:11.135Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Use generic ui table components for most tables, contained within a Card

Applied to files:

  • apps/studio/components/interfaces/APIKeys/SecretAPIKeys.tsx
🧬 Code graph analysis (6)
apps/studio/components/interfaces/APIKeys/ApiKeyPill.tsx (1)
apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts (1)
  • apiKey (728-739)
apps/studio/components/interfaces/APIKeys/APIKeyRow.tsx (2)
apps/studio/data/api-keys/api-keys-query.ts (1)
  • APIKeysData (67-67)
apps/studio/components/interfaces/APIKeys/ApiKeyPill.tsx (1)
  • ApiKeyPill (16-180)
apps/studio/components/layouts/APIKeys/APIKeysLayout.tsx (1)
apps/studio/lib/constants/index.ts (1)
  • DOCS_URL (48-48)
apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts (1)
apps/studio/data/api-keys/api-keys-query.ts (1)
  • useAPIKeysQuery (69-79)
apps/studio/components/interfaces/APIKeys/SecretAPIKeys.tsx (2)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/ui/NoPermission.tsx (1)
  • NoPermission (8-28)
apps/studio/components/interfaces/APIKeys/CreateNewAPIKeysButton.tsx (1)
apps/studio/data/api-keys/api-key-create-mutation.ts (2)
  • createAPIKey (14-42)
  • useAPIKeyCreateMutation (46-74)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: typecheck
  • GitHub Check: test
  • GitHub Check: test (1)
🔇 Additional comments (19)
apps/studio/data/api-keys/api-key-id-query.ts (1)

4-4: LGTM!

The import path normalization from ./../keys to ./keys is correct and improves readability.

apps/studio/data/api-keys/api-key-id-update-mutation.ts (1)

6-6: LGTM!

Consistent import path correction aligning with the same fix in api-key-id-query.ts.

apps/studio/hooks/misc/useQueryStateWithSelect.ts (1)

1-3: LGTM!

Import reordering is a non-functional change. The hook implementation correctly manages URL query state with proper memoization and error handling.

apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts (1)

19-22: Good documentation practice.

The deprecation note with reasoning helps future developers understand the intended direction for this code.

apps/studio/data/api-keys/api-key-create-mutation.ts (1)

8-12: LGTM on the type simplification.

The simplified union type is cleaner and sufficient for distinguishing between publishable and secret key types.

apps/studio/components/interfaces/APIKeys/APIKeyDeleteDialog.tsx (1)

37-37: LGTM!

Minor styling adjustment removing explicit strokeWidth from the Trash2 icon, allowing it to use default styling. No functional impact.

apps/studio/hooks/analytics/useLogsQuery.tsx (1)

34-38: LGTM!

Adding the named export while retaining the default export provides backward compatibility and supports the named import style used in SecretAPIKeys.tsx.

apps/studio/components/interfaces/APIKeys/ApiKeyPill.tsx (2)

129-131: LGTM!

Good improvement for non-secret keys: the title attribute enables full key visibility on hover, and truncate handles overflow gracefully within the constrained width container.


10-10: Import path is correctly updated.

The module api-key-id-query.ts exists at the new location data/api-keys/api-key-id-query, confirming the import path change from data/api-keys/[id]/api-key-id-query to data/api-keys/api-key-id-query is valid.

apps/studio/components/layouts/APIKeys/APIKeysLayout.tsx (1)

6-7: LGTM!

Adding documentation access via the DocsButton is a good UX improvement, providing users quick access to API keys guidance directly from the settings page.

Also applies to: 30-30

apps/studio/components/interfaces/APIKeys/APIKeyRow.tsx (2)

24-25: LGTM!

New optional props showLastSeen and isLoadingLastSeen with sensible defaults enable flexible control over the last-seen column visibility and loading state while maintaining backward compatibility.

Also applies to: 31-34


70-86: LGTM!

The dual condition showLastSeen && showApiKeysLastUsed correctly requires both the prop and the feature flag to be true before rendering the last-seen column.

apps/studio/components/interfaces/APIKeys/CreatePublishableAPIKeyDialog.tsx (1)

41-49: LGTM!

Query-state driven dialog visibility using nuqs is a good pattern that enables deep linking and shareable URLs. The 'publishable' value distinguishes this dialog from the secret key dialog.

Also applies to: 81-81

apps/studio/components/interfaces/APIKeys/SecretAPIKeys.tsx (4)

72-75: LGTM!

Good permission-gating pattern: the useAsyncCheckPermissions hook checks SECRETS_READ before enabling the API keys query, preventing unnecessary requests for unauthorized users.

Also applies to: 82-82


136-137: LGTM!

The NoPermission component provides clear user feedback when permissions are insufficient, with actionable guidance to contact an administrator.


103-109: LGTM!

Using a distinct query state key 'deleteSecretKey' prevents potential URL parameter conflicts with the publishable keys deletion flow.


26-26: The named export exists and the import is correct.

The import statement import { CreateSecretAPIKeyDialog } from './CreateSecretAPIKeyDialog' properly matches the named export export const CreateSecretAPIKeyDialog = () => { at line 48 of CreateSecretAPIKeyDialog.tsx.

apps/studio/pages/project/[ref]/settings/api-keys/index.tsx (1)

9-9: Verify the named export exists for DefaultLayout.

The import changed from default to named. Ensure DefaultLayout is actually exported as a named export from components/layouts/DefaultLayout.tsx. If it's only a default export, the import statement will fail at runtime.

apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx (1)

41-46: hasApiKeys logic correctly gates the “No publishable keys created yet” state

Deriving:

const newApiKeys = useMemo(
  () => apiKeysData.filter(({ type }) => type === 'publishable' || type === 'secret') ?? [],
  [apiKeysData]
)
const hasApiKeys = newApiKeys.length > 0

and then only showing the Admonition when hasApiKeys && publishableApiKeys.length === 0 means:

  • If there are some API keys (e.g. only secrets) but no publishable keys, the user sees the explicit “No publishable keys created yet” message.
  • If there are literally no API keys at all, the table stays empty and you can rely on the higher‑level CTA/empty‑state instead.

That matches the described behavior for the new publishable‑keys empty state.

Also applies to: 110-120

Comment on lines +56 to +83
// Track the ID being deleted to exclude it from error checking
const deletingAPIKeyIdRef = useRef<string | null>(null)

const { value: apiKeyToDelete, setValue: setAPIKeyToDelete } = useQueryStateWithSelect({
urlKey: 'deletePublishableKey',
select: (id: string) => (id ? publishableApiKeys?.find((key) => key.id === id) : undefined),
enabled: !!publishableApiKeys?.length,
onError: (_error, selectedId) => {
handleErrorOnDelete(deletingAPIKeyIdRef, selectedId, `API Key not found`)
},
})

const { mutate: deleteAPIKey, isPending: isDeletingAPIKey } = useAPIKeyDeleteMutation({
onSuccess: () => {
toast.success('Successfully deleted publishable key')
setAPIKeyToDelete(null)
},
onError: () => {
deletingAPIKeyIdRef.current = null
},
})

const onDeleteAPIKey = (apiKey: Extract<APIKeysData[number], { type: 'publishable' }>) => {
if (!projectRef) return console.error('Project ref is required')
if (!apiKey.id) return console.error('API key ID is required')
deletingAPIKeyIdRef.current = apiKey.id
deleteAPIKey({ projectRef, id: apiKey.id })
}

@coderabbitai coderabbitai Bot Dec 11, 2025 •

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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

fd -t f "APIKey.*Mutation\|useAPIKey" apps/studio --type ts --type tsx

Repository: supabase/supabase

Length of output: 230


🏁 Script executed:

find apps/studio -name "*APIKey*Mutation*" -o -name "*useAPIKey*" | head -20

Repository: supabase/supabase

Length of output: 43


🏁 Script executed:

rg "useAPIKeyDeleteMutation" apps/studio -A 5 -B 2

Repository: supabase/supabase

Length of output: 4223


🏁 Script executed:

cat -n apps/studio/data/api-keys/api-key-delete-mutation.ts

Repository: supabase/supabase

Length of output: 2065


🏁 Script executed:

rg "useAPIKeyCreateMutation" apps/studio/data/api-keys -A 30 | head -50

Repository: supabase/supabase

Length of output: 2435


🏁 Script executed:

sed -n '56,83p' apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx

Repository: supabase/supabase

Length of output: 1195


🏁 Script executed:

sed -n '56,83p' apps/studio/components/interfaces/APIKeys/SecretAPIKeys.tsx

Repository: supabase/supabase

Length of output: 777


🏁 Script executed:

rg "useAPIKeyDeleteMutation" apps/studio/components/interfaces/APIKeys/SecretAPIKeys.tsx -A 10

Repository: supabase/supabase

Length of output: 997


Add error toast to deletion onError callback to surface delete failures to users

The onError callback in useAPIKeyDeleteMutation only resets deletingAPIKeyIdRef without notifying the user of the failure. Because useAPIKeyDeleteMutation suppresses its default error toast when a callback is provided (as seen in the mutation implementation), a failed deletion will appear silent in the UI with the modal remaining open, leaving users unaware that the operation failed.

Update the callback to include error feedback:

const { mutate: deleteAPIKey, isPending: isDeletingAPIKey } = useAPIKeyDeleteMutation({
  onSuccess: () => {
    toast.success('Successfully deleted publishable key')
    setAPIKeyToDelete(null)
  },
  onError: (error) => {
    deletingAPIKeyIdRef.current = null
    toast.error(error.message ?? 'Failed to delete publishable key')
  },
})
🤖 Prompt for AI Agents
In apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx around lines
56 to 83, the onError callback for useAPIKeyDeleteMutation only clears
deletingAPIKeyIdRef and does not notify the user of a failed delete; update the
onError to both reset deletingAPIKeyIdRef.current = null and call toast.error
with the mutation error message (e.g., error.message) with a sensible fallback
like 'Failed to delete publishable key' so the UI surfaces the failure to users.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

intentional

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.

@joshenlim, understood — I'll respect that design decision. Thanks for clarifying!


🧠 Learnings used
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : When doing a mutation, always use the mutate function with onSuccess and onError callbacks that include toast.success and toast.error

Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use mutateAsync only if the mutation is part of multiple async actions, wrapping the call with try/catch block and adding toast.success and toast.error

Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/e2e-testing.mdc:0-0
Timestamp: 2025-12-11T16:46:03.665Z
Learning: Applies to e2e/studio/**/*.{ts,spec.ts} : Dismiss toasts before interacting with UI elements as they can overlay buttons and block interactions

@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

♻️ Duplicate comments (1)
apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx (1)

68-76: Surface delete failures (currently silent) and clear ref in all paths
onError only resets deletingAPIKeyIdRef and doesn’t notify users; delete failures will look like “nothing happened”. Also consider clearing the ref on success to avoid stale state.

 const { mutate: deleteAPIKey, isPending: isDeletingAPIKey } = useAPIKeyDeleteMutation({
   onSuccess: () => {
     toast.success('Successfully deleted publishable key')
+    deletingAPIKeyIdRef.current = null
     setAPIKeyToDelete(null)
   },
-  onError: () => {
+  onError: (error) => {
     deletingAPIKeyIdRef.current = null
+    toast.error(error?.message ?? 'Failed to delete publishable key')
   },
 })

Based on learnings, always include toast.success/toast.error in mutation callbacks.

🧹 Nitpick comments (2)
apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx (2)

41-54: Drop redundant ?? []/optional chaining around .filter()
apiKeysData already defaults to [], and .filter() always returns an array—so the fallbacks are dead code and add noise.

 const newApiKeys = useMemo(
-  () => apiKeysData.filter(({ type }) => type === 'publishable' || type === 'secret') ?? [],
+  () => apiKeysData.filter(({ type }) => type === 'publishable' || type === 'secret'),
   [apiKeysData]
 )

 const publishableApiKeys = useMemo(
   () =>
-    apiKeysData?.filter(
+    apiKeysData.filter(
       (key): key is Extract<APIKeysData[number], { type: 'publishable' }> =>
         key.type === 'publishable'
-    ) ?? [],
+    ),
   [apiKeysData]
 )

93-99: Prefer early-return branching over chained ternaries in JSX
This is readable today, but it tends to grow (permissions/loading/error/empty/etc.). Early returns would align better with the studio guideline for loading→error→empty→success.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3dccaf3 and 4618ddd.

📒 Files selected for processing (2)
  • apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx (1 hunks)
  • apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
apps/studio/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.{ts,tsx}: Assign complex conditions to descriptive variables instead of using multiple conditions in a single expression
Use consistent naming conventions for boolean variables: is prefix for state/identity, has prefix for possession, can prefix for capability/permission, should prefix for conditional behavior
Derive boolean state from existing state instead of storing it separately
Use early returns for guard clauses instead of deeply nested conditionals
Extract complex logic into custom hooks when logic becomes reusable or complex
Return objects from custom hooks instead of arrays for better extensibility and clearer API
Use discriminated unions for complex state management instead of multiple independent state fields
Avoid type casting (e.g., as any, as Type); instead validate values at runtime using zod schemas

Files:

  • apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx
  • apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts
apps/studio/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.tsx: Components should ideally be under 200-300 lines; break down large components with multiple distinct UI sections, complex conditional rendering, or multiple unrelated useState hooks
Extract repeated JSX patterns into reusable components instead of copying similar JSX blocks
Use consistent loading/error/success pattern: handle loading state first with early returns, then error state, then empty state, then render success state
Keep state as local as possible and only lift up when needed
Group related state using objects or reducers instead of multiple useState calls, preferring react-hook-form for form state management
Name event handlers consistently: use on prefix for prop callbacks and handle prefix for internal handlers
Avoid inline arrow functions for expensive operations; use useCallback to maintain stable function references
Use appropriate conditional rendering patterns: && for simple show/hide, ternary for binary choice, early returns or extracted components for multiple conditions
Avoid nested ternaries in JSX; use separate conditions or early returns instead
Use useMemo for expensive computations when the computation is genuinely expensive and the value is passed to memoized children
Define prop interfaces explicitly for React components with proper typing of props and callback handlers

Files:

  • apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx
🧠 Learnings (8)
📚 Learning: 2025-12-11T16:46:18.690Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.690Z
Learning: Applies to apps/studio/**/*.tsx : Use consistent loading/error/success pattern: handle loading state first with early returns, then error state, then empty state, then render success state

Applied to files:

  • apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : When doing a mutation, always use the mutate function with onSuccess and onError callbacks that include toast.success and toast.error

Applied to files:

  • apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use mutateAsync only if the mutation is part of multiple async actions, wrapping the call with try/catch block and adding toast.success and toast.error

Applied to files:

  • apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx
📚 Learning: 2025-12-11T16:46:03.665Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/e2e-testing.mdc:0-0
Timestamp: 2025-12-11T16:46:03.665Z
Learning: Applies to e2e/studio/**/*.{ts,spec.ts} : Dismiss toasts before interacting with UI elements as they can overlay buttons and block interactions

Applied to files:

  • apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Contain tables within a card

Applied to files:

  • apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use SheetHeader, SheetTitle, SheetSection, and SheetFooter for consistent sheet structure

Applied to files:

  • apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx
📚 Learning: 2025-12-11T16:46:18.690Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.690Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Return objects from custom hooks instead of arrays for better extensibility and clearer API

Applied to files:

  • apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts
📚 Learning: 2025-12-11T16:46:18.690Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.690Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Use consistent naming conventions for boolean variables: `is` prefix for state/identity, `has` prefix for possession, `can` prefix for capability/permission, `should` prefix for conditional behavior

Applied to files:

  • apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts
🧬 Code graph analysis (1)
apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts (1)
apps/studio/data/api-keys/api-keys-query.ts (1)
  • useAPIKeysQuery (69-79)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: test (1)
  • GitHub Check: typecheck
  • GitHub Check: test
🔇 Additional comments (2)
apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts (1)

30-41: Good: defaulting apiKeysData to [] avoids optional-chaining churn
This simplifies downstream filtering and keeps the hook’s return shape stable.

Also applies to: 42-49

apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.tsx (1)

110-130: Empty state behavior matches PR objective (show publishable empty when secrets exist)
hasApiKeys && publishableApiKeys.length === 0 correctly surfaces “No publishable keys created yet” when secret keys exist.

@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: 0

Caution

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

⚠️ Outside diff range comments (1)
apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts (1)

43-55: shouldDisableUI lacks permission check—add canReadAPIKeys to its logic

The hook exports shouldDisableUI = !hasNewApiKeys, but this doesn't verify canReadAPIKeys. In the api-keys page (line 22), the UI is wrapped with <DisableInteraction disabled={shouldDisableUI}>, which can enable the UI for users without read permissions. Update shouldDisableUI to also check canReadAPIKeys:

const shouldDisableUI = !canReadAPIKeys || !hasNewApiKeys

This ensures the UI remains disabled if either the user lacks permissions or no API keys have been created yet, aligning with the permission-gating logic already present in canInitApiKeys.

♻️ Duplicate comments (1)
apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts (1)

43-48: Inline comments mention “rollout/flag” but logic doesn’t—update to avoid misleading future changes
Also, please double-check whether shouldDisableUI should incorporate canReadAPIKeys (right now, lack of permission implies hasNewApiKeys === false → UI disabled). If consumers already gate on canReadAPIKeys, this is fine; otherwise it can create confusing states.

-  // Can initialize API keys when in rollout, has permissions, not loading, and no API keys yet
+  // Can initialize API keys when the user can read keys, we're not loading, and no keys exist yet
   const canInitApiKeys = canReadAPIKeys && !isLoadingApiKeys && !hasNewApiKeys

-  // Disable UI for publishable keys and secrets keys if flag is not enabled OR no API keys created yet
-  const shouldDisableUI = !hasNewApiKeys
+  // Disable UI until at least one key exists (permission-gate handled separately)
+  const shouldDisableUI = !hasNewApiKeys
🧹 Nitpick comments (3)
apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts (3)

16-21: Deprecation note is a bit “personal” and unclear on removal plan
Consider removing the personal tag ([Joshen]) and stating a concrete next step (e.g., “to be removed after X cleanup” / link an issue).


37-42: Naming: newApiKeys is slightly ambiguous
If these are “user-created”/“non-legacy” keys, consider createdApiKeys or managedApiKeys for readability.


49-55: Return shape is OK, but hasApiKeys now specifically means “has publishable or secret keys”
If any callers still interpret hasApiKeys as “has publishable keys”, consider renaming the field (or updating dependent UI copy) to prevent subtle regressions.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4618ddd and 4b1d9ad.

📒 Files selected for processing (1)
  • apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/studio/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.{ts,tsx}: Assign complex conditions to descriptive variables instead of using multiple conditions in a single expression
Use consistent naming conventions for boolean variables: is prefix for state/identity, has prefix for possession, can prefix for capability/permission, should prefix for conditional behavior
Derive boolean state from existing state instead of storing it separately
Use early returns for guard clauses instead of deeply nested conditionals
Extract complex logic into custom hooks when logic becomes reusable or complex
Return objects from custom hooks instead of arrays for better extensibility and clearer API
Use discriminated unions for complex state management instead of multiple independent state fields
Avoid type casting (e.g., as any, as Type); instead validate values at runtime using zod schemas

Files:

  • apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts
🧠 Learnings (3)
📚 Learning: 2025-12-11T16:46:18.690Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.690Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Return objects from custom hooks instead of arrays for better extensibility and clearer API

Applied to files:

  • apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts
📚 Learning: 2025-12-11T16:46:18.690Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.690Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Use consistent naming conventions for boolean variables: `is` prefix for state/identity, `has` prefix for possession, `can` prefix for capability/permission, `should` prefix for conditional behavior

Applied to files:

  • apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts
📚 Learning: 2025-12-12T05:20:17.409Z
Learnt from: joshenlim
Repo: supabase/supabase PR: 41258
File: apps/studio/pages/project/[ref]/storage/vectors/buckets/[bucketId].tsx:9-9
Timestamp: 2025-12-12T05:20:17.409Z
Learning: In apps/studio/**/*.{ts,tsx}, use named imports for DefaultLayout: import { DefaultLayout } from 'components/layouts/DefaultLayout' instead of default import. This is the new practice being adopted across the studio app.

Applied to files:

  • apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts
🧬 Code graph analysis (1)
apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts (1)
apps/studio/data/api-keys/api-keys-query.ts (1)
  • useAPIKeysQuery (69-79)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: test
  • GitHub Check: typecheck
  • GitHub Check: test (1)
🔇 Additional comments (1)
apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts (1)

29-35: enabled: canReadAPIKeys gating looks fine; verify canReadAPIKeys semantics while permissions load
If useAsyncCheckPermissions reports can: false while loading, this will defer the query (good). If it can transiently report can: true before settling, you may want enabled: canReadAPIKeys && !isLoadingPermissions for stability.

@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

Caution

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

⚠️ Outside diff range comments (1)
apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/index.tsx (1)

62-71: Fix blank/empty render while permissions are loading by including isLoadingCanReadAPIKeys in the loading gate.
As written, the component can show neither the skeleton nor the “no permission” banner while permissions are still resolving.

-  const isLoading =
-    isProjectLoading || isLoadingSigningKeys || isLoadingLegacyKey || isLoadingLegacyAPIKeysStatus
+  const isLoading =
+    isLoadingCanReadAPIKeys ||
+    isProjectLoading ||
+    isLoadingSigningKeys ||
+    isLoadingLegacyKey ||
+    isLoadingLegacyAPIKeysStatus

Also applies to: 167-183

🧹 Nitpick comments (3)
apps/studio/components/interfaces/Functions/TerminalInstructions.tsx (1)

1-1: Imports look fine; keep PermissionAction source stable across the app. If @supabase/shared-types/out/constants is considered an internal build output path, consider importing from a public entrypoint to reduce fragility during package refactors.

Also applies to: 13-13

apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx (1)

29-32: Unused variable: isLoadingPermissions.

The isLoading value is destructured as isLoadingPermissions but is not used anywhere in the visible code. Consider removing it to keep the code clean.

Apply this diff to remove the unused variable:

-  const { can: canReadAPIKeys, isLoading: isLoadingPermissions } = useAsyncCheckPermissions(
-    PermissionAction.SECRETS_READ,
-    '*'
-  )
+  const { can: canReadAPIKeys } = useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*')
apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/index.tsx (1)

62-77: Prefer scoping the permission check + query enablement to projectRef.
This avoids accidental checks against the wrong context and prevents queries firing if projectRef is temporarily unavailable.

-  const { can: canReadAPIKeys, isLoading: isLoadingCanReadAPIKeys } = useAsyncCheckPermissions(
-    PermissionAction.SECRETS_READ,
-    '*'
-  )
+  const { can: canReadAPIKeys, isLoading: isLoadingCanReadAPIKeys } = useAsyncCheckPermissions(
+    PermissionAction.SECRETS_READ,
+    '*',
+    undefined,
+    { projectRef }
+  )
+  const canFetchKeys = !!projectRef && canReadAPIKeys && !isLoadingCanReadAPIKeys

  const { data: signingKeys, isPending: isLoadingSigningKeys } = useJWTSigningKeysQuery(
    { projectRef },
-    { enabled: canReadAPIKeys }
+    { enabled: canFetchKeys }
  )
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4b1d9ad and 1fea667.

📒 Files selected for processing (21)
  • apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx (2 hunks)
  • apps/studio/components/interfaces/Database/Hooks/FormContents.tsx (2 hunks)
  • apps/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx (2 hunks)
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx (3 hunks)
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanelFields.tsx (2 hunks)
  • apps/studio/components/interfaces/Docs/Authentication.tsx (2 hunks)
  • apps/studio/components/interfaces/Docs/LangSelector.tsx (2 hunks)
  • apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx (1 hunks)
  • apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx (2 hunks)
  • apps/studio/components/interfaces/Functions/TerminalInstructions.tsx (3 hunks)
  • apps/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx (2 hunks)
  • apps/studio/components/interfaces/Integrations/CronJobs/HttpHeaderFieldsSection.tsx (2 hunks)
  • apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx (2 hunks)
  • apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/index.tsx (3 hunks)
  • apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx (1 hunks)
  • apps/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx (1 hunks)
  • apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx (2 hunks)
  • apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover.tsx (2 hunks)
  • apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/ConnectTablesDialog.tsx (3 hunks)
  • apps/studio/components/ui/ProjectSettings/ToggleLegacyApiKeys.tsx (1 hunks)
  • apps/studio/data/storage/iceberg-wrapper-create-mutation.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
apps/studio/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.{ts,tsx}: Assign complex conditions to descriptive variables instead of using multiple conditions in a single expression
Use consistent naming conventions for boolean variables: is prefix for state/identity, has prefix for possession, can prefix for capability/permission, should prefix for conditional behavior
Derive boolean state from existing state instead of storing it separately
Use early returns for guard clauses instead of deeply nested conditionals
Extract complex logic into custom hooks when logic becomes reusable or complex
Return objects from custom hooks instead of arrays for better extensibility and clearer API
Use discriminated unions for complex state management instead of multiple independent state fields
Avoid type casting (e.g., as any, as Type); instead validate values at runtime using zod schemas

Files:

  • apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx
  • apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/index.tsx
  • apps/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx
  • apps/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx
  • apps/studio/components/interfaces/Database/Hooks/FormContents.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanelFields.tsx
  • apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
  • apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx
  • apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx
  • apps/studio/components/interfaces/Functions/TerminalInstructions.tsx
  • apps/studio/components/interfaces/Integrations/CronJobs/HttpHeaderFieldsSection.tsx
  • apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover.tsx
  • apps/studio/data/storage/iceberg-wrapper-create-mutation.ts
  • apps/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx
  • apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx
  • apps/studio/components/ui/ProjectSettings/ToggleLegacyApiKeys.tsx
  • apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
  • apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/ConnectTablesDialog.tsx
  • apps/studio/components/interfaces/Docs/LangSelector.tsx
  • apps/studio/components/interfaces/Docs/Authentication.tsx
apps/studio/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.tsx: Components should ideally be under 200-300 lines; break down large components with multiple distinct UI sections, complex conditional rendering, or multiple unrelated useState hooks
Extract repeated JSX patterns into reusable components instead of copying similar JSX blocks
Use consistent loading/error/success pattern: handle loading state first with early returns, then error state, then empty state, then render success state
Keep state as local as possible and only lift up when needed
Group related state using objects or reducers instead of multiple useState calls, preferring react-hook-form for form state management
Name event handlers consistently: use on prefix for prop callbacks and handle prefix for internal handlers
Avoid inline arrow functions for expensive operations; use useCallback to maintain stable function references
Use appropriate conditional rendering patterns: && for simple show/hide, ternary for binary choice, early returns or extracted components for multiple conditions
Avoid nested ternaries in JSX; use separate conditions or early returns instead
Use useMemo for expensive computations when the computation is genuinely expensive and the value is passed to memoized children
Define prop interfaces explicitly for React components with proper typing of props and callback handlers

Files:

  • apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx
  • apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/index.tsx
  • apps/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx
  • apps/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx
  • apps/studio/components/interfaces/Database/Hooks/FormContents.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanelFields.tsx
  • apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
  • apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx
  • apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx
  • apps/studio/components/interfaces/Functions/TerminalInstructions.tsx
  • apps/studio/components/interfaces/Integrations/CronJobs/HttpHeaderFieldsSection.tsx
  • apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover.tsx
  • apps/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx
  • apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx
  • apps/studio/components/ui/ProjectSettings/ToggleLegacyApiKeys.tsx
  • apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
  • apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/ConnectTablesDialog.tsx
  • apps/studio/components/interfaces/Docs/LangSelector.tsx
  • apps/studio/components/interfaces/Docs/Authentication.tsx
🧠 Learnings (12)
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Build forms with react-hook-form and zod for validation

Applied to files:

  • apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanelFields.tsx
  • apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
  • apps/studio/components/interfaces/Integrations/CronJobs/HttpHeaderFieldsSection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
  • apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/ConnectTablesDialog.tsx
📚 Learning: 2025-12-11T16:46:18.690Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.690Z
Learning: Applies to apps/studio/**/*.tsx : Group related state using objects or reducers instead of multiple useState calls, preferring react-hook-form for form state management

Applied to files:

  • apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx
📚 Learning: 2025-12-11T02:39:45.932Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/docs-graphql.mdc:0-0
Timestamp: 2025-12-11T02:39:45.932Z
Learning: Applies to apps/docs/resources/**/[!Schema]*Resolver.ts : Use `supabase()` client for database operations with `convertPostgrestToApiError` for error handling in GraphQL resolvers

Applied to files:

  • apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx
  • apps/studio/components/interfaces/Database/Hooks/FormContents.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
📚 Learning: 2025-12-11T02:39:45.932Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/docs-graphql.mdc:0-0
Timestamp: 2025-12-11T02:39:45.932Z
Learning: Applies to apps/docs/resources/**/[!Schema]*Resolver.ts : Resolver functions in `{queryName}Resolver.ts` must use the Result class for error handling, import field selection utilities via `graphQLFields()`, and implement both a main resolve function and an implementation function separated by naming convention (e.g., `resolveNewQuery` and `resolveNewQueryImpl`)

Applied to files:

  • apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx
📚 Learning: 2025-12-12T05:20:17.409Z
Learnt from: joshenlim
Repo: supabase/supabase PR: 41258
File: apps/studio/pages/project/[ref]/storage/vectors/buckets/[bucketId].tsx:9-9
Timestamp: 2025-12-12T05:20:17.409Z
Learning: In apps/studio/**/*.{ts,tsx}, use named imports for DefaultLayout: import { DefaultLayout } from 'components/layouts/DefaultLayout' instead of default import. This is the new practice being adopted across the studio app.

Applied to files:

  • apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx
  • apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/index.tsx
  • apps/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx
  • apps/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx
  • apps/studio/components/interfaces/Database/Hooks/FormContents.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanelFields.tsx
  • apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
  • apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx
  • apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx
  • apps/studio/components/interfaces/Functions/TerminalInstructions.tsx
  • apps/studio/components/interfaces/Integrations/CronJobs/HttpHeaderFieldsSection.tsx
  • apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover.tsx
  • apps/studio/data/storage/iceberg-wrapper-create-mutation.ts
  • apps/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx
  • apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx
  • apps/studio/components/ui/ProjectSettings/ToggleLegacyApiKeys.tsx
  • apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
  • apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/ConnectTablesDialog.tsx
  • apps/studio/components/interfaces/Docs/LangSelector.tsx
  • apps/studio/components/interfaces/Docs/Authentication.tsx
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use mutateAsync only if the mutation is part of multiple async actions, wrapping the call with try/catch block and adding toast.success and toast.error

Applied to files:

  • apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/index.tsx
  • apps/studio/components/ui/ProjectSettings/ToggleLegacyApiKeys.tsx
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use Admonition component to alert users of important actions or restrictions

Applied to files:

  • apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/index.tsx
  • apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx
📚 Learning: 2025-12-11T16:46:18.690Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.690Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Use consistent naming conventions for boolean variables: `is` prefix for state/identity, `has` prefix for possession, `can` prefix for capability/permission, `should` prefix for conditional behavior

Applied to files:

  • apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx
  • apps/studio/components/ui/ProjectSettings/ToggleLegacyApiKeys.tsx
📚 Learning: 2025-12-11T02:39:45.932Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/docs-graphql.mdc:0-0
Timestamp: 2025-12-11T02:39:45.932Z
Learning: Applies to apps/docs/resources/**/[!Schema]*Model.ts : Data models in `{queryName}Model.ts` should be GraphQL-agnostic, containing only business logic and data fetching. They may import argument types from `~/__generated__/graphql` but should not import GraphQL-specific utilities outside of argument types

Applied to files:

  • apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use useFieldArray from react-hook-form for dynamic add/remove form fields

Applied to files:

  • apps/studio/components/interfaces/Integrations/CronJobs/HttpHeaderFieldsSection.tsx
📚 Learning: 2025-12-11T16:46:18.690Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.690Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Derive boolean state from existing state instead of storing it separately

Applied to files:

  • apps/studio/components/ui/ProjectSettings/ToggleLegacyApiKeys.tsx
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : When doing a mutation, always use the mutate function with onSuccess and onError callbacks that include toast.success and toast.error

Applied to files:

  • apps/studio/components/ui/ProjectSettings/ToggleLegacyApiKeys.tsx
🧬 Code graph analysis (20)
apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/index.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/Database/Hooks/FormContents.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanelFields.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/Integrations/CronJobs/HttpHeaderFieldsSection.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/data/storage/iceberg-wrapper-create-mutation.ts (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/ui/ProjectSettings/ToggleLegacyApiKeys.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/ConnectTablesDialog.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/Docs/LangSelector.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
apps/studio/components/interfaces/Docs/Authentication.tsx (1)
apps/studio/hooks/misc/useCheckPermissions.ts (1)
  • useAsyncCheckPermissions (139-190)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: test
  • GitHub Check: typecheck
  • GitHub Check: test (1)
🔇 Additional comments (22)
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx (2)

2-2: Confirm PermissionAction.SECRETS_READ is the right gate for “reveal: true” API keys
This ties “read secrets” permission to fetching revealed API keys; just verify that’s the intended permission boundary (vs a narrower API-keys-specific permission).

Also applies to: 22-22


134-140: The review comment is incorrect. The code is already safe and does not require the suggested fix.

The getKeys function is defined with a default parameter (apiKeys: APIKey[] = []), which means when apiKeys is undefined (as it would be when useAPIKeysQuery is disabled), the function safely defaults to an empty array. The .find() and .filter() calls operate on this empty array without throwing, returning undefined for each key property. Line 140's use of optional chaining (serviceKey?.api_key ?? '') further ensures safety when serviceKey is undefined.

The suggested fix getKeys(apiKeys ?? []) is redundant because getKeys already handles undefined internally via its default parameter.

apps/studio/data/storage/iceberg-wrapper-create-mutation.ts (1)

22-26: LGTM! Permission check migration follows established pattern.

The change correctly replaces the specialized permission hook with useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*') and follows the coding guidelines:

  • Uses the can prefix for capability/permission naming (canReadAPIKeys)
  • Properly gates the API keys query via the enabled flag
  • Aligns with the existing pattern already used for canCreateCredentials on lines 37-40

The permission check appropriately prevents fetching API keys until both permissions are loaded and the user has SECRETS_READ access.

Based on learnings, as per the broader migration pattern being adopted across the studio app, this replacement of specialized permission hooks with useAsyncCheckPermissions is the correct approach.

apps/studio/components/interfaces/Functions/TerminalInstructions.tsx (1)

37-38: The code is safe as-is and requires no changes.

The useAPIKeysQuery hook already handles the projectRef safety internally with the explicit check: enabled: enabled && typeof projectRef !== 'undefined'. This means the query will not execute if projectRef is undefined, regardless of the canReadAPIKeys flag. Additionally, the getKeys() function has a default parameter of [], making it safe when apiKeys is undefined.

The '*' resource parameter for PermissionAction.SECRETS_READ is the established pattern throughout the codebase (28+ consistent usages), not a security concern. No changes are needed.

Likely an incorrect or invalid review comment.

apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx (1)

86-86: LGTM - Consistent permission-based gating.

The migration from a visibility hook to useAsyncCheckPermissions with PermissionAction.SECRETS_READ properly gates API keys access based on user permissions. The boolean canReadAPIKeys follows the can prefix naming convention for capability checks and is correctly used to conditionally enable the API keys query.

apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx (1)

3-3: LGTM - Permission check properly integrated.

The addition of permission-based gating for API keys is correctly implemented. The canReadAPIKeys flag derived from useAsyncCheckPermissions appropriately controls data fetching in the GraphiQL tab.

Also applies to: 13-13, 26-26

apps/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx (1)

1-1: LGTM - Permission gating correctly applied.

The imports and permission check are properly added, and the canReadAPIKeys flag correctly gates the API keys query. This aligns with the broader refactoring to centralize permission checks across the codebase.

Also applies to: 3-4, 10-10, 18-19

apps/studio/components/ui/ProjectSettings/ToggleLegacyApiKeys.tsx (1)

33-33: LGTM - Consistent with permission-based access control.

The switch to useAsyncCheckPermissions maintains the same gating behavior while centralizing permission logic. The canReadAPIKeys boolean follows naming conventions and properly enables dependent queries.

Based on learnings, boolean variables should use the can prefix for capability/permission checks, which is correctly followed here.

apps/studio/components/interfaces/Integrations/CronJobs/HttpHeaderFieldsSection.tsx (1)

1-1: LGTM - Permission check properly implemented.

The migration to useAsyncCheckPermissions is consistent with the broader refactoring pattern. The permission-based gating correctly controls access to API keys data for HTTP header field population.

Also applies to: 7-7, 37-37

apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx (1)

2-2: LGTM - Permission-based access control applied correctly.

The addition of useAsyncCheckPermissions properly gates API keys access in the edge function tester. The canReadAPIKeys flag is correctly used to enable the query, maintaining secure access control.

Also applies to: 16-16, 92-93

apps/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx (1)

1-1: LGTM - Centralized permission checking implemented.

The refactoring to use useAsyncCheckPermissions properly replaces the previous visibility hook and maintains secure gating of API keys access. The implementation is consistent with the broader PR changes.

Also applies to: 12-12, 59-60

apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanelFields.tsx (1)

1-1: LGTM - Permission gating correctly integrated.

The migration to useAsyncCheckPermissions is properly implemented. The canReadAPIKeys flag appropriately controls API keys data fetching for destination panel fields, maintaining consistent permission-based access control.

Also applies to: 12-12, 126-130

apps/studio/components/interfaces/Realtime/Inspector/RealtimeTokensPopover.tsx (1)

1-1: LGTM! Permission-based gating correctly applied.

The migration from useApiKeysVisibility to useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*') is correct. The canReadAPIKeys value properly gates the API keys query, ensuring data is only fetched when the user has the necessary permissions.

Also applies to: 11-11, 28-34

apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/ConnectTablesDialog.tsx (1)

2-2: LGTM! Consistent permission-based access control.

The refactor from useApiKeysVisibility to useAsyncCheckPermissions is correctly implemented. The permission check properly gates API key data fetching via the enabled flag.

Also applies to: 24-24, 164-168

apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx (1)

94-104: LGTM! Permission-based gating for legacy API keys.

The addition of useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*') correctly gates access to legacy JWT signing keys and API keys status queries. The separation of concerns between JWT secret operations and API keys reading permissions is appropriate.

apps/studio/components/interfaces/Docs/Authentication.tsx (1)

1-1: LGTM! Permission check correctly applied.

The migration to useAsyncCheckPermissions properly gates API keys data access for the authentication documentation. The implementation is consistent with the broader permission-based access control pattern.

Also applies to: 7-7, 18-19

apps/studio/components/interfaces/Database/Hooks/FormContents.tsx (1)

2-2: LGTM! Permission check properly integrated.

The refactor to useAsyncCheckPermissions correctly gates API keys data fetching. The permission check ensures that the service role key is only accessed when the user has appropriate read permissions.

Also applies to: 10-10, 55-59

apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx (1)

1-1: LGTM! Permission-based gating correctly applied.

The migration to useAsyncCheckPermissions properly gates API keys access for the command menu. The implementation correctly enables the API keys query based on permission check results.

Also applies to: 6-6, 34-37

apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx (1)

1-1: LGTM! Permission check with appropriate compound condition.

The refactor to useAsyncCheckPermissions correctly gates API keys data access. The compound enabled condition (snap.showProjectApiDocs && canReadAPIKeys) appropriately ensures data is only fetched when both the docs panel is open and the user has read permissions.

Also applies to: 9-9, 48-51

apps/studio/components/interfaces/Docs/LangSelector.tsx (1)

1-1: LGTM! Permission-based gating correctly implemented.

The migration to useAsyncCheckPermissions properly controls API keys data access and UI visibility. The canReadAPIKeys flag is correctly used both to gate the query and to conditionally render the key selector UI (line 80).

Also applies to: 8-8, 38-44

apps/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx (1)

1-1: Verify PermissionAction.SECRETS_READ is the intended gate for “API keys read”.
If API keys have a narrower/different permission than “secrets”, this could unintentionally over/under-authorize the query.

Also applies to: 10-10

apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/index.tsx (1)

1-1: Verify PermissionAction.SECRETS_READ is the correct permission for JWT signing keys visibility.
(Especially if “signing keys” and “API keys/secrets” permissions differ.)

Also applies to: 62-65

@@ -1,12 +1,13 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'

@coderabbitai coderabbitai Bot Dec 12, 2025 •

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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

find apps/studio/components/interfaces/Database -name "*HTTP*" -type f 2>/dev/null

Repository: supabase/supabase

Length of output: 131


🏁 Script executed:

git ls-files "apps/studio/components/interfaces/Database/Hooks/*"

Repository: supabase/supabase

Length of output: 699


🏁 Script executed:

# Check if Hooks directory exists and what files are in it
ls -la apps/studio/components/interfaces/Database/Hooks/ 2>/dev/null || echo "Directory not found"

Repository: supabase/supabase

Length of output: 588


🏁 Script executed:

# Try a broader search
fd "HTTP" apps/studio/components/interfaces/Database 2>/dev/null | head -20

Repository: supabase/supabase

Length of output: 131


🏁 Script executed:

cat -n apps/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx

Repository: supabase/supabase

Length of output: 12725


🏁 Script executed:

# Find useAsyncCheckPermissions hook
fd "useCheckPermissions" apps/studio -type f | head -5

Repository: supabase/supabase

Length of output: 231


🏁 Script executed:

# Find useAPIKeysQuery hook
fd "api-keys-query" apps/studio -type f | head -5

Repository: supabase/supabase

Length of output: 231


🏁 Script executed:

fd "useCheckPermissions" apps/studio

Repository: supabase/supabase

Length of output: 106


🏁 Script executed:

fd "api-keys-query" apps/studio

Repository: supabase/supabase

Length of output: 153


🏁 Script executed:

cat -n apps/studio/hooks/misc/useCheckPermissions.ts

Repository: supabase/supabase

Length of output: 7537


🏁 Script executed:

cat -n apps/studio/data/api-keys/api-keys-query.ts | head -100

Repository: supabase/supabase

Length of output: 3320


Guard API keys query with !!ref and scope permission check to the current project.

Right now useAsyncCheckPermissions(...) isn't explicitly scoped to ref, and useAPIKeysQuery can be enabled purely by canReadAPIKeys even if ref is momentarily falsy/undefined or permissions are still loading.

-  const { can: canReadAPIKeys } = useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*')
+  const { can: canReadAPIKeys, isLoading: isLoadingCanReadAPIKeys } = useAsyncCheckPermissions(
+    PermissionAction.SECRETS_READ,
+    '*',
+    undefined,
+    { projectRef: ref }
+  )
+  const canFetchAPIKeys = !!ref && canReadAPIKeys && !isLoadingCanReadAPIKeys

   const { data: apiKeys } = useAPIKeysQuery(
     { projectRef: ref, reveal: true },
-    { enabled: canReadAPIKeys }
+    { enabled: canFetchAPIKeys }
   )

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/studio/components/interfaces/Database/Hooks/HTTPRequestFields.tsx around
line 1, the API keys query is being enabled solely by canReadAPIKeys which can
be true while ref is falsy or permissions are still loading; scope
useAsyncCheckPermissions to the current project ref and guard the API keys query
with a strict ref check. Update the permission hook call to pass the project ref
(e.g., useAsyncCheckPermissions(ref, PermissionAction.API_KEYS_READ) or
equivalent) and only enable useAPIKeysQuery when !!ref && canReadAPIKeys (and
permissions have finished loading if applicable), ensuring the query never runs
for an undefined ref or wrong project.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

this looks wrong - ignore

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.

@joshenlim, understood — I'll disregard that suggestion. Thanks for the clarification!


🧠 Learnings used
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use useFieldArray from react-hook-form for dynamic add/remove form fields

Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Build forms with react-hook-form and zod for validation

Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.690Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Return objects from custom hooks instead of arrays for better extensibility and clearer API

@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/components/interfaces/APIKeys/ApiKeysIllustrations.tsx (1)

48-87: Hide decorative mock-key table from screen readers

ApiKeysTableIllustration renders a real table with mock-looking API keys. Even with pointer-events-none, assistive tech can still read it, which is confusing (and “fake keys” are noisy). Consider marking the illustration subtree as decorative via aria-hidden.

-  return (
-    <Card className="w-full overflow-hidden opacity-60 pointer-events-none bg-surface-100">
+  return (
+    <Card
+      aria-hidden="true"
+      className="w-full overflow-hidden opacity-60 pointer-events-none bg-surface-100"
+    >
       <CardContent className="p-0">
         <Table className="p-5">
🧹 Nitpick comments (3)
apps/studio/components/interfaces/APIKeys/ApiKeysIllustrations.tsx (1)

92-108: Also consider aria-hidden for the overlay wrapper

Since ApiKeysIllustrationWithOverlay is purely presentational, marking its root as decorative helps prevent SR focus/readout of absolutely-positioned content.

apps/studio/pages/project/[ref]/settings/api-keys/index.tsx (2)

30-35: Consider whether useMemo is buying anything here (optional simplification).
The filter is cheap; if you keep it, it’s fine—just noting it’s not likely needed unless apiKeysData is large / this component re-renders frequently.


38-44: UX/permissions: components still render when canReadAPIKeys is false (but disabled), which can be confusing and/or cause duplicate fetching.
If PublishableAPIKeys / SecretAPIKeys also fetch internally, this page now does an extra query just for hasNewApiKeys. Consider either:

  • hiding the whole section behind canReadAPIKeys, or
  • passing apiKeysData down (or sharing via a context) to avoid redundant queries.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1fea667 and 8d03e04.

📒 Files selected for processing (3)
  • apps/studio/components/interfaces/APIKeys/ApiKeysIllustrations.tsx (5 hunks)
  • apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts (0 hunks)
  • apps/studio/pages/project/[ref]/settings/api-keys/index.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/studio/components/interfaces/APIKeys/hooks/useApiKeysVisibility.ts
🧰 Additional context used
📓 Path-based instructions (2)
apps/studio/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.{ts,tsx}: Assign complex conditions to descriptive variables instead of using multiple conditions in a single expression
Use consistent naming conventions for boolean variables: is prefix for state/identity, has prefix for possession, can prefix for capability/permission, should prefix for conditional behavior
Derive boolean state from existing state instead of storing it separately
Use early returns for guard clauses instead of deeply nested conditionals
Extract complex logic into custom hooks when logic becomes reusable or complex
Return objects from custom hooks instead of arrays for better extensibility and clearer API
Use discriminated unions for complex state management instead of multiple independent state fields
Avoid type casting (e.g., as any, as Type); instead validate values at runtime using zod schemas

Files:

  • apps/studio/components/interfaces/APIKeys/ApiKeysIllustrations.tsx
  • apps/studio/pages/project/[ref]/settings/api-keys/index.tsx
apps/studio/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.tsx: Components should ideally be under 200-300 lines; break down large components with multiple distinct UI sections, complex conditional rendering, or multiple unrelated useState hooks
Extract repeated JSX patterns into reusable components instead of copying similar JSX blocks
Use consistent loading/error/success pattern: handle loading state first with early returns, then error state, then empty state, then render success state
Keep state as local as possible and only lift up when needed
Group related state using objects or reducers instead of multiple useState calls, preferring react-hook-form for form state management
Name event handlers consistently: use on prefix for prop callbacks and handle prefix for internal handlers
Avoid inline arrow functions for expensive operations; use useCallback to maintain stable function references
Use appropriate conditional rendering patterns: && for simple show/hide, ternary for binary choice, early returns or extracted components for multiple conditions
Avoid nested ternaries in JSX; use separate conditions or early returns instead
Use useMemo for expensive computations when the computation is genuinely expensive and the value is passed to memoized children
Define prop interfaces explicitly for React components with proper typing of props and callback handlers

Files:

  • apps/studio/components/interfaces/APIKeys/ApiKeysIllustrations.tsx
  • apps/studio/pages/project/[ref]/settings/api-keys/index.tsx
🧠 Learnings (6)
📚 Learning: 2025-12-11T17:04:40.001Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.001Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Do not introduce new UI components unless asked to; check packages/ui/index.tsx for available components before composing interfaces

Applied to files:

  • apps/studio/components/interfaces/APIKeys/ApiKeysIllustrations.tsx
📚 Learning: 2025-12-11T00:21:01.839Z
Learnt from: dnywh
Repo: supabase/supabase PR: 41215
File: apps/design-system/content/docs/accessibility.mdx:30-30
Timestamp: 2025-12-11T00:21:01.839Z
Learning: In apps/design-system/content/docs/, MDX files use different relative path formats based on their location: root-level docs use `components/button` format, while subdirectory docs (ui-patterns/, components/) use `../components/button` format for linking to components.

Applied to files:

  • apps/studio/components/interfaces/APIKeys/ApiKeysIllustrations.tsx
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Contain tables within a card

Applied to files:

  • apps/studio/components/interfaces/APIKeys/ApiKeysIllustrations.tsx
📚 Learning: 2025-12-12T05:20:17.409Z
Learnt from: joshenlim
Repo: supabase/supabase PR: 41258
File: apps/studio/pages/project/[ref]/storage/vectors/buckets/[bucketId].tsx:9-9
Timestamp: 2025-12-12T05:20:17.409Z
Learning: In apps/studio/**/*.{ts,tsx}, use named imports for DefaultLayout: import { DefaultLayout } from 'components/layouts/DefaultLayout' instead of default import. This is the new practice being adopted across the studio app.

Applied to files:

  • apps/studio/components/interfaces/APIKeys/ApiKeysIllustrations.tsx
  • apps/studio/pages/project/[ref]/settings/api-keys/index.tsx
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/pages/**/*.{ts,tsx} : Use related layout components (e.g., AuthLayout) for pages within existing sections

Applied to files:

  • apps/studio/pages/project/[ref]/settings/api-keys/index.tsx
📚 Learning: 2025-12-11T17:04:40.002Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/pages/**/*.{ts,tsx} : When creating a new page, use the PageLayout component with appropriate props (title, subtitle, icon, breadcrumbs, primaryActions, secondaryActions, navigationItems, className, size, isCompact)

Applied to files:

  • apps/studio/pages/project/[ref]/settings/api-keys/index.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: test
  • GitHub Check: typecheck
  • GitHub Check: test (1)
🔇 Additional comments (4)
apps/studio/components/interfaces/APIKeys/ApiKeysIllustrations.tsx (2)

110-124: Permission gating is properly implemented at the call site — ApiKeysCreateCallout is guarded by canReadAPIKeys && !hasNewApiKeys (where canReadAPIKeys comes from useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*')), and ApiKeysFeedbackBanner is guarded by hasNewApiKeys. Users without SECRETS_READ permission won't see the create prompt.


1-7: Add aria-hidden="true" to decorative table illustration to prevent screen reader exposure of mock API keys

The ApiKeysTableIllustration component renders a real <Table> with mock API key data styled as decorative (pointer-events-none, opacity-60), but it's not hidden from assistive technologies. Add aria-hidden="true" to the root element to prevent screen readers from reading the fake key material.

InlineLink already handles external link security correctly—it auto-applies target="_blank" and rel="noreferrer noopener" for HTTP/HTTPS URLs. Parent components are properly gated by canReadAPIKeys permission.

⛔ Skipped due to learnings
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/components/interfaces/**/*.{ts,tsx} : Add table actions to the right of ScaffoldSectionTitle if table is main content of a page section without search or filters
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.002Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Use focus styles from apps/studio/styles/focus.scss for keyboard navigation consistency instead of hard-coding focus classes
apps/studio/pages/project/[ref]/settings/api-keys/index.tsx (2)

10-10: Good: switch to named DefaultLayout import aligns with current Studio practice.

Also applies to: 49-55


21-21: Reconsider permission model consistency for publishable vs. secret API keys.

The page gates reading and UI visibility with PermissionAction.SECRETS_READ, but deletion requires PermissionAction.TENANT_SQL_ADMIN_WRITE (admin-level permission). This creates inconsistent UX where users might see keys but can't delete them, or vice versa. Additionally, publishable API keys (intended for public use) arguably shouldn't require SECRETS_READ permission to create or view. Consider whether publishable keys should use a separate permission model from secret keys, or whether a single SECRETS_WRITE permission should gate both creation and deletion alongside SECRETS_READ for visibility.

Comment on lines 136 to 143
We've updated our API keys to better support your application needs.{' '}
<a
<InlineLink
href="https://github.com/orgs/supabase/discussions/29260"
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 text-foreground"
className="inline-flex items-center gap-1 "
>
Join the discussion on GitHub <ExternalLink size={14} strokeWidth={1.5} />
</a>
</InlineLink>
</p>

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.

⚠️ Potential issue | 🟡 Minor

Tighten external link markup (and remove trailing class whitespace)

Minor: className="inline-flex items-center gap-1 " has a trailing space. Also consider aria-hidden on the icon if it’s decorative, and (if not handled by InlineLink) pass target/rel for GitHub.

           <InlineLink
             href="https://github.com/orgs/supabase/discussions/29260"
-            className="inline-flex items-center gap-1 "
+            className="inline-flex items-center gap-1"
+            target="_blank"
+            rel="noopener noreferrer"
           >
-            Join the discussion on GitHub <ExternalLink size={14} strokeWidth={1.5} />
+            Join the discussion on GitHub{' '}
+            <ExternalLink aria-hidden="true" focusable="false" size={14} strokeWidth={1.5} />
           </InlineLink>

(Only add target/rel if InlineLink doesn’t already enforce them.)

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
We've updated our API keys to better support your application needs.{' '}
<a
<InlineLink
href="https://github.com/orgs/supabase/discussions/29260"
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 text-foreground"
className="inline-flex items-center gap-1 "
>
Join the discussion on GitHub <ExternalLink size={14} strokeWidth={1.5} />
</a>
</InlineLink>
</p>
We've updated our API keys to better support your application needs.{' '}
<InlineLink
href="https://github.com/orgs/supabase/discussions/29260"
className="inline-flex items-center gap-1"
target="_blank"
rel="noopener noreferrer"
>
Join the discussion on GitHub{' '}
<ExternalLink aria-hidden="true" focusable="false" size={14} strokeWidth={1.5} />
</InlineLink>
</p>
🤖 Prompt for AI Agents
In apps/studio/components/interfaces/APIKeys/ApiKeysIllustrations.tsx around
lines 136 to 143, tighten the external link markup by removing the trailing
whitespace in className ("inline-flex items-center gap-1 "), mark the
ExternalLink icon as decorative with aria-hidden="true" (or provide an
accessible label if it’s meaningful), and ensure the link opens safely in a new
tab by adding target="_blank" and rel="noopener noreferrer" only if the
InlineLink component does not already enforce those attributes — verify
InlineLink’s implementation first and add the attributes here only when needed.

Comment on lines +20 to +28
const { ref: projectRef } = useParams()
const { can: canReadAPIKeys } = useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*')
const { data: apiKeysData = [] } = useAPIKeysQuery(
{
projectRef,
reveal: false,
},
{ enabled: canReadAPIKeys }
)

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.

⚠️ Potential issue | 🟠 Major

Guard useAPIKeysQuery against projectRef being undefined (avoid firing query with invalid params).
Right now enabled: canReadAPIKeys can still run the query if permissions resolve before projectRef is available (route params can be transiently undefined), which can lead to noisy errors / bad cache keys.

 const ApiKeysNewPage: NextPageWithLayout = () => {
   const { ref: projectRef } = useParams()
   const { can: canReadAPIKeys } = useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*')
+  const hasProjectRef = typeof projectRef === 'string' && projectRef.length > 0
   const { data: apiKeysData = [] } = useAPIKeysQuery(
     {
       projectRef,
       reveal: false,
     },
-    { enabled: canReadAPIKeys }
+    { enabled: canReadAPIKeys && hasProjectRef }
   )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const { ref: projectRef } = useParams()
const { can: canReadAPIKeys } = useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*')
const { data: apiKeysData = [] } = useAPIKeysQuery(
{
projectRef,
reveal: false,
},
{ enabled: canReadAPIKeys }
)
const { ref: projectRef } = useParams()
const { can: canReadAPIKeys } = useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*')
const hasProjectRef = typeof projectRef === 'string' && projectRef.length > 0
const { data: apiKeysData = [] } = useAPIKeysQuery(
{
projectRef,
reveal: false,
},
{ enabled: canReadAPIKeys && hasProjectRef }
)
🤖 Prompt for AI Agents
In apps/studio/pages/project/[ref]/settings/api-keys/index.tsx around lines 20
to 28, the useAPIKeysQuery can be triggered with an undefined projectRef because
enabled only depends on canReadAPIKeys; update the guard so the query only runs
when both permissions are granted and projectRef is defined. Either include
projectRef truthiness in the enabled option (e.g. enabled: canReadAPIKeys &&
!!projectRef) or early-return / skip calling useAPIKeysQuery until projectRef
exists, ensuring queries are not fired with invalid params and avoiding noisy
errors/bad cache keys.

@blacksmith-sh

This comment has been minimized.

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