Skip to content

fix(auth): incremento atômico de tentativas de login (corrige race) - #63

Open
felipetruman wants to merge 1 commit into
thaleslaray:mainfrom
felipetruman:fix/auth-ratelimit-atomic
Open

fix(auth): incremento atômico de tentativas de login (corrige race)#63
felipetruman wants to merge 1 commit into
thaleslaray:mainfrom
felipetruman:fix/auth-ratelimit-atomic

Conversation

@felipetruman

Copy link
Copy Markdown

Problema

recordFailedAttempt (lib/user-auth.ts) fazia read-then-write em dois passos:

const setting = await getSetting('login_attempts')
const current = setting ? parseInt(setting.value) || 0 : 0
await upsertSetting('login_attempts', (current + 1).toString())

Dois logins concorrentes leem o mesmo valor e escrevem o mesmo +1 → o contador fica defasado e um atacante ganha tentativas extras antes do lockout. Severidade prática é menor no single-tenant (atacante já precisa da senha master), mas a race é real.

Correção

  • Nova migration 20260616000000_atomic_login_attempts.sql: RPC increment_login_attempts() que incrementa em uma instrução atômica (INSERT .. ON CONFLICT (key) DO UPDATE), SECURITY DEFINER, grant só pro service_role.
  • recordFailedAttempt passa a chamar o RPC. Fallback não-atômico mantido e acionado em 42883 (função inexistente), então o deploy do código é seguro independente da ordem de aplicação da migration.

⚠️ Pós-merge / deploy

A migration precisa ser aplicada ao banco Supabase de produção para a atomicidade entrar em vigor (instalações novas já a aplicam no Step 9). Até lá, o fallback mantém o comportamento atual.

Test plan

  • Aplicar migration → select increment_login_attempts(); retorna contador incrementado.
  • Login errado → contador sobe; 5 erros → lockout 15min.
  • Sem a migration aplicada → fallback funciona (sem erro no login).

recordFailedAttempt fazia read-then-write (getSetting + upsertSetting):
dois logins concorrentes liam o mesmo valor e escreviam o mesmo +1,
permitindo tentativas extras antes do lockout disparar.

Adiciona RPC increment_login_attempts (INSERT .. ON CONFLICT DO UPDATE,
atômico no nível da linha) e a usa em recordFailedAttempt. Fallback
não-atômico mantido para quando a migration ainda não foi aplicada
(detecta 42883 = função inexistente), então o deploy do código é seguro
independente da ordem de aplicação da migration.
@vercel

vercel Bot commented Jun 16, 2026

Copy link
Copy Markdown

@felipetruman is attempting to deploy a commit to the Thales Laray Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown

Warning

Review limit reached

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

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

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 596b6047-1650-4bc0-af5a-9fadda316526

📥 Commits

Reviewing files that changed from the base of the PR and between 17c69e2 and 692e05a.

📒 Files selected for processing (2)
  • lib/user-auth.ts
  • supabase/migrations/20260616000000_atomic_login_attempts.sql
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

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.

1 participant