mirror of
https://github.com/supabase/supabase.git
synced 2026-09-06 09:59:03 +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>
98 lines
2.8 KiB
TypeScript
98 lines
2.8 KiB
TypeScript
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',
|
|
})
|
|
})
|
|
})
|