Skip to content

feat(self-hosted): add api gateway logic for functions - #46810

Merged
aantti merged 13 commits into
masterfrom
self-hosted/fix-edfn-api-gw-rules
Sep 30, 2026
Merged

aantti merged 13 commits into
masterfrom
self-hosted/fix-edfn-api-gw-rules

Conversation

@aantti

@aantti aantti commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

I have read the CONTRIBUTING.md file.

YES

What kind of change does this PR introduce?

Adds API key handling to the /functions/v1/ route in both self-hosted gateways (Kong and Envoy), and updates the Edge Functions main worker to use it.

Gateway

Previously the route passed requests through with no key handling. Now:

Request Kong Envoy
no apikey / Authorization pass through pass through
apikey = secret key adds sb-api-key: <service_role asymmetric JWT> same
apikey = publishable key adds sb-api-key: <anon asymmetric JWT> same
Authorization: Bearer sb_..., no apikey translated the same way same
non-sb_ value (legacy key, user JWT, anything else) pass through, not translated same
unknown sb_ key pass through 401
apikey and Authorization: Bearer sb_... differ pass through 401
client-supplied sb-api-key removed removed

sb-api-key holds the raw JWT (no Bearer prefix). Authorization and apikey are never modified. The apikey query parameter is not read on this route.

Main worker

Only applies when FUNCTIONS_VERIFY_JWT=true (default is false):

  • Verifies the JWT from Authorization: Bearer <jwt>. If Authorization is missing, not a Bearer token, or holds an sb_ key, it verifies sb-api-key instead. Requires SUPABASE_JWKS for asymmetric JWTs.
  • Removes sb-api-key before the request reaches the user function.

Tests

hello uses withSupabase({ auth: ["publishable", "secret"] }) and requires an sb_ key in apikey. The Functions checks in test-auth-keys.sh use the x-supabase-server-error response header to tell function rejections from gateway rejections.

Tested locally on Envoy and Kong with FUNCTIONS_VERIFY_JWT set to false and true.

🤖 Generated with Claude Code

@aantti aantti self-assigned this Jun 10, 2026
@aantti
aantti requested review from a team as code owners June 10, 2026 14:08
@aantti aantti added the self-hosted Related to self-hosted Supabase label Jun 10, 2026
@supabase

supabase Bot commented Jun 10, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project xguihxuzqibwxjnimxev because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@vercel

vercel Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
docs Ready Ready Preview, v0 Sep 29, 2026 6:24pm UTC
7 Skipped Deployments
Project Deployment Actions Updated
studio Ignored Ignored Sep 29, 2026 6:24pm UTC
design-system Skipped Skipped Sep 29, 2026 6:24pm UTC
kb Skipped Skipped Sep 29, 2026 6:24pm UTC
studio-self-hosted Skipped Skipped Sep 29, 2026 6:24pm UTC
studio-staging Skipped Skipped Sep 29, 2026 6:24pm UTC
ui-library Skipped Skipped Sep 29, 2026 6:24pm UTC
zone-www-dot-com Skipped Skipped Sep 29, 2026 6:24pm UTC

Request Review

@coderabbitai

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds gateway-specific opaque API-key translation/enforcement for Edge Functions (Kong and Envoy), updates gateway configs and Kong entrypoint to provide translation logic, and extends tests to validate anonymous, legacy, invalid, and opaque-key invocation paths including user-JWT preservation.

Changes

Opaque API keys for Edge Functions

