Skip to content

fix(rls): Onda 13 — audit_log_gravacao + seo_audit_log admin-only (B-3 ENCERRADA)#207

Merged
adm01-debug merged 1 commit into
mainfrom
hardening/onda-13-rls-audit-logs
May 14, 2026
Merged

fix(rls): Onda 13 — audit_log_gravacao + seo_audit_log admin-only (B-3 ENCERRADA)#207
adm01-debug merged 1 commit into
mainfrom
hardening/onda-13-rls-audit-logs

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

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

🎯 Objetivo

Fecha 2 audit logs reais que estavam legíveis por qualquer usuário authenticated, encerrando o bloqueador B-3 da auditoria pré-prod.

🔒 Mudança

Tabela Policy ANTES Policy DEPOIS
audit_log_gravacao audit_log_gravacao_read_authenticated com USING (true) audit_log_gravacao_select_supervisor_or_above com is_supervisor_or_above((SELECT auth.uid()))
seo_audit_log auth_read_seo_audit_log com USING (true) seo_audit_log_select_supervisor_or_above com is_supervisor_or_above((SELECT auth.uid()))

🚨 Por que importa

audit_log_gravacao

Colunas: id, tabela_origem, operacao, registro_id, codigo_tabela, campos_alterados, valor_antes, valor_depois, usuario, ts

É o log de mudanças em tabela_preco_gravacao_oficial — guarda:

  • Quem alterou (usuario)
  • O que mudou (campos_alterados)
  • Valor antes (valor_antes) e depois (valor_depois)

Vendedor que conhecesse o nome da tabela podia ver histórico completo de mudanças de preço + identificar quem fez cada alteração. Sensível comercialmente.

seo_audit_log

Histórico de auditorias SEO — info operacional interna. Vendedor não precisa ver.

✅ Pré-deploy: investigação completa

$ code_search 'audit_log_gravacao' --repo Promo_Gifts
→ 0 matches em src/ e supabase/functions/
→ Apenas referências em docs/ e snapshots de auditoria

$ code_search 'seo_audit_log' --repo Promo_Gifts
→ 0 matches em src/ e supabase/functions/

Conclusão: nenhum código de aplicação consulta essas tabelas. São acessadas apenas via Supabase Dashboard pelo admin. Mudança 100% transparente para clientes.

✅ Pós-deploy validado em PROD

Aplicada via MCP apply_migration em 14/mai/2026 22:09 UTC. Validação SELECT * FROM pg_policies:

audit_log_gravacao:
  ✅ audit_log_gravacao_insert_service (service_role, INSERT) — mantido
  ✅ audit_log_gravacao_select_supervisor_or_above (authenticated, SELECT) — NOVO
  ❌ audit_log_gravacao_read_authenticated — DROPADA

seo_audit_log:
  ✅ seo_audit_log_select_supervisor_or_above (authenticated, SELECT) — NOVO
  ❌ auth_read_seo_audit_log — DROPADA

📊 Estado da B-3 após este PR

Auditoria pré-prod listou 7 tabelas com policies USING(true). Investigação cruzada com banco real revelou:

