Skip to content

fix(security): Etapa 3 (C2) — fecha vazamento de cost_price ao público (anon)#530

Merged
adm01-debug merged 1 commit into
mainfrom
fix/etapa3-c2-products-cost-leak
May 30, 2026
Merged

fix(security): Etapa 3 (C2) — fecha vazamento de cost_price ao público (anon)#530
adm01-debug merged 1 commit into
mainfrom
fix/etapa3-c2-products-cost-leak

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

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

Etapa 3 — Correção C2 (cost leak)

DB já corrigido em produção via Supabase MCP (projeto doufsxqlfjyuvxuezpln). Este PR adiciona o .sql em supabase/migrations/ apenas para rastreio/versionamento — o estado do banco já reflete a mudança.

Vazamento (confirmado e explorável)

A policy products_public_read era SELECT USING (true) para {anon, authenticated}, e anon tinha grant de coluna em campos sensíveis. Qualquer pessoa com a anon key (que vai no bundle do front) lia o custo de todos os produtos via GET /rest/v1/products?select=cost_price,supplier_reference,ipi_rate, contornando a view mascarada v_products_public.

  • Medido: 6.123 produtos, 6.118 com cost_price exposto ao anon.

Correção

ALTER POLICY products_public_read ON public.products TO authenticated;
REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON public.products FROM anon;
  • O público passa a ler somente via v_products_public (security_invoker=false, roda como dono, mascara as 16 colunas sensíveis) — catálogo inalterado.
  • As 8 views derivadas (v_products_complete, v_products_kit_builder, vw_packagings_catalog, vw_products_packaging_info, vw_products_commercial_packing, ...) são security_invoker=on → herdam a RLS da base e deixam de vazar custo em cascata (validado: 0 não-nulos para anon).
  • suppliers já era seguro p/ anon (policy de SELECT só authenticated) — sem mudança.
  • Mantém-se o SELECT grant do anon para que leituras residuais (ex.: mockup .select('id')) degradem para vazio via RLS em vez de permission denied.

Validação (sem mutar produção)

>340 asserções executadas em produção dentro de transações revertidas (RAISE EXCEPTION), 0 violações. Sentinelas pós-aplicação (estado real):

cenário resultado
anon base products 0 linhas / 0 cost (era 6123 / 6118)
anon v_products_complete (cost) 0 (cascata)
authenticated base products 6123 (admin intacto)
v_products_public 6123 linhas, cost mascarado (NULL)
anon INSERT/UPDATE/DELETE revogados
anon SELECT-grant / SELECT na view preservados
products_public_read roles {authenticated}

Residuais (fora do escopo C2 — passos próprios)

  1. authenticated (logados) ainda leem cost_price da base (USING true). Se houver clientes logados não-admin, exige separar a leitura de custo do admin (RPC/edge com service_role).
  2. O form de admin lê o produto pela view mascarada (cost_price NULL com bridge OFF) — possível bug de UX pré-existente.
  3. system_kill_switches é legível por anon (exposição menor de config) — avaliar à parte.

🤖 Gerado durante a sessão de remediação do subsistema invokeExternalDb (Etapa 3/10).


Summary by cubic

Closes the cost_price leak by removing public (anon) access to the base products table while keeping the public catalog unchanged via the masked v_products_public view. Adds a Supabase migration for tracking; production DB was already updated.

  • Bug Fixes

    • Restricted products_public_read to authenticated only.
    • Revoked INSERT, UPDATE, DELETE, TRUNCATE on public.products from anon.
    • Stops cascade leaks from derived views; public reads continue via v_products_public (masked).
  • Migration

    • Added supabase/migrations/20260530173000_etapa3_c2_products_cost_leak_anon.sql for versioning (no runtime changes required).

Written for commit e5e255c. Summary will update on new commits.

Review in cubic

…o (anon)

