Files
supabase/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionTesterSheet.tsx
claude[bot] 058b546b56 fix(studio): send API keys on the apikey header in the edge function tester (#49650)
<!-- ccr-slack-attribution -->
_Requested by **Kalleby Santos** · [Slack
thread](https://supabase.slack.com/archives/C0AQ3UHCCKW/p1787840441551609?thread_ts=1787840441.551609&cid=C0AQ3UHCCKW)_

**Before:** you deploy the editor's default template ("Deploy a new
function" → "Via Editor"), which wraps its handler in `withSupabase({
auth: ["publishable", "secret"] })`. You click **Test** and get `401
{"message":"Invalid credentials","code":"INVALID_CREDENTIALS"}` — from
the function's own middleware, with an empty Headers section. Studio was
quietly setting `Authorization` to a legacy `service_role` JWT (and,
before that, to your dashboard session token), routed through a private
`x-test-authorization` header that the proxy route renamed to
`Authorization`. A legacy JWT is neither a publishable nor a secret key,
so the middleware rejected it. Pasting your own `Authorization` row did
not help: the route overwrote it unconditionally. On a project with
legacy keys disabled there was no `service_role` key at all and the
literal string `Bearer undefined` went out.

**After:** the tester sends your publishable key on the `apikey` header,
where new-format keys belong, and never generates an `Authorization`
header. `Authorization` only ever comes from your own header rows —
typed by hand, or prefilled for you by the role selector. The editor's
default template works on the first click, a header you paste is
actually sent, and an **Add secret key** action in the "Add header"
dropdown gives you one-click access to a secret key, the same affordance
the database webhooks and cron job screens already have.

**How:** header construction moves into `buildEdgeFunctionTestHeaders`
(`EdgeFunctionTesterSheet.utils.ts`), which sets `Content-Type` and
`apikey` and then applies the user's rows last. The
`x-test-authorization` hop is gone from both the component and
`pages/api/edge-functions/test.ts`; the route now forwards the supplied
headers as given. Both sides merge on the lowercased header name, so a
row typed `authorization` or `apikey` replaces the generated one instead
of sitting beside it and being comma-joined by `fetch`. The Headers and
Query Parameters sections now use the shared `KeyValueFieldArray`, which
is what makes `buildEdgeFunctionHeaderAddActions` reusable here.

## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

## What kind of change does this PR introduce?

Bug fix.

## What is the current behavior?

Fixes #42755.

- `EdgeFunctionTesterSheet.tsx` sent the legacy `service_role` JWT (or a
role-impersonation JWT) as the value of `x-test-authorization` on every
request, plus the dashboard session access token as `Authorization`.
- `pages/api/edge-functions/test.ts` then overwrote `Authorization` with
`x-test-authorization` whenever that header was present, discarding any
`Authorization` the user had entered.
- No `apikey` header was ever sent, so `withSupabase` in `publishable`
or `secret` auth mode — the modes used by the editor's own templates —
could never succeed.
- Header merging was case-sensitive on both sides of the proxy, so a row
typed in the conventional lowercase form produced two entries that
`fetch` comma-joined into one malformed value.
- The API keys query did not pass `reveal: true`, unlike the webhooks
and cron job UIs.

## What is the new behavior?

- `apikey` carries the publishable key, falling back to the legacy
`anon` key. This mirrors the example snippets on the function details
page, which already prefer `publishableKey ?? anonKey`. Defaulting to
the least-privileged key means a secret key is only ever sent when the
user explicitly adds it.
- `Authorization` is never generated. The `useSessionAccessTokenQuery`
call is removed from this component entirely — the dashboard user's own
session token has no business being forwarded to a project's function.
- `x-test-authorization` is removed from both files. The proxy route
stays, because it is what reads the raw upstream response for the
response panel (`redirect: 'manual'`, full status/header/body capture),
keeps the request off the browser's CORS path, and holds the
`isValidEdgeFunctionURL` guard and the local-dev URL rewrite. Only the
header rewriting is gone.
- Role impersonation keeps working, but as a visible, editable
`Authorization` row rather than a hidden injected header, so what is
sent is always what is displayed. Two details worth reviewing: the
selector tracks the value it last wrote, so clearing the role removes
only that row and leaves an `Authorization` row you typed by hand alone;
and an incrementing request id discards a JWT that resolves after a
newer role has already been picked.
- Headers merge case-insensitively, user rows winning.
- `reveal: true` is passed on the API keys query, matching
`Database/Hooks/HTTPHeaders.tsx`.

## Additional context

**Relationship to #47159.** #47159 identified the same root cause
independently and got the important part right: the key belongs on
`apikey`, and neither the legacy service-role JWT nor the dashboard
session token should be forwarded. Its extraction of a testable header
builder is a good shape, and this PR keeps it — including the spirit of
its test suite. The differences are in scope rather than direction. This
PR also removes the `x-test-authorization` hop and the route's
unconditional `Authorization` overwrite (#47159 leaves the route
untouched); drops the remaining legacy service-role fallback rather than
keeping it for projects without a publishable key; adds `reveal: true`,
secret-key support and the shared "Add secret key" affordance; and
normalizes header casing for every header rather than only
`x-test-authorization`. Whether to land that PR first and layer this on
top, or take this one, is the maintainers' call — either way the credit
for spotting it belongs there too.

**Overlap with #48143.** That open PR fixes the same case-sensitivity
defect for `Content-Type` in these two files. It is not addressed
separately here, but the case-insensitive merge in this PR covers
`Content-Type` as a side effect, so the two will conflict textually.
Happy to rebase on whichever lands first.

**A note on `verify_jwt`.** The gateway creates a temporary token when
`apikey` is present, so `verify_jwt` does not affect this path and a
request with `apikey` and no `Authorization` reaches the function
normally. No deploy defaults are changed here.

**Compatibility.** One behaviour gets worse and is worth an explicit
decision: a function that expects a legacy JWT on `Authorization` used
to "just work" in the tester because Studio injected the service-role
key. It now needs an `Authorization` row, which the **Add secret key**
action produces in one click — the shared helper already emits an
`Authorization: Bearer` row for legacy-format keys. Projects with legacy
keys disabled strictly improve: they used to receive `Bearer undefined`.
Functions using `auth: "user"` are unchanged — the tester never had a
real end-user JWT, only the impersonation token.

## Testing

`apps/studio` dependencies could not be installed in the environment
this was written in (`pnpm install` fails on a 403 from `npm.jsr.io`),
so `vitest`, `tsc --noEmit` and `eslint` were not run. What was run
instead:

- Prettier with the repo's config, including
`@ianvs/prettier-plugin-sort-imports`: clean on all five files.
- `tsc` parse of the changed files: no syntax or type errors beyond
pre-existing unresolved-module noise.
- Both new test suites transpiled and executed as plain Node assertions:
7/7 for `buildEdgeFunctionTestHeaders`, 4/4 driving the API route
handler with a stubbed `fetch`.

Please run the real suites in CI. `pnpm --filter studio exec vitest
--run tests/components/Functions/EdgeFunctionTesterSheet.utils.test.ts
tests/pages/api/edge-functions/test.test.ts` covers the added tests. A
component-level test of the impersonation prefill is not included and
would be a reasonable follow-up.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Kalleby Santos <105971119+kallebysantos@users.noreply.github.com>
2026-08-31 13:43:01 -03:00

401 lines
16 KiB
TypeScript

import { zodResolver } from '@hookform/resolvers/zod'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useParams } from 'common'
import { BookOpen, Loader2, Send } from 'lucide-react'
import { useState } from 'react'
import { useForm, useWatch } from 'react-hook-form'
import {
Badge,
Button,
Form,
FormControl,
FormField,
Label,
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetTitle,
Tabs,
TabsContent,
TabsList,
TabsTrigger,
Textarea,
} 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 { 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 { 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 { prettifyJSON } from '@/lib/helpers'
import { useTrack } from '@/lib/telemetry/track'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
interface EdgeFunctionTesterSheetProps {
visible: boolean
onClose: () => void
}
const FormSchema = z.object({
method: z.enum(HTTP_METHODS),
body: z
.string()
.optional()
.transform((str) => str || '{}'),
headers: z.array(
z.object({
key: z.string(),
value: z.string(),
})
),
queryParams: z.array(
z.object({
key: z.string(),
value: z.string(),
})
),
})
type FormValues = z.infer<typeof FormSchema>
export const EdgeFunctionTesterSheet = ({ visible, onClose }: EdgeFunctionTesterSheetProps) => {
const { ref: projectRef, functionSlug } = useParams()
const [response, setResponse] = useState<ResponseData | null>(null)
const [error, setError] = useState<string | null>(null)
const errorDocs = response ? getEdgeFunctionErrorDocs(response.headers) : undefined
const { can: canReadAPIKeys } = useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*')
const { data: apiKeysData } = useAPIKeys(
{ projectRef, reveal: true },
{ enabled: canReadAPIKeys }
)
const { anonKey, publishableKey, secretKey, serviceKey } = apiKeysData ?? {}
const { data: settings } = useProjectSettingsV2Query({ projectRef })
// 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({
onSuccess: (res) => setResponse(res),
onError: (err) => {
setError(err instanceof Error ? err.message : 'An unknown error occurred')
if (err instanceof Error) {
const errorWithStatus = err as ErrorWithStatus
setResponse({
status: errorWithStatus.cause?.status || 500,
headers: {},
body: '',
})
}
},
})
const protocol = settings?.app_config?.protocol ?? 'https'
const endpoint = settings?.app_config?.endpoint ?? ''
const url = `${protocol}://${endpoint}/functions/v1/${functionSlug}`
const form = useForm<FormValues>({
resolver: zodResolver(FormSchema),
defaultValues: {
method: 'POST',
body: '{ "name": "Functions" }',
headers: [{ key: '', value: '' }],
queryParams: [{ key: '', value: '' }],
},
})
const method = useWatch({ control: form.control, name: 'method' })
useShortcut(
SHORTCUT_IDS.FUNCTION_DETAIL_SUBMIT_TEST,
() => {
form.handleSubmit(onSubmit)()
},
{ enabled: visible && !isPending }
)
const onSubmit = async (values: FormValues) => {
setError(null)
setResponse(null)
// Validate that the body is valid JSON
try {
JSON.parse(JSON.stringify(values.body))
} catch (e) {
form.setError('body', { message: 'Must be a valid JSON string' })
return
}
// Construct query parameters
const queryString = values.queryParams
.filter(({ key, value }) => key && value)
.map(({ key, value }) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&')
const finalUrl = queryString ? `${url}?${queryString}` : url
testEdgeFunction({
url: finalUrl,
method: values.method,
body: values.body,
headers: buildEdgeFunctionTestHeaders({
apiKey: clientApiKey,
customHeaders: values.headers,
}),
})
}
return (
<Sheet open={visible} onOpenChange={onClose}>
<SheetContent
size="default"
hasOverlay={false}
className="flex flex-col gap-0 p-0"
onPointerDownOutside={(e) => {
// react-resizable-panels v4 registers document-level capture-phase pointer
// handlers that can interfere with Radix Dialog's outside-interaction detection.
// Prevent the sheet from closing when interacting with the resize handle.
const target = (e as CustomEvent<{ originalEvent: PointerEvent }>).detail?.originalEvent
?.target as HTMLElement | null
if (target?.closest?.('[data-separator]')) {
e.preventDefault()
}
}}
onFocusOutside={(e) => {
// The v4 Separator explicitly calls .focus() on itself during pointerdown,
// which can trigger Radix Dialog's focus-outside detection.
const target = e.target as HTMLElement | null
if (target?.closest?.('[data-separator]')) {
e.preventDefault()
}
}}
>
<SheetHeader>
<SheetTitle>Test {functionSlug}</SheetTitle>
</SheetHeader>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="flex-1 overflow-y-auto flex flex-col"
>
<ResizablePanelGroup orientation="vertical">
<ResizablePanel>
<div className="flex flex-col gap-y-4 p-5 h-full overflow-y-auto">
<FormField
control={form.control}
name="method"
render={({ field }) => (
<FormItemLayout layout="vertical" label="HTTP Method">
<FormControl>
<Select
value={field.value}
onValueChange={field.onChange}
disabled={isPending}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="Select method" />
</SelectTrigger>
<SelectContent>
{HTTP_METHODS.map((m) => (
<SelectItem key={m} value={m}>
{m}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
</FormItemLayout>
)}
/>
{method !== 'GET' && (
<FormField
control={form.control}
name="body"
render={({ field }) => (
<FormItemLayout layout="vertical" label="Request Body">
<FormControl>
<Textarea
{...field}
placeholder="Request body (JSON)"
rows={3}
disabled={isPending}
className="font-mono text-xs"
/>
</FormControl>
</FormItemLayout>
)}
/>
)}
<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 />
<ResizablePanel defaultSize="41" minSize="41" maxSize="83">
<div className="h-full bg-surface-100 border-t flex-1 flex flex-col overflow-hidden">
{response ? (
<div className="h-full bg-surface-100 flex flex-col overflow-hidden">
{error ? (
<>
<div className="flex gap-2 items-center p-5 text-sm pb-3">
Function responded with
<Badge variant={response.status >= 400 ? 'destructive' : 'success'}>
{response.status}
</Badge>
</div>
<p className="px-5 text-sm text-foreground-light">{error}</p>
</>
) : (
<Tabs
defaultValue="body"
className="h-full flex-1 flex flex-col overflow-hidden"
>
<TabsList className="gap-4 px-5 pt-2">
<div className="flex items-center gap-4 flex-1">
<TabsTrigger className="text-sm" value="body">
Body
</TabsTrigger>
<TabsTrigger className="text-sm" value="headers">
Headers
</TabsTrigger>
</div>
<div className="-translate-y-1 flex items-center gap-2">
{errorDocs !== undefined && (
<Button
asChild
variant="text"
size="tiny"
icon={<BookOpen size={14} />}
>
<a
href={errorDocs.href}
target="_blank"
rel="noreferrer"
aria-label={`View documentation for ${errorDocs.code} (opens in new tab)`}
>
Error docs
</a>
</Button>
)}
<Badge variant={response.status >= 400 ? 'destructive' : 'success'}>
{response.status}
</Badge>
</div>
</TabsList>
<TabsContent value="body" className="mt-0 flex-1 overflow-auto p-0">
<CodeBlock
language="json"
hideLineNumbers
className="rounded-md border-none! px-4! py-3! h-full"
value={prettifyJSON(response.body)}
/>
</TabsContent>
<TabsContent value="headers" className="mt-0 flex-1 overflow-auto p-0">
<CodeBlock
language="json"
hideLineNumbers
className="rounded-md border-none! px-4! py-3! h-full"
value={prettifyJSON(JSON.stringify(response.headers, null, 2))}
/>
</TabsContent>
</Tabs>
)}
</div>
) : isPending ? (
<div className="h-full flex flex-col items-center justify-center gap-2">
<Loader2 size={24} className="text-foreground-muted animate-spin" />
<p className="text-sm text-foreground-light">Sending request...</p>
</div>
) : (
<div className="h-full flex flex-col items-center justify-center gap-2">
<Send size={24} className="text-foreground-muted" />
<p className="text-sm text-foreground-light">Send your first test request</p>
</div>
)}
</div>
</ResizablePanel>
</ResizablePanelGroup>
<SheetFooter className="px-5 py-3 border-t">
<div className="flex items-center gap-2">
<ShortcutTooltip shortcutId={SHORTCUT_IDS.FUNCTION_DETAIL_SUBMIT_TEST} side="top">
<Button
variant="primary"
type="submit"
loading={isPending}
disabled={isPending}
onClick={() =>
track('edge_function_test_send_button_clicked', { httpMethod: method })
}
>
Send Request
</Button>
</ShortcutTooltip>
</div>
</SheetFooter>
</form>
</Form>
</SheetContent>
</Sheet>
)
}