mirror of
https://github.com/supabase/supabase.git
synced 2026-09-10 03:51:51 +08:00
<!-- 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>
125 lines
4.4 KiB
TypeScript
125 lines
4.4 KiB
TypeScript
import type { KeyValueFieldArrayAction } from 'ui-patterns/form/KeyValueFieldArray/KeyValueFieldArray'
|
|
|
|
interface 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?: string
|
|
createRow: (name: string, value: string) => TRow
|
|
}
|
|
|
|
interface HTTPHeader {
|
|
name: string
|
|
value: string
|
|
}
|
|
|
|
interface EnsureEdgeFunctionAuthorizationHeaderParams<TRow extends HTTPHeader> {
|
|
headers: TRow[]
|
|
serviceRoleKey?: string
|
|
verifyJwt?: boolean
|
|
createRow: (name: string, value: string) => TRow
|
|
}
|
|
|
|
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 }
|
|
: { name: 'Authorization', value: `Bearer ${apiKey}` }
|
|
|
|
export const ensureEdgeFunctionAuthorizationHeader = <TRow extends HTTPHeader>({
|
|
headers,
|
|
serviceRoleKey,
|
|
verifyJwt,
|
|
createRow,
|
|
}: EnsureEdgeFunctionAuthorizationHeaderParams<TRow>): TRow[] => {
|
|
if (!verifyJwt || !serviceRoleKey || isNewApiKey(serviceRoleKey)) return headers
|
|
|
|
const isAuthorization = (header: HTTPHeader) =>
|
|
header.name.trim().toLowerCase() === 'authorization'
|
|
const authorizationIndex = headers.findIndex(isAuthorization)
|
|
|
|
if (authorizationIndex === -1) {
|
|
return [...headers, createRow('Authorization', `Bearer ${serviceRoleKey}`)]
|
|
}
|
|
|
|
const authorizationHeader = headers[authorizationIndex]
|
|
const normalizedHeaders = headers.filter(
|
|
(header, index) => index === authorizationIndex || !isAuthorization(header)
|
|
)
|
|
|
|
if (normalizedHeaders.length === headers.length && authorizationHeader.name === 'Authorization') {
|
|
return headers
|
|
}
|
|
|
|
normalizedHeaders[authorizationIndex] = {
|
|
...authorizationHeader,
|
|
name: 'Authorization',
|
|
}
|
|
return normalizedHeaders
|
|
}
|
|
|
|
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',
|
|
// 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'
|
|
: 'Required for edge functions that enforce JWT verification',
|
|
createRows: () => [createRow(authHeader.name, authHeader.value)],
|
|
},
|
|
{
|
|
key: 'add-source-header',
|
|
label: 'Add custom source',
|
|
description: 'Useful to verify that the edge function was triggered from this webhook',
|
|
createRows: () => createRow('x-supabase-webhook-source', '[Use a secret value]'),
|
|
separatorAbove: true,
|
|
},
|
|
]
|
|
}
|