Causa-raiz: a policy `products_public_read` concedia SELECT USING(true) a `anon`
(além de `authenticated`), e `anon` tinha grant de coluna em cost_price/
suggested_price/supplier_reference/ipi_rate. Assim qualquer cliente com a anon
key lia a base `products` direto (6.123 produtos, 6.118 com custo) contornando a
view mascarada `v_products_public`.

Correção: remove `anon` da policy de SELECT (catálogo público continua via
`v_products_public`, security_invoker=false/owner — inalterado) e revoga grants
de escrita do `anon` (já bloqueados por RLS is_org_owner_or_admin; higiene).

As 8 views derivadas (v_products_complete, vw_products_packaging_info, etc.) são
security_invoker=on → herdam a RLS da base e deixam de vazar em cascata (validado).
`suppliers` já era seguro p/ anon (policy só authenticated) — sem mudança.

Aplicado em produção via Supabase MCP (projeto doufsxqlfjyuvxuezpln); este arquivo
é para rastreio em git. Validação: >340 asserções em produção (revertidas), 0 violações.
@vercel
Copy link
Copy Markdown

vercel Bot commented May 30, 2026

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

Project Deployment Actions Updated (UTC)
we-dream-big Error Error May 30, 2026 5:16pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 30, 2026

Warning

Review limit reached

@adm01-debug, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 20 minutes and 39 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0fdfbff9-68b0-4a5a-8bab-2b275887cb6a

📥 Commits

Reviewing files that changed from the base of the PR and between 9a60afa and e5e255c.

📒 Files selected for processing (1)
  • supabase/migrations/20260530173000_etapa3_c2_products_cost_leak_anon.sql
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/etapa3-c2-products-cost-leak

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

@supabase
Copy link
Copy Markdown

supabase Bot commented May 30, 2026

Updates to Preview Branch (fix/etapa3-c2-products-cost-leak) ↗︎

Deployments Status Updated
Database Sat, 30 May 2026 17:18:57 UTC
Services Sat, 30 May 2026 17:18:57 UTC
APIs Sat, 30 May 2026 17:18:57 UTC

Tasks are run on every commit but only new migration files are pushed.
Close and reopen this PR if you want to apply changes from existing seed or migration files.

Tasks Status Updated
Configurations Sat, 30 May 2026 17:19:04 UTC
Migrations Sat, 30 May 2026 17:21:30 UTC
Seeding ⏸️ Sat, 30 May 2026 17:18:50 UTC
Edge Functions ⏸️ Sat, 30 May 2026 17:18:50 UTC

❌ Branch Error • Sat, 30 May 2026 17:21:31 UTC

