chore(edges): remove 6 edge functions órfãs (1 com vazamento ativo)#133
Conversation
Adiciona dois arquivos para resolver as 6 edge functions zumbis identificadas
no banco doufsxqlfjyuvxuezpln que nunca tiveram código no repo:
1) docs/historico/orphan-edges-2026-05-10.md — auditoria forense
completa com evidências, probe results, e a decisão consolidada.
Sobrevive à compactação de chat e protege contra "esqueci o que decidi".
2) .github/workflows/delete-orphan-edges.yml — workflow_dispatch com
gate de confirmação ("digite DELETE") + dryRun default=true.
Usa o secret SUPABASE_ACCESS_TOKEN já configurado.
[DECISION] As 6 edges (super-processor, quick-task, create_user,
product-search-v2, product-classifier, guardrails-ml) serão deletadas.
Razões em docs/historico/orphan-edges-2026-05-10.md.
🚨 ALERTA: product-search-v2 está ativamente vazando 6.123 produtos do
catálogo (com cost_price, stock_quantity, supplier_id, ncm_code) para
qualquer pessoa na internet sem auth. Remoção URGENTE recomendada.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Visão GeralPR integra auditoria de segurança de funções Edge orphan, documentação de vazamento ativo confirmado em produção, e workflow GitHub Actions com duplo gate (dry-run obrigatório + confirmação explícita) para deletar seis serviços não-rastreados. Inclui validação pós-deleção. MudançasRemoção de Funções Edge Orphan
Aspectos de Segurança & Review🔴 Crítico:
🟡 Notas:
Estimativa de Esforço de Review🎯 3 (Moderado) | ⏱️ ~20 minutos 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fe3d18e3f2
ℹ️ 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".
| if [[ $FAIL -gt 0 ]]; then | ||
| echo "::warning::Algumas edges falharam ao deletar (podem já não existir)." |
There was a problem hiding this comment.
Fail the workflow when deletion fails
When dryRun=false, any supabase functions delete failure only increments FAIL and emits a warning, so a bad token, API outage, or permission error can leave all six functions in production while the job still finishes green and the success() post-delete hint runs. Because this workflow is intended to remediate an active public data leak, please return a non-zero exit when FAIL > 0 (or validate the functions are gone) so operators do not treat an unsuccessful cleanup as completed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
.github/workflows/delete-orphan-edges.yml (1)
34-39: ⚡ Quick winAdicionar proteção de
environmentpara operação destrutivaO gate por texto (
DELETE) ajuda, mas não substitui aprovação formal para delete em produção. Recomendo atrelar o job a umenvironmentprotegido com required reviewers.Patch sugerido
jobs: delete: name: Delete orphan edges runs-on: ubuntu-latest timeout-minutes: 10 + environment: production🤖 Prompt for 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. In @.github/workflows/delete-orphan-edges.yml around lines 34 - 39, O job "delete" é uma operação destrutiva e precisa de proteção por environment; add a chave environment: "<environment-name>" (e.g. "production" ou "delete-protection") ao bloco do job `delete` no workflow para forçar revisores obrigatórios e aprovações configuradas no GitHub Environments; depois configure esse Environment nas configurações do repositório com required reviewers/approvals e, se desejar, restrinja quem pode executar o workflow.
🤖 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 @.github/workflows/delete-orphan-edges.yml:
- Around line 102-108: The delete loop currently treats failures as warnings
(increments FAIL) but lets the job exit successfully; update the logic around
the supabase functions delete "$fn" --project-ref "$PROJECT_REF" branch so that
any deletion error causes the script to fail fast (or at minimum exit non-zero
after the loop) instead of only echoing a warning—e.g., when the else branch for
the supabase delete runs, ensure you either call exit 1 immediately or set a
fatal flag and after the loop check FAIL>0 and exit 1; apply the same change to
the other delete block that manipulates PASS and FAIL (lines referenced in the
comment) so any operational error (token/network/permission/CLI) breaks the job.
In `@docs/historico/orphan-edges-2026-05-10.md`:
- Line 4: The markdown currently contains real sensitive identifiers (e.g., the
bank identifier "doufsxqlfjyuvxuezpln" and other UUIDs/SKUs/endpoints referenced
in the file) and must be sanitized: replace each real identifier with an
anonymized placeholder (e.g., BANK_ID_REDACTED, PROJECT_ENDPOINT_REDACTED,
SKU_REDACTED) consistently throughout the document (including the other ranges
noted: 124-153, 247-263) and add a short note pointing readers to a restricted
incident channel for raw evidence; ensure no real costs, stock values, UUIDs, or
endpoints remain in the repo version.
- Around line 100-105: Replace the language-less fenced code blocks with
annotated ones by changing the opening "```" to "```text" for the examples shown
(the block containing GET → {"service":"product-classifier",...} / POST {} →
{"error":"action: classify or batch_classify"}, the block with GET →
{"service":"guardrails-ml",...} / POST {} → {"error":"text required"}, and the
pricing block starting with "cost_price → 13.92"), and apply the same change to
the other occurrences mentioned (lines corresponding to the second and third
examples around 113-116 and 140-153) so the markdown linter MD040 warnings are
resolved.
---
Nitpick comments:
In @.github/workflows/delete-orphan-edges.yml:
- Around line 34-39: O job "delete" é uma operação destrutiva e precisa de
proteção por environment; add a chave environment: "<environment-name>" (e.g.
"production" ou "delete-protection") ao bloco do job `delete` no workflow para
forçar revisores obrigatórios e aprovações configuradas no GitHub Environments;
depois configure esse Environment nas configurações do repositório com required
reviewers/approvals e, se desejar, restrinja quem pode executar o workflow.
🪄 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: 31dbf7d8-48a7-4ce6-8025-af03abe37bed
📒 Files selected for processing (2)
.github/workflows/delete-orphan-edges.ymldocs/historico/orphan-edges-2026-05-10.md
| if supabase functions delete "$fn" --project-ref "$PROJECT_REF" 2>&1; then | ||
| echo " ✅ Deleted: $fn" | ||
| PASS=$((PASS+1)) | ||
| else | ||
| echo " ⚠️ Failed (talvez já não exista): $fn" | ||
| FAIL=$((FAIL+1)) | ||
| fi |
There was a problem hiding this comment.
Falha parcial está passando como sucesso e pode deixar edge vulnerável ativa
Hoje, em execução real, o fluxo só emite warning quando há erro no delete e finaliza com sucesso. Isso mascara falha operacional (token, rede, permissão, CLI) e pode manter product-search-v2 exposta. Em operação de contenção, erro real precisa quebrar o job.
Patch sugerido
- if supabase functions delete "$fn" --project-ref "$PROJECT_REF" 2>&1; then
+ DELETE_OUTPUT="$(supabase functions delete "$fn" --project-ref "$PROJECT_REF" 2>&1)" && RC=0 || RC=$?
+ if [[ $RC -eq 0 ]]; then
echo " ✅ Deleted: $fn"
PASS=$((PASS+1))
else
- echo " ⚠️ Failed (talvez já não exista): $fn"
- FAIL=$((FAIL+1))
+ if grep -qiE "not found|does not exist" <<<"$DELETE_OUTPUT"; then
+ echo " ℹ️ Já não existia: $fn"
+ SKIP=$((SKIP+1))
+ else
+ echo " ❌ Falha ao deletar: $fn"
+ echo "$DELETE_OUTPUT"
+ FAIL=$((FAIL+1))
+ fi
fi
@@
else
echo "Deleted successfully: $PASS"
echo "Failed: $FAIL"
+ echo "Already absent: $SKIP"
if [[ $FAIL -gt 0 ]]; then
- echo "::warning::Algumas edges falharam ao deletar (podem já não existir)."
+ echo "::error::Falhas reais na remoção. Abortando para evitar falso positivo."
+ exit 1
fi
fiAlso applies to: 124-128
🤖 Prompt for 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.
In @.github/workflows/delete-orphan-edges.yml around lines 102 - 108, The delete
loop currently treats failures as warnings (increments FAIL) but lets the job
exit successfully; update the logic around the supabase functions delete "$fn"
--project-ref "$PROJECT_REF" branch so that any deletion error causes the script
to fail fast (or at minimum exit non-zero after the loop) instead of only
echoing a warning—e.g., when the else branch for the supabase delete runs,
ensure you either call exit 1 immediately or set a fatal flag and after the loop
check FAIL>0 and exit 1; apply the same change to the other delete block that
manipulates PASS and FAIL (lines referenced in the comment) so any operational
error (token/network/permission/CLI) breaks the job.
| # Auditoria & remoção das 6 Edge Functions órfãs | ||
|
|
||
| **Data:** 10 de maio de 2026 | ||
| **Banco:** `doufsxqlfjyuvxuezpln` |
There was a problem hiding this comment.
Evitar persistir dados sensíveis reais do incidente no repositório
O markdown está versionando identificadores e dados comerciais reais (endpoint do projeto, UUIDs, SKU, custos, estoque). Isso amplia o vazamento para o histórico Git. Troque por amostras anonimizadas e mantenha evidência bruta em canal restrito (ex.: sistema de incidentes interno).
Patch sugerido (sanitização)
-**Banco:** `doufsxqlfjyuvxuezpln`
+**Banco:** `<project-ref-redacted>`
@@
-curl -X POST https://doufsxqlfjyuvxuezpln.supabase.co/functions/v1/product-search-v2 \
+curl -X POST https://<project-ref>.supabase.co/functions/v1/product-search-v2 \
@@
-supplier_id → 841cd690-210a-422a-908c-7676828db272
+supplier_id → <redacted-uuid>
@@
-organization_id → 5db5aee1-064b-4ef4-9193-345dcd8274ea
+organization_id → <redacted-uuid>
@@
-sku → LE-34373
+sku → <redacted>
@@
- "id": "b887805d-7ae2-4f28-912a-5e879bca8b75",
+ "id": "<redacted-uuid>",
@@
- "sku": "LE-34373",
+ "sku": "<redacted>",
@@
- "supplier_id": "841cd690-210a-422a-908c-7676828db272",
+ "supplier_id": "<redacted-uuid>",
@@
- "organization_id": "5db5aee1-064b-4ef4-9193-345dcd8274ea",
+ "organization_id": "<redacted-uuid>",Also applies to: 124-153, 247-263
🤖 Prompt for 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.
In `@docs/historico/orphan-edges-2026-05-10.md` at line 4, The markdown currently
contains real sensitive identifiers (e.g., the bank identifier
"doufsxqlfjyuvxuezpln" and other UUIDs/SKUs/endpoints referenced in the file)
and must be sanitized: replace each real identifier with an anonymized
placeholder (e.g., BANK_ID_REDACTED, PROJECT_ENDPOINT_REDACTED, SKU_REDACTED)
consistently throughout the document (including the other ranges noted: 124-153,
247-263) and add a short note pointing readers to a restricted incident channel
for raw evidence; ensure no real costs, stock values, UUIDs, or endpoints remain
in the repo version.
| ``` | ||
| GET → {"service":"product-classifier","version":"v1.1", | ||
| "categories":["escrita","bebidas","vestuario","bags","tech", | ||
| "escritorio","utilidades","saude"]} | ||
| POST {} → {"error":"action: classify or batch_classify"} | ||
| ``` |
There was a problem hiding this comment.
Fenced code blocks sem linguagem (MD040)
Os blocos nessas seções estão sem linguagem e geram warning de lint. Vale definir text para estabilizar o pipeline de docs.
Patch sugerido
-```
+```text
GET → {"service":"product-classifier","version":"v1.1",
"categories":["escrita","bebidas","vestuario","bags","tech",
"escritorio","utilidades","saude"]}
POST {} → {"error":"action: classify or batch_classify"}@@
- +text
GET → {"service":"guardrails-ml","version":"v2.3","status":"healthy"}
POST {} → {"error":"text required"}
@@
-```
+```text
cost_price → 13.92 (CUSTO INTERNO)
sale_price → 20.88
...
</details>
Also applies to: 113-116, 140-153
<details>
<summary>🧰 Tools</summary>
<details>
<summary>🪛 markdownlint-cli2 (0.22.1)</summary>
[warning] 100-100: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
</details>
</details>
<details>
<summary>🤖 Prompt for AI Agents</summary>
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In @docs/historico/orphan-edges-2026-05-10.md around lines 100 - 105, Replace
the language-less fenced code blocks with annotated ones by changing the opening
"" to "text" for the examples shown (the block containing GET →
{"service":"product-classifier",...} / POST {} → {"error":"action: classify or
batch_classify"}, the block with GET → {"service":"guardrails-ml",...} / POST {}
→ {"error":"text required"}, and the pricing block starting with "cost_price →
13.92"), and apply the same change to the other occurrences mentioned (lines
corresponding to the second and third examples around 113-116 and 140-153) so
the markdown linter MD040 warnings are resolved.
</details>
<!-- fingerprinting:phantom:poseidon:hawk -->
<!-- d98c2f50 -->
<!-- This is an auto-generated comment by CodeRabbit -->
There was a problem hiding this comment.
Pull request overview
Adds an operational mechanism (GitHub Actions workflow) and supporting documentation to remove 6 “orphan” Supabase Edge Functions that exist in production but are not present/referenced in the repository, including one public function reportedly leaking sensitive catalog data.
Changes:
- Added a forensic audit write-up documenting evidence of non-usage and probe results for the 6 orphan edge functions.
- Added a
workflow_dispatchGitHub Actions workflow to dry-run and (with a confirmation gate) delete the 6 functions via Supabase CLI.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 5 comments.
| File | Description |
|---|---|
docs/historico/orphan-edges-2026-05-10.md |
Audit report documenting the orphan edges, evidence of non-usage, and probe results (including the reported data leak). |
.github/workflows/delete-orphan-edges.yml |
Manual workflow to dry-run or delete the 6 orphan edge functions using Supabase CLI with a confirmation gate. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| Probe sem auth, sem token, sem nada: | ||
|
|
||
| ```bash | ||
| curl -X POST https://doufsxqlfjyuvxuezpln.supabase.co/functions/v1/product-search-v2 \ |
| "id": "b887805d-7ae2-4f28-912a-5e879bca8b75", | ||
| "name": " CADERNETA S/ PAUTA - 14X21CM - BEGE/AZUL", | ||
| "sku": "LE-34373", | ||
| "category_id": "b1000000-0000-0000-0000-000000000006", | ||
| "supplier_id": "841cd690-210a-422a-908c-7676828db272", | ||
| "cost_price": 13.92, | ||
| "sale_price": 20.88, | ||
| "suggested_price": 16.26, | ||
| "stock_quantity": 300, | ||
| "ncm_code": "48202000", | ||
| "origin_country": "China", | ||
| "brand": "Só Marcas", | ||
| "organization_id": "5db5aee1-064b-4ef4-9193-345dcd8274ea", |
| echo "Deleted successfully: $PASS" | ||
| echo "Failed: $FAIL" | ||
| if [[ $FAIL -gt 0 ]]; then | ||
| echo "::warning::Algumas edges falharam ao deletar (podem já não existir)." |
| echo "## Próximos passos" | ||
| echo "" | ||
| echo "1. Validar via Supabase MCP que as 6 edges sumiram:" | ||
| echo " MCP \`SUPABASE - GESTÃO DE PRODUTOS:list_edge_functions\`" | ||
| echo "" | ||
| echo "2. Conferir que ai_function_routing não tem entradas órfãs:" | ||
| echo " SQL: SELECT function_name FROM public.ai_function_routing" | ||
| echo " WHERE function_name IN ('super-processor', ...);" | ||
| echo "" | ||
| echo "3. Atualizar memória/notes do projeto: 6 edges removidas em $(date -u +%Y-%m-%d)." |
| @@ -0,0 +1,273 @@ | |||
| # Auditoria & remoção das 6 Edge Functions órfãs | |||
|
|
|||
O que faz
Adiciona o mecanismo para remover 6 edge functions órfãs identificadas na auditoria de 10/mai/2026 — functions ativas em produção mas que nunca tiveram código no repositório, nunca foram chamadas pelo frontend e nunca registraram uso.
Critério de "órfã" (todas as 6 satisfazem):
grep -rnpor src/ + supabase/functions/ai_usage_logspara qualquer uma delas🚨 Achado crítico
product-search-v2(verify_jwt=false, pública desde 4/abr/2026) está ativamente vazando o catálogo inteiro para qualquer pessoa na internet:Resposta: 6.123 produtos × 148 campos, incluindo
cost_price,sale_price,supplier_id,stock_quantity,ncm_code,origin_country,brand. Margem dos primeiros 500 produtos: R$ 15.420,44 exposta.Concorrente que descubra essa URL tem em 1 minuto: lista completa de SKUs, custos, margens, fornecedores, estoques.
As 6 edges
super-processorquick-taskcreate_userproduct-search-v2product-classifierguardrails-mlArquivos
docs/historico/orphan-edges-2026-05-10.md.github/workflows/delete-orphan-edges.ymlworkflow_dispatchcomdryRun=truepor default + gate de confirmação (digite DELETE). UsaSUPABASE_ACCESS_TOKENjá configuradoComo usar (após mergear)
dryRun=true(default). Confirmar que lista as 6 edges esperadasdryRun=falseE digitarDELETEno campoconfirmlist_edge_functionsque sumiramPor que workflow em vez de delete direto
SUPABASE_ACCESS_TOKENem chatdeploy-edge-functions.yml)dryRunpermite verificar antes de deletarDELETE) previne click acidentalRisco
ai_usage_logsestá vazio para todas, isso é improvável.product-search-v2(vazamento ativo).Validação pós-delete
[DECISION] As 6 edges foram aprovadas para deletar conforme análise consolidada em
docs/historico/orphan-edges-2026-05-10.md. Aprovado pelo PO em 10/mai/2026.Summary by CodeRabbit
Release Notes
New Features
Documentation