Skip to content

fix(db): Onda 19 follow-up — track trigger functions + restaurar segurança da view#219

Merged
adm01-debug merged 1 commit into
mainfrom
claude/code-review-architecture-68yFv
May 15, 2026
Merged

fix(db): Onda 19 follow-up — track trigger functions + restaurar segurança da view#219
adm01-debug merged 1 commit into
mainfrom
claude/code-review-architecture-68yFv

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

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

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_values e fn_kit_print_area_normalizar_eixos existiam apenas como drift de PROD — não havia nenhuma migration que as criasse. Em supabase db reset ou novo ambiente, os triggers recriados pela Onda 19 falhariam com ERROR: function does not exist.

Fix: CREATE OR REPLACE com as definições exatas extraídas de PROD. Idempotente — sem efeito no banco atual.

P1/P2 — View v_audit_paradoxos_gravacao sem hardening de segurança (Copilot + CodeRabbit)

O DROP + CREATE OR REPLACE da Onda 19 resetou as opções e ACL da view. Confirmado via pg_class pós-Onda 19:

reloptions: null                    ← security_invoker perdido
relacl: anon=arwdDxtm, authenticated=arwdDxtm  ← acesso total para todos os roles

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:

ALTER VIEW public.v_audit_paradoxos_gravacao SET (security_invoker = true);
REVOKE ALL ON public.v_audit_paradoxos_gravacao FROM anon;
REVOKE ALL ON public.v_audit_paradoxos_gravacao FROM authenticated;

Validação em PROD (doufsxqlfjyuvxuezpln)

Aplicado via apply_migration antes do commit:

Check Resultado
fn_quotes_calc_real_values presente
fn_kit_print_area_normalizar_eixos presente
search_path seguro nas duas funções (pg_catalog, public)
reloptions = [security_invoker=true] na view
relacl = {postgres, service_role} (anon/authenticated removidos)

O que NÃO foi alterado

  • Definições dos triggers em si (já corretos desde a Onda 19)
  • Coluna numeric precision (já aplicada e validada com drift=0)
  • Qualquer outra view ou função

Refs


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

  • Bug Fixes
    • Registra fn_quotes_calc_real_values e fn_kit_print_area_normalizar_eixos via CREATE OR REPLACE (definições de PROD, idempotente; search_path seguro), evitando falhas de triggers em supabase db reset.
    • Reaplica hardening da public.v_audit_paradoxos_gravacao: security_invoker=true e REVOKE de anon/authenticated, mantendo acesso apenas para service_role.

Written for commit 84ebcc5. Summary will update on new commits.

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Formalizaram-se funções de cálculo de orçamento e normalização de dimensões que operavam como drift em produção, garantindo estabilidade nas derivações de campos.
  • Security

    • Endureceram-se permissões em view de auditoria, restringindo acessos anônimos e autenticados não autorizados.

Review Change Stack

…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
@vercel
Copy link
Copy Markdown

vercel Bot commented May 15, 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 15, 2026 10:42am

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 15, 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: b097191c-0a20-4b4b-a8af-f02760a35a98

📥 Commits

Reviewing files that changed from the base of the PR and between 224d149 and 84ebcc5.

📒 Files selected for processing (1)
  • supabase/migrations/20260515040000_onda19_followup_track_functions_fix_view_security.sql

Walkthrough

Migration do Supabase que registra como código versionado duas funções trigger (fn_quotes_calc_real_values e fn_kit_print_area_normalizar_eixos) que existem apenas como drift em produção, e restaura hardening de permissões na view v_audit_paradoxos_gravacao com security_invoker = true e REVOKE ALL para anon/authenticated.

Changes

Database Functions and View Security

Layer / File(s) Summary
Quote value calculation trigger function
supabase/migrations/20260515040000_onda19_followup_track_functions_fix_view_security.sql
Função trigger fn_quotes_calc_real_values() clampeia negotiation_markup_percent entre 0% e 50%, recalcula real_subtotal e real_discount_percent com tratamento para edge cases onde real_subtotal não é positivo. Documentada com COMMENT ON FUNCTION.
Kit print area axis normalization trigger function
supabase/migrations/20260515040000_onda19_followup_track_functions_fix_view_security.sql
Função trigger fn_kit_print_area_normalizar_eixos() arredonda max_width e max_height para 2 casas decimais e normaliza eixos invertendo valores quando max_height > max_width para garantir consistência. Documentada com COMMENT ON FUNCTION.
Audit view access hardening
supabase/migrations/20260515040000_onda19_followup_track_functions_fix_view_security.sql
View v_audit_paradoxos_gravacao passa a usar security_invoker = true e sofre REVOKE ALL para anon e authenticated, restringindo acesso apenas ao invocador autenticado.
Transaction envelope
supabase/migrations/20260515040000_onda19_followup_track_functions_fix_view_security.sql
Todas as operações executadas em bloco transacional atômico BEGIN/COMMIT.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutos

Possibly related PRs

  • adm01-debug/Promo_Gifts#214: Define os triggers trg_quotes_calc_real_values e trg_kit_print_area_normalizar_eixos que chamam as funções agora versionadas nesta migration, além de tocar na mesma view v_audit_paradoxos_gravacao.
  • adm01-debug/Promo_Gifts#212: Ajusta lógica de recálculo de real_subtotal e campos de desconto em quote, relacionada ao conserto do drift de valores financeiros desta migration.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/code-review-architecture-68yFv

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

@supabase
Copy link
Copy Markdown

supabase Bot commented May 15, 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 ↗︎.

@adm01-debug adm01-debug marked this pull request as ready for review May 15, 2026 11:04
Copilot AI review requested due to automatic review settings May 15, 2026 11:04
@adm01-debug adm01-debug merged commit ed7da4b into main May 15, 2026
19 of 24 checks passed
@adm01-debug adm01-debug deleted the claude/code-review-architecture-68yFv branch May 15, 2026 11:04
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

@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: 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()
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 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 👍 / 👎.

Comment on lines +59 to +60
END
$function$;
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 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()
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

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

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 FUNCTION para public.fn_quotes_calc_real_values() e public.fn_kit_print_area_normalizar_eixos() com search_path hardening.
  • Reaplica hardening da view public.v_audit_paradoxos_gravacao via ALTER VIEW ... SET (security_invoker=true) + REVOKE de anon/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 END sem ;. Trocar para END; para o CREATE OR REPLACE FUNCTION compilar.
  END IF;

  RETURN NEW;
END
$function$;

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

Comment on lines +24 to +36
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
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.

3 participants