The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix(studio): send API keys on the apikey header in the edge function tester (#49650)
claude[bot]058b546b56b6
diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsxindex 44280555658..cd5666b0596 100644--- a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx@@ -1,16 +1,15 @@import { zodResolver } from '@hookform/resolvers/zod'import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'-import { BookOpen, Loader2, Plus, Send, X } from 'lucide-react'+import { BookOpen, Loader2, Send } from 'lucide-react'import { useState } from 'react'-import { useFieldArray, useForm, useWatch } from 'react-hook-form'+import { useForm, useWatch } from 'react-hook-form'import {Badge,Button,Form,FormControl,FormField,- Input,Label,ResizableHandle,ResizablePanel,@@ -33,27 +32,21 @@ import {} from 'ui'import { CodeBlock } from 'ui-patterns/CodeBlock'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import { KeyValueFieldArray } from 'ui-patterns/form/KeyValueFieldArray/KeyValueFieldArray'import * as z from 'zod'import { HTTP_METHODS } from './EdgeFunctionDetails.constants'import { ErrorWithStatus, ResponseData } from './EdgeFunctionDetails.types'import { getEdgeFunctionErrorDocs } from './EdgeFunctionDetails.utils'-import { RoleImpersonationPopover } from '@/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover'+import { buildEdgeFunctionTestHeaders } from './EdgeFunctionTesterSheet.utils'+import { buildEdgeFunctionHeaderAddActions } from '@/components/interfaces/Functions/httpHeaderAddActions'import { ShortcutTooltip } from '@/components/ui/ShortcutTooltip'import { useAPIKeys } from '@/data/api-keys/api-keys-query'-import { useSessionAccessTokenQuery } from '@/data/auth/session-access-token-query'-import { useProjectPostgrestConfigQuery } from '@/data/config/project-postgrest-config-query'import { useProjectSettingsV2Query } from '@/data/config/project-settings-v2-query'import { useEdgeFunctionTestMutation } from '@/data/edge-functions/edge-function-test-mutation'import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'-import { IS_PLATFORM } from '@/lib/constants'import { prettifyJSON } from '@/lib/helpers'-import { getRoleImpersonationJWT } from '@/lib/role-impersonation'import { useTrack } from '@/lib/telemetry/track'-import {- RoleImpersonationStateContextProvider,- useGetImpersonatedRoleState,-} from '@/state/role-impersonation-state'import { SHORTCUT_IDS } from '@/state/shortcuts/registry'import { useShortcut } from '@/state/shortcuts/useShortcut'@@ -84,31 +77,33 @@ const FormSchema = z.object({type FormValues = z.infer<typeof FormSchema>-export const EdgeFunctionTesterSheet = (props: EdgeFunctionTesterSheetProps) => {- const { ref: projectRef } = useParams()-- // [Alaister]: We're using a fresh context here as edge functions don't allow impersonating users.- return (- <RoleImpersonationStateContextProvider key={`role-impersonation-state-${projectRef}`}>- <EdgeFunctionTesterSheetContent {...props} />- </RoleImpersonationStateContextProvider>- )-}--const EdgeFunctionTesterSheetContent = ({ visible, onClose }: EdgeFunctionTesterSheetProps) => {+export const EdgeFunctionTesterSheet = ({ visible, onClose }: EdgeFunctionTesterSheetProps) => {const { ref: projectRef, functionSlug } = useParams()- const getImpersonatedRoleState = useGetImpersonatedRoleState()const [response, setResponse] = useState<ResponseData | null>(null)const [error, setError] = useState<string | null>(null)const errorDocs = response ? getEdgeFunctionErrorDocs(response.headers) : undefinedconst { can: canReadAPIKeys } = useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*')- const { data: apiKeysData } = useAPIKeys({ projectRef }, { enabled: canReadAPIKeys })- const { serviceKey } = apiKeysData ?? {}- const { data: config } = useProjectPostgrestConfigQuery({ projectRef })+ const { data: apiKeysData } = useAPIKeys(+ { projectRef, reveal: true },+ { enabled: canReadAPIKeys }+ )+ const { anonKey, publishableKey, secretKey, serviceKey } = apiKeysData ?? {}const { data: settings } = useProjectSettingsV2Query({ projectRef })- const { data: accessToken } = useSessionAccessTokenQuery({ enabled: IS_PLATFORM })++ // Sent on the `apikey` header. Defaults to the least privileged key available, matching what the+ // function details page shows in its example snippets.+ const clientApiKey = publishableKey?.api_key ?? anonKey?.api_key+ const secretApiKey = secretKey?.api_key ?? serviceKey?.api_key++ // Both keys are offered so the user can swap the request's credential without looking one up.+ // The webhook specific action the helper also builds is not relevant here.+ const headerAddActions = buildEdgeFunctionHeaderAddActions({+ apiKey: secretApiKey ?? '[YOUR API KEY]',+ publishableKey: clientApiKey,+ createRow: (key: string, value: string) => ({ key, value }),+ }).filter(({ key }) => key !== 'add-source-header')const track = useTrack()const { mutate: testEdgeFunction, isPending } = useEdgeFunctionTestMutation({@@ -141,40 +136,6 @@ const EdgeFunctionTesterSheetContent = ({ visible, onClose }: EdgeFunctionTester})const method = useWatch({ control: form.control, name: 'method' })- const {- fields: headerFields,- append: appendHeader,- remove: removeHeader,- } = useFieldArray({- control: form.control,- name: 'headers',- })-- const {- fields: queryParamFields,- append: appendQueryParam,- remove: removeQueryParam,- } = useFieldArray({- control: form.control,- name: 'queryParams',- })-- const addKeyValuePair = (type: 'headers' | 'queryParams') => {- if (type === 'headers') {- appendHeader({ key: '', value: '' })- } else {- appendQueryParam({ key: '', value: '' })- }- }-- const removeKeyValuePair = (index: number, type: 'headers' | 'queryParams') => {- if (type === 'headers') {- removeHeader(index)- } else {- removeQueryParam(index)- }- }-useShortcut(SHORTCUT_IDS.FUNCTION_DETAIL_SUBMIT_TEST,() => {@@ -195,34 +156,6 @@ const EdgeFunctionTesterSheetContent = ({ visible, onClose }: EdgeFunctionTesterreturn}- let testAuthorization: string | undefined- const role = getImpersonatedRoleState().role-- if (- projectRef !== undefined &&- config?.jwt_secret !== undefined &&- role !== undefined &&- role.type === 'postgrest'- ) {- try {- const token = await getRoleImpersonationJWT(projectRef, config.jwt_secret, role)- testAuthorization = 'Bearer ' + token- } catch (err: any) {- console.error('Failed to generate JWT:', {- error: err.message,- roleDetails: role,- })- }- }-- // Construct custom headers- const customHeaders: Record<string, string> = {}- values.headers.forEach(({ key, value }) => {- if (key && value) {- customHeaders[key] = value- }- })-// Construct query parametersconst queryString = values.queryParams.filter(({ key, value }) => key && value)@@ -235,80 +168,13 @@ const EdgeFunctionTesterSheetContent = ({ visible, onClose }: EdgeFunctionTesterurl: finalUrl,method: values.method,body: values.body,- headers: {- ...(accessToken && {- Authorization: `Bearer ${accessToken}`,- }),- 'x-test-authorization': testAuthorization ?? `Bearer ${serviceKey?.api_key}`,- 'Content-Type': 'application/json',- ...customHeaders,- },+ headers: buildEdgeFunctionTestHeaders({+ apiKey: clientApiKey,+ customHeaders: values.headers,+ }),})}- const renderKeyValuePairs = (type: 'headers' | 'queryParams', label: string) => (- <div className="space-y-2">- <div className="flex items-center justify-between">- <Label className="text-foreground text-sm">{label}</Label>- <Button- variant="default"- size="tiny"- icon={<Plus size={14} />}- onClick={() => addKeyValuePair(type)}- >- Add {label}- </Button>- </div>- <div className="border rounded-md bg-surface-200">- {(type === 'headers' ? headerFields : queryParamFields).map((field, index) => (- <div key={field.id} className="grid grid-cols-[1fr_1fr_32px] border-b last:border-b-0">- <FormField- control={form.control}- name={`${type}.${index}.key`}- render={({ field }) => (- <FormControl>- <Input- {...field}- size="tiny"- placeholder="Enter key..."- disabled={isPending}- className="h-auto py-2 font-mono rounded-none shadow-none bg-transparent border-l-0 border-r border-t-0 border-b-0 border-border"- />- </FormControl>- )}- />- <FormField- control={form.control}- name={`${type}.${index}.value`}- render={({ field }) => (- <FormControl>- <Input- {...field}- size="tiny"- placeholder="Enter value..."- disabled={isPending}- className="h-auto py-2 font-mono rounded-none shadow-none bg-transparent border-none"- />- </FormControl>- )}- />- <div className="flex items-center justify-center">- {(type === 'headers' ? headerFields : queryParamFields).length > 1 && (- <Button- variant="text"- size="tiny"- icon={<X strokeWidth={1.5} size={14} />}- className="w-6 h-6"- onClick={() => removeKeyValuePair(index, type)}- />- )}- </div>- </div>- ))}- </div>- </div>- )-return (<Sheet open={visible} onOpenChange={onClose}><SheetContent@@ -392,8 +258,35 @@ const EdgeFunctionTesterSheetContent = ({ visible, onClose }: EdgeFunctionTester/>)}- {renderKeyValuePairs('headers', 'Headers')}- {renderKeyValuePairs('queryParams', 'Query Parameters')}+ <div className="space-y-2">+ <Label className="text-foreground text-sm">Headers</Label>+ <KeyValueFieldArray+ control={form.control}+ name="headers"+ keyFieldName="key"+ valueFieldName="value"+ createEmptyRow={() => ({ key: '', value: '' })}+ keyPlaceholder="Header name"+ valuePlaceholder="Header value"+ addLabel="Add header"+ addActions={headerAddActions}+ disabled={isPending}+ />+ </div>+ <div className="space-y-2">+ <Label className="text-foreground text-sm">Query Parameters</Label>+ <KeyValueFieldArray+ control={form.control}+ name="queryParams"+ keyFieldName="key"+ valueFieldName="value"+ createEmptyRow={() => ({ key: '', value: '' })}+ keyPlaceholder="Parameter name"+ valuePlaceholder="Parameter value"+ addLabel="Add parameter"+ disabled={isPending}+ />+ </div></div></ResizablePanel><ResizableHandle withHandle />@@ -484,10 +377,6 @@ const EdgeFunctionTesterSheetContent = ({ visible, onClose }: EdgeFunctionTester<SheetFooter className="px-5 py-3 border-t"><div className="flex items-center gap-2">- <RoleImpersonationPopover- disallowAuthenticatedOption- header="Run edge function as a role"- /><ShortcutTooltip shortcutId={SHORTCUT_IDS.FUNCTION_DETAIL_SUBMIT_TEST} side="top"><Buttonvariant="primary"diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.utils.ts b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.utils.tsnew file mode 100644index 00000000000..52759fe1a14--- /dev/null+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.utils.ts@@ -0,0 +1,46 @@+export interface EdgeFunctionTestHeaderRow {+ key: string+ value: string+}++interface BuildEdgeFunctionTestHeadersParams {+ /**+ * Publishable (or legacy anon) key sent on the `apikey` header. New format API keys are not+ * JWTs, so they must never be sent as a bearer token on `Authorization`.+ */+ apiKey?: string+ /** Header rows entered by the user in the tester's "Headers" section. */+ customHeaders: EdgeFunctionTestHeaderRow[]+}++/**+ * Builds the headers forwarded to the edge function.+ *+ * `Authorization` is deliberately never generated here: it is only ever set by the user, either by+ * typing a header row or by picking a role in the impersonation popover (which prefills a row).+ *+ * Header names are case insensitive, so rows are merged on their lowercased name to make sure a row+ * typed as `apikey` cannot end up alongside a generated `Apikey` and get comma joined by `fetch`.+ * User rows are applied last and win over the generated defaults.+ */+export const buildEdgeFunctionTestHeaders = ({+ apiKey,+ customHeaders,+}: BuildEdgeFunctionTestHeadersParams): Record<string, string> => {+ const headers = new Map<string, { name: string; value: string }>()++ const set = (name: string, value: string) => {+ headers.set(name.toLowerCase(), { name, value })+ }++ set('Content-Type', 'application/json')+ if (apiKey) set('apikey', apiKey)++ customHeaders.forEach(({ key, value }) => {+ const name = key.trim()+ if (name.length === 0 || value.length === 0) return+ set(name, value)+ })++ return Object.fromEntries([...headers.values()].map(({ name, value }) => [name, value]))+}diff --git a/apps/studio/components/interfaces/Functions/httpHeaderAddActions.test.ts b/apps/studio/components/interfaces/Functions/httpHeaderAddActions.test.tsindex f9089b9c680..609c0792f13 100644--- a/apps/studio/components/interfaces/Functions/httpHeaderAddActions.test.ts+++ b/apps/studio/components/interfaces/Functions/httpHeaderAddActions.test.ts@@ -32,6 +32,67 @@ describe('buildEdgeFunctionHeaderAddActions', () => {{ name: 'Authorization', value: 'Bearer legacy-service-role-jwt' },])})+ it('offers no publishable key action unless a publishable key is given', () => {+ const actions = buildEdgeFunctionHeaderAddActions({+ apiKey: 'sb_secret_123',+ createRow: (name, value) => ({ name, value }),+ })++ expect(actions.map(({ key }) => key)).toEqual(['add-auth-header', 'add-source-header'])+ })++ it('prepends a publishable key action when one is given', () => {+ const [publishableAction, ...rest] = buildEdgeFunctionHeaderAddActions({+ apiKey: 'sb_secret_123',+ publishableKey: 'sb_publishable_123',+ createRow: (name, value) => ({ name, value }),+ })++ expect(publishableAction.key).toBe('add-publishable-key-header')+ expect(publishableAction.label).toBe('Add publishable key')+ expect(publishableAction.description).toBe(+ 'For functions that accept a publishable key and authorize the request themselves'+ )+ expect(publishableAction.createRows()).toEqual([+ { name: 'apikey', value: 'sb_publishable_123' },+ ])+ expect(rest.map(({ key }) => key)).toEqual(['add-auth-header', 'add-source-header'])+ })++ it('labels a legacy anon key in the publishable slot accordingly', () => {+ const [publishableAction] = buildEdgeFunctionHeaderAddActions({+ apiKey: 'legacy-service-role-jwt',+ publishableKey: 'legacy-anon-jwt',+ createRow: (name, value) => ({ name, value }),+ })++ expect(publishableAction.label).toBe('Add anon key')+ expect(publishableAction.description).toBe(+ 'Legacy anon key, for edge functions that enforce JWT verification'+ )+ expect(publishableAction.createRows()).toEqual([+ { name: 'Authorization', value: 'Bearer legacy-anon-jwt' },+ ])+ })++ it('labels the auth action after the key it carries', () => {+ const [authAction] = buildEdgeFunctionHeaderAddActions({+ apiKey: 'sb_publishable_123',+ createRow: (name, value) => ({ name, value }),+ })++ expect(authAction.label).toBe('Add publishable key')+ })++ it('does not mislabel a secret key passed in the publishable slot', () => {+ const [publishableAction] = buildEdgeFunctionHeaderAddActions({+ apiKey: 'legacy-service-role-jwt',+ publishableKey: 'sb_secret_999',+ createRow: (name, value) => ({ name, value }),+ })++ expect(publishableAction.label).toBe('Add secret key')+ })})describe('getEdgeFunctionAuthHeader', () => {diff --git a/apps/studio/components/interfaces/Functions/httpHeaderAddActions.ts b/apps/studio/components/interfaces/Functions/httpHeaderAddActions.tsindex 75e446c5e39..5f3d79ee9df 100644--- a/apps/studio/components/interfaces/Functions/httpHeaderAddActions.ts+++ b/apps/studio/components/interfaces/Functions/httpHeaderAddActions.ts@@ -2,6 +2,12 @@ import type { KeyValueFieldArrayAction } from 'ui-patterns/form/KeyValueFieldArrinterface BuildEdgeFunctionHeaderAddActionsParams<TRow> {apiKey: string+ /**+ * When provided, an extra action is offered for the project's publishable (or legacy anon) key.+ * Surfaces that should only ever offer a secret key, such as database webhooks and cron jobs,+ * leave this undefined.+ */+ publishableKey?: stringcreateRow: (name: string, value: string) => TRow}@@ -20,6 +26,19 @@ interface EnsureEdgeFunctionAuthorizationHeaderParams<TRow extends HTTPHeader> {const isNewApiKey = (apiKey: string) =>apiKey.startsWith('sb_secret_') || apiKey.startsWith('sb_publishable_')+const isPublishableApiKey = (apiKey: string) => apiKey.startsWith('sb_publishable_')++/**+ * Labels an action after the key it actually carries. Legacy keys are not self describing, so the+ * caller names them: the secret slot falls back to "Add secret key", the publishable slot to+ * "Add anon key".+ */+const getApiKeyActionLabel = (apiKey: string, legacyLabel: string) => {+ if (isPublishableApiKey(apiKey)) return 'Add publishable key'+ if (isNewApiKey(apiKey)) return 'Add secret key'+ return legacyLabel+}+export const getEdgeFunctionAuthHeader = (apiKey: string) =>isNewApiKey(apiKey)? { name: 'apikey', value: apiKey }@@ -59,14 +78,35 @@ export const ensureEdgeFunctionAuthorizationHeader = <TRow extends HTTPHeader>({export const buildEdgeFunctionHeaderAddActions = <TRow>({apiKey,+ publishableKey,createRow,}: BuildEdgeFunctionHeaderAddActionsParams<TRow>): KeyValueFieldArrayAction<TRow>[] => {const authHeader = getEdgeFunctionAuthHeader(apiKey)+ // `add-auth-header` stays at a stable position for callers that do not pass a publishable key,+ // so the publishable action is prepended only when one is available.+ const publishableActions: KeyValueFieldArrayAction<TRow>[] = []++ if (publishableKey !== undefined) {+ const publishableHeader = getEdgeFunctionAuthHeader(publishableKey)++ publishableActions.push({+ key: 'add-publishable-key-header',+ label: getApiKeyActionLabel(publishableKey, 'Add anon key'),+ description:+ publishableHeader.name === 'apikey'+ ? 'For functions that accept a publishable key and authorize the request themselves'+ : 'Legacy anon key, for edge functions that enforce JWT verification',+ createRows: () => [createRow(publishableHeader.name, publishableHeader.value)],+ })+ }+return [+ ...publishableActions,{key: 'add-auth-header',- label: 'Add secret key',+ // The label follows the key the action actually carries rather than being hardcoded+ label: getApiKeyActionLabel(apiKey, 'Add secret key'),description:authHeader.name === 'apikey'? 'Requires JWT verification to be disabled and authorization handled by the function'diff --git a/apps/studio/pages/api/edge-functions/test.ts b/apps/studio/pages/api/edge-functions/test.tsindex 096d66fa205..6e03a9c229a 100644--- a/apps/studio/pages/api/edge-functions/test.ts+++ b/apps/studio/pages/api/edge-functions/test.ts@@ -36,34 +36,27 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {})}- // Remove any undefined or null values from custom headers- const sanitizedCustomHeaders = Object.entries(customHeaders || {}).reduce(- (acc, [key, value]) => {- if (value !== undefined && value !== null && value !== '') {- acc[key] = value as string- }- return acc- },- {} as Record<string, string>- )+ // Forward the supplied headers as given, dropping empty values. Header names are case+ // insensitive, so they are merged on their lowercased name: a supplied `content-type` replaces+ // the default rather than sitting beside it and being comma joined by `fetch`.+ const suppliedHeaders = new Map<string, { name: string; value: string }>([+ ['content-type', { name: 'Content-Type', value: 'application/json' }],+ ])- // Only use custom headers and ensure Content-Type is set- const requestHeaders: Record<string, string> = {- 'Content-Type': 'application/json',- ...sanitizedCustomHeaders,- }+ Object.entries(customHeaders || {}).forEach(([key, value]) => {+ const name = key.trim()+ if (name.length === 0 || value === undefined || value === null || value === '') return+ suppliedHeaders.set(name.toLowerCase(), { name, value: value as string })+ })- // Use the test authorization header if provided- if (sanitizedCustomHeaders['x-test-authorization']) {- requestHeaders['Authorization'] = sanitizedCustomHeaders['x-test-authorization']- // Remove the x-test-authorization header as we've moved it to Authorization- delete requestHeaders['x-test-authorization']- }+ const requestHeaders: Record<string, string> = Object.fromEntries(+ [...suppliedHeaders.values()].map(({ name, value }) => [name, value])+ )// Prepare the request body based on method and Content-Typelet finalBody = undefinedif (method !== 'GET' && method !== 'HEAD') {- if (requestHeaders['Content-Type'] === 'application/json') {+ if (suppliedHeaders.get('content-type')?.value === 'application/json') {finalBody = typeof requestBody === 'string' ? requestBody : JSON.stringify(requestBody)} else {finalBody = requestBodydiff --git a/apps/studio/tests/components/Functions/EdgeFunctionTesterSheet.utils.test.ts b/apps/studio/tests/components/Functions/EdgeFunctionTesterSheet.utils.test.tsnew file mode 100644index 00000000000..f2a33e59ffa--- /dev/null+++ b/apps/studio/tests/components/Functions/EdgeFunctionTesterSheet.utils.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it } from 'vitest'++import { buildEdgeFunctionTestHeaders } from '@/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.utils'++const PUBLISHABLE_KEY = 'sb_publishable_test_key'++describe('buildEdgeFunctionTestHeaders', () => {+ it('sends the API key on the apikey header', () => {+ const headers = buildEdgeFunctionTestHeaders({+ apiKey: PUBLISHABLE_KEY,+ customHeaders: [],+ })++ expect(headers).toEqual({+ 'Content-Type': 'application/json',+ apikey: PUBLISHABLE_KEY,+ })+ })++ it('never generates an Authorization header', () => {+ const headers = buildEdgeFunctionTestHeaders({+ apiKey: PUBLISHABLE_KEY,+ customHeaders: [{ key: '', value: '' }],+ })++ expect(headers.Authorization).toBeUndefined()+ expect(headers.authorization).toBeUndefined()+ })++ it('omits apikey when no key is available', () => {+ const headers = buildEdgeFunctionTestHeaders({ apiKey: undefined, customHeaders: [] })++ expect(headers).toEqual({ 'Content-Type': 'application/json' })+ })++ it('keeps a user supplied Authorization header', () => {+ const headers = buildEdgeFunctionTestHeaders({+ apiKey: PUBLISHABLE_KEY,+ customHeaders: [{ key: 'Authorization', value: 'Bearer user-token' }],+ })++ expect(headers).toEqual({+ 'Content-Type': 'application/json',+ apikey: PUBLISHABLE_KEY,+ Authorization: 'Bearer user-token',+ })+ })++ it('keeps the apikey alongside several user rows', () => {+ const headers = buildEdgeFunctionTestHeaders({+ apiKey: PUBLISHABLE_KEY,+ customHeaders: [+ { key: 'Authorization', value: 'Bearer user-token' },+ { key: 'x-custom', value: 'kept' },+ ],+ })++ expect(headers).toEqual({+ 'Content-Type': 'application/json',+ apikey: PUBLISHABLE_KEY,+ Authorization: 'Bearer user-token',+ 'x-custom': 'kept',+ })+ })++ it('lets a user row replace a generated header whatever its casing', () => {+ const headers = buildEdgeFunctionTestHeaders({+ apiKey: PUBLISHABLE_KEY,+ customHeaders: [+ { key: 'Apikey', value: 'sb_secret_manual_key' },+ { key: 'content-type', value: 'text/plain' },+ ],+ })++ expect(headers).toEqual({+ Apikey: 'sb_secret_manual_key',+ 'content-type': 'text/plain',+ })+ })++ it('trims header names and drops incomplete rows', () => {+ const headers = buildEdgeFunctionTestHeaders({+ apiKey: PUBLISHABLE_KEY,+ customHeaders: [+ { key: ' x-spaced ', value: 'value' },+ { key: 'x-no-value', value: '' },+ { key: ' ', value: 'orphan' },+ ],+ })++ expect(headers).toEqual({+ 'Content-Type': 'application/json',+ apikey: PUBLISHABLE_KEY,+ 'x-spaced': 'value',+ })+ })+})diff --git a/apps/studio/tests/pages/api/edge-functions/test.test.ts b/apps/studio/tests/pages/api/edge-functions/test.test.tsindex a3fdf4b656d..0e732df72ed 100644--- a/apps/studio/tests/pages/api/edge-functions/test.test.ts+++ b/apps/studio/tests/pages/api/edge-functions/test.test.ts@@ -5,14 +5,17 @@ import handler from '../../../../pages/api/edge-functions/test'vi.mock('common', () => ({ IS_PLATFORM: true }))-const createRequest = (url = 'https://abcdefghijklmnopqrst.supabase.co/functions/v1/test') =>+const createRequest = (+ url = 'https://abcdefghijklmnopqrst.supabase.co/functions/v1/test',+ headers: Record<string, string> = {}+) =>createMocks({method: 'POST',body: {url,method: 'POST',body: '{}',- headers: {},+ headers,},})@@ -126,6 +129,47 @@ describe('/api/edge-functions/test', () => {})})+ it('forwards the supplied headers without rewriting Authorization', async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response(null))+ vi.stubGlobal('fetch', fetchMock)+ const { req, res } = createRequest(undefined, {+ apikey: 'sb_publishable_test_key',+ Authorization: 'Bearer user-token',+ })++ await handler(req, res)++ expect(fetchMock).toHaveBeenCalledTimes(1)+ expect(fetchMock.mock.calls[0][1].headers).toEqual({+ 'Content-Type': 'application/json',+ apikey: 'sb_publishable_test_key',+ Authorization: 'Bearer user-token',+ })+ })++ it('lets a supplied header replace the default whatever its casing', async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response(null))+ vi.stubGlobal('fetch', fetchMock)+ const { req, res } = createRequest(undefined, { 'content-type': 'text/plain' })++ await handler(req, res)++ expect(fetchMock.mock.calls[0][1].headers).toEqual({ 'content-type': 'text/plain' })+ })++ it('drops empty header values', async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response(null))+ vi.stubGlobal('fetch', fetchMock)+ const { req, res } = createRequest(undefined, { apikey: '', 'x-kept': 'value' })++ await handler(req, res)++ expect(fetchMock.mock.calls[0][1].headers).toEqual({+ 'Content-Type': 'application/json',+ 'x-kept': 'value',+ })+ })+it('returns fetch failures as proxy errors', async () => {vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Connection refused')))const { req, res } = createRequest()