Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

fix(self-hosted): reveal and copy secret api key in project settings (#46592)

Andrey A.b28f91741f10
diff --git a/apps/studio/components/interfaces/APIKeys/ApiKeyPill.test.tsx b/apps/studio/components/interfaces/APIKeys/ApiKeyPill.test.tsx
new file mode 100644
index 00000000000..bff0ed53f46
--- /dev/null
+++ b/apps/studio/components/interfaces/APIKeys/ApiKeyPill.test.tsx
@@ -0,0 +1,93 @@
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { components } from 'api-types'
+import { HttpResponse } from 'msw'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { ApiKeyPill } from './ApiKeyPill'
+import type { APIKeysData } from '@/data/api-keys/api-keys-query'
+import { customRender } from '@/tests/lib/custom-render'
+import { addAPIMock } from '@/tests/lib/msw'
+
+type ApiKeyResponse = components['schemas']['ApiKeyResponse']
+
+// Permissions are non-network global state — mock the hook (the skill's allowed
+// exception), matching the neighboring PublishableAPIKeys.test.tsx.
+const { mockUseAsyncCheckPermissions } = vi.hoisted(() => ({
+ mockUseAsyncCheckPermissions: vi.fn(),
+}))
+vi.mock('@/hooks/misc/useCheckPermissions', () => ({
+ useAsyncCheckPermissions: mockUseAsyncCheckPermissions,
+}))
+
+// CopyButton writes via copyToClipboard from 'ui'. Stub just that export so we can
+// assert the value handed to the clipboard without depending on jsdom's
+// document.hasFocus() / navigator.clipboard. Everything else in 'ui' stays real.
+const { mockCopyToClipboard } = vi.hoisted(() => ({ mockCopyToClipboard: vi.fn() }))
+vi.mock('ui', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('ui')>()),
+ copyToClipboard: mockCopyToClipboard,
+}))
+
+// The masked value the list endpoint returns for a secret key (first 15 chars),
+// and the full key the reveal-by-id endpoint returns.
+const MASKED = 'sb_secret_abcde'
+const FULL = 'sb_secret_abcdefghijklmnop'
+
+// ApiKeyPill is strongly typed against the query's secret-key shape; the fields it
+// reads are id/type/api_key, so cast a minimal object through unknown.
+const secretKey = {
+ id: 'secret',
+ name: 'secret',
+ type: 'secret',
+ api_key: MASKED,
+ prefix: MASKED,
+} as unknown as Extract<APIKeysData[number], { type: 'secret' }>
+
+function mockRevealById() {
+ addAPIMock({
+ method: 'get',
+ path: '/v1/projects/:ref/api-keys/:id',
+ response: () =>
+ HttpResponse.json<ApiKeyResponse>({
+ id: 'secret',
+ name: 'secret',
+ type: 'secret',
+ api_key: FULL,
+ prefix: MASKED,
+ }),
+ })
+}
+
+describe('ApiKeyPill', () => {
+ beforeEach(() => {
+ mockUseAsyncCheckPermissions.mockReturnValue({ can: true, isLoading: false })
+ mockCopyToClipboard.mockClear()
+ })
+
+ it('masks the secret key by default and does not expose the full key', () => {
+ customRender(<ApiKeyPill apiKey={secretKey} />)
+
+ expect(screen.getByText(MASKED)).toBeInTheDocument()
+ expect(screen.queryByText(FULL.slice(15))).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Reveal API key' })).toBeInTheDocument()
+ })
+
+ it('reveals the full secret key when the reveal button is clicked', async () => {
+ mockRevealById()
+ customRender(<ApiKeyPill apiKey={secretKey} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Reveal API key' }))
+
+ expect(await screen.findByText(FULL.slice(15))).toBeInTheDocument()
+ })
+
+ it('copies the full secret key to the clipboard', async () => {
+ mockRevealById()
+ customRender(<ApiKeyPill apiKey={secretKey} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Copy API key' }))
+
+ await waitFor(() => expect(mockCopyToClipboard).toHaveBeenCalledTimes(1))
+ await expect(Promise.resolve(mockCopyToClipboard.mock.calls[0][0])).resolves.toBe(FULL)
+ })
+})
diff --git a/apps/studio/components/interfaces/APIKeys/ApiKeyPill.tsx b/apps/studio/components/interfaces/APIKeys/ApiKeyPill.tsx
index d1af5cf0365..2bb4c76bd64 100644
--- a/apps/studio/components/interfaces/APIKeys/ApiKeyPill.tsx
+++ b/apps/studio/components/interfaces/APIKeys/ApiKeyPill.tsx
@@ -112,6 +112,7 @@ export function ApiKeyPill({
<TooltipTrigger asChild>
<Button
type="outline"
+ aria-label={show ? 'Hide API key' : 'Reveal API key'}
className="rounded-full px-2 pointer-events-auto"
loading={show && isLoading}
icon={show ? <EyeOff strokeWidth={2} /> : <Eye strokeWidth={2} />}
@@ -135,6 +136,7 @@ export function ApiKeyPill({
<TooltipTrigger asChild>
<CopyButton
type="default"
+ aria-label="Copy API key"
asyncText={onCopy}
iconOnly
className="rounded-full px-2 pointer-events-auto"
diff --git a/apps/studio/lib/api/self-hosted/api-keys.ts b/apps/studio/lib/api/self-hosted/api-keys.ts
new file mode 100644
index 00000000000..60c4299414b
--- /dev/null
+++ b/apps/studio/lib/api/self-hosted/api-keys.ts
@@ -0,0 +1,98 @@
+/**
+ * Both CLI and self-hosted inject the same env vars.
+ */
+import { assertSelfHosted } from './util'
+
+export type NonPlatformApiKey = {
+ name: string
+ api_key: string
+ id: string
+ type: 'legacy' | 'publishable' | 'secret'
+ hash: string
+ prefix: string
+ description: string
+}
+
+/**
+ * Length of the identifying prefix shown for a secret key before it is
+ * revealed. Mirrors the platform management API and the `ApiKeyPill` UI.
+ */
+const SECRET_KEY_VISIBLE_PREFIX_LENGTH = 15
+
+export function parseRevealQuery(value: string | string[] | undefined): boolean {
+ const raw = Array.isArray(value) ? value[0] : value
+ return raw === 'true'
+}
+
+export function getNonPlatformApiKeys(): NonPlatformApiKey[] {
+ assertSelfHosted()
+
+ const keys: NonPlatformApiKey[] = [
+ {
+ name: 'anon',
+ api_key: process.env.SUPABASE_ANON_KEY ?? '',
+ id: 'anon',
+ type: 'legacy',
+ hash: '',
+ prefix: '',
+ description: 'Legacy anon API key',
+ },
+ {
+ name: 'service_role',
+ api_key: process.env.SUPABASE_SERVICE_KEY ?? '',
+ id: 'service_role',
+ type: 'legacy',
+ hash: '',
+ prefix: '',
+ description: 'Legacy service_role API key',
+ },
+ ]
+
+ const publishableKey = process.env.SUPABASE_PUBLISHABLE_KEY
+ if (publishableKey) {
+ keys.push({
+ name: 'publishable',
+ api_key: publishableKey,
+ id: 'publishable',
+ type: 'publishable',
+ hash: '',
+ prefix: '',
+ description: 'Publishable API key (anon role)',
+ })
+ }
+
+ const secretKey = process.env.SUPABASE_SECRET_KEY
+ if (secretKey) {
+ keys.push({
+ name: 'secret',
+ api_key: secretKey,
+ id: 'secret',
+ type: 'secret',
+ hash: '',
+ // Only expose the prefix when the key is genuinely longer than the prefix.
+ prefix:
+ secretKey.length > SECRET_KEY_VISIBLE_PREFIX_LENGTH
+ ? secretKey.slice(0, SECRET_KEY_VISIBLE_PREFIX_LENGTH)
+ : '',
+ description: 'Secret API key (service_role)',
+ })
+ }
+
+ return keys
+}
+
+export function applyRevealToApiKey(key: NonPlatformApiKey, reveal: boolean): NonPlatformApiKey {
+ if (key.type !== 'secret' || reveal) return key
+
+ return { ...key, api_key: key.prefix }
+}
+
+export function getNonPlatformApiKeyById(
+ id: string,
+ reveal: boolean
+): NonPlatformApiKey | undefined {
+ const key = getNonPlatformApiKeys().find((entry) => entry.id === id)
+ if (!key) return undefined
+
+ return applyRevealToApiKey(key, reveal)
+}
diff --git a/apps/studio/pages/api/v1/projects/[ref]/api-keys.ts b/apps/studio/pages/api/v1/projects/[ref]/api-keys.ts
index 60ee93438b2..2b7878f12ba 100644
--- a/apps/studio/pages/api/v1/projects/[ref]/api-keys.ts
+++ b/apps/studio/pages/api/v1/projects/[ref]/api-keys.ts
@@ -1,14 +1,11 @@
-import { components } from 'api-types'
import { NextApiRequest, NextApiResponse } from 'next'
import apiWrapper from '@/lib/api/apiWrapper'
-
-type ProjectAppConfig = components['schemas']['ProjectSettingsResponse']['app_config'] & {
- protocol?: string
-}
-export type ProjectSettings = components['schemas']['ProjectSettingsResponse'] & {
- app_config?: ProjectAppConfig
-}
+import {
+ applyRevealToApiKey,
+ getNonPlatformApiKeys,
+ parseRevealQuery,
+} from '@/lib/api/self-hosted/api-keys'
export default (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
@@ -24,53 +21,9 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
}
}
-const handleGetAll = async (_req: NextApiRequest, res: NextApiResponse) => {
- const response = [
- {
- name: 'anon',
- api_key: process.env.SUPABASE_ANON_KEY ?? '',
- id: 'anon',
- type: 'legacy',
- hash: '',
- prefix: '',
- description: 'Legacy anon API key',
- },
- {
- name: 'service_role',
- api_key: process.env.SUPABASE_SERVICE_KEY ?? '',
- id: 'service_role',
- type: 'legacy',
- hash: '',
- prefix: '',
- description: 'Legacy service_role API key',
- },
- ...(process.env.SUPABASE_PUBLISHABLE_KEY
- ? [
- {
- name: 'publishable',
- api_key: process.env.SUPABASE_PUBLISHABLE_KEY,
- id: 'publishable',
- type: 'publishable',
- hash: '',
- prefix: '',
- description: 'Publishable API key (anon role)',
- },
- ]
- : []),
- ...(process.env.SUPABASE_SECRET_KEY
- ? [
- {
- name: 'secret',
- api_key: process.env.SUPABASE_SECRET_KEY,
- id: 'secret',
- type: 'secret',
- hash: '',
- prefix: '',
- description: 'Secret API key (service_role)',
- },
- ]
- : []),
- ]
+const handleGetAll = async (req: NextApiRequest, res: NextApiResponse) => {
+ const reveal = parseRevealQuery(req.query.reveal)
+ const response = getNonPlatformApiKeys().map((key) => applyRevealToApiKey(key, reveal))
return res.status(200).json(response)
}
diff --git a/apps/studio/pages/api/v1/projects/[ref]/api-keys/[id].ts b/apps/studio/pages/api/v1/projects/[ref]/api-keys/[id].ts
new file mode 100644
index 00000000000..650e58098fb
--- /dev/null
+++ b/apps/studio/pages/api/v1/projects/[ref]/api-keys/[id].ts
@@ -0,0 +1,38 @@
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import apiWrapper from '@/lib/api/apiWrapper'
+import { getNonPlatformApiKeyById, parseRevealQuery } from '@/lib/api/self-hosted/api-keys'
+
+const apiKeyByIdRoute = (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
+
+export default apiKeyByIdRoute
+
+async function handler(req: NextApiRequest, res: NextApiResponse) {
+ const { method } = req
+
+ switch (method) {
+ case 'GET':
+ return handleGet(req, res)
+ default:
+ res.setHeader('Allow', ['GET'])
+ res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })
+ }
+}
+
+const handleGet = async (req: NextApiRequest, res: NextApiResponse) => {
+ const idParam = req.query.id
+ const id = Array.isArray(idParam) ? idParam[0] : idParam
+
+ if (!id) {
+ return res.status(404).json({ error: { message: 'API key not found' } })
+ }
+
+ const reveal = parseRevealQuery(req.query.reveal)
+ const apiKey = getNonPlatformApiKeyById(id, reveal)
+
+ if (!apiKey) {
+ return res.status(404).json({ error: { message: 'API key not found' } })
+ }
+
+ return res.status(200).json(apiKey)
+}
diff --git a/apps/studio/tests/pages/api/v1/projects/[ref]/api-keys.test.ts b/apps/studio/tests/pages/api/v1/projects/[ref]/api-keys.test.ts
index 906c2195d54..f4568467983 100644
--- a/apps/studio/tests/pages/api/v1/projects/[ref]/api-keys.test.ts
+++ b/apps/studio/tests/pages/api/v1/projects/[ref]/api-keys.test.ts
@@ -103,7 +103,7 @@ describe('/api/v1/projects/[ref]/api-keys', () => {
vi.stubEnv('SUPABASE_ANON_KEY', 'anon-key-value')
vi.stubEnv('SUPABASE_SERVICE_KEY', 'service-key-value')
vi.stubEnv('SUPABASE_PUBLISHABLE_KEY', '')
- vi.stubEnv('SUPABASE_SECRET_KEY', 'sb_secret_xyz')
+ vi.stubEnv('SUPABASE_SECRET_KEY', 'sb_secret_abcdefghijklmnop')
const { req, res } = createMocks({ method: 'GET', query: { ref: 'default' } })
await handler(req, res)
@@ -112,21 +112,55 @@ describe('/api/v1/projects/[ref]/api-keys', () => {
expect(data).toHaveLength(3)
expect(data[2]).toEqual({
name: 'secret',
- api_key: 'sb_secret_xyz',
+ api_key: 'sb_secret_abcde',
id: 'secret',
type: 'secret',
hash: '',
- prefix: '',
+ prefix: 'sb_secret_abcde',
description: 'Secret API key (service_role)',
})
expect(data.find((k: { type: string }) => k.type === 'publishable')).toBeUndefined()
})
+ it('fully masks a short secret key so the unrevealed list never leaks it', async () => {
+ vi.stubEnv('SUPABASE_ANON_KEY', 'anon-key-value')
+ vi.stubEnv('SUPABASE_SERVICE_KEY', 'service-key-value')
+ vi.stubEnv('SUPABASE_PUBLISHABLE_KEY', '')
+ // <= 15 chars: the prefix would otherwise equal the whole secret.
+ vi.stubEnv('SUPABASE_SECRET_KEY', 'sb_secret_xyz')
+
+ const { req, res } = createMocks({ method: 'GET', query: { ref: 'default' } })
+ await handler(req, res)
+
+ const data = JSON.parse(res._getData())
+ const secret = data.find((k: { id: string }) => k.id === 'secret')
+ expect(secret.api_key).toBe('')
+ expect(secret.prefix).toBe('')
+ })
+
+ it('returns the full secret key in the list when reveal=true', async () => {
+ vi.stubEnv('SUPABASE_ANON_KEY', 'anon-key-value')
+ vi.stubEnv('SUPABASE_SERVICE_KEY', 'service-key-value')
+ vi.stubEnv('SUPABASE_PUBLISHABLE_KEY', '')
+ vi.stubEnv('SUPABASE_SECRET_KEY', 'sb_secret_abcdefghijklmnop')
+
+ const { req, res } = createMocks({
+ method: 'GET',
+ query: { ref: 'default', reveal: 'true' },
+ })
+ await handler(req, res)
+
+ const data = JSON.parse(res._getData())
+ expect(data.find((k: { id: string }) => k.id === 'secret')?.api_key).toBe(
+ 'sb_secret_abcdefghijklmnop'
+ )
+ })
+
it('appends both new entries when both env vars are set, in publishable-then-secret order', async () => {
vi.stubEnv('SUPABASE_ANON_KEY', 'anon-key-value')
vi.stubEnv('SUPABASE_SERVICE_KEY', 'service-key-value')
vi.stubEnv('SUPABASE_PUBLISHABLE_KEY', 'sb_publishable_abc')
- vi.stubEnv('SUPABASE_SECRET_KEY', 'sb_secret_xyz')
+ vi.stubEnv('SUPABASE_SECRET_KEY', 'sb_secret_abcdefghijklmnop')
const { req, res } = createMocks({ method: 'GET', query: { ref: 'default' } })
await handler(req, res)
diff --git a/apps/studio/tests/pages/api/v1/projects/[ref]/api-keys/[id].test.ts b/apps/studio/tests/pages/api/v1/projects/[ref]/api-keys/[id].test.ts
new file mode 100644
index 00000000000..b554dd8829e
--- /dev/null
+++ b/apps/studio/tests/pages/api/v1/projects/[ref]/api-keys/[id].test.ts
@@ -0,0 +1,126 @@
+import { createMocks } from 'node-mocks-http'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import handler from '../../../../../../../pages/api/v1/projects/[ref]/api-keys/[id]'
+import { mswServer } from '@/tests/lib/msw'
+
+vi.mock('@/lib/constants', () => ({
+ IS_PLATFORM: false,
+ API_URL: 'https://api.example.com',
+}))
+
+describe('/api/v1/projects/[ref]/api-keys/[id]', () => {
+ beforeEach(() => {
+ mswServer.close()
+ vi.unstubAllEnvs()
+ })
+
+ afterEach(() => {
+ vi.unstubAllEnvs()
+ })
+
+ describe('Method handling', () => {
+ it('should return 405 for non-GET methods', async () => {
+ const { req, res } = createMocks({
+ method: 'POST',
+ query: { ref: 'default', id: 'secret' },
+ })
+
+ await handler(req, res)
+
+ expect(res._getStatusCode()).toBe(405)
+ expect(JSON.parse(res._getData())).toEqual({
+ data: null,
+ error: { message: 'Method POST Not Allowed' },
+ })
+ expect(res.getHeader('Allow')).toEqual(['GET'])
+ })
+ })
+
+ describe('GET', () => {
+ it('returns 404 when the key id is unknown', async () => {
+ vi.stubEnv('SUPABASE_SECRET_KEY', 'sb_secret_xyz')
+
+ const { req, res } = createMocks({
+ method: 'GET',
+ query: { ref: 'default', id: 'missing' },
+ })
+ await handler(req, res)
+
+ expect(res._getStatusCode()).toBe(404)
+ expect(JSON.parse(res._getData())).toEqual({
+ error: { message: 'API key not found' },
+ })
+ })
+
+ it('returns the publishable key by id', async () => {
+ vi.stubEnv('SUPABASE_PUBLISHABLE_KEY', 'sb_publishable_abc')
+
+ const { req, res } = createMocks({
+ method: 'GET',
+ query: { ref: 'default', id: 'publishable' },
+ })
+ await handler(req, res)
+
+ expect(res._getStatusCode()).toBe(200)
+ expect(JSON.parse(res._getData())).toMatchObject({
+ id: 'publishable',
+ type: 'publishable',
+ api_key: 'sb_publishable_abc',
+ })
+ })
+
+ it('masks the secret key when reveal is false', async () => {
+ vi.stubEnv('SUPABASE_SECRET_KEY', 'sb_secret_abcdefghijklmnop')
+
+ const { req, res } = createMocks({
+ method: 'GET',
+ query: { ref: 'default', id: 'secret', reveal: 'false' },
+ })
+ await handler(req, res)
+
+ expect(res._getStatusCode()).toBe(200)
+ expect(JSON.parse(res._getData())).toMatchObject({
+ id: 'secret',
+ type: 'secret',
+ api_key: 'sb_secret_abcde',
+ prefix: 'sb_secret_abcde',
+ })
+ })
+
+ it('masks the secret key by default when no reveal query param is set', async () => {
+ vi.stubEnv('SUPABASE_SECRET_KEY', 'sb_secret_abcdefghijklmnop')
+
+ const { req, res } = createMocks({
+ method: 'GET',
+ query: { ref: 'default', id: 'secret' },
+ })
+ await handler(req, res)
+
+ expect(res._getStatusCode()).toBe(200)
+ expect(JSON.parse(res._getData())).toMatchObject({
+ id: 'secret',
+ type: 'secret',
+ api_key: 'sb_secret_abcde',
+ prefix: 'sb_secret_abcde',
+ })
+ })
+
+ it('returns the full secret key when reveal is true', async () => {
+ vi.stubEnv('SUPABASE_SECRET_KEY', 'sb_secret_abcdefghijklmnop')
+
+ const { req, res } = createMocks({
+ method: 'GET',
+ query: { ref: 'default', id: 'secret', reveal: 'true' },
+ })
+ await handler(req, res)
+
+ expect(res._getStatusCode()).toBe(200)
+ expect(JSON.parse(res._getData())).toMatchObject({
+ id: 'secret',
+ type: 'secret',
+ api_key: 'sb_secret_abcdefghijklmnop',
+ })
+ })
+ })
+})