Commit 28e9ac64 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Rate-limit /auth/login against brute force

Username/password login had zero rate limiting since it shipped - unlimited
guesses against any account from anywhere. Adds a username column to the
existing AuthAttempt table (migration d22ca64d291e) and reuses the same
DB-backed approach already protecting /auth/telegram/request_code: 10
attempts per account per 15 minutes, 100 per source per hour. Kept
independent of the Telegram rate limit despite sharing a table - both
_check_rate_limit and the new _check_login_rate_limit filter on their own
column (phone_number.isnot(None) / username.isnot(None)) so hammering one
endpoint never burns the other's budget.

Verified live: 10 wrong-password attempts succeed with 401, the 11th (even
with the correct password) gets 429; a telegram request_code call
immediately after is unaffected.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 31e1b608
Pipeline #1095 passed with stage
in 3 minutes and 12 seconds
"""add username to auth_attempts
Revision ID: d22ca64d291e
Revises: 347da5d41656
Create Date: 2026-08-16 14:05:16.764245
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'd22ca64d291e'
down_revision: Union[str, Sequence[str], None] = '347da5d41656'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
op.add_column("auth_attempts", sa.Column("username", sa.String(), nullable=True))
op.create_index(op.f("ix_auth_attempts_username"), "auth_attempts", ["username"])
def downgrade() -> None:
"""Downgrade schema."""
op.drop_index(op.f("ix_auth_attempts_username"), table_name="auth_attempts")
op.drop_column("auth_attempts", "username")
...@@ -36,6 +36,20 @@ PHONE_WINDOW = timedelta(minutes=10) ...@@ -36,6 +36,20 @@ PHONE_WINDOW = timedelta(minutes=10)
MAX_REQUESTS_PER_IP = 20 MAX_REQUESTS_PER_IP = 20
IP_WINDOW = timedelta(hours=1) IP_WINDOW = timedelta(hours=1)
# Brute-force protection for /auth/login - same cheap DB-backed approach, kept independent of
# the Telegram limits above (separate columns, separate queries) even though they share a
# table. Per-username stops guessing passwords for one account; per-IP stops credential
# stuffing across many usernames from one source. Counts every attempt (successful or not),
# not just failures - simpler than tracking outcome, and a real user logging in/out repeatedly
# within the window is rare enough not to matter.
MAX_LOGIN_ATTEMPTS_PER_USERNAME = 10
LOGIN_USERNAME_WINDOW = timedelta(minutes=15)
# Meaningfully higher than the per-username limit on purpose - the per-username lock is the
# primary defense against guessing one account's password, this is just a backstop against
# mass credential-stuffing across many accounts from one source.
MAX_LOGIN_ATTEMPTS_PER_IP = 100
LOGIN_IP_WINDOW = timedelta(hours=1)
class RequestCodeReq(BaseModel): class RequestCodeReq(BaseModel):
phone_number: str phone_number: str
...@@ -77,15 +91,45 @@ def _check_rate_limit(db: Session, phone_number: str, ip: str): ...@@ -77,15 +91,45 @@ def _check_rate_limit(db: Session, phone_number: str, ip: str):
if phone_count >= MAX_REQUESTS_PER_PHONE: if phone_count >= MAX_REQUESTS_PER_PHONE:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many code requests for this number, try again later") raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many code requests for this number, try again later")
# Scoped to phone_number rows only (AuthAttempt.phone_number.isnot(None)) so this stays
# independent of login attempts sharing the same table/ip_address column.
ip_count = ( ip_count = (
db.query(AuthAttempt) db.query(AuthAttempt)
.filter(AuthAttempt.ip_address == ip, AuthAttempt.created_at >= now - IP_WINDOW) .filter(
AuthAttempt.ip_address == ip,
AuthAttempt.phone_number.isnot(None),
AuthAttempt.created_at >= now - IP_WINDOW,
)
.count() .count()
) )
if ip_count >= MAX_REQUESTS_PER_IP: if ip_count >= MAX_REQUESTS_PER_IP:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many code requests from this address, try again later") raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many code requests from this address, try again later")
def _check_login_rate_limit(db: Session, username: str, ip: str):
now = _utcnow()
username_count = (
db.query(AuthAttempt)
.filter(AuthAttempt.username == username, AuthAttempt.created_at >= now - LOGIN_USERNAME_WINDOW)
.count()
)
if username_count >= MAX_LOGIN_ATTEMPTS_PER_USERNAME:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many login attempts for this account, try again later")
# Scoped to username rows only, same independence reasoning as _check_rate_limit above.
ip_count = (
db.query(AuthAttempt)
.filter(
AuthAttempt.ip_address == ip,
AuthAttempt.username.isnot(None),
AuthAttempt.created_at >= now - LOGIN_IP_WINDOW,
)
.count()
)
if ip_count >= MAX_LOGIN_ATTEMPTS_PER_IP:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many login attempts from this address, try again later")
def _issue_tokens(db: Session, user_id: int) -> TokenResponse: def _issue_tokens(db: Session, user_id: int) -> TokenResponse:
access = create_access_token(user_id) access = create_access_token(user_id)
refresh = create_refresh_token(user_id) refresh = create_refresh_token(user_id)
...@@ -116,7 +160,12 @@ _DUMMY_PASSWORD_HASH = hash_password(uuid.uuid4().hex) ...@@ -116,7 +160,12 @@ _DUMMY_PASSWORD_HASH = hash_password(uuid.uuid4().hex)
@router.post("/login", response_model=TokenResponse) @router.post("/login", response_model=TokenResponse)
async def auth_login(req: UsernameLoginReq, db: Session = Depends(get_db)): async def auth_login(req: UsernameLoginReq, request: Request, db: Session = Depends(get_db)):
client_ip = request.client.host if request.client else "unknown"
_check_login_rate_limit(db, req.username, client_ip)
db.add(AuthAttempt(username=req.username, ip_address=client_ip))
db.commit()
user = db.query(User).filter(User.username == req.username).first() user = db.query(User).filter(User.username == req.username).first()
password_ok = verify_password(req.password, (user.password_hash if user else None) or _DUMMY_PASSWORD_HASH) password_ok = verify_password(req.password, (user.password_hash if user else None) or _DUMMY_PASSWORD_HASH)
if not user or not user.password_hash or not password_ok: if not user or not user.password_hash or not password_ok:
......
...@@ -51,10 +51,14 @@ class RefreshToken(Base): ...@@ -51,10 +51,14 @@ class RefreshToken(Base):
revoked_at = Column(DateTime, nullable=True) revoked_at = Column(DateTime, nullable=True)
class AuthAttempt(Base): class AuthAttempt(Base):
"""Logged on every /auth/telegram/request_code call to rate-limit our own Telegram API usage.""" """Logged on every /auth/telegram/request_code call (phone_number set) to rate-limit our
own Telegram API usage, and on every /auth/login call (username set) to rate-limit
brute-force login attempts - the two purposes share this table but stay independent of
each other (queries always filter on whichever column is relevant, never mix the two)."""
__tablename__ = "auth_attempts" __tablename__ = "auth_attempts"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
phone_number = Column(String, index=True) phone_number = Column(String, index=True, nullable=True)
username = Column(String, index=True, nullable=True)
ip_address = Column(String, index=True) ip_address = Column(String, index=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
......
from src.api.routers.auth import MAX_REQUESTS_PER_PHONE from src.api.routers import auth as auth_router
from src.api.routers.auth import MAX_LOGIN_ATTEMPTS_PER_USERNAME, MAX_REQUESTS_PER_PHONE
from src.core.database import User from src.core.database import User
...@@ -68,6 +69,65 @@ def test_auth_login_missing_fields(client): ...@@ -68,6 +69,65 @@ def test_auth_login_missing_fields(client):
assert response.status_code == 422 assert response.status_code == 422
def test_auth_login_rate_limited_per_username(client):
client.post("/auth/register", json={"username": "bruteforcetarget", "password": "correcthorse1"})
for _ in range(MAX_LOGIN_ATTEMPTS_PER_USERNAME):
response = client.post("/auth/login", json={"username": "bruteforcetarget", "password": "wrongpassword"})
assert response.status_code == 401
response = client.post("/auth/login", json={"username": "bruteforcetarget", "password": "correcthorse1"})
assert response.status_code == 429
def test_auth_login_rate_limit_is_per_username_not_global(client):
# Hammering one account's login shouldn't lock out a completely different account.
client.post("/auth/register", json={"username": "victimaccount", "password": "correcthorse1"})
client.post("/auth/register", json={"username": "unrelatedaccount", "password": "correcthorse2"})
for _ in range(MAX_LOGIN_ATTEMPTS_PER_USERNAME):
client.post("/auth/login", json={"username": "victimaccount", "password": "wrongpassword"})
response = client.post("/auth/login", json={"username": "unrelatedaccount", "password": "correcthorse2"})
assert response.status_code == 200
def test_auth_login_rate_limit_independent_of_telegram_rate_limit(client, mocker):
# Login attempts and telegram request_code attempts share the same underlying table -
# confirm they don't consume each other's budget.
client.post("/auth/register", json={"username": "sharedtabletest", "password": "correcthorse1"})
mocker.patch(
"src.telegram_worker.telegram_auth.request_code",
return_value={"phone_code_hash": "hash123", "is_registered": True},
)
for _ in range(MAX_LOGIN_ATTEMPTS_PER_USERNAME):
client.post("/auth/login", json={"username": "sharedtabletest", "password": "wrongpassword"})
# The telegram endpoint's own (much lower) per-phone limit should still apply on its own
# terms, unaffected by how many login attempts just happened.
response = client.post("/auth/telegram/request_code", json={"phone_number": "+15559998888"})
assert response.status_code == 200
def test_auth_login_rate_limited_per_ip_across_different_usernames(client, db_session, monkeypatch):
# Credential stuffing: many different accounts guessed from one source, each individually
# well under its own per-username limit. The test DB persists for the whole pytest
# session (no per-test reset - other tests in this file already logged in many times
# against the same TestClient IP), so the threshold is patched to "however many attempts
# already happened, plus 3" rather than a fixed small number - keeps this deterministic
# regardless of run order instead of assuming a fresh counter.
from src.core.database import AuthAttempt
already = db_session.query(AuthAttempt).filter(AuthAttempt.username.isnot(None)).count()
monkeypatch.setattr(auth_router, "MAX_LOGIN_ATTEMPTS_PER_IP", already + 3)
for i in range(3):
client.post("/auth/login", json={"username": f"stuffing-target-{i}", "password": "whatever1"})
response = client.post("/auth/login", json={"username": "stuffing-target-3", "password": "whatever1"})
assert response.status_code == 429
# --- Telegram (account linking / chat scanning, not primary auth) --- # --- Telegram (account linking / chat scanning, not primary auth) ---
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment