fix(db): Onda 19 follow-up — track trigger functions + restaurar segurança da view#219
Conversation
…rança da view Fecha os 6 review comments não resolvidos do PR #214: P1 (CodeRabbit): fn_quotes_calc_real_values e fn_kit_print_area_normalizar_eixos existiam apenas como drift de PROD — supabase db reset falharia ao recriar os triggers (function does not exist). Adicionadas as definições exatas extraídas de PROD via CREATE OR REPLACE (idempotente, sem efeito em PROD). P1/P2 (Copilot + CodeRabbit): DROP+RECREATE da view na Onda 19 resetou security_invoker e grants — anon/authenticated receberam acesso total (confirmado via pg_class.relacl). View é service_role-only (REDEPLOY-FASE2-EXECUTION-LOG.md). Restaurado: ALTER VIEW SET (security_invoker=true) + REVOKE de anon/authenticated. Validação pós-aplicação em PROD (doufsxqlfjyuvxuezpln): - 2 funções com search_path seguro (pg_catalog, public) ✅ - reloptions=[security_invoker=true] ✅ - relacl={postgres, service_role} — anon/authenticated removidos ✅ https://claude.ai/code/session_01NahCsAw7oJWnd78egBJt8p
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
WalkthroughMigration do Supabase que registra como código versionado duas funções trigger ( ChangesDatabase Functions and View Security
Estimated code review effort🎯 1 (Trivial) | ⏱️ ~3 minutos Possibly related PRs
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 84ebcc52bd
ℹ️ 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".
| -- a partir do subtotal com markup já aplicado (negotiation_markup_percent). | ||
| -- Limite de markup: 0-50% (LEAST/GREATEST). | ||
| -- ---------------------------------------------------------------- | ||
| CREATE OR REPLACE FUNCTION public.fn_quotes_calc_real_values() |
There was a problem hiding this comment.
Define trigger functions before recreating triggers
This migration is timestamped after 20260515030000_onda19_numeric_precision.sql, but that earlier migration recreates trg_quotes_calc_real_values and trg_kit_print_area_normalizar_eixos with EXECUTE FUNCTION public.fn_quotes_calc_real_values() / public.fn_kit_print_area_normalizar_eixos() before the definitions added here exist. I checked repo-wide with rg and these functions are only defined in this new 20260515040000 file, so a fresh supabase db reset or new environment still fails in the 20260515030000 migration and never reaches this follow-up. The function definitions need to be available before the trigger recreation, e.g. by moving them into an earlier migration or a pre-0300 migration.
Useful? React with 👍 / 👎.
| END | ||
| $function$; |
There was a problem hiding this comment.
Terminate PL/pgSQL blocks with semicolons
PostgreSQL parses the dollar-quoted body as PL/pgSQL and the final END statement must be terminated with ;; as written this first CREATE FUNCTION fails to compile, so applying this migration stops before either trigger function or the view hardening is installed. The second function below has the same missing terminator, but the migration will already fail here.
Useful? React with 👍 / 👎.
| -- a partir do subtotal com markup já aplicado (negotiation_markup_percent). | ||
| -- Limite de markup: 0-50% (LEAST/GREATEST). | ||
| -- ---------------------------------------------------------------- | ||
| CREATE OR REPLACE FUNCTION public.fn_quotes_calc_real_values() |
There was a problem hiding this comment.
Revoke authenticated execute from new trigger functions
In a fresh database these new trigger functions are created after 20260512000014_t36_alter_default_privileges_functions.sql, whose default privileges grant EXECUTE on new public functions to authenticated, while 20260513000002_t37c_revoke_authenticated_trigger_vault.sql explicitly revoked authenticated from trigger functions because they should only run via triggers. Since this migration does not add matching REVOKE EXECUTE statements for fn_quotes_calc_real_values() and fn_kit_print_area_normalizar_eixos(), it reintroduces the authenticated-executable trigger-function exposure that T37c was meant to eliminate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Pull request overview
Este PR adiciona uma migration de follow-up da Onda 19 para registrar duas funções de trigger que existiam apenas como drift em PROD e para restaurar o hardening (security_invoker + revokes) da view public.v_audit_paradoxos_gravacao, removendo acesso indevido para anon/authenticated.
Changes:
- Adiciona
CREATE OR REPLACE FUNCTIONparapublic.fn_quotes_calc_real_values()epublic.fn_kit_print_area_normalizar_eixos()comsearch_pathhardening. - Reaplica hardening da view
public.v_audit_paradoxos_gravacaoviaALTER VIEW ... SET (security_invoker=true)+REVOKEdeanon/authenticated.
Comments suppressed due to low confidence (1)
supabase/migrations/20260515040000_onda19_followup_track_functions_fix_view_security.sql:98
- Mesmo problema de sintaxe aqui: o bloco PL/pgSQL termina com
ENDsem;. Trocar paraEND;para oCREATE OR REPLACE FUNCTIONcompilar.
END IF;
RETURN NEW;
END
$function$;
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| BEGIN; | ||
|
|
||
| -- ---------------------------------------------------------------- | ||
| -- 1. fn_quotes_calc_real_values | ||
| -- Trigger BEFORE em quotes: calcula real_subtotal e real_discount_percent | ||
| -- a partir do subtotal com markup já aplicado (negotiation_markup_percent). | ||
| -- Limite de markup: 0-50% (LEAST/GREATEST). | ||
| -- ---------------------------------------------------------------- | ||
| CREATE OR REPLACE FUNCTION public.fn_quotes_calc_real_values() | ||
| RETURNS trigger | ||
| LANGUAGE plpgsql | ||
| SET search_path TO 'pg_catalog', 'public' | ||
| AS $function$ |
| END IF; | ||
|
|
||
| RETURN NEW; | ||
| END |
Contexto
Follow-up do PR #214 (Onda 19 — precisão numeric). Fecha os 6 review comments não resolvidos do PR merged.
Problemas resolvidos
P1 — Funções de trigger ausentes das migrations (CodeRabbit)
fn_quotes_calc_real_valuesefn_kit_print_area_normalizar_eixosexistiam apenas como drift de PROD — não havia nenhuma migration que as criasse. Emsupabase db resetou novo ambiente, os triggers recriados pela Onda 19 falhariam comERROR: function does not exist.Fix:
CREATE OR REPLACEcom as definições exatas extraídas de PROD. Idempotente — sem efeito no banco atual.P1/P2 — View
v_audit_paradoxos_gravacaosem hardening de segurança (Copilot + CodeRabbit)O DROP +
CREATE OR REPLACEda Onda 19 resetou as opções e ACL da view. Confirmado viapg_classpós-Onda 19:A view é classificada como "auditoria interna / service_role apenas" em
docs/redeploy/REDEPLOY-FASE2-EXECUTION-LOG.md. O hardening revertido abria acesso a dados de auditoria de preços para qualquer usuário autenticado.Fix: padrão idêntico ao T15 e t34b:
Validação em PROD (
doufsxqlfjyuvxuezpln)Aplicado via
apply_migrationantes do commit:fn_quotes_calc_real_valuespresentefn_kit_print_area_normalizar_eixospresentesearch_pathseguro nas duas funções (pg_catalog, public)reloptions = [security_invoker=true]na viewrelacl = {postgres, service_role}(anon/authenticated removidos)O que NÃO foi alterado
numericprecision (já aplicada e validada com drift=0)Refs
docs/redeploy/REDEPLOY-FASE2-EXECUTION-LOG.md— classificação das views admin-only20260512201500_t15_fix_system_health_dashboard_exposure.sql— padrão de segurança usadoGenerated by Claude Code
Summary by cubic
Follow-up da Onda 19 (#214): adiciona as funções de trigger às migrations e restaura o hardening da view de auditoria. Evita erros em novos ambientes e remove acesso indevido para usuários autenticados.
fn_quotes_calc_real_valuesefn_kit_print_area_normalizar_eixosvia CREATE OR REPLACE (definições de PROD, idempotente;search_pathseguro), evitando falhas de triggers emsupabase db reset.public.v_audit_paradoxos_gravacao:security_invoker=truee REVOKE deanon/authenticated, mantendo acesso apenas paraservice_role.Written for commit 84ebcc5. Summary will update on new commits.
Summary by CodeRabbit
Release Notes
Bug Fixes
Security