feat(api): finish Group A stubbed endpoints

Implements previously-stubbed /api/v1 endpoints (hexagonal: ports -> repos
-> services -> routers wired in deps):

- playlists: GET /{id}/cover (serves stored cover, 404 when absent)
- settings: GET/PATCH /settings + GET/PUT /settings/scrobbling — lazy
  per-user row, write-only Fernet-encrypted scrobble session key; adds
  user_settings table + migration (chains off dc126696f5a6)
- storage: GET /duplicates, /broken, /missing-metadata + admin POST
  /cleanup (arq cleanup_storage worker; reconciles local refs only,
  guarded against a storage-outage mass delete)
- admin: GET /services, /sources, /settings + POST /reindex; PATCH
  /settings and /sources/{source} return 501 (config is env-managed)

Adds NotSupportedError (-> HTTP 501). Integration tests for each surface.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Цвылев Александр Вадимович
2026-07-28 14:33:12 +03:00
parent df580578f6
commit a263272935
27 changed files with 1362 additions and 27 deletions
+142
View File
@@ -0,0 +1,142 @@
"""Integration tests for the admin instance-management endpoints.
Covers ``/admin/services`` (dependency health), ``/admin/sources``,
``/admin/reindex`` (enqueue), and ``/admin/settings`` (effective config) plus
their admin gating. Requires a reachable Postgres; skips otherwise.
"""
import asyncio
import os
from collections.abc import AsyncIterator
from pathlib import Path
import pytest
from app.core.config import get_settings
from app.infrastructure.db import Base, dispose_engine, get_engine, session_scope
from app.infrastructure.db.repositories import (
SqlAlchemyRefreshTokenRepository,
SqlAlchemyUserRepository,
)
from asgi_lifespan import LifespanManager
from httpx import ASGITransport, AsyncClient
pytestmark = pytest.mark.asyncio
_db_reachable_cache: bool | None = None
async def _db_reachable() -> bool:
global _db_reachable_cache
if _db_reachable_cache is not None:
return _db_reachable_cache
from sqlalchemy import text
try:
async with asyncio.timeout(3):
async with get_engine().connect() as conn:
await conn.execute(text("SELECT 1"))
_db_reachable_cache = True
except Exception:
_db_reachable_cache = False
return _db_reachable_cache
@pytest.fixture
async def api(tmp_path: Path) -> AsyncIterator[AsyncClient]:
if not await _db_reachable():
pytest.skip("Postgres not reachable — integration test skipped.")
os.environ["MEDIA_PATH"] = str(tmp_path)
get_settings.cache_clear()
try:
async with get_engine().begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
from app.application.user_service import UserService
from app.core.security import Argon2PasswordHasher
async with session_scope() as session:
svc = UserService(
users=SqlAlchemyUserRepository(session),
refresh_tokens=SqlAlchemyRefreshTokenRepository(session),
hasher=Argon2PasswordHasher(),
)
await svc.create_user(username="user", password="testpass1", is_superuser=False)
await svc.create_user(username="admin", password="testpass1", is_superuser=True)
from app.main import create_app
app = create_app()
async with LifespanManager(app):
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
yield client
async with get_engine().begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await dispose_engine()
finally:
os.environ.pop("MEDIA_PATH", None)
get_settings.cache_clear()
async def _auth(api: AsyncClient, username: str) -> dict[str, str]:
resp = await api.post(
"/api/v1/auth/login", json={"username": username, "password": "testpass1"}
)
assert resp.status_code == 200, resp.text
return {"Authorization": f"Bearer {resp.json()['access_token']}"}
async def test_services_reports_dependency_health(api: AsyncClient) -> None:
headers = await _auth(api, "admin")
resp = await api.get("/api/v1/admin/services", headers=headers)
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["database"] == "ok"
assert body["redis"] in ("ok", "down") # redis is up in CI/dev, but don't hard-require it
assert body["ml"] == "skipped" # no ML_SERVICE_URL configured
async def test_services_requires_admin(api: AsyncClient) -> None:
headers = await _auth(api, "user")
resp = await api.get("/api/v1/admin/services", headers=headers)
assert resp.status_code == 403
async def test_sources_list_is_admin_only(api: AsyncClient) -> None:
user = await _auth(api, "user")
assert (await api.get("/api/v1/admin/sources", headers=user)).status_code == 403
admin = await _auth(api, "admin")
resp = await api.get("/api/v1/admin/sources", headers=admin)
assert resp.status_code == 200, resp.text
assert isinstance(resp.json(), list)
async def test_reindex_without_indexable_source_is_503(api: AsyncClient) -> None:
# No LOCAL_MEDIA_IMPORT_PATH configured → nothing to index.
headers = await _auth(api, "admin")
resp = await api.post("/api/v1/admin/reindex", headers=headers)
assert resp.status_code == 503, resp.text
async def test_settings_exposes_effective_config_without_secrets(api: AsyncClient) -> None:
headers = await _auth(api, "admin")
resp = await api.get("/api/v1/admin/settings", headers=headers)
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["environment"] == "test"
assert body["storage_backend"] == "local"
assert body["allow_registration"] is True
# No secret material should ever appear in the payload.
assert "jwt_secret" not in body
assert "subsonic_secret_key" not in body
async def test_settings_requires_admin(api: AsyncClient) -> None:
headers = await _auth(api, "user")
resp = await api.get("/api/v1/admin/settings", headers=headers)
assert resp.status_code == 403