7c20b518d4
Repositorio estava ha ~5 sessoes sem commit. Consolida tudo desde d088a89.
Ver commit.md na raiz para descricao completa por sessao.
# Numeros
- A# auditoria abertos: 0/30
- V# verificacoes abertos: 5/52 (todos adiados com plano)
- T# testes escritos: 10/10
- Vitest: 192/192
- SQL integration: 33/33
- E2E (Playwright, novo): 5/5
- Migrations: 17 (10 novas Sessao 6)
- Areas auditadas: 7 (+documentos com 10 V#)
# Highlights Sessao 6 (hoje)
- V#34/V#41 Opcao B2: tenant_features com plano + override (RPC SECURITY DEFINER, tela /saas/tenant-features)
- A#20 rev2 self-hosted: defesa em 5 camadas (honeypot + rate limit + math captcha condicional + paranoid mode + dashboard /saas/security)
- Documentos hardening (V#43-V#49): tenant scoping em storage policies (vazamento entre clinicas eliminado), RPC validate_share_token, signatures policy granular
- SaaS Twilio Config (/saas/twilio-config): UI editavel para SID/webhook/cotacao; AUTH_TOKEN permanece em env var
- T#9 + T#10: useAgendaEvents.spec.js + Playwright E2E (descobriu bug no front que foi corrigido)
# Sessoes anteriores (1-5) consolidadas
- Sessao 1: auth/router/session, normalizeRole extraido
- Sessao 2: agenda - composables/services consolidados
- Sessao 3: pacientes - tenant_id em todas queries
- Sessao 4: security review pagina publica - 14/15 vulnerabilidades corrigidas
- Sessao 5: SaaS - P0 (A#30: 7 tabelas com RLS off corrigidas)
# .gitignore ajustado
- supabase/* + !supabase/functions/ (mantem 10 edge functions, ignora .temp/migrations gerados pelo CLI)
- database-novo/backups/ (regeneravel via db.cjs backup)
- test-results/ + playwright-report/
- .claude/settings.local.json (config local com senha de dev removida do tracking)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
137 lines
7.3 KiB
SQL
137 lines
7.3 KiB
SQL
-- =============================================================================
|
|
-- Migration: 20260419000006_layered_bot_defense
|
|
-- A#20 (rev2) — Defesa em camadas self-hosted (substitui Turnstile).
|
|
--
|
|
-- Camadas:
|
|
-- 1. Honeypot field (no front) → invisível, sempre ativo
|
|
-- 2. Rate limit por IP no edge → submission_rate_limits
|
|
-- 3. Math captcha CONDICIONAL → só se IP teve N falhas recentes
|
|
-- 4. Logging em public_submission_attempts (genérico, não só intake)
|
|
-- 5. Modo paranoid global → saas_security_config.captcha_required
|
|
--
|
|
-- Substitui chamadas Turnstile na edge function submit-patient-intake.
|
|
-- =============================================================================
|
|
|
|
-- ─────────────────────────────────────────────────────────────────────────
|
|
-- 1. saas_security_config (singleton)
|
|
-- -----------------------------------------------------------------------------
|
|
CREATE TABLE IF NOT EXISTS public.saas_security_config (
|
|
id boolean PRIMARY KEY DEFAULT true,
|
|
honeypot_enabled boolean NOT NULL DEFAULT true,
|
|
rate_limit_enabled boolean NOT NULL DEFAULT true,
|
|
rate_limit_window_min integer NOT NULL DEFAULT 10,
|
|
rate_limit_max_attempts integer NOT NULL DEFAULT 5,
|
|
captcha_after_failures integer NOT NULL DEFAULT 3,
|
|
captcha_required_globally boolean NOT NULL DEFAULT false,
|
|
block_duration_min integer NOT NULL DEFAULT 30,
|
|
captcha_required_window_min integer NOT NULL DEFAULT 60,
|
|
updated_at timestamptz NOT NULL DEFAULT now(),
|
|
updated_by uuid,
|
|
CONSTRAINT saas_security_config_singleton CHECK (id = true)
|
|
);
|
|
|
|
INSERT INTO public.saas_security_config (id) VALUES (true)
|
|
ON CONFLICT (id) DO NOTHING;
|
|
|
|
ALTER TABLE public.saas_security_config ENABLE ROW LEVEL SECURITY;
|
|
|
|
REVOKE ALL ON public.saas_security_config FROM anon, authenticated;
|
|
GRANT SELECT, UPDATE ON public.saas_security_config TO authenticated;
|
|
|
|
DROP POLICY IF EXISTS saas_security_config_read ON public.saas_security_config;
|
|
CREATE POLICY saas_security_config_read ON public.saas_security_config
|
|
FOR SELECT TO authenticated
|
|
USING (true); -- qualquer logado pode ler config global (não tem segredo)
|
|
|
|
DROP POLICY IF EXISTS saas_security_config_write ON public.saas_security_config;
|
|
CREATE POLICY saas_security_config_write ON public.saas_security_config
|
|
FOR UPDATE TO authenticated
|
|
USING (public.is_saas_admin())
|
|
WITH CHECK (public.is_saas_admin());
|
|
|
|
COMMENT ON TABLE public.saas_security_config IS 'Singleton: configuração global de defesa contra bots em endpoints públicos.';
|
|
|
|
-- ─────────────────────────────────────────────────────────────────────────
|
|
-- 2. public_submission_attempts (log genérico)
|
|
-- -----------------------------------------------------------------------------
|
|
CREATE TABLE IF NOT EXISTS public.public_submission_attempts (
|
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
endpoint text NOT NULL,
|
|
ip_hash text,
|
|
success boolean NOT NULL,
|
|
error_code text,
|
|
error_msg text,
|
|
blocked_by text, -- 'honeypot' | 'rate_limit' | 'captcha' | 'rpc' | null
|
|
user_agent text,
|
|
metadata jsonb,
|
|
created_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_psa_endpoint_created ON public.public_submission_attempts (endpoint, created_at DESC);
|
|
CREATE INDEX IF NOT EXISTS idx_psa_ip_hash_created ON public.public_submission_attempts (ip_hash, created_at DESC) WHERE ip_hash IS NOT NULL;
|
|
CREATE INDEX IF NOT EXISTS idx_psa_failed ON public.public_submission_attempts (created_at DESC) WHERE success = false;
|
|
|
|
ALTER TABLE public.public_submission_attempts ENABLE ROW LEVEL SECURITY;
|
|
|
|
REVOKE ALL ON public.public_submission_attempts FROM anon, authenticated;
|
|
GRANT SELECT ON public.public_submission_attempts TO authenticated;
|
|
|
|
DROP POLICY IF EXISTS psa_read_saas_admin ON public.public_submission_attempts;
|
|
CREATE POLICY psa_read_saas_admin ON public.public_submission_attempts
|
|
FOR SELECT TO authenticated
|
|
USING (public.is_saas_admin());
|
|
|
|
COMMENT ON TABLE public.public_submission_attempts IS 'Log de tentativas em endpoints públicos (intake, signup, agendador). Escrita apenas via RPC SECURITY DEFINER.';
|
|
|
|
-- ─────────────────────────────────────────────────────────────────────────
|
|
-- 3. submission_rate_limits (estado vigente por IP+endpoint)
|
|
-- -----------------------------------------------------------------------------
|
|
CREATE TABLE IF NOT EXISTS public.submission_rate_limits (
|
|
ip_hash text NOT NULL,
|
|
endpoint text NOT NULL,
|
|
attempt_count integer NOT NULL DEFAULT 0,
|
|
fail_count integer NOT NULL DEFAULT 0,
|
|
window_start timestamptz NOT NULL DEFAULT now(),
|
|
blocked_until timestamptz,
|
|
requires_captcha_until timestamptz,
|
|
last_attempt_at timestamptz NOT NULL DEFAULT now(),
|
|
created_at timestamptz NOT NULL DEFAULT now(),
|
|
PRIMARY KEY (ip_hash, endpoint)
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_srl_blocked_until ON public.submission_rate_limits (blocked_until) WHERE blocked_until IS NOT NULL;
|
|
CREATE INDEX IF NOT EXISTS idx_srl_endpoint ON public.submission_rate_limits (endpoint, last_attempt_at DESC);
|
|
|
|
ALTER TABLE public.submission_rate_limits ENABLE ROW LEVEL SECURITY;
|
|
|
|
REVOKE ALL ON public.submission_rate_limits FROM anon, authenticated;
|
|
GRANT SELECT ON public.submission_rate_limits TO authenticated;
|
|
|
|
DROP POLICY IF EXISTS srl_read_saas_admin ON public.submission_rate_limits;
|
|
CREATE POLICY srl_read_saas_admin ON public.submission_rate_limits
|
|
FOR SELECT TO authenticated
|
|
USING (public.is_saas_admin());
|
|
|
|
COMMENT ON TABLE public.submission_rate_limits IS 'Estado de rate limit por IP+endpoint. Escrita apenas via RPC. SaaS admin lê pra dashboard.';
|
|
|
|
-- ─────────────────────────────────────────────────────────────────────────
|
|
-- 4. math_challenges (TTL 5min, limpa via cron)
|
|
-- -----------------------------------------------------------------------------
|
|
CREATE TABLE IF NOT EXISTS public.math_challenges (
|
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
question text NOT NULL,
|
|
answer integer NOT NULL,
|
|
used boolean NOT NULL DEFAULT false,
|
|
created_at timestamptz NOT NULL DEFAULT now(),
|
|
expires_at timestamptz NOT NULL DEFAULT (now() + interval '5 minutes')
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_mc_expires ON public.math_challenges (expires_at);
|
|
|
|
ALTER TABLE public.math_challenges ENABLE ROW LEVEL SECURITY;
|
|
|
|
REVOKE ALL ON public.math_challenges FROM anon, authenticated;
|
|
-- nenhum grant: tabela acessada apenas via RPC SECURITY DEFINER
|
|
|
|
COMMENT ON TABLE public.math_challenges IS 'Challenges de math captcha. TTL 5min. Escrita/leitura apenas via RPC.';
|