Skip to content

The platform for continuously improving AI agents.

5.0 KB
Raw Blame
"""Self-hosted local auth: login-or-register without Clerk."""

from __future__ import annotations

import uuid

import pytest
from django.core.cache import cache
from rest_framework.test import APIClient
from rest_framework_simplejwt.tokens import RefreshToken

from overbae.models import (
    Project,
    ProjectInvite,
    ProjectMembership,
    User,
)

pytestmark = [pytest.mark.django_db, pytest.mark.covers("authentication")]


@pytest.fixture(autouse=True)
def _clear_throttle():
    cache.clear()


@pytest.fixture(autouse=True)
def _clerk_off(settings):
    settings.CLERK_API_SECRET_KEY = ""


def _auth(user: User) -> APIClient:
    client = APIClient()
    token = RefreshToken.for_user(user)
    client.credentials(HTTP_AUTHORIZATION=f"Bearer {token.access_token}")
    return client


def _owner() -> tuple[User, Project]:
    user = User.objects.create_user(
        email=f"owner-{uuid.uuid4().hex[:8]}@example.com",
        password="test-pass-123",
        clerk_user_id=f"local_{uuid.uuid4().hex}",
    )
    project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
    ProjectMembership.objects.create(user=user, project=project)
    return user, project


def test_local_session_creates_account_on_first_use():
    res = APIClient().post(
        "/api/auth/local/",
        {"email": "[email protected]", "password": "password123"},
        format="json",
    )
    assert res.status_code == 201
    body = res.json()
    assert body["access"] and body["refresh"]
    assert body["user"]["email"] == "[email protected]"
    assert body["user"]["email_verified"] is True
    assert body["user"]["is_guest"] is False
    user = User.objects.get(email="[email protected]")
    assert user.clerk_user_id.startswith("local_")
    assert user.check_password("password123")


def test_local_session_signs_in_existing_user():
    User.objects.create_user(
        email="[email protected]",
        password="password123",
        clerk_user_id=f"local_{uuid.uuid4().hex}",
    )
    res = APIClient().post(
        "/api/auth/local/",
        {"email": "[email protected]", "password": "password123"},
        format="json",
    )
    assert res.status_code == 200
    assert res.json()["user"]["email"] == "[email protected]"
    assert User.objects.filter(email="[email protected]").count() == 1


def test_local_session_wrong_password():
    User.objects.create_user(
        email="[email protected]",
        password="password123",
        clerk_user_id=f"local_{uuid.uuid4().hex}",
    )
    res = APIClient().post(
        "/api/auth/local/",
        {"email": "[email protected]", "password": "wrong-password"},
        format="json",
    )
    assert res.status_code == 401, res.content
    assert res.json().get("detail")


def test_local_session_refused_when_clerk_enabled(settings):
    settings.CLERK_API_SECRET_KEY = "sk_test_xxx"
    res = APIClient().post(
        "/api/auth/local/",
        {"email": "[email protected]", "password": "password123"},
        format="json",
    )
    assert res.status_code == 403
    assert res.json()["code"] == "clerk_required"
    assert not User.objects.filter(email="[email protected]").exists()


def test_local_session_claims_pending_invite():
    owner, project = _owner()
    ProjectInvite.objects.create(
        project=project,
        email="[email protected]",
        invited_by=owner,
        clerk_invitation_id="",
    )
    res = APIClient().post(
        "/api/auth/local/",
        {"email": "[email protected]", "password": "password123"},
        format="json",
    )
    assert res.status_code == 201
    user = User.objects.get(email="[email protected]")
    assert ProjectMembership.objects.filter(user=user, project=project).exists()
    assert not ProjectInvite.objects.filter(email="[email protected]").exists()


def test_invite_create_without_clerk_skips_email():
    owner, project = _owner()
    res = _auth(owner).post(
        f"/api/projects/{project.id}/invites/",
        {"email": "[email protected]"},
        format="json",
    )
    assert res.status_code == 201
    invite = ProjectInvite.objects.get(project=project, email="[email protected]")
    assert invite.clerk_invitation_id == ""


def test_local_sign_in_attempts_are_limited_per_address():
    User.objects.create_user(email="[email protected]", password="password123")
    client = APIClient()
    statuses = [
        client.post(
            "/api/auth/local/",
            {"email": "[email protected]", "password": f"guess-{n:04d}"},
            format="json",
            # A client can send any forwarded-for value: the count follows the address tried.
            HTTP_X_FORWARDED_FOR=f"203.0.113.{n}",
        ).status_code
        for n in range(11)
    ]
    assert statuses[:10] == [401] * 10
    assert statuses[10] == 429


def test_an_email_longer_than_the_account_column_is_refused():
    res = APIClient().post(
        "/api/auth/local/",
        {"email": "a" * 250 + "@ops.local", "password": "password123"},
        format="json",
    )
    assert res.status_code == 400
    assert not User.objects.filter(email__startswith="a" * 250).exists()