← Back to Pull requests

fix(db): RLS multi-tenant aberta em 7 tabelas copilot_* [SEGURANÇA] #2763

Merged
adm01-debug merged 2 files (87 lines) on Nov 07, 2026 15:57 UTC
View on GitHub
adm01-debug adm01-debug commented on Nov 07, 2026 13:49 UTC
Author

O que estava errado

Durante uma validação pedida pelo Joaquim sobre o copiloto de vendas, achei que 7 das 10 tabelas copilot_ em produção têm RLS habilitada mas com policies USING (true) / WITH CHECK (true) restritas só à role authenticated — ou seja, qualquer vendedor logado consegue ler (e em 2 casos escrever) os dados de QUALQUER outro vendedor:

| Tabela | Exposição antes do fix |
|---|---|
| copilot_help_requests | SELECT/INSERT de qualquer vendedor |
| copilot_outcomes | SELECT/INSERT de qualquer vendedor |
| copilot_seller_settings | SELECT/INSERT/UPDATE de qualquer vendedor (dava pra alterar a config de outro vendedor) |
| copilot_usage | SELECT/INSERT de qualquer vendedor (cota/uso) |
| copilot_conversation_scores | SELECT/INSERT/UPDATE de qualquer score, mesmo de conversa alheia |
| copilot_learning_moments | SELECT de qualquer learning moment |
| copilot_objection_catalog | INSERT podia atribuir a entrada a outro submitted_by |

service_role tem BYPASSRLS=true, então as Edge Functions não eram afetadas — o vazamento era vendedor→vendedor, pelo client autenticado direto no Supabase.

O que mudou

Escopo pelo padrão já usado em copilot_sessions/copilot_insights/copilot_feedback (que já estavam corretas):

  • 4 tabelas com seller_id: seller_id = auth.uid().

  • copilot_conversation_scores/copilot_learning_moments (sem seller_id direto): visível para quem agiu (scored_by/tagged_by) OU para o vendedor dono da conversa (conversation_id → copilot_sessions.profile_id).

  • copilot_objection_catalog: mantém SELECT aberto de propósito (é catálogo compartilhado do time); só travei o INSERT para não deixar atribuir a entrada a outro submitted_by.
  • Evidência

    DDL já aplicado em produção via MCP (db_query) + registrado no ledger (version 20261107133000, RETURNING não-vazio confirmado) — seguindo o fluxo da seção "Decisões de 2026-09-26" do CLAUDE.md para não deixar o furo aberto esperando o merge. Re-consultei pg_policy depois do apply: as 16 policies das 7 tabelas agora têm using_expr/check_expr escopados (confirmado via pg_get_expr), e copilot_objection_catalog_select continua true (intencional).

    Não consegui rodar node scripts/db-audit/supabase-usage-guard.mjs nem regenerar schema-catalog.json/manifesto nesta sessão (sem acesso a shell/clone local no momento) — isso deve rodar no db-guard.yml/db-live-guard.yml desta PR; se o guard pedir atualização do catálogo, é esse passo que falta, não o DDL em si.

    Pendência que NÃO resolvi (decisão de produto, não bug de segurança)

    Nenhuma das 10 tabelas copilot_ tem policy de gestor/supervisor — hoje só o próprio vendedor (e quem fez a ação) vê seus dados. Se gestores precisam ver dados do time (como em fix-copilot-rls-supervisor-261101-1530, que parece não ter chegado a estas tabelas), isso é uma policy nova a desenhar, não uma correção deste PR.

    ---
    🤖 Gerado por sessão do Claude Code a pedido do Joaquim (validação de segurança do copiloto de vendas)

    Diff: 87 lines (+87 / -0) across 2 files Reviewer: adm01-debug Review duration: 127m
    All Vouch review confidence checks passed
    Residual risk 0.08 = Change Risk (0.50) × (1 − Review Confidence (0.83)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.50 · 87 lines diff across 2 files
    0.50
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.89 · 5 substantive comment(s)
    0.89
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    83%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.268
    Self Review self_review
    0.140
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    7 items
    vercel[bot] vercel[bot] commented on Nov 07, 2026 13:49 UTC
    Bot

    [vc]: #kj6DxZbdonwtvgurkBEGBD73HP8CS1L1h5rO9B2Ihx4=:eyJpc01vbm9yZXBvIjp0cnVlLCJ0eXBlIjoiZ2l0aHViIiwicHJvamVjdHMiOlt7Im5hbWUiOiJ6YXBwX3dlYl92MiIsInByb2plY3RJZCI6InByal9KNHdiOGVneno4aUwxQ0puU09YSkR0cW5idlJwIiwibGl2ZUZlZWRiYWNrIjp7InJlc29sdmVkIjowLCJ1bnJlc29sdmVkIjowLCJ0b3RhbCI6MCwibGluayI6IiJ9LCJpbnNwZWN0b3JVcmwiOiJodHRwczovL3ZlcmNlbC5jb20vanVjYTEvemFwcF93ZWJfdjIvM3BUS21wdW5DdEQ5bXBZMUxFU2FDNUpWMjJDZSIsIm5leHRDb21taXRTdGF0dXMiOiJJR05PUkVEIiwicm9vdERpcmVjdG9yeSI6bnVsbCwicHJldmlld1VybCI6InphcHB3ZWJ2Mi1naXQtY2xhdWRlLWZpeC1jb3BpbG90LXJscy1vcGVuLXBvbGljaWVzLWEyYTZkYy1qdWNhMS52ZXJjZWwuYXBwIn1dfQ==
    The latest updates on your projects. Learn more about Vercel for GitHub.

    <details><summary>1 Skipped Deployment</summary>

    | Project | Deployment | Actions | Updated |
    | :--- | :----- | :------ | :------ |
    | <a href="https://vercel.com/juca1/zapp_web_v2"><sup><img src="https://vercel.com/api/www/avatar?projectId=prj_J4wb8egzz8iL1CJnSOXJDtqnbvRp&teamId=team_QyN41X0q8hrqhW80AwokbFLv&s=32" width="16" height="16" align="middle" alt="" /></sup></a> zapp_web_v2 | !Ignored Ignored | Preview | <relative-time datetime="2026-11-07T15:33:31.908Z">Nov 7, 2026 3:33pm UTC</relative-time> |
    </details>

    qodo-code-review[bot] qodo-code-review[bot] commented on Nov 07, 2026 13:49 UTC
    Bot

    <!-- qodo:billing-blocked -->

    ⓘ Qodo reviews are paused because your trial has ended. Ask your workspace admin to add credits to resume reviews. Manage billing

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 07, 2026 13:49 UTC
    Bot

    <!-- codex-pull-request-review-summary -->
    <!-- codex-review-state:v1 {"code_review":{"commit_sha":"01439cd37c98e6e6b71a9e7534fb857bfac56cc7","has_any_findings":false,"has_unresolved_findings":false,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} -->

    <details>
    <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary>

    This comment shows the latest Codex review activity on this pull request.

    | Review | Status | Commit | Review trigger |
    | --- | --- | --- | --- |
    | 📝 Code Review | ✅ Completed <relative-time datetime="2026-11-07T15:01:23.599732Z">2026-11-07T15:01:23.599732Z</relative-time> | 01439cd | New commits |

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    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" or "@codex security review".
  • Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

    </details>

    </details>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 07, 2026 13:51 UTC
    Code Review
    supabase/migrations/20261107133000_fix_copilot_rls_open_policies.sql:1
    @@ -0,0 +1,68 @@
    +-- Corrige RLS aberta (USING/CHECK true) em 7 tabelas copilot_*.
    +-- Achado: qualquer vendedor autenticado lia/escrevia os dados de
    +-- QUALQUER outro vendedor nestas tabelas (service_role tem BYPASSRLS,
    +-- não é afetado). Escopo por seller_id = auth.uid(), ou pelo autor da
    +-- ação (scored_by/tagged_by) OR dono da conversa via
    +-- copilot_sessions.profile_id — mesmo padrão já usado em
    +-- copilot_sessions/copilot_insights/copilot_feedback.
    +
    +DROP POLICY IF EXISTS copilot_help_requests_select ON copilot_help_requests;
    +DROP POLICY IF EXISTS copilot_help_requests_insert ON copilot_help_requests;
    +CREATE POLICY copilot_help_requests_select ON copilot_help_requests
    +  FOR SELECT TO authenticated USING (seller_id = auth.uid());
    +CREATE POLICY copilot_help_requests_insert ON copilot_help_requests
    +  FOR INSERT TO authenticated WITH CHECK (seller_id = auth.uid());
    +
    +DROP POLICY IF EXISTS copilot_outcomes_select ON copilot_outcomes;
    +DROP POLICY IF EXISTS copilot_outcomes_insert ON copilot_outcomes;
    +CREATE POLICY copilot_outcomes_select ON copilot_outcomes
    +  FOR SELECT TO authenticated USING (seller_id = auth.uid());
    +CREATE POLICY copilot_outcomes_insert ON copilot_outcomes
    +  FOR INSERT TO authenticated WITH CHECK (seller_id = auth.uid());
    +
    +DROP POLICY IF EXISTS copilot_seller_settings_select ON copilot_seller_settings;
    +DROP POLICY IF EXISTS copilot_seller_settings_insert ON copilot_seller_settings;
    +DROP POLICY IF EXISTS copilot_seller_settings_update ON copilot_seller_settings;
    +CREATE POLICY copilot_seller_settings_select ON copilot_seller_settings
    +  FOR SELECT TO authenticated USING (seller_id = auth.uid());
    +CREATE POLICY copilot_seller_settings_insert ON copilot_seller_settings
    +  FOR INSERT TO authenticated WITH CHECK (seller_id = auth.uid());
    +CREATE POLICY copilot_seller_settings_update ON copilot_seller_settings
    +  FOR UPDATE TO authenticated USING (seller_id = auth.uid()) WITH CHECK (seller_id = auth.uid());
    +
    +DROP POLICY IF EXISTS copilot_usage_select ON copilot_usage;
    +DROP POLICY IF EXISTS copilot_usage_insert ON copilot_usage;
    +CREATE POLICY copilot_usage_select ON copilot_usage
    +  FOR SELECT TO authenticated USING (seller_id = auth.uid());
    +CREATE POLICY copilot_usage_insert ON copilot_usage
    +  FOR INSERT TO authenticated WITH CHECK (seller_id = auth.uid());
    +
    +DROP POLICY IF EXISTS copilot_conversation_scores_select ON copilot_conversation_scores;
    +DROP POLICY IF EXISTS copilot_conversation_scores_insert ON copilot_conversation_scores;
    +DROP POLICY IF EXISTS copilot_conversation_scores_update ON copilot_conversation_scores;
    +CREATE POLICY copilot_conversation_scores_select ON copilot_conversation_scores
    +  FOR SELECT TO authenticated USING (
    +    scored_by = auth.uid()
    +    OR conversation_id IN (SELECT id FROM copilot_sessions WHERE profile_id = auth.uid())

    <sub><sub>!P2 Badge</sub></sub> Compare a conversa com conversation_id, não com o ID da sessão

    Quando a avaliação ou o momento de aprendizado é registrado por outra pessoa, o vendedor dono da conversa perde acesso ao registro: esta condição compara conversation_id com a chave da sessão, não com a conversa. Em supabase/migrations/20261030100000_copilot_sessions.sql:5-6, id é gerado independentemente de conversation_id; a edge supabase/functions/copilot-live/index.ts:98-100 também grava o identificador da conversa apenas em conversation_id. Assim, o ramo destinado ao proprietário não encontra a sessão correspondente. Selecione conversation_id na subconsulta, tanto nesta policy quanto em copilot_learning_moments_select (linha 58), para preservar a leitura pelo dono sem reabrir o acesso aos demais vendedores.

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 07, 2026 13:51 UTC
    Reviewer

    <!-- codex-review-receipt:v1 -->

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: a74434b513

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

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

    </details>

    adm01-debug adm01-debug commented on code on Nov 07, 2026 13:52 UTC
    Code Review
    supabase/migrations/20261107133000_fix_copilot_rls_open_policies.sql:1
    @@ -0,0 +1,68 @@
    +-- Corrige RLS aberta (USING/CHECK true) em 7 tabelas copilot_*.
    +-- Achado: qualquer vendedor autenticado lia/escrevia os dados de
    +-- QUALQUER outro vendedor nestas tabelas (service_role tem BYPASSRLS,
    +-- não é afetado). Escopo por seller_id = auth.uid(), ou pelo autor da
    +-- ação (scored_by/tagged_by) OR dono da conversa via
    +-- copilot_sessions.profile_id — mesmo padrão já usado em
    +-- copilot_sessions/copilot_insights/copilot_feedback.
    +
    +DROP POLICY IF EXISTS copilot_help_requests_select ON copilot_help_requests;
    +DROP POLICY IF EXISTS copilot_help_requests_insert ON copilot_help_requests;
    +CREATE POLICY copilot_help_requests_select ON copilot_help_requests
    +  FOR SELECT TO authenticated USING (seller_id = auth.uid());
    +CREATE POLICY copilot_help_requests_insert ON copilot_help_requests
    +  FOR INSERT TO authenticated WITH CHECK (seller_id = auth.uid());
    +
    +DROP POLICY IF EXISTS copilot_outcomes_select ON copilot_outcomes;
    +DROP POLICY IF EXISTS copilot_outcomes_insert ON copilot_outcomes;
    +CREATE POLICY copilot_outcomes_select ON copilot_outcomes
    +  FOR SELECT TO authenticated USING (seller_id = auth.uid());
    +CREATE POLICY copilot_outcomes_insert ON copilot_outcomes
    +  FOR INSERT TO authenticated WITH CHECK (seller_id = auth.uid());
    +
    +DROP POLICY IF EXISTS copilot_seller_settings_select ON copilot_seller_settings;
    +DROP POLICY IF EXISTS copilot_seller_settings_insert ON copilot_seller_settings;
    +DROP POLICY IF EXISTS copilot_seller_settings_update ON copilot_seller_settings;
    +CREATE POLICY copilot_seller_settings_select ON copilot_seller_settings
    +  FOR SELECT TO authenticated USING (seller_id = auth.uid());
    +CREATE POLICY copilot_seller_settings_insert ON copilot_seller_settings
    +  FOR INSERT TO authenticated WITH CHECK (seller_id = auth.uid());
    +CREATE POLICY copilot_seller_settings_update ON copilot_seller_settings
    +  FOR UPDATE TO authenticated USING (seller_id = auth.uid()) WITH CHECK (seller_id = auth.uid());
    +
    +DROP POLICY IF EXISTS copilot_usage_select ON copilot_usage;
    +DROP POLICY IF EXISTS copilot_usage_insert ON copilot_usage;
    +CREATE POLICY copilot_usage_select ON copilot_usage
    +  FOR SELECT TO authenticated USING (seller_id = auth.uid());
    +CREATE POLICY copilot_usage_insert ON copilot_usage
    +  FOR INSERT TO authenticated WITH CHECK (seller_id = auth.uid());
    +
    +DROP POLICY IF EXISTS copilot_conversation_scores_select ON copilot_conversation_scores;
    +DROP POLICY IF EXISTS copilot_conversation_scores_insert ON copilot_conversation_scores;
    +DROP POLICY IF EXISTS copilot_conversation_scores_update ON copilot_conversation_scores;
    +CREATE POLICY copilot_conversation_scores_select ON copilot_conversation_scores
    +  FOR SELECT TO authenticated USING (
    +    scored_by = auth.uid()
    +    OR conversation_id IN (SELECT id FROM copilot_sessions WHERE profile_id = auth.uid())

    Confirmado — copilot_sessions.id e conversation_id são colunas distintas, meu join estava errado. Corrigido no commit 01ab77f (migration 20261107163000), já aplicado em produção (RETURNING confirmado).

    ---
    _Generated by Claude Code_

    Reviewers
    Assignees
    adm01-debug adm01-debug
    Labels
    risk: low confidence: 83.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 50.2% (MEDIUM) · Higher = larger blast radius
    50.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 83.2% · Lower = rushed or shallow review
    83.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 8.5% · Safe to merge
    8.5%