FATAL: terminating connection due to administrator command (SQLSTATE 57P01)
At statement: 0
-- ============================================================================
-- T17: Garantir search_path seguro em funções públicas (postgres-owned)
-- ============================================================================
-- Contexto (Tarefa #17 do redeploy Promo_Gifts 2026-05-12):
--   A Supabase Security Advisor alerta quando funções não têm search_path
--   explícito — vetor de SQL injection via search_path hijacking.
--
-- Diagnóstico (2026-05-12 via pg_proc query):
--   - 768 funções postgres-owned em public: TODAS já têm search_path definido.
--   - 4 funções supabase_admin-owned (unaccent): NÃO podem ser alteradas
--     — são gerenciadas pela plataforma Supabase (pg_catalog-owned extension).
--
-- Esta migration é IDEMPOTENTE e serve como guardrail futuro:
--   Re-execução em ambiente onde funções ainda não têm search_path aplica
--   a correção. Em produção (2026-05-12), o DO block completa sem ALTER.
--
-- SEGURANÇA: NÃO altera funções de supabase_admin (platform-managed).
--   Alterá-las causaria erro de permissão ou comportamento inesperado.
-- ============================================================================

DO $$
DECLARE
  r          RECORD;
  v_count    INT := 0;
  v_skipped  INT := 0;
BEGIN
  FOR r IN
    SELECT
      p.oid,
      p.proname,
      n.nspname AS schema_name,
      pg_get_userbyid(p.proowner) AS owner
    FROM pg_proc p
    JOIN pg_namespace n ON n.oid = p.pronamespace
    WHERE n.nspname = 'public'
      AND pg_get_userbyid(p.proowner) = 'postgres'
      AND (
        p.proconfig IS NULL
        OR NOT EXISTS (
          SELECT 1 FROM unnest(p.proconfig) AS cfg
          WHERE cfg LIKE 'search_path=%'
        )
      )
  LOOP
    BEGIN
      EXECUTE format(
        'ALTER FUNCTION %s SET search_path = public',
        r.oid::regprocedure
      );
      v_count := v_count + 1;
      RAISE NOTICE 'T17: search_path definido em %.% (owner=postgres)',
        r.schema_name, r.proname;
    EXCEPTION WHEN OTHERS THEN
      v_skipped := v_skipped + 1;
      RAISE WARNING 'T17: não foi possível alterar %.% — %',
        r.schema_name, r.proname, SQLERRM;
    END;
  END LOOP;

  IF v_count = 0 AND v_skipped = 0 THEN
    RAISE NOTICE 'T17: todas as funções postgres-owned já têm search_path definido. Nada a fazer.';
  ELSE
    RAISE NOTICE 'T17: concluído — % função(ões) corrigida(s), % ignorada(s).', v_count, v_skipped;
  END IF;
END $$

View logs for this Workflow Run ↗︎.
Learn more about Supabase for Git ↗︎.

@adm01-debug adm01-debug marked this pull request as ready for review May 30, 2026 17:20
Copilot AI review requested due to automatic review settings May 30, 2026 17:20
@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@adm01-debug adm01-debug merged commit 338036c into main May 30, 2026
42 of 55 checks passed
@adm01-debug adm01-debug deleted the fix/etapa3-c2-products-cost-leak branch May 30, 2026 17:21
Copy link
Copy Markdown
Contributor

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.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

adm01-debug added a commit that referenced this pull request May 30, 2026
Rebase limpo sobre main atual (inclui #526 telemetria, #527 RLS, #530).
- bridge.ts: WRITE_OPERATIONS + isWriteOperation() + WriteUnavailableError;
  escrita com bridge OFF / kill-switch / CORS agora LANCA em vez de retornar
  vazio. Leitura mantem vazio silencioso. Telemetria do #526 preservada
  (recordBridgeCall/recordKillSwitchHit) — recordCall roda ANTES do throw.
- index.ts: exporta isWriteOperation + WriteUnavailableError.
Apenas estes 2 arquivos (rest-native writes + testes ficam no #525).
adm01-debug added a commit that referenced this pull request May 30, 2026
…A) (#531)

* PR#1 (C): escrita falha LOUD em vez de no-op silencioso

Rebase limpo sobre main atual (inclui #526 telemetria, #527 RLS, #530).
- bridge.ts: WRITE_OPERATIONS + isWriteOperation() + WriteUnavailableError;
  escrita com bridge OFF / kill-switch / CORS agora LANCA em vez de retornar
  vazio. Leitura mantem vazio silencioso. Telemetria do #526 preservada
  (recordBridgeCall/recordKillSwitchHit) — recordCall roda ANTES do throw.
- index.ts: exporta isWriteOperation + WriteUnavailableError.
Apenas estes 2 arquivos (rest-native writes + testes ficam no #525).

* test(A): cobertura do caminho de escrita REST nativo (Plano A) — 12 testes das 6 guardas + remap + LOUD

* feat(A): escrita REST nativo (Plano A) em rest-native.ts — 6 guardas, remap EN→PT, fail LOUD; preserva telemetria #526

* style(A): normaliza separadores de comentário em rest-native.ts (byte-exato ao artefato validado)

* style(A): separadores uniformes em rest-native.ts (determinístico, byte-exato 32a30c5c)

* feat(A)+test: wire write fast-path em bridge.ts (tryExecuteRestNativeWrite) + corrige bridge.test.ts (evita REST path no mock) — 23/23 verde
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