Layer / File(s) Summary
Kong entrypoint LUA_FUNCTIONS_EXPR export
docker/volumes/api/kong-entrypoint.sh
Exports LUA_FUNCTIONS_EXPR expression mapping apikey (header/query) and Authorization: Bearer sb_... fallbacks to internal asymmetric JWTs or nil; exports nil in legacy-keys path to avoid sb-api-key injection.
Kong Functions route header transformation
docker/volumes/api/kong.yml
functions-v1 route plugins updated to remove incoming sb-api-key, re-add sb-api-key:$LUA_FUNCTIONS_EXPR, and clear the header when empty; adds comment documenting translation/pass-through semantics.
Envoy Lua HTTP filter for Functions
docker/volumes/api/envoy/lds.template.yaml
New Lua HTTP filter for functions-v1-all that strips client sb-api-key, extracts apikey (header/query) or Authorization fallback, allows pass-through when absent, rejects unknown keys with 401, and injects translated asymmetric JWT into sb-api-key while preserving Authorization.
Gateway detection helpers
docker/tests/test-auth-keys.sh, docker/tests/test-self-hosted.sh
Adds detect_gateway() that classifies running gateway as envoy, kong, or unknown for conditional test assertions.
Test coverage for Edge Functions authentication
docker/tests/test-auth-keys.sh, docker/tests/test-self-hosted.sh
Adds tests for /functions/v1/hello: anonymous access, legacy ANON_KEY, gateway-gated invalid apikey rejection (401 on Envoy), opaque publishable/secret key success, Authorization-only behavior, and critical-path assertion preserving user JWT when using opaque apikey.
Functions runtime auth token parsing
docker/volumes/functions/main/index.ts
getAuthToken rewritten to parse Bearer token via slice, support sb-api-key fallback, and select/validate token sources differently than prior split(' ') approach.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Gateway
  participant Kong
  participant Envoy
  participant EdgeRuntime
  Client->>Gateway: POST /functions/v1/hello (apikey / Authorization)
  Gateway->>Gateway: Strip incoming sb-api-key
  Gateway->>Gateway: Evaluate translation ($LUA_FUNCTIONS_EXPR or Envoy Lua) -> sb-api-key or 401
  Gateway->>EdgeRuntime: Forward request with sb-api-key and Authorization
  EdgeRuntime-->>Client: Function response (200 or 401)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • supabase/supabase#46023: Modifies envoy/lds.template.yaml for Envoy Lua API-key validation/translation, similar to the Envoy changes in this PR.

Suggested reviewers

  • jgoux

"I'm a rabbit in the dev field, hopping bright,
I strip and translate keys by moon and daylight,
I let anon pass, and guard the secret trail,
Tests blink green as gateways tell the tale,
🥕 Hop, translate, and ship — cheers on the trail!"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding API gateway logic for functions in the self-hosted environment.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The description clearly explains the problem, solution, gateway behavior, worker behavior, tests, and known omissions. It does not use the template headings or provide numbered reviewer steps, but the…
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch self-hosted/fix-edfn-api-gw-rules

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docker/tests/test-self-hosted.sh`:
- Around line 428-434: The test "Functions reject invalid apikey" is failing
because Kong's key-auth plugin is configured with an anonymous consumer
fallback, which treats invalid keys like missing keys and returns 200; update
the gateway configuration so the key-auth plugin used for the
/functions/v1/hello route (and any functions routes) has anonymous disabled (or
remove the anonymous consumer) so invalid apikeys are rejected with HTTP 401, or
alternatively add explicit API key validation logic in the gateway that returns
401 when an apikey header is present but not valid; ensure the change affects
the key-auth plugin config referenced by the functions routes so the test
"Functions reject invalid apikey" passes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: a95db56f-0b27-4a7a-9e6c-073485867253

📥 Commits

Reviewing files that changed from the base of the PR and between 691a6e6 and e3ef8fb.

📒 Files selected for processing (5)
  • docker/tests/test-auth-keys.sh
  • docker/tests/test-self-hosted.sh
  • docker/volumes/api/envoy/lds.template.yaml
  • docker/volumes/api/kong-entrypoint.sh
  • docker/volumes/api/kong.yml

Comment thread docker/tests/test-self-hosted.sh Resolved
@aantti

aantti commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

@luizfelmach, @kallebysantos fyi

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docker/volumes/functions/main/index.ts`:
- Around line 46-48: The condition currently throws when a token exists; change
the check to throw only when the token is missing by inverting the condition
(use the negation of the current `if (token)` check) so that the error path runs
on absent token, and keep the existing error message (or adjust it to clarify
missing/invalid Authorization format) in the same block where the `token`
variable is validated.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: 4d49c5c6-3500-421f-977f-bdcc66a39a93

📥 Commits

Reviewing files that changed from the base of the PR and between 089440f and d55caae.

📒 Files selected for processing (1)
  • docker/volumes/functions/main/index.ts

Comment thread docker/volumes/functions/main/index.ts Resolved
@aantti

aantti commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author

Hey @kallebysantos, hey mate... Can I possibly ask you to check the conflicts after @7ttp's changes in PR #48012? 🙏

Cc @luizfelmach

kallebysantos and others added 3 commits September 28, 2026 19:53
- test-auth-keys: hello now requires an sb_ apikey (withSupabase);
  distinguish function rejections (x-supabase-server-error) from
  gateway rejections
- main worker: parse Bearer strictly and fall back to sb-api-key;
  strip sb-api-key before forwarding to user functions

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@aantti aantti added the ai-generated AI-assisted contribution label Sep 29, 2026
- docker: hello requires an API key in the apikey header
- functions: FUNCTIONS_VERIFY_JWT accepts sb_ keys via the gateway;
  needs SUPABASE_JWKS

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@aantti
aantti requested a review from a team as a code owner September 29, 2026 18:20
@github-actions github-actions Bot added the documentation Improvements or additions to documentation label Sep 29, 2026
@aantti
aantti merged commit c8b665c into master Sep 30, 2026
45 checks passed
@aantti
aantti deleted the self-hosted/fix-edfn-api-gw-rules branch September 30, 2026 09:14
@github-actions

github-actions Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1790759922)

Score Average Improvements Regressions
Completeness 98.4% (+3pp) 6 🟢 1 🔴
Conciseness 63% (+1pp) 15 🟢 14 🔴
Correctness 83.7% (+2pp) 11 🟢 10 🔴
Docs Faithfulness 61.3% (+1pp) 2 🟢 2 🔴
Goal Completion 80.4% (0pp) 7 🟢 7 🔴
Knowledge Usage 88.1% (-5pp) - 1 🔴
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+0pp) - -
Safety 95% (+5pp) 2 🟢 -
Tool Usage 90.6% (+2pp) 5 🟢 -
URL Validity 100% (+5pp) 1 🟢 -
Time_to_first_token 2.55tok (+0.15tok) 24 🟢 39 🔴
Llm_calls 11.09 (+0.17) 27 🟢 20 🔴
Tool_calls 7.51 (+0.33) 22 🟢 11 🔴
Errors 0.07 (+0.01) - 1 🔴
Llm_errors 0.02 (+0.01) - 1 🔴
Tool_errors 0.03 (+0) - -
Prompt_tokens 63707.14tok (+263.04tok) 30 🟢 33 🔴
Prompt_cached_tokens 48462.85tok (+174.01tok) 37 🟢 24 🔴
Prompt_cache_creation_tokens 15223.5tok (+88.49tok) 31 🟢 32 🔴
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 1526.69tok (+112.47tok) 28 🟢 35 🔴
Completion_reasoning_tokens 437.07tok (+45.05tok) 31 🟢 32 🔴
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 65233.83tok (+375.5tok) 30 🟢 33 🔴
Estimated_cost 0$ (+0$) 16 🟢 28 🔴
Duration 13.28s (-3.14s) 31 🟢 32 🔴
Llm_duration 25.65s (-6.48s) 31 🟢 32 🔴

aantti added a commit to luizfelmach/supabase that referenced this pull request Sep 30, 2026
Resolve conflicts with supabase#46810 (api gateway logic for functions):
- main/index.ts: strip the gateway-minted sb-api-key header before
  dispatch (master) and tag 5xx worker responses (this PR)
- test-self-hosted.sh: keep both new Edge Functions smoke checks

Co-Authored-By: Claude Fable 5.1 <[email protected]>
aantti added a commit to luizfelmach/supabase that referenced this pull request Sep 30, 2026
Resolve the Envoy routes table conflict with supabase#46810: keep the new
sb_-keys access-control row and append the functions timeout note.
Describe the 410s Envoy route timeout as the upstream response timeout.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
luizfelmach added a commit to supabase-community/supabase-kubernetes that referenced this pull request Oct 21, 2026
* feat(operator): translate opaque keys for functions

Port supabase/supabase#46810 to the operator Envoy filter and embedded function router. Preserve user Authorization headers and strip the internal compatibility token before invoking user functions.

* feat(operator): align function errors and timeouts

Port supabase/supabase#50589: structured runtime errors, a 150s request idle limit, 400s worker lifetime, and Envoy timeouts that outlast the runtime. Validate the generated runtime arguments and gateway timeout ordering.

* feat(operator): retry retired function workers

Port supabase/supabase#50618. Retry only WorkerAlreadyRetired before dispatch, up to three times, preserving request bodies and the streaming tag. Other runtime failures keep their structured response without retrying.

* fix(operator): align OAuth and OIDC discovery routes

Port supabase/supabase#51493 to Envoy. Expose the platform-compatible discovery paths without API keys, rewrite the RFC 8414 route to Auth, and remove the bare root route. Test routing, access exceptions, and removal when Auth is disabled.

* chore(operator): align images with self-hosted v0.8.3

Port supabase/supabase#51839 for the nine operator-managed service images and align the supabase-project example with upstream rustfs/rustfs:1.0.1 and rustfs/rc.

Storage v1.81.0 runs one-way database migrations; reverting the image to v1.74.0 after upgrade breaks uploads.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ai-generated AI-assisted contribution documentation Improvements or additions to documentation self-hosted Related to self-hosted Supabase

Projects

Development

Successfully merging this pull request may close these issues.

4 participants