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>
221 lines
7.1 KiB
TypeScript
221 lines
7.1 KiB
TypeScript
import { describe, expect, it } from 'vitest'
|
|
|
|
import {
|
|
buildEdgeFunctionHeaderAddActions,
|
|
ensureEdgeFunctionAuthorizationHeader,
|
|
getEdgeFunctionAuthHeader,
|
|
} from './httpHeaderAddActions'
|
|
|
|
describe('buildEdgeFunctionHeaderAddActions', () => {
|
|
it('includes the apikey header for secret keys', () => {
|
|
const [authAction] = buildEdgeFunctionHeaderAddActions({
|
|
apiKey: 'sb_secret_123',
|
|
createRow: (name, value) => ({ name, value }),
|
|
})
|
|
|
|
expect(authAction.label).toBe('Add secret key')
|
|
expect(authAction.description).toBe(
|
|
'Requires JWT verification to be disabled and authorization handled by the function'
|
|
)
|
|
expect(authAction.createRows()).toEqual([{ name: 'apikey', value: 'sb_secret_123' }])
|
|
})
|
|
|
|
it('falls back to the Authorization header for legacy keys', () => {
|
|
const [authAction] = buildEdgeFunctionHeaderAddActions({
|
|
apiKey: 'legacy-service-role-jwt',
|
|
createRow: (name, value) => ({ name, value }),
|
|
})
|
|
|
|
expect(authAction.label).toBe('Add secret key')
|
|
expect(authAction.description).toBe('Required for edge functions that enforce JWT verification')
|
|
expect(authAction.createRows()).toEqual([
|
|
{ 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', () => {
|
|
it('returns the apikey header for publishable keys', () => {
|
|
expect(getEdgeFunctionAuthHeader('sb_publishable_123')).toEqual({
|
|
name: 'apikey',
|
|
value: 'sb_publishable_123',
|
|
})
|
|
})
|
|
|
|
it('returns the Authorization header for non-prefixed keys', () => {
|
|
expect(getEdgeFunctionAuthHeader('legacy-service-role-jwt')).toEqual({
|
|
name: 'Authorization',
|
|
value: 'Bearer legacy-service-role-jwt',
|
|
})
|
|
})
|
|
|
|
it.each(['sb_secretly_123', 'sb_publishableish_123'])(
|
|
'does not treat %s as a new API key',
|
|
(apiKey) => {
|
|
expect(getEdgeFunctionAuthHeader(apiKey)).toEqual({
|
|
name: 'Authorization',
|
|
value: `Bearer ${apiKey}`,
|
|
})
|
|
}
|
|
)
|
|
})
|
|
|
|
describe('ensureEdgeFunctionAuthorizationHeader', () => {
|
|
const createRow = (name: string, value: string) => ({ id: 'new', name, value })
|
|
|
|
it('preserves apikey while normalizing Authorization rows', () => {
|
|
const headers = [
|
|
{ id: 'custom-before', name: 'X-Before', value: 'before' },
|
|
{ id: 'authorization', name: ' authorization ', value: 'Bearer old-key' },
|
|
{ id: 'apikey', name: 'apikey', value: 'sb_secret_123' },
|
|
{ id: 'duplicate', name: 'AUTHORIZATION', value: 'Bearer stale-key' },
|
|
{ id: 'custom-after', name: 'X-After', value: 'after' },
|
|
]
|
|
|
|
expect(
|
|
ensureEdgeFunctionAuthorizationHeader({
|
|
headers,
|
|
serviceRoleKey: 'legacy-service-role-jwt',
|
|
verifyJwt: true,
|
|
createRow,
|
|
})
|
|
).toEqual([
|
|
{ id: 'custom-before', name: 'X-Before', value: 'before' },
|
|
{
|
|
id: 'authorization',
|
|
name: 'Authorization',
|
|
value: 'Bearer old-key',
|
|
},
|
|
{ id: 'apikey', name: 'apikey', value: 'sb_secret_123' },
|
|
{ id: 'custom-after', name: 'X-After', value: 'after' },
|
|
])
|
|
})
|
|
|
|
it('adds Authorization alongside apikey when JWT verification is enabled', () => {
|
|
const headers = [{ id: 'apikey', name: 'apikey', value: 'sb_secret_123' }]
|
|
|
|
expect(
|
|
ensureEdgeFunctionAuthorizationHeader({
|
|
headers,
|
|
serviceRoleKey: 'legacy-service-role-jwt',
|
|
verifyJwt: true,
|
|
createRow,
|
|
})
|
|
).toEqual([
|
|
{ id: 'apikey', name: 'apikey', value: 'sb_secret_123' },
|
|
{ id: 'new', name: 'Authorization', value: 'Bearer legacy-service-role-jwt' },
|
|
])
|
|
})
|
|
|
|
it('does not change headers without an applicable service role key', () => {
|
|
const headers = [
|
|
{ id: 'authorization', name: 'Authorization', value: 'Bearer existing-key' },
|
|
{ id: 'apikey', name: 'apikey', value: 'sb_secret_123' },
|
|
]
|
|
|
|
expect(
|
|
ensureEdgeFunctionAuthorizationHeader({
|
|
headers,
|
|
serviceRoleKey: 'legacy-service-role-jwt',
|
|
verifyJwt: false,
|
|
createRow,
|
|
})
|
|
).toBe(headers)
|
|
expect(ensureEdgeFunctionAuthorizationHeader({ headers, verifyJwt: true, createRow })).toBe(
|
|
headers
|
|
)
|
|
expect(
|
|
ensureEdgeFunctionAuthorizationHeader({
|
|
headers,
|
|
serviceRoleKey: 'sb_secret_456',
|
|
verifyJwt: true,
|
|
createRow,
|
|
})
|
|
).toBe(headers)
|
|
})
|
|
|
|
it.each(['Bearer user-entered-token', ''])(
|
|
'preserves a user-entered Authorization value: %j',
|
|
(value) => {
|
|
const headers = [
|
|
{
|
|
id: 'authorization',
|
|
name: 'Authorization',
|
|
value,
|
|
},
|
|
{ id: 'apikey', name: 'apikey', value: 'sb_secret_123' },
|
|
]
|
|
|
|
expect(
|
|
ensureEdgeFunctionAuthorizationHeader({
|
|
headers,
|
|
serviceRoleKey: 'legacy-service-role-jwt',
|
|
verifyJwt: true,
|
|
createRow,
|
|
})
|
|
).toBe(headers)
|
|
}
|
|
)
|
|
})
|