Tabela Estado atual Resolvido em
audit_log is_supervisor_or_above onda anterior (sem registro)
analytics_events user_id = self OR is_coord_or_above onda anterior
product_views is_admin OR seller_id = self onda anterior
search_queries user_id = self OR is_coord_or_above onda anterior
quote_templates auth.uid() = created_by onda anterior
sync_jobs ✅ Tabela DROPADA N/A
notification_templates is_supervisor_or_above Onda 8 (PR #199)
audit_log_gravacao is_supervisor_or_above Onda 13 (este PR)
seo_audit_log is_supervisor_or_above Onda 13 (este PR)

B-3 ENCERRADA. 🎉

🔍 Cenários adversos simulados

# Cenário Resultado
F1 DROP POLICY falha por dependência ✅ aplicou sem erro
F2 Admin não consegue ler audit_log_gravacao ✅ função is_supervisor_or_above ativa
F3 Frontend quebra por perda de acesso ✅ ZERO matches no código (não consulta)
F4 Edges quebram ✅ usam service_role (bypassa RLS)
F5 Triggers SECDEF param de gravar ✅ INSERT via service_role mantido
F6 Migration não aplica em CI ✅ aplicada via MCP direto (ADR 0006) — repo só registra

📁 Arquivos

  • supabase/migrations/20260514220543_onda13_rls_audit_logs_admin_only.sql (+61 linhas)

📚 Ref


Summary by cubic

Restricts SELECT on audit_log_gravacao and seo_audit_log to supervisors or above, replacing open USING (true) policies. Closes audit blocker B-3 with no app impact.

  • Bug Fixes
    • Added audit_log_gravacao_select_supervisor_or_above and seo_audit_log_select_supervisor_or_above using is_supervisor_or_above((SELECT auth.uid())).
    • Dropped audit_log_gravacao_read_authenticated and auth_read_seo_audit_log.
    • Inserts unchanged via SECDEF/service role; confirmed no frontend or edge code queries these tables.

Written for commit 014bb74. Summary will update on new commits.

Summary by CodeRabbit

Release Notes

  • Segurança

    • Restringido acesso aos logs de auditoria para apenas usuários com permissões de supervisor ou superiores, removendo permissões de leitura anterior para usuários autenticados.
  • Documentação

    • Adicionados comentários que documentam o caráter sensível dos dados nos logs de auditoria.

Review Change Stack

…isor_or_above (Onda 13, B-3 ENCERRADA)

Auditoria pre-prod (10/mai/2026) apontou 7 tabelas overly-permissive. Investigacao mostrou
que 5 ja foram fechadas em ondas anteriores, sync_jobs foi removida, e notification_templates
fechada na Onda 8. Restavam 2 audit logs reais:

- audit_log_gravacao: log de mudancas em precos de gravacao, contem usuario/valor_antes/depois
- seo_audit_log: historico de auditorias SEO

Mudanca: SELECT restrito a is_supervisor_or_above. INSERT continua via triggers SECDEF.

Pre-deploy: code_search zero matches em src/ e supabase/functions/ para ambas.
APLICADA EM PROD via MCP apply_migration (ADR 0006). B-3 ENCERRADA.

Ref: docs/AUDITORIA-PROFUNDA-PROMOGIFTS-PRE-PROD.md (B-3, secao 2.3)
Copilot AI review requested due to automatic review settings May 14, 2026 22:07
@vercel
Copy link
Copy Markdown

vercel Bot commented May 14, 2026

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

Project Deployment Actions Updated (UTC)
promo-gifts Ready Ready Preview, Comment May 14, 2026 10:08pm

@supabase
Copy link
Copy Markdown

supabase Bot commented May 14, 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
Contributor

coderabbitai Bot commented May 14, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 113eed3f-2343-45d4-b116-cd7bc0fbbd90

📥 Commits

Reviewing files that changed from the base of the PR and between 55285ce and 014bb74.

📒 Files selected for processing (1)
  • supabase/migrations/20260514220543_onda13_rls_audit_logs_admin_only.sql

Visão geral

Esta migration SQL restringe o acesso de leitura nas tabelas de auditoria (audit_log_gravacao e seo_audit_log) para apenas usuários supervisores ou acima, removendo as políticas de leitura autenticadas anteriores e adicionando documentação sobre o caráter sensível dos dados.

Mudanças

Restrição de acesso a logs de auditoria

Layer / File(s) Sumário
RLS policies restritas a supervisores
supabase/migrations/20260514220543_onda13_rls_audit_logs_admin_only.sql
Remove políticas de leitura públicas/autenticadas em audit_log_gravacao e seo_audit_log, substituindo por políticas FOR SELECT que exigem is_supervisor_or_above(auth.uid()). Adiciona comentários explicativos nas policies documentando que os logs contêm dados potencialmente sensíveis.

Esforço estimado de revisão

🎯 1 (Trivial) | ⏱️ ~3 minutos

PRs possivelmente relacionadas

  • adm01-debug/Promo_Gifts#199: Aplica a mesma abordagem de restricão is_supervisor_or_above em outras políticas RLS (notificação de templates).
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed O título descreve com precisão a mudança principal: restrição de leitura das tabelas de audit_log (audit_log_gravacao e seo_audit_log) para apenas supervisores+, fechando a issue B-3 da Onda 13.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 hardening/onda-13-rls-audit-logs

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

Copy link
Copy Markdown

@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.

No issues found across 1 file

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 records a Supabase RLS hardening migration that restricts two audit-log tables to supervisor-or-above access, closing the stated B-3 audit blocker without changing frontend or edge-function code.

Changes:

  • Drops permissive authenticated SELECT policies on audit_log_gravacao and seo_audit_log.
  • Adds supervisor-or-above SELECT policies using is_supervisor_or_above((SELECT auth.uid())).
  • Adds policy comments documenting the security rationale.

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

Comment on lines +20 to +30
-- ESTADO DA B-3 APOS ESTA MIGRATION:
-- Auditoria pre-prod listou 7 tabelas overly-permissive. Estado final:
-- - audit_log: ja correta (supervisor_or_above) — fechada antes
-- - analytics_events: ja correta (self ou coord) — fechada antes
-- - product_views: ja correta (admin ou seller_id) — fechada antes
-- - search_queries: ja correta (self ou coord) — fechada antes
-- - quote_templates: ja correta (por created_by) — fechada antes
-- - sync_jobs: tabela nao existe mais — N/A
-- - notification_templates: fechada em Onda 8 (PR #199)
-- - audit_log_gravacao (esta migration): supervisor_or_above
-- - seo_audit_log (esta migration): supervisor_or_above
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: 014bb74641

ℹ️ 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".

-- APLICADA EM PROD via MCP apply_migration (ADR 0006).

-- ─── audit_log_gravacao ───
DROP POLICY IF EXISTS audit_log_gravacao_read_authenticated ON public.audit_log_gravacao;
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 the migration when audit log tables are absent

On Supabase Preview branches that replay supabase/migrations from scratch, this migration will fail before applying because audit_log_gravacao and seo_audit_log are not created anywhere earlier in supabase/migrations (repo-wide rg -i only finds this new file). DROP POLICY IF EXISTS ... ON public.audit_log_gravacao still requires the target relation to exist, so branches/environments without these production-only tables hit undefined_table; wrap these policy changes in table-existence guards as done in the recent migration fixes.

Useful? React with 👍 / 👎.

@adm01-debug adm01-debug merged commit 0b4bf60 into main May 14, 2026
23 of 27 checks passed
@adm01-debug adm01-debug deleted the hardening/onda-13-rls-audit-logs branch May 14, 2026 22:46
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