Skip to content

feat(audit): sessão Maestro 2026-05-12 — RLS 100%, FK órfãos limpos, guardas anti-órfão#147

Merged
adm01-debug merged 1 commit into
mainfrom
fix/pr129-maestro-audit
May 20, 2026
Merged

feat(audit): sessão Maestro 2026-05-12 — RLS 100%, FK órfãos limpos, guardas anti-órfão#147
adm01-debug merged 1 commit into
mainfrom
fix/pr129-maestro-audit

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

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

Versão limpa de #129 rebaseada no main atual. Arquivos já presentes no main foram omitidos (scripts/verify_rls_compliance.ts já mergeado via #143, vite.config.ts via #145, package.json sem mudanças reais).

Incluído

Migrations SQL (5 arquivos):

  • 20260512170857 — RLS nas partições + RPC rpc_check_rls_compliance
  • 20260512170900 — Corrige referências quebradas no smoke test v2
  • 20260512170915 — Limpeza de 7.249 FK órfãos + constraint fk_evolution_messages_contact
  • 20260512170920 — Otimização do refresh da MV mv_daily_metrics
  • 20260512201500 — Fix schema instance_auth_events

Scripts:

  • scripts/check-references.ts — guarda anti-órfão integrado no CI
  • scripts/smoke-pre-deploy.sh — smoke pre-deploy (5 etapas)
  • scripts/reconnect-wpp2.sh — helper de reconexão da instância wpp2

CI:

  • Step "Check for orphaned references" adicionado após Install
  • Remove apply-chatpanel-fixes.yml (workflow one-shot, ref órfã)

Docs (9 arquivos docs/audit/):

  • AUDIT.md, REMEDIATION_PLAN.md, SESSION_2026-05-12_MAESTRO.md + docs C2/C3

Closes #129


Generated by Claude Code


Summary by cubic

Hardened the database and CI after the Maestro 2026-05-12 audit: 100% RLS on evolution partitions, orphan FKs cleaned and prevented, faster daily metrics, and new guards in CI and pre-deploy. Adds docs and operational scripts; removes a stale workflow.

  • New Features

    • CI guard scripts/check-references.ts to fail on broken file/script/doc references; wired into CI via bunx tsx scripts/check-references.ts.
    • Pre-deploy smoke test scripts/smoke-pre-deploy.sh (types, lint, build, RPC smoke).
    • WhatsApp reconnection helper scripts/reconnect-wpp2.sh.
    • Audit documentation bundle and Inbox Read Contract (docs/audit/*, docs/INBOX_READ_CONTRACT.md).
    • Removed orphan workflow .github/workflows/apply-chatpanel-fixes.yml.
  • Migration

    • Enabled RLS across all evolution partitions and added public.rpc_check_rls_compliance.
    • Fixed fn_zapp_web_smoke_test_v2 broken references and thresholds.
    • Cleaned 7,249 orphan evolution_messages.contact_id and added FK with ON DELETE SET NULL.
    • Optimized mv_daily_metrics refresh with targeted partial index and ANALYZE.
    • Aligned public.instance_auth_events schema to match Edge Function writes.

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

Summary by CodeRabbit

Release Notes

  • Documentation

    • Documentação extensiva adicionada: auditoria de segurança, planos de conformidade, cenários de teste e guias operacionais
  • Refactor

    • Verificação automática de referências órfãs integrada ao CI para detectar dependências quebradas
  • Infrastructure

    • Scripts de validação pré-deploy e reconexão WhatsApp adicionados
    • Migrations SQL: habilitação de RLS em partições, limpeza de dados órfãos, otimizações de performance
  • Chores

    • Workflow GitHub Actions deprecado removido

Review Change Stack

…guardas anti-órfão

- 5 migrations SQL: RLS partições, smoke test v2 refs, FK órfãos, MV metrics, instance auth events
- scripts/check-references.ts: guarda anti-órfão no CI (detecta referências quebradas)
- scripts/smoke-pre-deploy.sh: smoke pre-deploy (env → tsc → eslint → build → RPC smoke)
- scripts/reconnect-wpp2.sh: helper de reconexão da instância wpp2
- CI: step "Check for orphaned references" adicionado após Install
- Remove apply-chatpanel-fixes.yml (workflow one-shot já consumado, ref órfã)
- docs/audit/*: 9 arquivos de auditoria e plano de remediação
- docs/INBOX_READ_CONTRACT.md: contrato real alinhado com regra ESLint no-restricted-imports

Closes #129
Copilot AI review requested due to automatic review settings May 20, 2026 10:59
@vercel
Copy link
Copy Markdown

vercel Bot commented May 20, 2026

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

Project Deployment Actions Updated (UTC)
zapp-web Building Building Preview, Comment May 20, 2026 10:59am

@adm01-debug adm01-debug merged commit 0343e3e into main May 20, 2026
4 of 10 checks passed
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 20, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: adf3eeb2-d089-4480-aabf-16437a27b3ee

📥 Commits

Reviewing files that changed from the base of the PR and between a630d84 and 39b404d.

📒 Files selected for processing (21)
  • .github/workflows/apply-chatpanel-fixes.yml
  • .github/workflows/ci.yml
  • docs/INBOX_READ_CONTRACT.md
  • docs/audit/AUDIT.md
  • docs/audit/C2_QUICK_WINS_2026-05-12.md
  • docs/audit/C2_RESOLUTION_VALIDATED.md
  • docs/audit/C2_ROOT_CAUSE_DEFINITIVE.md
  • docs/audit/DIAGNOSTIC_C2_RABBITMQ_HMAC.md
  • docs/audit/ONDA5_QUALIDADE.md
  • docs/audit/ONDA6_CENARIOS.md
  • docs/audit/PLAYBOOK_C3_SUPABASE_DRIFT.md
  • docs/audit/REMEDIATION_PLAN.md
  • docs/audit/SESSION_2026-05-12_MAESTRO.md
  • scripts/check-references.ts
  • scripts/reconnect-wpp2.sh
  • scripts/smoke-pre-deploy.sh
  • supabase/migrations/20260512170857_rls_partitions_and_compliance_rpc.sql
  • supabase/migrations/20260512170900_fix_smoke_test_v2_broken_refs.sql
  • supabase/migrations/20260512170915_fk_orfaos_cleanup_and_constraint.sql
  • supabase/migrations/20260512170920_optimize_mv_daily_metrics_refresh.sql
  • supabase/migrations/20260512201500_fix_instance_auth_events_schema.sql

Walkthrough

Sessão de remediação autônoma (Maestro 2026-05-12) implementando plano pós-auditoria: 6 migrations SQL executam 51 tabelas com RLS, removem 7.249 FK órfãos, corrigem smoke test quebrado e otimizam índice. Scripts e CI adicionam guardas anti-órfão, pré-deploy e RPC compliance. Docs consolidam achados, playbooks e contrato Inbox. Removido workflow obsoleto.

Changes

Remediação pós-auditoria e guardas anti-regressão

Layer / File(s) Summary
Guarda anti-órfão & integração CI
scripts/check-references.ts, .github/workflows/ci.yml
Script TypeScript detecta referências órfãs em package.json, workflows e docs do eslint.config.js; integrado no CI entre Install e Lint para falhar PRs com refs quebradas. Funciona com múltiplos launchers (bunx tsx, npx tsx, bun run, etc.).
RLS compliance framework & smoke test gates
supabase/migrations/20260512170857_rls_partitions_and_compliance_rpc.sql, supabase/migrations/20260512170900_fix_smoke_test_v2_broken_refs.sql, scripts/smoke-pre-deploy.sh
Migration 1 habilita RLS em 51 partições (evolution_*_) via loop no catálogo Postgres, cria RPC rpc_check_rls_compliance() com SECURITY DEFINER e SET search_path. Migration 2 corrige fn_zapp_web_smoke_test_v2() que crashava (refs a v_webhook_health, rpc_dashboard_home inexistentes). Script smoke-pre-deploy.sh executa 5 gates sequenciais (env vars → tsc → eslint → build → RPC smoke) com suporte a FAILs temporários via SMOKE_ACCEPTED_FAILS.
Limpeza de integridade & alinhamento schema
supabase/migrations/20260512170915_fk_orfaos_cleanup_and_constraint.sql, supabase/migrations/20260512201500_fix_instance_auth_events_schema.sql
Migration 1 limpa 7.249 registros em evolution_messages com contact_id órfão (backup em archive.fk_orfaos_backup_20260512), executa UPDATE para SET NULL, adiciona constraint FK fk_evolution_messages_contact com ON DELETE SET NULL de forma idempotente. Migration 2 torna event_type anulável em instance_auth_events, adiciona colunas source/http_status/detail, cria CHECK constraints leves (NOT VALID para não bloquear histórico).
Otimização de performance & ferramentas operacionais
supabase/migrations/20260512170920_optimize_mv_daily_metrics_refresh.sql, scripts/reconnect-wpp2.sh
Migration cria índice parcial idx_evo_wpp2_mv_daily_cover com WHERE deleted_at IS NULL e INCLUDE de colunas de agregação (reduz refresh de mv_daily_metrics de 3.4s → ~2.1s). Script Bash oferece modo interativo para reconectar WhatsApp Web via QR (Evolution API endpoints connectionState e instance/connect).
Contrato arquitetural Inbox & regra ESLint
docs/INBOX_READ_CONTRACT.md
Centraliza regras: fonte única via queryExternalProxy no FATOR X, uso obrigatório de lib/externalProxy.ts, importações proibidas de evolution-api/find*, list-messages*, deep imports. Inclui diagramas de fluxo (leitura via external-db-proxy, envio via evolution-sender), procedimento de mudanças em contrato (issue → PR → sync eslint.config.js + doc + hooks), FAQ. Alinhado com ESLint rule que antes apontava para arquivo inexistente.
Auditoria consolidada & plano de remediação
docs/audit/AUDIT.md, docs/audit/C2_*.md, docs/audit/DIAGNOSTIC_C2_*.md, docs/audit/ONDA5_QUALIDADE.md, docs/audit/ONDA6_CENARIOS.md, docs/audit/PLAYBOOK_C3_SUPABASE_DRIFT.md, docs/audit/REMEDIATION_PLAN.md, docs/audit/SESSION_2026-05-12_MAESTRO.md
Consolidação completa de achados: AUDIT.md mapeia frontend/backend/banco com Ondas 1-4 + pendências C1-C4 + lições pós-Maestro (RLS futuras, FK propagadas). C2 docs descrevem causa raiz (WhatsApp desconectado), diagnóstico HMAC, validação end-to-end, quick wins. PLAYBOOK_C3 detalha drift de 11 services Supabase com fases críticas (PostgREST v12→v14, supavisor 1.1→2.7). REMEDIATION_PLAN estrutura P0 (obrigatório: RLS, FK, índice), P1 (guardas: RPC, scripts, contrato), P2 (pós-deploy: cleanup, optimizações). SESSION_2026-05-12_MAESTRO consolida 10/10 tarefas com score smoke 18 PASS / 2 WARN / 0 FAIL.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

PR é grande (3000+ linhas) com mudanças heterogêneas (SQL migrations, shell scripts, TypeScript, 11 docs Markdown). Esforço concentra-se em: (1) validar 6 migrations SQL (idempotência, guards com DO $$, constraints leves, índices condicionais); (2) revisar scripts bash/TypeScript para hardening (env validation, error codes, regex de parsing); (3) validar alinhamento de contrato Inbox com regra ESLint; (4) ler docs de auditoria para context (não bloqueante, mas altamente recomendado para entender Why). Zero mudanças em application code (frontend/backend), apenas DB + tooling + docs, mitigando risco de introduzir bugs lógicos.

Possibly related issues

  • adm01-debug/Promo_Gifts#153 — Ambas endereçam mismatch Supabase migrations/state e introduzem artefatos de validação (migrations baseline/cleanup, CI steps, docs para evitar db push unsafe).

Possibly related PRs

  • adm01-debug/Promo_Gifts#168 — Padrão paralelo de SECURITY DEFINER com SET search_path e hardening de permissões (REVOKE/GRANT específicos); PR atual introduz rpc_check_rls_compliance com exatamente esse pattern, similar a script de verificação de security definer do retrieved PR.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

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: 39b404dbdb

ℹ️ 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 +22 to +23
ALTER TABLE public.instance_auth_events
ALTER COLUMN event_type DROP NOT NULL;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Guard missing event_type before altering instance_auth_events

This migration unconditionally executes ALTER COLUMN event_type DROP NOT NULL, but in this repo's own migration chain public.instance_auth_events is initially created without an event_type column (and later CREATE TABLE IF NOT EXISTS statements do not backfill missing columns). On a clean supabase db reset/replay, this statement fails with column "event_type" does not exist, which blocks this migration and all subsequent migrations.

Useful? React with 👍 / 👎.


-- T10: CORRIGIDO (rpc_dashboard_home → rpc_zapp_dashboard)
RETURN QUERY SELECT '10_rpc_dashboard'::text, 'rpc'::text,
CASE WHEN (SELECT count(*) FROM public.rpc_zapp_dashboard()) > 0 THEN 'PASS' ELSE 'FAIL' END,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Call a defined dashboard RPC from smoke test

Test 10_rpc_dashboard now calls public.rpc_zapp_dashboard(), but there is no migration in the repository that defines this function (the only occurrence is this call site). In environments provisioned from migrations, executing fn_zapp_web_smoke_test_v2 will error with function ... does not exist at this step, aborting the smoke function instead of returning results.

Useful? React with 👍 / 👎.

Comment thread .github/workflows/ci.yml


- name: Check for orphaned references
run: bunx tsx scripts/check-references.ts
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Remove failing orphan-check gate or fix missing script refs

Adding this CI gate makes the pipeline fail on the current repository state, because scripts/check-references.ts validates package.json script targets and package.json still contains perf:budget/perf:budget:baseline pointing to scripts/check-performance-budget.mjs, which is not present. As a result, every PR run will fail at this new step before lint/build/tests.

Useful? React with 👍 / 👎.

-- T07: CORRIGIDO (v_webhook_health → v_webhook_events_last_hour)
RETURN QUERY SELECT '07_webhook_saude_1h'::text, 'webhook'::text,
'PASS'::text,
'evt_1h=' || COALESCE((SELECT count(*) FROM public.v_webhook_events_last_hour)::text, '0'),
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reference a view that exists in migrations for T07 smoke check

The updated smoke function now queries public.v_webhook_events_last_hour, but this view is not defined anywhere in the repository's migration set (its only SQL occurrence is this call). In migration-provisioned environments, fn_zapp_web_smoke_test_v2() fails at test T07 with relation does not exist, so the pre-deploy smoke gate aborts before reporting downstream checks.

Useful? React with 👍 / 👎.

RETURN QUERY SELECT '15_migration_audit_registros'::text, 'governance'::text,
CASE WHEN count(*) >= 40 THEN 'PASS' ELSE 'WARN' END,
count(*)::text, '✅'::text
FROM archive.migration_audit;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Point T15 to a table created by the tracked migration chain

T15 now reads from archive.migration_audit, but there is no migration in the repo that creates that table, so this reference is unresolved in a clean database built from versioned SQL. When execution reaches this branch, fn_zapp_web_smoke_test_v2() errors and stops instead of returning a full smoke result set.

Useful? React with 👍 / 👎.

@adm01-debug adm01-debug review requested due to automatic review settings May 20, 2026 11:20
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