The admin area was managing a Hacker News-style Item model that the
public site never consumed, so the homepage always fell back to sample
data. Rebuild the admin area around the real public content model.
Backend:
- Remove the Item model, schema and admin API
- Admin API now manages articles at /api/v1/admin/articles (CRUD) with
/api/v1/admin/authors and /api/v1/admin/categories reference data
- Add public read-only article endpoints (/api/v1/articles,
/api/v1/articles/{id}): no auth, published-only, newest-first
- Rewrite Article schemas; ArticleRead embeds author and category
- Add idempotent seed_content.py dev seeder (3 authors, 4 categories,
6 published articles)
Frontend:
- Admin UI rewritten around articles: AdminDashboard list, new
EditArticlePage (create/edit, author/category selects, published
toggle, Lexical editor, debounced auto-save)
- Replace AdminItem types and api client with the article domain
- Update App routes, AdminLayout sidebar, DeleteConfirmation, Lexical
editor labels and Home/client comments to article terminology
Tests:
- Rewrite admin unit tests and the Playwright admin e2e spec for the
article domain; add test_articles.py for the public endpoints and
seeder
672 lines
28 KiB
Python
672 lines
28 KiB
Python
"""Tests for the admin area (M6): /api/v1/admin/articles CRUD, reference
|
|
data (authors/categories), access control, rate limiting, and the is_admin
|
|
startup migration.
|
|
|
|
Covers the M6 acceptance criteria: 401/403 handling for the admin
|
|
dependency, pagination/search/sort on the list endpoint, article creation,
|
|
partial updates, deletion and input validation.
|
|
"""
|
|
|
|
import time
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import jwt as pyjwt
|
|
import pytest
|
|
|
|
from api.v1 import admin as admin_api
|
|
from core import auth
|
|
from models import Article, Author, Category, User
|
|
|
|
BASE = "/api/v1/admin/articles"
|
|
|
|
|
|
def _make_user(session, username: str, is_admin: bool = False) -> User:
|
|
user = User(username=username, password_hash="salt$digest", is_admin=is_admin)
|
|
session.add(user)
|
|
session.commit()
|
|
return user
|
|
|
|
|
|
def _headers(session, username: str) -> dict:
|
|
"""A valid Bearer token for an (already persisted) user."""
|
|
return {"Authorization": f"Bearer {auth.create_token(username)}"}
|
|
|
|
|
|
def _make_author(
|
|
session, name: str = "Byline Writer", email: str = "writer@example.com"
|
|
) -> Author:
|
|
author = Author(name=name, email=email)
|
|
session.add(author)
|
|
session.commit()
|
|
return author
|
|
|
|
|
|
def _make_category(
|
|
session, name: str = "Technology", slug: str = "technology"
|
|
) -> Category:
|
|
category = Category(name=name, slug=slug)
|
|
session.add(category)
|
|
session.commit()
|
|
return category
|
|
|
|
|
|
def _seed_articles(
|
|
session,
|
|
count: int,
|
|
prefix: str = "Story",
|
|
author: Author | None = None,
|
|
category: Category | None = None,
|
|
) -> list[Article]:
|
|
author = author or _make_author(session)
|
|
category = category or _make_category(session)
|
|
articles = []
|
|
for i in range(count):
|
|
article = Article(
|
|
title=f"{prefix} {i:02d}",
|
|
content=f"<p>Body {i}</p>",
|
|
author_id=author.id,
|
|
category_id=category.id,
|
|
published=True,
|
|
)
|
|
session.add(article)
|
|
articles.append(article)
|
|
session.commit()
|
|
return articles
|
|
|
|
|
|
ADMIN_ROUTES = [
|
|
("GET", f"{BASE}"),
|
|
("POST", BASE),
|
|
("GET", f"{BASE}/1"),
|
|
("PUT", f"{BASE}/1"),
|
|
("DELETE", f"{BASE}/1"),
|
|
("GET", "/api/v1/admin/authors"),
|
|
("GET", "/api/v1/admin/categories"),
|
|
]
|
|
|
|
|
|
class TestAdminAccessControl:
|
|
"""The admin dependency validates the JWT AND the is_admin flag."""
|
|
|
|
@pytest.mark.parametrize("method, path", ADMIN_ROUTES)
|
|
def test_missing_token_returns_401(self, client, method, path) -> None:
|
|
payload = {"title": "x"} if method in ("POST", "PUT") else None
|
|
response = client.request(method, path, json=payload)
|
|
assert response.status_code == 401
|
|
assert response.json()["code"] == "unauthorized"
|
|
|
|
def test_invalid_token_returns_401(self, client) -> None:
|
|
response = client.get(BASE, headers={"Authorization": "Bearer not.a.jwt"})
|
|
assert response.status_code == 401
|
|
assert response.json()["code"] == "unauthorized"
|
|
|
|
def test_expired_token_returns_401(self, client, session) -> None:
|
|
_make_user(session, "admin", is_admin=True)
|
|
now = int(time.time())
|
|
token = pyjwt.encode(
|
|
{"sub": "admin", "iat": now - 200, "exp": now - 100},
|
|
auth.SECRET_KEY,
|
|
algorithm="HS256",
|
|
)
|
|
response = client.get(BASE, headers={"Authorization": f"Bearer {token}"})
|
|
assert response.status_code == 401
|
|
|
|
def test_token_for_deleted_user_returns_401(self, client, session) -> None:
|
|
_make_user(session, "admin", is_admin=True)
|
|
headers = _headers(session, "admin")
|
|
session.delete(session.query(User).filter(User.username == "admin").one())
|
|
session.commit()
|
|
response = client.get(BASE, headers=headers)
|
|
assert response.status_code == 401
|
|
assert response.json()["detail"] == "Unknown user"
|
|
|
|
@pytest.mark.parametrize("method, path", ADMIN_ROUTES)
|
|
def test_non_admin_receives_403(self, client, session, method, path) -> None:
|
|
_make_user(session, "alice", is_admin=False)
|
|
payload = {"title": "x"} if method in ("POST", "PUT") else None
|
|
response = client.request(
|
|
method, path, json=payload, headers=_headers(session, "alice")
|
|
)
|
|
assert response.status_code == 403
|
|
body = response.json()
|
|
assert body["code"] == "forbidden"
|
|
assert body["detail"] == "Admin access required"
|
|
|
|
|
|
class TestListArticles:
|
|
def test_empty_list(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
response = client.get(BASE, headers=_headers(session, "root"))
|
|
assert response.status_code == 200
|
|
body = response.json()
|
|
assert body["articles"] == []
|
|
assert body["total"] == 0
|
|
assert body["page"] == 1
|
|
assert body["page_size"] == 20
|
|
assert body["total_pages"] == 0
|
|
|
|
def test_pagination_math_and_contents(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
_seed_articles(session, 25)
|
|
headers = _headers(session, "root")
|
|
|
|
page1 = client.get(BASE, params={"page": 1, "page_size": 10}, headers=headers).json()
|
|
assert page1["total"] == 25
|
|
assert page1["total_pages"] == 3
|
|
assert len(page1["articles"]) == 10
|
|
assert page1["page"] == 1
|
|
|
|
page2 = client.get(BASE, params={"page": 2, "page_size": 10}, headers=headers).json()
|
|
assert len(page2["articles"]) == 10
|
|
# Pages are disjoint.
|
|
ids1 = {a["id"] for a in page1["articles"]}
|
|
ids2 = {a["id"] for a in page2["articles"]}
|
|
assert ids1.isdisjoint(ids2)
|
|
|
|
page3 = client.get(BASE, params={"page": 3, "page_size": 10}, headers=headers).json()
|
|
assert len(page3["articles"]) == 5
|
|
|
|
def test_page_size_bounds(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
headers = _headers(session, "root")
|
|
assert client.get(BASE, params={"page_size": 0}, headers=headers).status_code == 422
|
|
assert client.get(BASE, params={"page_size": 101}, headers=headers).status_code == 422
|
|
assert client.get(BASE, params={"page": 0}, headers=headers).status_code == 422
|
|
assert client.get(BASE, params={"page_size": 100}, headers=headers).status_code == 200
|
|
|
|
def test_search_matches_title_and_content_case_insensitively(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
_seed_articles(session, 5)
|
|
headers = _headers(session, "root")
|
|
|
|
by_title = client.get(BASE, params={"search": "STORY 02"}, headers=headers).json()
|
|
assert [a["title"] for a in by_title["articles"]] == ["Story 02"]
|
|
|
|
# Bodies are "<p>Body <n></p>" — search inside the HTML content.
|
|
by_content = client.get(BASE, params={"search": "BODY 4"}, headers=headers).json()
|
|
assert [a["title"] for a in by_content["articles"]] == ["Story 04"]
|
|
|
|
none = client.get(BASE, params={"search": "does-not-exist"}, headers=headers).json()
|
|
assert none["articles"] == []
|
|
assert none["total"] == 0
|
|
|
|
def test_search_with_sql_metacharacters_is_treated_as_text(self, client, session) -> None:
|
|
"""Search input is a parameterized substring filter, never raw SQL."""
|
|
_make_user(session, "root", is_admin=True)
|
|
_seed_articles(session, 5)
|
|
headers = _headers(session, "root")
|
|
|
|
attack = "1=1' OR '1'='1"
|
|
resp = client.get(BASE, params={"search": attack}, headers=headers)
|
|
assert resp.status_code == 200
|
|
body = resp.json()
|
|
assert body["articles"] == []
|
|
assert body["total"] == 0
|
|
|
|
# The table is intact after the "attack".
|
|
intact = client.get(BASE, headers=headers).json()
|
|
assert intact["total"] == 5
|
|
|
|
@pytest.mark.parametrize("order, expected_first", [("asc", "Story 00"), ("desc", "Story 04")])
|
|
def test_sort_by_title(self, client, session, order, expected_first) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
_seed_articles(session, 5)
|
|
headers = _headers(session, "root")
|
|
body = client.get(
|
|
BASE, params={"sort_by": "title", "sort_order": order}, headers=headers
|
|
).json()
|
|
assert body["articles"][0]["title"] == expected_first
|
|
assert [a["title"] for a in body["articles"]] == sorted(
|
|
(a["title"] for a in body["articles"]), reverse=(order == "desc")
|
|
)
|
|
|
|
@pytest.mark.parametrize("order", ["asc", "desc"])
|
|
def test_sort_by_created_at(self, client, session, order) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
articles = _seed_articles(session, 5)
|
|
# Distinct timestamps so the ordering is deterministic.
|
|
base = datetime(2025, 1, 1, tzinfo=timezone.utc)
|
|
for index, article in enumerate(articles):
|
|
article.created_at = base + timedelta(minutes=index)
|
|
session.commit()
|
|
|
|
headers = _headers(session, "root")
|
|
body = client.get(
|
|
BASE, params={"sort_by": "created_at", "sort_order": order}, headers=headers
|
|
).json()
|
|
stamps = [a["created_at"] for a in body["articles"]]
|
|
assert stamps == sorted(stamps, reverse=(order == "desc"))
|
|
|
|
def test_invalid_sort_values_rejected(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
headers = _headers(session, "root")
|
|
assert client.get(BASE, params={"sort_by": "title"}, headers=headers).status_code == 200
|
|
# "points" was an Item column — it is no longer a valid sort field.
|
|
assert client.get(BASE, params={"sort_by": "points"}, headers=headers).status_code == 422
|
|
assert (
|
|
client.get(BASE, params={"sort_by": "username"}, headers=headers).status_code == 422
|
|
)
|
|
assert (
|
|
client.get(BASE, params={"sort_order": "up"}, headers=headers).status_code == 422
|
|
)
|
|
|
|
def test_article_payload_shape(self, client, session) -> None:
|
|
"""List entries embed the related author and category."""
|
|
_make_user(session, "root", is_admin=True)
|
|
author = _make_author(session, name="Amara Osei", email="amara@example.com")
|
|
category = _make_category(session, name="Culture", slug="culture")
|
|
_seed_articles(session, 1, author=author, category=category)
|
|
headers = _headers(session, "root")
|
|
body = client.get(BASE, headers=headers).json()
|
|
article = body["articles"][0]
|
|
assert set(article) == {
|
|
"id", "title", "content", "author_id", "category_id",
|
|
"created_at", "published", "author", "category",
|
|
}
|
|
assert article["author"] == {
|
|
"id": author.id, "name": "Amara Osei", "email": "amara@example.com", "bio": None
|
|
}
|
|
assert article["category"] == {
|
|
"id": category.id, "name": "Culture", "slug": "culture"
|
|
}
|
|
|
|
|
|
class TestGetArticle:
|
|
def test_returns_full_article_including_content(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
author = _make_author(session, name="Jonas Weber", email="jonas@example.com")
|
|
category = _make_category(session, name="Science", slug="science")
|
|
articles = _seed_articles(session, 1, author=author, category=category)
|
|
headers = _headers(session, "root")
|
|
response = client.get(f"{BASE}/{articles[0].id}", headers=headers)
|
|
assert response.status_code == 200
|
|
body = response.json()
|
|
assert body["id"] == articles[0].id
|
|
assert body["title"] == "Story 00"
|
|
assert body["content"] == "<p>Body 0</p>"
|
|
assert body["author"]["name"] == "Jonas Weber"
|
|
assert body["category"]["slug"] == "science"
|
|
|
|
def test_unknown_id_returns_404(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
headers = _headers(session, "root")
|
|
response = client.get(f"{BASE}/9999", headers=headers)
|
|
assert response.status_code == 404
|
|
assert response.json()["code"] == "not_found"
|
|
|
|
|
|
class TestCreateArticle:
|
|
def test_create_defaults_published_false(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
author = _make_author(session)
|
|
category = _make_category(session)
|
|
headers = _headers(session, "root")
|
|
payload = {
|
|
"title": "Fresh news",
|
|
"content": "<p>Hello world.</p>",
|
|
"author_id": author.id,
|
|
"category_id": category.id,
|
|
}
|
|
response = client.post(BASE, json=payload, headers=headers)
|
|
assert response.status_code == 201
|
|
body = response.json()
|
|
assert body["title"] == "Fresh news"
|
|
assert body["content"] == "<p>Hello world.</p>"
|
|
assert body["author_id"] == author.id
|
|
assert body["category_id"] == category.id
|
|
assert body["published"] is False
|
|
assert body["created_at"]
|
|
|
|
def test_create_with_published_true(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
author = _make_author(session)
|
|
category = _make_category(session)
|
|
payload = {
|
|
"title": "Ready to ship",
|
|
"content": "<p>Live now.</p>",
|
|
"author_id": author.id,
|
|
"category_id": category.id,
|
|
"published": True,
|
|
}
|
|
response = client.post(BASE, json=payload, headers=_headers(session, "root"))
|
|
assert response.status_code == 201
|
|
assert response.json()["published"] is True
|
|
|
|
@pytest.mark.parametrize(
|
|
"payload",
|
|
[
|
|
{}, # everything missing
|
|
{"title": "t", "content": "<p>c</p>"}, # missing author/category
|
|
{"title": "t", "author_id": 1, "category_id": 1}, # missing content
|
|
{"title": ""}, # empty title
|
|
{"title": "x" * 201}, # too long
|
|
{"title": "t", "content": "<p>c</p>", "author_id": 0}, # invalid ids
|
|
],
|
|
)
|
|
def test_validation_failures_return_422(self, client, session, payload) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
response = client.post(BASE, json=payload, headers=_headers(session, "root"))
|
|
assert response.status_code == 422
|
|
assert response.json()["code"] == "validation_error"
|
|
|
|
def test_unknown_author_returns_422(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
category = _make_category(session)
|
|
payload = {
|
|
"title": "Orphan author",
|
|
"content": "<p>x</p>",
|
|
"author_id": 9999,
|
|
"category_id": category.id,
|
|
}
|
|
response = client.post(BASE, json=payload, headers=_headers(session, "root"))
|
|
assert response.status_code == 422
|
|
assert response.json()["detail"] == "Author 9999 not found"
|
|
|
|
def test_unknown_category_returns_422(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
author = _make_author(session)
|
|
payload = {
|
|
"title": "Orphan category",
|
|
"content": "<p>x</p>",
|
|
"author_id": author.id,
|
|
"category_id": 9999,
|
|
}
|
|
response = client.post(BASE, json=payload, headers=_headers(session, "root"))
|
|
assert response.status_code == 422
|
|
assert response.json()["detail"] == "Category 9999 not found"
|
|
|
|
def test_duplicate_title_returns_409(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
author = _make_author(session)
|
|
category = _make_category(session)
|
|
_seed_articles(session, 1, author=author, category=category)
|
|
payload = {
|
|
"title": "Story 00",
|
|
"content": "<p>another body</p>",
|
|
"author_id": author.id,
|
|
"category_id": category.id,
|
|
}
|
|
response = client.post(BASE, json=payload, headers=_headers(session, "root"))
|
|
assert response.status_code == 409
|
|
assert response.json()["code"] == "conflict"
|
|
|
|
|
|
class TestUpdateArticle:
|
|
def test_partial_update_changes_only_provided_fields(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
articles = _seed_articles(session, 1)
|
|
headers = _headers(session, "root")
|
|
|
|
response = client.put(
|
|
f"{BASE}/{articles[0].id}", json={"published": False}, headers=headers
|
|
)
|
|
assert response.status_code == 200
|
|
body = response.json()
|
|
assert body["published"] is False
|
|
# Untouched fields keep their values.
|
|
assert body["title"] == "Story 00"
|
|
assert body["content"] == "<p>Body 0</p>"
|
|
|
|
def test_full_update(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
author = _make_author(session, name="Old Byline", email="old@example.com")
|
|
category = _make_category(session, name="Old Cat", slug="old-cat")
|
|
articles = _seed_articles(session, 1, author=author, category=category)
|
|
new_author = _make_author(session, name="New Byline", email="new@example.com")
|
|
new_category = _make_category(session, name="New Cat", slug="new-cat")
|
|
payload = {
|
|
"title": "Retitled",
|
|
"content": "<p>Updated</p>",
|
|
"author_id": new_author.id,
|
|
"category_id": new_category.id,
|
|
"published": False,
|
|
}
|
|
response = client.put(
|
|
f"{BASE}/{articles[0].id}", json=payload, headers=_headers(session, "root")
|
|
)
|
|
assert response.status_code == 200
|
|
body = response.json()
|
|
assert body["title"] == "Retitled"
|
|
assert body["content"] == "<p>Updated</p>"
|
|
assert body["author_id"] == new_author.id
|
|
assert body["category_id"] == new_category.id
|
|
assert body["published"] is False
|
|
assert body["author"]["name"] == "New Byline"
|
|
|
|
def test_unknown_id_returns_404(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
response = client.put(f"{BASE}/9999", json={"title": "x"}, headers=_headers(session, "root"))
|
|
assert response.status_code == 404
|
|
|
|
def test_invalid_payload_returns_422(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
articles = _seed_articles(session, 1)
|
|
response = client.put(
|
|
f"{BASE}/{articles[0].id}",
|
|
json={"title": "", "author_id": -3},
|
|
headers=_headers(session, "root"),
|
|
)
|
|
assert response.status_code == 422
|
|
|
|
def test_empty_payload_is_a_no_op(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
articles = _seed_articles(session, 1)
|
|
response = client.put(f"{BASE}/{articles[0].id}", json={}, headers=_headers(session, "root"))
|
|
assert response.status_code == 200
|
|
assert response.json()["title"] == "Story 00"
|
|
|
|
def test_title_collision_returns_409(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
articles = _seed_articles(session, 2)
|
|
response = client.put(
|
|
f"{BASE}/{articles[1].id}",
|
|
json={"title": "Story 00"},
|
|
headers=_headers(session, "root"),
|
|
)
|
|
assert response.status_code == 409
|
|
|
|
def test_update_to_unknown_author_returns_422(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
articles = _seed_articles(session, 1)
|
|
response = client.put(
|
|
f"{BASE}/{articles[0].id}",
|
|
json={"author_id": 9999},
|
|
headers=_headers(session, "root"),
|
|
)
|
|
assert response.status_code == 422
|
|
assert response.json()["detail"] == "Author 9999 not found"
|
|
|
|
def test_update_to_unknown_category_returns_422(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
articles = _seed_articles(session, 1)
|
|
response = client.put(
|
|
f"{BASE}/{articles[0].id}",
|
|
json={"category_id": 9999},
|
|
headers=_headers(session, "root"),
|
|
)
|
|
assert response.status_code == 422
|
|
assert response.json()["detail"] == "Category 9999 not found"
|
|
|
|
|
|
class TestDeleteArticle:
|
|
def test_delete_removes_the_article(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
articles = _seed_articles(session, 1)
|
|
headers = _headers(session, "root")
|
|
article_id = articles[0].id
|
|
|
|
response = client.delete(f"{BASE}/{article_id}", headers=headers)
|
|
assert response.status_code == 204
|
|
assert response.content == b""
|
|
|
|
assert client.get(f"{BASE}/{article_id}", headers=headers).status_code == 404
|
|
assert session.query(Article).filter(Article.id == article_id).first() is None
|
|
|
|
def test_delete_unknown_id_returns_404(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
response = client.delete(f"{BASE}/9999", headers=_headers(session, "root"))
|
|
assert response.status_code == 404
|
|
|
|
|
|
class TestReferenceData:
|
|
def test_list_authors_ordered_by_name(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
zed = _make_author(session, name="Zed Last", email="zed@example.com")
|
|
amy = _make_author(session, name="Amy First", email="amy@example.com")
|
|
response = client.get("/api/v1/admin/authors", headers=_headers(session, "root"))
|
|
assert response.status_code == 200
|
|
body = response.json()
|
|
assert [a["id"] for a in body] == [amy.id, zed.id]
|
|
assert body[0] == {
|
|
"id": amy.id, "name": "Amy First", "email": "amy@example.com", "bio": None
|
|
}
|
|
|
|
def test_list_authors_empty(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
response = client.get("/api/v1/admin/authors", headers=_headers(session, "root"))
|
|
assert response.status_code == 200
|
|
assert response.json() == []
|
|
|
|
def test_list_categories_ordered_by_name(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
world = _make_category(session, name="World", slug="world")
|
|
tech = _make_category(session, name="Technology", slug="technology")
|
|
response = client.get("/api/v1/admin/categories", headers=_headers(session, "root"))
|
|
assert response.status_code == 200
|
|
body = response.json()
|
|
assert [c["id"] for c in body] == [tech.id, world.id]
|
|
assert body[0] == {"id": tech.id, "name": "Technology", "slug": "technology"}
|
|
|
|
def test_list_categories_empty(self, client, session) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
response = client.get("/api/v1/admin/categories", headers=_headers(session, "root"))
|
|
assert response.status_code == 200
|
|
assert response.json() == []
|
|
|
|
|
|
class TestStartupMigration:
|
|
"""Pre-M6 databases (users table without is_admin) get the column."""
|
|
|
|
def test_legacy_users_table_gains_is_admin(self) -> None:
|
|
from sqlalchemy import inspect, text
|
|
|
|
from core.app import _ensure_user_columns
|
|
from db.session import engine
|
|
from models import Base
|
|
|
|
with engine.begin() as connection:
|
|
# Simulate a pre-M6 schema: users without is_admin.
|
|
connection.execute(text("DROP TABLE IF EXISTS users"))
|
|
connection.execute(
|
|
text(
|
|
"CREATE TABLE users ("
|
|
"id INTEGER PRIMARY KEY, "
|
|
"username VARCHAR(60) NOT NULL UNIQUE, "
|
|
"password_hash VARCHAR(128) NOT NULL, "
|
|
"created_at DATETIME)"
|
|
)
|
|
)
|
|
|
|
_ensure_user_columns()
|
|
|
|
names = {c["name"] for c in inspect(engine).get_columns("users")}
|
|
assert "is_admin" in names
|
|
# The standard create_all path stays idempotent on the patched table.
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
def test_is_noop_when_column_exists(self) -> None:
|
|
from sqlalchemy import inspect, text
|
|
|
|
from core.app import _ensure_user_columns
|
|
from db.session import engine
|
|
from models import Base
|
|
|
|
Base.metadata.create_all(bind=engine) # fresh, M6 schema
|
|
before = [c["name"] for c in inspect(engine).get_columns("users")]
|
|
_ensure_user_columns()
|
|
after = [c["name"] for c in inspect(engine).get_columns("users")]
|
|
assert before == after # unchanged, no ALTER issued
|
|
assert "is_admin" in before
|
|
|
|
|
|
class TestSeedAdminScript:
|
|
def test_creates_admin_user(self, session, monkeypatch, capsys) -> None:
|
|
import seed_admin
|
|
|
|
monkeypatch.setenv("ADMIN_USERNAME", "root")
|
|
monkeypatch.setenv("ADMIN_PASSWORD", "super-secret-1")
|
|
monkeypatch.setattr(seed_admin, "SessionLocal", lambda: session)
|
|
|
|
assert seed_admin.main() == 0
|
|
|
|
user = session.query(User).filter(User.username == "root").first()
|
|
assert user is not None
|
|
assert user.is_admin is True
|
|
assert auth.verify_password("super-secret-1", user.password_hash)
|
|
assert "Created admin user 'root'" in capsys.readouterr().out
|
|
|
|
def test_promotes_existing_user_and_resets_password(
|
|
self, session, monkeypatch, capsys
|
|
) -> None:
|
|
import seed_admin
|
|
|
|
_make_user(session, "root", is_admin=False)
|
|
monkeypatch.setenv("ADMIN_USERNAME", "root")
|
|
monkeypatch.setenv("ADMIN_PASSWORD", "new-secret-2")
|
|
monkeypatch.setattr(seed_admin, "SessionLocal", lambda: session)
|
|
|
|
assert seed_admin.main() == 0
|
|
|
|
user = session.query(User).filter(User.username == "root").first()
|
|
assert user is not None
|
|
assert user.is_admin is True
|
|
assert auth.verify_password("new-secret-2", user.password_hash)
|
|
assert "Promoted existing user 'root'" in capsys.readouterr().out
|
|
|
|
def test_missing_env_vars_exit_with_error(self, monkeypatch, capsys) -> None:
|
|
import seed_admin
|
|
|
|
monkeypatch.delenv("ADMIN_USERNAME", raising=False)
|
|
monkeypatch.delenv("ADMIN_PASSWORD", raising=False)
|
|
assert seed_admin.main() == 1
|
|
assert "ADMIN_USERNAME" in capsys.readouterr().err
|
|
|
|
|
|
class TestRateLimiting:
|
|
"""The (placeholder) limiter rejects bursts beyond the configured budget."""
|
|
|
|
def test_burst_over_budget_returns_429(self, client, session, monkeypatch) -> None:
|
|
_make_user(session, "root", is_admin=True)
|
|
headers = _headers(session, "root")
|
|
# Start from a clean budget (earlier tests may have used "root").
|
|
admin_api._limiter._hits.clear()
|
|
monkeypatch.setattr(admin_api._limiter, "limit", 3)
|
|
monkeypatch.setattr(admin_api._limiter, "window_seconds", 60.0)
|
|
try:
|
|
for _ in range(3):
|
|
assert client.get(BASE, headers=headers).status_code == 200
|
|
response = client.get(BASE, headers=headers)
|
|
assert response.status_code == 429
|
|
assert response.json()["code"] == "too_many_requests"
|
|
finally:
|
|
admin_api._limiter.limit = 1000
|
|
admin_api._limiter._hits.clear()
|
|
|
|
def test_budget_is_per_admin(self, client, session, monkeypatch) -> None:
|
|
"""One admin exhausting the budget does not block another admin."""
|
|
_make_user(session, "root", is_admin=True)
|
|
_make_user(session, "other", is_admin=True)
|
|
admin_api._limiter._hits.clear()
|
|
monkeypatch.setattr(admin_api._limiter, "limit", 1)
|
|
monkeypatch.setattr(admin_api._limiter, "window_seconds", 60.0)
|
|
try:
|
|
root = _headers(session, "root")
|
|
other = _headers(session, "other")
|
|
assert client.get(BASE, headers=root).status_code == 200
|
|
assert client.get(BASE, headers=root).status_code == 429
|
|
# "other" still has its own budget.
|
|
assert client.get(BASE, headers=other).status_code == 200
|
|
finally:
|
|
admin_api._limiter.limit = 1000
|
|
admin_api._limiter._hits.clear()
|