Skip to content

Use shared CORS header helper in proxy endpoints#27

Merged
adm01-debug merged 4 commits into
mainfrom
codex/realizar-auditoria-tecnica-exaustiva
Apr 27, 2026
Merged

Use shared CORS header helper in proxy endpoints#27
adm01-debug merged 4 commits into
mainfrom
codex/realizar-auditoria-tecnica-exaustiva

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

@adm01-debug adm01-debug commented Apr 27, 2026

Motivation

  • Centralize and reuse CORS header logic for the proxy endpoints to ensure consistent, request-aware CORS behavior.
  • Replace ad-hoc static header objects so responses (including OPTIONS and error paths) include the shared validation-derived headers.

Description

  • Import getCorsHeaders from ../_shared/validation.ts into both proxy-health and proxy-metrics functions.
  • Replace static corsHeaders / PROM_HEADERS with small wrapper functions getJsonCorsHeaders(req?) and getPromHeaders(req?) that merge getCorsHeaders(req) with endpoint-specific headers like Content-Type and caching directives.
  • Update all Response constructions (OPTIONS, success, method/error, and DB error responses) to call the new header helper with the incoming req.

Testing

  • No automated tests were executed as part of this change.

Codex Task

Summary by CodeRabbit

  • Refactor
    • Centralized API response header management across proxy services to improve consistency and maintainability.

Copilot AI review requested due to automatic review settings April 27, 2026 11:59
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 27, 2026

Warning

Rate limit exceeded

@adm01-debug has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 47 minutes and 14 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: bc88ed11-900e-4560-a152-b2192fa2631f

📥 Commits

Reviewing files that changed from the base of the PR and between 9ecaed7 and 82e2de1.

📒 Files selected for processing (4)
  • supabase/functions/_shared/__tests__/validation-headers.test.ts
  • supabase/functions/_shared/validation.ts
  • supabase/functions/proxy-health/index.ts
  • supabase/functions/proxy-metrics/index.ts
📝 Walkthrough

Walkthrough

Both Supabase proxy functions refactor header management by extracting CORS logic into shared helpers. The proxy-health function uses getJsonCorsHeaders(req?) for JSON responses with fixed authorization headers, while proxy-metrics uses getPromHeaders(req?) to merge shared CORS headers with Prometheus-specific headers.

Changes

Cohort / File(s) Summary
CORS Header Centralization
supabase/functions/proxy-health/index.ts, supabase/functions/proxy-metrics/index.ts
Both functions extract CORS header logic into request-aware helpers. proxy-health introduces getJsonCorsHeaders(req?) that enforces fixed authorization/content-type headers; proxy-metrics introduces getPromHeaders(req?) that combines shared CORS headers with Prometheus exposition headers. All response paths (OPTIONS, error codes, success) now use these centralized helpers.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 Hops of joy for headers clean,
CORS logic now unseen,
Shared and centered, what a dream,
Prometheus and health aligned supreme!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Use shared CORS header helper in proxy endpoints' directly and accurately summarizes the main refactoring: centralizing CORS header logic across proxy endpoints by introducing and using shared helper functions.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/realizar-auditoria-tecnica-exaustiva

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 and usage tips.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR centralizes CORS behavior for the proxy-health and proxy-metrics Supabase Edge Functions by switching from local/static header objects to the shared getCorsHeaders(req) helper (origin-validated + request-aware).

Changes:

  • Import getCorsHeaders from supabase/functions/_shared/validation.ts into both proxy endpoints.
  • Replace static CORS header constants with request-aware header builder helpers (getJsonCorsHeaders, getPromHeaders).
  • Update all Response paths (including OPTIONS and error responses) to use the new helpers with the incoming req.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
supabase/functions/proxy-metrics/index.ts Replaces static Prometheus response headers with getPromHeaders(req) built on shared CORS helper.
supabase/functions/proxy-health/index.ts Replaces static CORS headers with getJsonCorsHeaders(req) built on shared CORS helper for OPTIONS/error/success responses.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
function getJsonCorsHeaders(req?: Request) {
return {
...getCorsHeaders(req),
Copy link

Copilot AI Apr 27, 2026

Choose a reason for hiding this comment

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

getCorsHeaders(req) includes Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS. Because this handler doesn’t enforce GET-only, this change makes cross-origin non-GET requests from allowed origins pass CORS preflight (previously the endpoint didn’t advertise allowed methods). To avoid widening the callable surface, either add an explicit method guard (405 for non-GET/OPTIONS) and/or override Access-Control-Allow-Methods here to GET, OPTIONS to match the endpoint contract.

Suggested change
...getCorsHeaders(req),
...getCorsHeaders(req),
'Access-Control-Allow-Methods': 'GET, OPTIONS',

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
supabase/functions/proxy-health/index.ts (1)

15-20: Inconsistent helper shape vs. getPromHeaders — embed Content-Type to actually centralize headers.

getJsonCorsHeaders is named *Json* but does not set Content-Type: application/json, so call sites at lines 198 and 265 still have to manually spread it back in. The sibling helper getPromHeaders in supabase/functions/proxy-metrics/index.ts already embeds its Content-Type, so aligning this helper removes duplication and makes the OPTIONS / JSON responses use one source of truth.

♻️ Proposed refactor
 function getJsonCorsHeaders(req?: Request) {
   return {
     ...getCorsHeaders(req),
+    'Content-Type': 'application/json',
     'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
   }
 }

Then simplify the call sites:

-    return new Response(JSON.stringify({ error: error.message }), {
-      status: 500, headers: { ...getJsonCorsHeaders(req), 'Content-Type': 'application/json' },
-    })
+    return new Response(JSON.stringify({ error: error.message }), {
+      status: 500, headers: getJsonCorsHeaders(req),
+    })
-  }, null, 2), {
-    headers: { ...getJsonCorsHeaders(req), 'Content-Type': 'application/json' },
-  })
+  }, null, 2), {
+    headers: getJsonCorsHeaders(req),
+  })

OPTIONS responses returning a Content-Type header is benign and matches the pattern used by proxy-metrics.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@supabase/functions/proxy-health/index.ts` around lines 15 - 20,
getJsonCorsHeaders currently omits the Content-Type header while getPromHeaders
includes it; update getJsonCorsHeaders to add 'Content-Type': 'application/json'
so it centralizes JSON response headers (mirror getPromHeaders' shape), then
remove the manual spreading of Content-Type at the call sites that currently add
it (so they simply use getJsonCorsHeaders for OPTIONS and JSON responses).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@supabase/functions/proxy-health/index.ts`:
- Around line 15-20: getJsonCorsHeaders currently omits the Content-Type header
while getPromHeaders includes it; update getJsonCorsHeaders to add
'Content-Type': 'application/json' so it centralizes JSON response headers
(mirror getPromHeaders' shape), then remove the manual spreading of Content-Type
at the call sites that currently add it (so they simply use getJsonCorsHeaders
for OPTIONS and JSON responses).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 96dee699-bb17-4544-a941-efba0cd695eb

📥 Commits

Reviewing files that changed from the base of the PR and between 6ad6d57 and 9ecaed7.

📒 Files selected for processing (2)
  • supabase/functions/proxy-health/index.ts
  • supabase/functions/proxy-metrics/index.ts

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5e26ec0dd3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +28 to +30
const shared = getCorsHeaders(req)
return {
...shared,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep permissive CORS for public health endpoint

This helper now inherits getCorsHeaders(req), which only echoes a small allowlist of origins and otherwise falls back to a fixed Lovable origin, so browser requests from any other domain will fail CORS even though this endpoint was previously wildcard (*). If teams consume /proxy-health from external dashboards or status pages hosted outside that allowlist, those clients will start getting blocked at the browser despite the API still being reachable over HTTP.

Useful? React with 👍 / 👎.

@adm01-debug adm01-debug merged commit 4c46c48 into main Apr 27, 2026
4 of 5 checks passed
@adm01-debug adm01-debug deleted the codex/realizar-auditoria-tecnica-exaustiva branch May 9, 2026 01:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants