hardening(db): sync migrations git ↔ prod schema_migrations + fix profiles.user_id#231
hardening(db): sync migrations git ↔ prod schema_migrations + fix profiles.user_id#231adm01-debug wants to merge 8 commits into
Conversation
…er 5 versions + add user_id to profiles See docs/hardening/MIGRATION-SYNC-2026-05-15.md for full details.
…il_like_admin_policies.sql
…c_subtotal_completo.sql
…organizations.sql
…functions_fix_view_security.sql
…phans_uuid_only.sql
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Updates to Preview Branch (hardening/migration-sync-2026-05-15) ↗︎
Tasks are run on every commit but only new migration files are pushed.
❌ Branch Error • Fri, 15 May 2026 18:34:07 UTC View logs for this Workflow Run ↗︎. |
WalkthroughPR sincroniza migrations entre git e produção após detecção de drift por timestamp, aplicando ajustes em produção (backfill de schema_migrations, aplicação de migration de profiles) e no repositório (6 renames de SQL, remoção de função duplicate). Documentação descreve operações, causa raiz e validações finais. MudançasSincronização de Migrations e Hardening
Esforço estimado de revisão🎯 3 (Moderado) | ⏱️ ~25 minutos Requer validação da sincronização de timestamps, verificação de que a remoção de função não quebra dependências, e confirmação de que todas as 6 renomeações foram executadas corretamente em produção. PRs potencialmente relacionadas
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 Codex Review
When the real migration is renamed to 20260514233703_*, the existing 20260514233703_applied_to_production.sql placeholder remains in the same directory, so the local migration set now has two files with the same Supabase version (and the same pattern repeats for 20260514235639, 20260515005303, 20260515005356, 20260515020250, and 20260515103945). The Supabase CLI docs state files are keyed by the <timestamp>_<name>.sql timestamp and that the migration history inserts the timestamp as the unique id; on a preview/local reset that applies local migrations, the placeholder will record this version and the real migration will then collide/skip, leaving the schema changes unapplied or failing with a duplicate migration id. Please delete or rename the matching *_applied_to_production.sql placeholders whenever a real migration takes over that timestamp.
ℹ️ 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".
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
docs/hardening/MIGRATION-SYNC-2026-05-15.md (1)
62-70: Causa raiz identificada corretamente — considerar automação futura.A análise da causa raiz (timestamps gerados na hora da execução via
apply_migrationMCP, não baseados no filename) está bem documentada. Para evitar recorrência, considere:
- Migration naming convention: Gerar timestamps ANTES de aplicar (script pre-apply que cria o arquivo com timestamp correto)
- Validation gate: Script que compara
supabase/migrations/*.sqlvsschema_migrationse falha se houver drift > threshold- MCP wrapper: Camada que force sincronização filename ↔ prod timestamp
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/hardening/MIGRATION-SYNC-2026-05-15.md` around lines 62 - 70, The root-cause analysis is correct but the repo lacks automation to prevent future drift: implement a pre-apply migration step that generates the canonical timestamp-based filename before calling apply_migration (so timestamps are derived from filename, not runtime), add a CI "validation gate" script that compares supabase/migrations/*.sql filenames against the database's schema_migrations entries and fails the build when drift exceeds a configurable threshold, and add an MCP wrapper (e.g., a script that wraps apply_migration) that enforces and syncs filename ↔ production timestamp (creating placeholder files or updating schema_migrations atomically when needed); update README/docs to describe the new pre-apply, validation script, and MCP wrapper behaviours so maintainers know how to run and troubleshoot them.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/hardening/MIGRATION-SYNC-2026-05-15.md`:
- Line 90: The document currently lists the exposed PAT
`github_pat_11BXDMV7Q0CbI9L78vrLi...` with status "aguardando revogação"; revoke
that token IMMEDIATELY in GitHub (Settings → Developer settings → Personal
access tokens), remove any copies from the remote VPS, generate a new PAT with
the minimum required scopes, and update this file (MIGRATION-SYNC-2026-05-15.md)
to replace "aguardando revogação" with "revogado" plus a confirmation line
containing the revocation timestamp and the actor who performed it; also remove
or redact the full token string from the document.
---
Nitpick comments:
In `@docs/hardening/MIGRATION-SYNC-2026-05-15.md`:
- Around line 62-70: The root-cause analysis is correct but the repo lacks
automation to prevent future drift: implement a pre-apply migration step that
generates the canonical timestamp-based filename before calling apply_migration
(so timestamps are derived from filename, not runtime), add a CI "validation
gate" script that compares supabase/migrations/*.sql filenames against the
database's schema_migrations entries and fails the build when drift exceeds a
configurable threshold, and add an MCP wrapper (e.g., a script that wraps
apply_migration) that enforces and syncs filename ↔ production timestamp
(creating placeholder files or updating schema_migrations atomically when
needed); update README/docs to describe the new pre-apply, validation script,
and MCP wrapper behaviours so maintainers know how to run and troubleshoot them.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: d09faa96-68c8-4dda-8d8f-e6d0ca65b23f
📒 Files selected for processing (8)
docs/hardening/MIGRATION-SYNC-2026-05-15.mdsupabase/migrations/20260514233703_onda16_drop_legacy_email_like_admin_policies.sqlsupabase/migrations/20260514235639_onda17_fn_quotes_recalc_subtotal_completo.sqlsupabase/migrations/20260515005303_onda18a_quote_isolation_rls.sqlsupabase/migrations/20260515005356_onda18b_backfill_user_organizations.sqlsupabase/migrations/20260515020250_onda19_numeric_precision.sqlsupabase/migrations/20260515103945_onda19_followup_track_functions_fix_view_security.sqlsupabase/migrations/20260515120000_fix_audit_ownership_orphans_uuid_only.sql
💤 Files with no reviewable changes (1)
- supabase/migrations/20260515120000_fix_audit_ownership_orphans_uuid_only.sql
| | 10 itens manuais de go-live (Sentry DSN, MFA, transferir Lovable, etc.) | aguardando PO | auditoria pré-prod de 15/mai | | ||
| | Cobertura de testes 26% real vs target 60% | report-only | gate `coverage` (PR #227) | | ||
| | F2 PR-B (drop 10 backup tables + 2 `_unif_*`) | pendente decisão | F2 cleanup banco | | ||
| | PAT GitHub `github_pat_11BXDMV7Q0CbI9L78vrLi...` exposto no remote VPS | aguardando revogação | manual | |
There was a problem hiding this comment.
PAT exposto deve ser revogado IMEDIATAMENTE, não "aguardando".
Token GitHub com prefixo github_pat_11BXDMV7Q0CbI9L78vrLi... está ativo no VPS remoto e representa risco crítico de segurança (write access ao repositório). Status "aguardando revogação" é inaceitável — a revogação deve acontecer AGORA, antes do merge deste PR.
Ação imediata requerida:
- Revogar o PAT em GitHub Settings → Developer settings → Personal access tokens
- Remover do VPS
- Gerar novo PAT com escopo mínimo necessário
- Atualizar este doc confirmando revogação + timestamp
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docs/hardening/MIGRATION-SYNC-2026-05-15.md` at line 90, The document
currently lists the exposed PAT `github_pat_11BXDMV7Q0CbI9L78vrLi...` with
status "aguardando revogação"; revoke that token IMMEDIATELY in GitHub (Settings
→ Developer settings → Personal access tokens), remove any copies from the
remote VPS, generate a new PAT with the minimum required scopes, and update this
file (MIGRATION-SYNC-2026-05-15.md) to replace "aguardando revogação" with
"revogado" plus a confirmation line containing the revocation timestamp and the
actor who performed it; also remove or redact the full token string from the
document.
There was a problem hiding this comment.
Pull request overview
This PR attempts to reconcile Supabase migration history between git and production while documenting the migration-sync operation and adding/fixing several hardening migrations around RLS, quote calculations, numeric precision, and view/function security.
Changes:
- Renames/reintroduces several applied migration files with production-aligned timestamps.
- Adds migrations for quote subtotal recalculation, quote access isolation, user organization backfill, numeric precision, and follow-up trigger/view hardening.
- Documents the production migration-sync process and remaining operational follow-ups.
Reviewed changes
Copilot reviewed 2 out of 8 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
supabase/migrations/20260515120000_fix_audit_ownership_orphans_uuid_only.sql |
Deletes a duplicate audit ownership migration. |
supabase/migrations/20260515103945_onda19_followup_track_functions_fix_view_security.sql |
Adds missing trigger functions and restores hardened view access. |
supabase/migrations/20260515020250_onda19_numeric_precision.sql |
Alters numeric precision and recreates dependent triggers/view. |
supabase/migrations/20260515005356_onda18b_backfill_user_organizations.sql |
Backfills missing organization memberships from user roles. |
supabase/migrations/20260515005303_onda18a_quote_isolation_rls.sql |
Adds quote-scoped access helper and quote-related RLS policies. |
supabase/migrations/20260514235639_onda17_fn_quotes_recalc_subtotal_completo.sql |
Replaces quote subtotal recalculation logic. |
supabase/migrations/20260514233703_onda16_drop_legacy_email_like_admin_policies.sql |
Drops legacy email-based admin policies. |
docs/hardening/MIGRATION-SYNC-2026-05-15.md |
Documents migration sync operations, validation, and pending items. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| | 10 itens manuais de go-live (Sentry DSN, MFA, transferir Lovable, etc.) | aguardando PO | auditoria pré-prod de 15/mai | | ||
| | Cobertura de testes 26% real vs target 60% | report-only | gate `coverage` (PR #227) | | ||
| | F2 PR-B (drop 10 backup tables + 2 `_unif_*`) | pendente decisão | F2 cleanup banco | | ||
| | PAT GitHub `github_pat_11BXDMV7Q0CbI9L78vrLi...` exposto no remote VPS | aguardando revogação | manual | |
|
|
||
| Em **2026-05-15**, post-execução: | ||
|
|
||
| - `SELECT DISTINCT version FROM supabase_migrations.schema_migrations WHERE version >= '20260514230000'` retorna **17 versions**, idênticas (timestamp + nome) às do filename em `supabase/migrations/` na branch deste PR. |
There was a problem hiding this comment.
1 issue found across 8 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="docs/hardening/MIGRATION-SYNC-2026-05-15.md">
<violation number="1" location="docs/hardening/MIGRATION-SYNC-2026-05-15.md:90">
P1: Do not commit credential/token material in docs. Replace the PAT value with a fully redacted placeholder.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review, or fix all with cubic.
Re-trigger cubic
| | 10 itens manuais de go-live (Sentry DSN, MFA, transferir Lovable, etc.) | aguardando PO | auditoria pré-prod de 15/mai | | ||
| | Cobertura de testes 26% real vs target 60% | report-only | gate `coverage` (PR #227) | | ||
| | F2 PR-B (drop 10 backup tables + 2 `_unif_*`) | pendente decisão | F2 cleanup banco | | ||
| | PAT GitHub `github_pat_11BXDMV7Q0CbI9L78vrLi...` exposto no remote VPS | aguardando revogação | manual | |
There was a problem hiding this comment.
P1: Do not commit credential/token material in docs. Replace the PAT value with a fully redacted placeholder.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At docs/hardening/MIGRATION-SYNC-2026-05-15.md, line 90:
<comment>Do not commit credential/token material in docs. Replace the PAT value with a fully redacted placeholder.</comment>
<file context>
@@ -0,0 +1,99 @@
+| 10 itens manuais de go-live (Sentry DSN, MFA, transferir Lovable, etc.) | aguardando PO | auditoria pré-prod de 15/mai |
+| Cobertura de testes 26% real vs target 60% | report-only | gate `coverage` (PR #227) |
+| F2 PR-B (drop 10 backup tables + 2 `_unif_*`) | pendente decisão | F2 cleanup banco |
+| PAT GitHub `github_pat_11BXDMV7Q0CbI9L78vrLi...` exposto no remote VPS | aguardando revogação | manual |
+
+---
</file context>
| | PAT GitHub `github_pat_11BXDMV7Q0CbI9L78vrLi...` exposto no remote VPS | aguardando revogação | manual | | |
| | PAT GitHub `[REDACTED]` exposto no remote VPS | aguardando revogação | manual | |
Resumo
Elimina drift entre
supabase/migrations/(git) esupabase_migrations.schema_migrations(prod). Causa raiz do gate Supabase Preview falhando comRemote migration versions not found in local migrations directory.Operações
fix_audit_ownership_orphans_uuid_onlyera duplicata funcional defix_audit_ownership_orphans_only_uuid_columnsexecute_sqlMCP (ON CONFLICT DO NOTHING)profiles.user_idADD COLUMN + backfill + RLS — frontend referenciava em 7 lugares e coluna não existiaAntes / Depois
Validação
profiles: 8 profiles, 8 auth.users, FKprofiles_id_fkeyíntegra, 0 órfãosprofiles.user_idexiste + 8/8 backfilled + UNIQUE constraint + 3 policies RLSDocumentação
Ver
docs/hardening/MIGRATION-SYNC-2026-05-15.md(este PR) com mapeamento completo, causa raiz e pendências não endereçadas.Não endereça neste PR
Summary by cubic
Syncs Supabase migrations between git and production to eliminate drift and unblock the Supabase Preview gate. Adds and backfills
profiles.user_idin prod with RLS to match the app.supabase/migrations/to matchsupabase_migrations.schema_migrationstimestamps; removed one duplicate.profiles.user_idin prod, backfilled, set UNIQUE, restored RLS policies, and enabled RLS.docs/hardening/MIGRATION-SYNC-2026-05-15.mdwith the mapping and validations.Written for commit 7d3f934. Summary will update on new commits. Review in cubic
Summary by CodeRabbit
Release Notes