Skip to content

fix(edge): CORS migration + forensic audit doc (substitui #133)#136

Merged
adm01-debug merged 9 commits into
mainfrom
chore/pr126-cherry-pick
May 23, 2026
Merged

fix(edge): CORS migration + forensic audit doc (substitui #133)#136
adm01-debug merged 9 commits into
mainfrom
chore/pr126-cherry-pick

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

@adm01-debug adm01-debug commented May 23, 2026

Substitui PR #133 (fechado sem merge)

Branch chore/pr126-cherry-pick foi force-pushed sobre o main atual (a9a667ff) após o merge dos PRs intermediários #130 / #132 / #135. Os 3 arquivos abaixo continuam com valor único e não-redundante vs main.

O que entra (3 arquivos)

Arquivo Tipo Linhas Razão
docs/AUDITORIA_BUGS_2026-05-23.md docs (novo) +497 Auditoria forense reconciliando 4 auditorias anteriores (B-1..B-9) — referência permanente
supabase/functions/simulation-orchestrator/index.ts edge fix +3 −5 corsHeaders inline → buildPublicCorsHeaders()
supabase/functions/sync-external-db/index.ts edge fix +3 −5 corsHeaders inline → buildPublicCorsHeaders()

Por quê

Os 2 edge functions declaravam corsHeaders inline (sem x-request-id), violando o gate de CORS do projeto (check:edge-cors + check:no-inline-cors). A migration restaura observabilidade — x-request-id cross-referenciável entre browser logs e Sentry/server logs no preflight.

Confirmado via git grep no main atual:

buildPublicCorsHeaders em simulation-orchestrator/index.ts: 0 ocorrências
buildPublicCorsHeaders em sync-external-db/index.ts:        0 ocorrências

Helper buildPublicCorsHeaders() existe em supabase/functions/_shared/cors.ts:204.

O que NÃO entra (descartado do PR #126 original)

Item Status
B-1 validateUrlFormat ✅ já em main (extraído via outro PR)
useGlobalShortcuts hooks fix ✅ já em main via #124
T-FIX-3 GH Actions bump ✅ já em main via #124
AdminStandardRules PascalCase ✅ já em main via #124
B-3 toast leaks ❌ rejeitado — baseline 176→179 seria regressão

Test plan

  • git diff origin/main...origin/chore/pr126-cherry-pick confirma só 3 arquivos
  • git log origin/main..origin/chore/pr126-cherry-pick mostra 2 commits limpos sobre a9a667ff
  • CI deste PR validará check:edge-cors + check:no-inline-cors passando
  • CodeRabbit / cubic revisam (sem rate-limit desta vez se possível)

Referências

🤖 Cherry-pick cirúrgico via Claude — 3 arquivos validados sobre o main pós-#135.


Summary by cubic

Migrated CORS in simulation-orchestrator and sync-external-db to buildPublicCorsHeaders() to include x-request-id and pass CORS gates. Added docs/AUDITORIA_BUGS_2026-05-23.md, a forensic audit reconciling prior audits with current code and listing open items.

  • Bug Fixes

    • Replaced inline CORS headers with buildPublicCorsHeaders() in supabase/functions/simulation-orchestrator/index.ts and supabase/functions/sync-external-db/index.ts, satisfying check:edge-cors and check:no-inline-cors and restoring preflight observability.
  • Documentation

    • Added docs/AUDITORIA_BUGS_2026-05-23.md: notes 13/13 criticals closed, 0 npm audit vulnerabilities, 9 open bugs, and coverage gaps (103 skipped P0/E2E tests) with next steps.

Written for commit f343e28. Summary will update on new commits. Review in cubic

Summary by CodeRabbit

Notas da Versão

  • Documentação

    • Adicionado relatório de auditoria detalhado com métricas de segurança e status de bugs.
  • Correções de Bugs

    • Corrigidas vulnerabilidades de CORS em funções cloud.
    • Melhorada validação de URLs.
    • Atualizadas dependências do GitHub Actions para versões mais recentes.
  • Otimizações

    • Refatorizado gerenciamento de headers CORS para maior consistência.

Review Change Stack

…B-2)

Both edge functions declared corsHeaders inline (without x-request-id),
violating the project's CORS gate (check:edge-cors + check:no-inline-cors).

Migration:
- simulation-orchestrator: corsHeaders inline → buildPublicCorsHeaders()
- sync-external-db: corsHeaders inline → buildPublicCorsHeaders()

This restores observability: x-request-id can now be cross-referenced
between browser logs and Sentry/server logs across preflight.

Substitutes PR #126 B-2 finding. Other items of #126:
- B-1 validateUrlFormat: ✅ already merged via #124
- B-3 toast leaks: rejected (baseline 176→179 would be regression)
- useGlobalShortcuts hooks fix: ✅ already merged via #124
- T-FIX-3 GH Actions bump: ✅ already merged via #124
- AdminStandardRules PascalCase: ✅ already merged via #124

Helper used (verified existing in main):
- supabase/functions/_shared/cors.ts:204 exports buildPublicCorsHeaders()
Adds AUDITORIA_BUGS_2026-05-23.md reconciling findings from 4 prior
audits (2026-04-29, 05-07, 05-12, 05-13) against the current code state.

Different focus from AUDITORIA-EXAUSTIVA-2026-05-23.md (#124, which is a
20-step plan) — this one is a P0/P1 forensic inventory with 7-pass
analysis.

Key findings documented:
- 13 critical security issues from prior audits: 13/13 CLOSED
- 9 currently-open bugs identified (B-1 through B-9)
- 103 it.skip in P0/E2E tests (test coverage gap)
- 1333 TS + 473 ESLint + 73 toast.error leaks in baselines
- 0 npm audit vulnerabilities

Resolution status of B-1 through B-3:
- B-1 (validateUrlFormat): ✅ already fixed in #124
- B-2 (CORS inline simulation-orchestrator + sync-external-db):
  ✅ fixed in companion commit 507692b of this branch
- B-3 through B-9: documented for follow-up

Substitutes PR #126 docs delivery.
Copilot AI review requested due to automatic review settings May 23, 2026 12:37
@vercel
Copy link
Copy Markdown

vercel Bot commented May 23, 2026

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

Project Deployment Actions Updated (UTC)
we-dream-big Ready Ready Preview, Comment May 23, 2026 1:26pm

@supabase
Copy link
Copy Markdown

supabase Bot commented May 23, 2026

This pull request has been ignored for the connected project doufsxqlfjyuvxuezpln due to reaching the limit of concurrent preview branches.
Go to Project Integrations Settings ↗︎ if you wish to update this limit.


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

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 23, 2026

Walkthrough

Refatoração de CORS headers em duas funções Supabase (simulation-orchestrator e sync-external-db) para usar helper centralizado, eliminando duplicação de configuração. Novo relatório de auditoria documenta bugs abertos, métricas de segurança, cobertura desativada e recomendações priorizadas com resultados de gates locais.

Changes

CORS Consolidation and Audit Documentation

Layer / File(s) Summary
CORS headers consolidation in Supabase functions
supabase/functions/simulation-orchestrator/index.ts, supabase/functions/sync-external-db/index.ts
Ambas as funções substituem objetos CORS inline por buildPublicCorsHeaders() importado de _shared/cors.ts, eliminando duplicação de headers e centralizando a lógica de configuração CORS para OPTIONS e respostas JSON.
May 2026 bug audit report
docs/AUDITORIA_BUGS_2026-05-23.md
Consolidação completa de achados: métricas de segurança, items P0–P3 (CORS issues, toast leaks com error.message, warnings ESLint/TypeScript, falhas de cobertura), testes skip, issues abertas, recomendações curto/médio/longo prazo, "QA deep dive" com gates locais (typecheck, lint, coverage, toast-leaks, edge-cors, no-inline-cors, observability) e tracking de métricas absolutas.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • adm01-debug/promo-gifts-v4#39: Adiciona *.vercel.app ao allowlist CORS em _shared/cors.ts; este PR torna essa mudança efetiva ao fazer funções Supabase consumirem buildPublicCorsHeaders().
🚥 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
Title check ✅ Passed O título é direto e específico: identifica claramente que é um fix de CORS (edge functions) + documento de auditoria forense, e referencia a substituição do PR #133. Resume bem os dois commits principais do changeset.
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 Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/pr126-cherry-pick

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

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.

Actionable comments posted: 2

🤖 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 `@docs/AUDITORIA_BUGS_2026-05-23.md`:
- Around line 372-373: The table in docs/AUDITORIA_BUGS_2026-05-23.md has rows
with 3 pipe-separated cells (`| A3: console.warn/error droppped | ✅ FECHADO |
`vite.config.ts:34-35` |` and `| 5 vulnerabilidades npm | ✅ FECHADO | `npm
audit` retorna 0 vulnerabilidades em prod e dev |`) while the header defines
only 2 columns, causing an MD056 lint error; fix by either updating the table
header to three columns (add a third header cell and divider) or collapse those
rows to two cells (merge the status and location into one cell or remove the
extra cell) so the header and all rows consistently have the same column count.
- Line 85: Os blocos fenced (``` ... ```) neste documento estão sem
identificador de linguagem; atualize cada bloco de código removendo a fence
vazia e adicionando uma linguagem apropriada (por exemplo ```text, ```bash ou
```json conforme o conteúdo) para evitar MD040 e melhorar highlighting no
preview; procure todas as ocorrências das fences triplas (``` ) no arquivo e
substituir por fences com a tag de linguagem correspondente mantendo o conteúdo
interno inalterado.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4bdc4f9a-a7b8-4a4f-8278-bcfca5453aa7

📥 Commits

Reviewing files that changed from the base of the PR and between a9a667f and 08681b0.

📒 Files selected for processing (3)
  • docs/AUDITORIA_BUGS_2026-05-23.md
  • supabase/functions/simulation-orchestrator/index.ts
  • supabase/functions/sync-external-db/index.ts

Comment thread docs/AUDITORIA_BUGS_2026-05-23.md
Comment thread docs/AUDITORIA_BUGS_2026-05-23.md
Copy link
Copy Markdown
Contributor

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 cherry-picks a small Edge Functions fix to eliminate inline CORS headers (to satisfy the repo’s CORS gates and restore x-request-id exposure), and adds a long-form forensic audit document meant to be a permanent reference snapshot of known issues/status.

Changes:

  • Migrates simulation-orchestrator and sync-external-db from inline corsHeaders to _shared/cors.ts’s buildPublicCorsHeaders().
  • Adds docs/AUDITORIA_BUGS_2026-05-23.md consolidating prior audit findings and current status.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 9 comments.

File Description
supabase/functions/simulation-orchestrator/index.ts Replaces inline CORS header object with buildPublicCorsHeaders() helper.
supabase/functions/sync-external-db/index.ts Replaces inline CORS header object with buildPublicCorsHeaders() helper.
docs/AUDITORIA_BUGS_2026-05-23.md Adds a consolidated audit/status document; currently contains several statements that don’t match repo/PR reality and should be corrected.

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

Comment thread docs/AUDITORIA_BUGS_2026-05-23.md Outdated
Comment thread docs/AUDITORIA_BUGS_2026-05-23.md Outdated
Comment thread docs/AUDITORIA_BUGS_2026-05-23.md Outdated
Comment thread docs/AUDITORIA_BUGS_2026-05-23.md Outdated
Comment thread docs/AUDITORIA_BUGS_2026-05-23.md Outdated

Quando malformada, retorna `result = { ok: false, error: "URL_MALFORMED: …", error_kind: "config" }` antes do `pingX()`. Mensagem mostra os primeiros 40 chars da URL ofensora (sem expor JWT, que só está em `key`).

**Follow-up (não aplicado aqui):** teste unitário cobrindo (URL válida, URL do dashboard, trailing slash, path, vazia, sem https) — registrado como #B-1-FU.
Comment thread docs/AUDITORIA_BUGS_2026-05-23.md Outdated
Comment on lines +123 to +124
**Baseline (.toast-leaks-baseline.json):** 0 ocorrências. Esta é uma **regressão pós-baseline** — entre 2026-05-22 (data do baseline) e hoje (2026-05-23), 73 novos call sites apareceram.

| Críticos de segurança (auditorias 04→05/2026) | 3 + 3 + 3 + 4 = **13** | **0 abertos · 13 fechados** |
| Bugs em código aberto agora | — | **9** (com fonte verificável) |
| Cobertura P0 desligada (`it.skip`/`test.skip`) | — | **103 tests** (48 em `tests/p0/` + 55 em `e2e/`) |
| Dívida em baselines aceita (TSC + ESLint + toast) | — | **1.333 TS + 473 ESLint + 73 toast** |
Comment thread docs/AUDITORIA_BUGS_2026-05-23.md Outdated
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

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

3 issues found across 3 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread docs/AUDITORIA_BUGS_2026-05-23.md
Comment thread docs/AUDITORIA_BUGS_2026-05-23.md Outdated
Comment thread docs/AUDITORIA_BUGS_2026-05-23.md
adm01-debug and others added 7 commits May 23, 2026 10:23
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
@vercel
Copy link
Copy Markdown

vercel Bot commented May 23, 2026

Deployment failed with the following error:

There is no GitHub account connected to this Vercel account.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants