Backend: - Item model (title, url, points, username, content, created_at) - is_admin flag on User + startup migration for pre-existing DBs - get_current_admin dependency (401 without/invalid token, 403 for non-admins); server-side check on every admin endpoint - /api/v1/admin/items CRUD: pagination, case-insensitive title/url search, sort by title/created_at/points, in-memory rate limiting (1000 req/60s per admin -> 429) - seed_admin.py (ADMIN_USERNAME/ADMIN_PASSWORD), documented in backend/.env.example Frontend: - Auth context exposes is_admin; RequireAdmin route guard (redirects signed-out users, renders 403 page for non-admins) - AdminLayout with responsive dark sidebar; Admin link in header for admins only - AdminDashboard: paginated table (page size 10/20/50), 300ms debounced search, sortable title/points/created_at columns, edit/delete row actions - EditItemPage: create + edit with client-side validation and a Lexical (0.25) WYSIWYG editor (bold/italic/underline, H1-H6, lists, code blocks, links, undo/redo), optional debounced auto-save - DeleteConfirmation modal with warning icon and explicit "Yes, delete" confirmation - Unit tests (34) and mocked E2E workflow tests (10) All acceptance criteria for milestones/m6-setup-admin-area-prompt.md verified: 108 backend, 87 frontend unit and 29 E2E tests pass.
202 lines
7.8 KiB
Python
202 lines
7.8 KiB
Python
"""Tests for the auth primitives (core.auth) and the /api/v1/auth endpoints."""
|
|
|
|
import re
|
|
import time
|
|
|
|
import jwt as pyjwt
|
|
import pytest
|
|
|
|
from core import auth
|
|
from models import User
|
|
|
|
|
|
class TestPasswordHashing:
|
|
def test_hash_format_and_roundtrip(self) -> None:
|
|
hashed = auth.hash_password("s3cret!")
|
|
salt, digest = hashed.split("$", 1)
|
|
# salt = secrets.token_hex(16) -> 32 hex chars; sha256 digest -> 64.
|
|
assert re.fullmatch(r"[0-9a-f]{32}", salt)
|
|
assert re.fullmatch(r"[0-9a-f]{64}", digest)
|
|
assert auth.verify_password("s3cret!", hashed)
|
|
|
|
def test_unique_salt_per_hash(self) -> None:
|
|
assert auth.hash_password("same-password") != auth.hash_password("same-password")
|
|
|
|
def test_verify_wrong_password(self) -> None:
|
|
hashed = auth.hash_password("correct-horse")
|
|
assert not auth.verify_password("wrong-password", hashed)
|
|
|
|
def test_verify_rejects_malformed_stored_values(self) -> None:
|
|
assert not auth.verify_password("x", "no-salt-separator")
|
|
assert not auth.verify_password("x", "zz-!$deadbeef") # non-hex salt
|
|
assert not auth.verify_password("x", "")
|
|
assert not auth.verify_password("x", "validhex$") # empty digest
|
|
|
|
def test_iteration_count_is_owasp_minimum(self) -> None:
|
|
assert auth.PBKDF2_ITERATIONS >= 120_000
|
|
|
|
|
|
class TestTokenCreation:
|
|
def test_payload_and_seven_day_expiry(self) -> None:
|
|
token = auth.create_token("alice")
|
|
payload = pyjwt.decode(token, auth.SECRET_KEY, algorithms=["HS256"])
|
|
assert payload["sub"] == "alice"
|
|
assert auth.TOKEN_TTL_SECONDS == 7 * 24 * 60 * 60
|
|
assert payload["exp"] == payload["iat"] + auth.TOKEN_TTL_SECONDS
|
|
assert payload["exp"] > int(time.time())
|
|
|
|
def test_token_signed_with_wrong_key_fails(self) -> None:
|
|
token = auth.create_token("alice")
|
|
with pytest.raises(pyjwt.InvalidSignatureError):
|
|
pyjwt.decode(token, "some-other-secret", algorithms=["HS256"])
|
|
|
|
|
|
def _register(client, username: str = "alice", password: str = "password123"):
|
|
return client.post(
|
|
"/api/v1/auth/register", json={"username": username, "password": password}
|
|
)
|
|
|
|
|
|
class TestRegisterEndpoint:
|
|
def test_register_creates_user_and_returns_token(self, client, session) -> None:
|
|
response = _register(client)
|
|
assert response.status_code == 201
|
|
body = response.json()
|
|
assert body["username"] == "alice"
|
|
assert body["token"]
|
|
# Registration never grants admin rights (M6).
|
|
assert body["is_admin"] is False
|
|
|
|
# The token decodes to the registered username.
|
|
payload = pyjwt.decode(body["token"], auth.SECRET_KEY, algorithms=["HS256"])
|
|
assert payload["sub"] == "alice"
|
|
|
|
# The user is persisted with a hashed (not plaintext) password.
|
|
user = session.query(User).filter(User.username == "alice").first()
|
|
assert user is not None
|
|
assert user.password_hash != "password123"
|
|
assert "$" in user.password_hash
|
|
assert auth.verify_password("password123", user.password_hash)
|
|
assert user.created_at is not None
|
|
|
|
def test_register_duplicate_username_returns_400(self, client) -> None:
|
|
assert _register(client).status_code == 201
|
|
response = _register(client)
|
|
assert response.status_code == 400
|
|
assert response.json()["code"] == "bad_request"
|
|
assert response.json()["detail"] == "Username already exists"
|
|
|
|
@pytest.mark.parametrize(
|
|
"username",
|
|
["", "ab", "a" * 21, "bad name", "semi;colon", "with-dash", "dot.name", "ünicode"],
|
|
)
|
|
def test_register_rejects_invalid_usernames(self, client, username: str) -> None:
|
|
assert _register(client, username=username).status_code == 422
|
|
|
|
def test_register_rejects_short_password(self, client) -> None:
|
|
response = client.post(
|
|
"/api/v1/auth/register", json={"username": "alice", "password": "short"}
|
|
)
|
|
assert response.status_code == 422
|
|
|
|
def test_register_requires_both_fields(self, client) -> None:
|
|
response = client.post("/api/v1/auth/register", json={"username": "alice"})
|
|
assert response.status_code == 422
|
|
|
|
|
|
class TestLoginEndpoint:
|
|
def test_login_success_returns_token(self, client) -> None:
|
|
assert _register(client).status_code == 201
|
|
response = client.post(
|
|
"/api/v1/auth/login", json={"username": "alice", "password": "password123"}
|
|
)
|
|
assert response.status_code == 200
|
|
body = response.json()
|
|
assert body["username"] == "alice"
|
|
payload = pyjwt.decode(body["token"], auth.SECRET_KEY, algorithms=["HS256"])
|
|
assert payload["sub"] == "alice"
|
|
|
|
def test_login_wrong_password_returns_401(self, client) -> None:
|
|
_register(client)
|
|
response = client.post(
|
|
"/api/v1/auth/login", json={"username": "alice", "password": "nope-nope"}
|
|
)
|
|
assert response.status_code == 401
|
|
assert response.json()["code"] == "unauthorized"
|
|
|
|
def test_login_unknown_user_returns_401(self, client) -> None:
|
|
response = client.post(
|
|
"/api/v1/auth/login", json={"username": "ghost", "password": "password123"}
|
|
)
|
|
assert response.status_code == 401
|
|
|
|
|
|
def _auth_headers(client, username: str = "alice") -> dict:
|
|
token = _register(client, username=username).json()["token"]
|
|
return {"Authorization": f"Bearer {token}"}
|
|
|
|
|
|
class TestMeEndpoint:
|
|
def test_me_with_valid_token(self, client) -> None:
|
|
response = client.get("/api/v1/auth/me", headers=_auth_headers(client))
|
|
assert response.status_code == 200
|
|
# Registered (non-admin) accounts report is_admin=False (M6).
|
|
assert response.json() == {"username": "alice", "is_admin": False}
|
|
|
|
def test_me_without_token_returns_401(self, client) -> None:
|
|
response = client.get("/api/v1/auth/me")
|
|
assert response.status_code == 401
|
|
assert response.json()["code"] == "unauthorized"
|
|
|
|
def test_me_with_garbage_token_returns_401(self, client) -> None:
|
|
response = client.get(
|
|
"/api/v1/auth/me", headers={"Authorization": "Bearer not.a.jwt"}
|
|
)
|
|
assert response.status_code == 401
|
|
|
|
def test_me_with_expired_token_returns_401(self, client) -> None:
|
|
_register(client)
|
|
now = int(time.time())
|
|
token = pyjwt.encode(
|
|
{"sub": "alice", "iat": now - 10, "exp": now - 5},
|
|
auth.SECRET_KEY,
|
|
algorithm="HS256",
|
|
)
|
|
response = client.get(
|
|
"/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"}
|
|
)
|
|
assert response.status_code == 401
|
|
|
|
def test_me_with_wrong_secret_returns_401(self, client) -> None:
|
|
_register(client)
|
|
now = int(time.time())
|
|
token = pyjwt.encode(
|
|
{"sub": "alice", "iat": now, "exp": now + 3600},
|
|
"some-other-secret",
|
|
algorithm="HS256",
|
|
)
|
|
response = client.get(
|
|
"/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"}
|
|
)
|
|
assert response.status_code == 401
|
|
|
|
def test_me_token_for_deleted_user_returns_401(self, client, session) -> None:
|
|
headers = _auth_headers(client)
|
|
user = session.query(User).filter(User.username == "alice").first()
|
|
assert user is not None
|
|
session.delete(user)
|
|
session.commit()
|
|
response = client.get("/api/v1/auth/me", headers=headers)
|
|
assert response.status_code == 401
|
|
|
|
|
|
class TestLogoutEndpoint:
|
|
def test_logout_with_valid_token_returns_204(self, client) -> None:
|
|
response = client.post("/api/v1/auth/logout", headers=_auth_headers(client))
|
|
assert response.status_code == 204
|
|
assert response.content == b""
|
|
|
|
def test_logout_without_token_returns_401(self, client) -> None:
|
|
response = client.post("/api/v1/auth/logout")
|
|
assert response.status_code == 401
|