From 8e6ef05304cf81640c6313bbd02e360f65aa7911 Mon Sep 17 00:00:00 2001 From: dbildhauer Date: Sun, 25 Oct 2026 09:44:16 +0100 Subject: [PATCH] feat: fastapi-backend mit healthcheck und alembic-basis MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GET /api/health prüft die Datenbankverbindung - SQLite im WAL-Modus unter /data/app.db - Auslieferung des gebauten Frontends mit SPA-Fallback - leere Basis-Migration, Tests mit pytest Co-Authored-By: Claude Opus 5.5 --- backend/alembic.ini | 39 ++++++++++++++++ backend/alembic/env.py | 40 +++++++++++++++++ backend/alembic/script.py.mako | 25 +++++++++++ .../alembic/versions/20261025_0001_initial.py | 22 ++++++++++ backend/app/__init__.py | 6 +++ backend/app/api/__init__.py | 0 backend/app/api/health.py | 37 ++++++++++++++++ backend/app/config.py | 21 +++++++++ backend/app/db.py | 38 ++++++++++++++++ backend/app/main.py | 40 +++++++++++++++++ backend/app/models/__init__.py | 5 +++ backend/pyproject.toml | 44 +++++++++++++++++++ backend/tests/conftest.py | 36 +++++++++++++++ backend/tests/test_frontend.py | 38 ++++++++++++++++ backend/tests/test_health.py | 23 ++++++++++ 15 files changed, 414 insertions(+) create mode 100644 backend/alembic.ini create mode 100644 backend/alembic/env.py create mode 100644 backend/alembic/script.py.mako create mode 100644 backend/alembic/versions/20261025_0001_initial.py create mode 100644 backend/app/__init__.py create mode 100644 backend/app/api/__init__.py create mode 100644 backend/app/api/health.py create mode 100644 backend/app/config.py create mode 100644 backend/app/db.py create mode 100644 backend/app/main.py create mode 100644 backend/app/models/__init__.py create mode 100644 backend/pyproject.toml create mode 100644 backend/tests/conftest.py create mode 100644 backend/tests/test_frontend.py create mode 100644 backend/tests/test_health.py diff --git a/backend/alembic.ini b/backend/alembic.ini new file mode 100644 index 0000000..2dfd719 --- /dev/null +++ b/backend/alembic.ini @@ -0,0 +1,39 @@ +[alembic] +script_location = %(here)s/alembic +file_template = %%(year)d%%(month).2d%%(day).2d_%%(rev)s_%%(slug)s +prepend_sys_path = . +# sqlalchemy.url is taken from app settings in alembic/env.py + +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = logging.StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/backend/alembic/env.py b/backend/alembic/env.py new file mode 100644 index 0000000..d6c22cf --- /dev/null +++ b/backend/alembic/env.py @@ -0,0 +1,40 @@ +from logging.config import fileConfig + +from alembic import context + +from app.db import get_engine +from app.models import Base + +config = context.config + +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +target_metadata = Base.metadata + + +def run_migrations_offline() -> None: + context.configure( + url=str(get_engine().url), + target_metadata=target_metadata, + literal_binds=True, + render_as_batch=True, + ) + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + with get_engine().connect() as connection: + # render_as_batch: SQLite needs table rebuilds for most ALTER operations + context.configure( + connection=connection, target_metadata=target_metadata, render_as_batch=True + ) + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/backend/alembic/script.py.mako b/backend/alembic/script.py.mako new file mode 100644 index 0000000..3a15569 --- /dev/null +++ b/backend/alembic/script.py.mako @@ -0,0 +1,25 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op +${imports if imports else ""} + +revision: str = ${repr(up_revision)} +down_revision: str | None = ${repr(down_revision)} +branch_labels: str | Sequence[str] | None = ${repr(branch_labels)} +depends_on: str | Sequence[str] | None = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/backend/alembic/versions/20261025_0001_initial.py b/backend/alembic/versions/20261025_0001_initial.py new file mode 100644 index 0000000..293bf3f --- /dev/null +++ b/backend/alembic/versions/20261025_0001_initial.py @@ -0,0 +1,22 @@ +"""initial (empty baseline) + +Revision ID: 0001 +Revises: +Create Date: 2026-10-25 + +""" + +from collections.abc import Sequence + +revision: str = "0001" +down_revision: str | None = None +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + pass + + +def downgrade() -> None: + pass diff --git a/backend/app/__init__.py b/backend/app/__init__.py new file mode 100644 index 0000000..9d52a98 --- /dev/null +++ b/backend/app/__init__.py @@ -0,0 +1,6 @@ +from importlib.metadata import PackageNotFoundError, version + +try: + __version__ = version("lan-clipboard") +except PackageNotFoundError: # running from source without install + __version__ = "0.0.0" diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/api/health.py b/backend/app/api/health.py new file mode 100644 index 0000000..93afdd7 --- /dev/null +++ b/backend/app/api/health.py @@ -0,0 +1,37 @@ +import logging +from typing import Annotated, Literal + +from fastapi import APIRouter, Depends, Response, status +from pydantic import BaseModel +from sqlalchemy import text +from sqlalchemy.orm import Session + +from app import __version__ +from app.db import get_db + +logger = logging.getLogger(__name__) + +router = APIRouter() + + +class HealthResponse(BaseModel): + status: Literal["ok", "error"] + version: str + db: Literal["ok", "error"] + + +@router.get("/health", response_model=HealthResponse) +def health(response: Response, db: Annotated[Session, Depends(get_db)]) -> HealthResponse: + try: + db.execute(text("SELECT 1")) + db_status = "ok" + except Exception: + logger.exception("Database health check failed") + db_status = "error" + response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE + + return HealthResponse( + status="ok" if db_status == "ok" else "error", + version=__version__, + db=db_status, + ) diff --git a/backend/app/config.py b/backend/app/config.py new file mode 100644 index 0000000..67788f6 --- /dev/null +++ b/backend/app/config.py @@ -0,0 +1,21 @@ +from functools import lru_cache +from pathlib import Path + +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + model_config = SettingsConfigDict(env_file=".env", extra="ignore") + + data_dir: Path = Path("/data") + static_dir: Path = Path("/app/static") + log_level: str = "info" + + @property + def database_url(self) -> str: + return f"sqlite:///{self.data_dir / 'app.db'}" + + +@lru_cache +def get_settings() -> Settings: + return Settings() diff --git a/backend/app/db.py b/backend/app/db.py new file mode 100644 index 0000000..bf250ba --- /dev/null +++ b/backend/app/db.py @@ -0,0 +1,38 @@ +from collections.abc import Iterator +from functools import lru_cache + +from sqlalchemy import Engine, create_engine, event +from sqlalchemy.orm import Session, sessionmaker + +from app.config import get_settings + + +def _set_sqlite_pragmas(dbapi_connection, _connection_record) -> None: + cursor = dbapi_connection.cursor() + cursor.execute("PRAGMA journal_mode=WAL") + cursor.execute("PRAGMA foreign_keys=ON") + cursor.execute("PRAGMA busy_timeout=5000") + cursor.close() + + +def create_db_engine(url: str) -> Engine: + engine = create_engine(url, connect_args={"check_same_thread": False}) + event.listen(engine, "connect", _set_sqlite_pragmas) + return engine + + +@lru_cache +def get_engine() -> Engine: + settings = get_settings() + settings.data_dir.mkdir(parents=True, exist_ok=True) + return create_db_engine(settings.database_url) + + +@lru_cache +def _session_factory() -> sessionmaker[Session]: + return sessionmaker(bind=get_engine(), expire_on_commit=False) + + +def get_db() -> Iterator[Session]: + with _session_factory()() as session: + yield session diff --git a/backend/app/main.py b/backend/app/main.py new file mode 100644 index 0000000..9d5d1d3 --- /dev/null +++ b/backend/app/main.py @@ -0,0 +1,40 @@ +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import FileResponse + +from app import __version__ +from app.api import health +from app.config import get_settings + + +def _register_frontend(app: FastAPI, static_dir: Path) -> None: + """Serve the built Vue SPA; unknown non-API paths fall back to index.html.""" + root = static_dir.resolve() + index_file = root / "index.html" + + @app.get("/{path:path}", include_in_schema=False) + def spa(path: str) -> FileResponse: + if path == "api" or path.startswith("api/") or not index_file.is_file(): + raise HTTPException(status_code=404) + candidate = (root / path).resolve() + if path and candidate.is_relative_to(root) and candidate.is_file(): + return FileResponse(candidate) + return FileResponse(index_file, headers={"Cache-Control": "no-cache"}) + + +def create_app() -> FastAPI: + settings = get_settings() + app = FastAPI( + title="LAN-Clipboard", + version=__version__, + docs_url="/api/docs", + openapi_url="/api/openapi.json", + redoc_url=None, + ) + app.include_router(health.router, prefix="/api") + _register_frontend(app, settings.static_dir) + return app + + +app = create_app() diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py new file mode 100644 index 0000000..fa2b68a --- /dev/null +++ b/backend/app/models/__init__.py @@ -0,0 +1,5 @@ +from sqlalchemy.orm import DeclarativeBase + + +class Base(DeclarativeBase): + pass diff --git a/backend/pyproject.toml b/backend/pyproject.toml new file mode 100644 index 0000000..789f0ee --- /dev/null +++ b/backend/pyproject.toml @@ -0,0 +1,44 @@ +[project] +name = "lan-clipboard" +version = "0.1.0" +description = "Self-hosted web clipboard for the private network" +requires-python = ">=3.13" +dependencies = [ + "fastapi>=0.115", + "uvicorn[standard]>=0.32", + "sqlalchemy>=2.0.36", + "alembic>=1.14", + "pydantic>=2.10", + "pydantic-settings>=2.6", +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.3", + "httpx>=0.28", + "ruff>=0.8", +] + +[build-system] +requires = ["setuptools>=75"] +build-backend = "setuptools.build_meta" + +[tool.setuptools.packages.find] +include = ["app*"] + +[tool.ruff] +line-length = 100 +target-version = "py313" + +[tool.ruff.lint] +select = ["E", "F", "W", "I", "B", "UP", "SIM", "S", "ASYNC"] + +[tool.ruff.lint.isort] +known-first-party = ["app"] +known-third-party = ["alembic"] + +[tool.ruff.lint.per-file-ignores] +"tests/**" = ["S101"] + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py new file mode 100644 index 0000000..f6cdec5 --- /dev/null +++ b/backend/tests/conftest.py @@ -0,0 +1,36 @@ +from collections.abc import Iterator + +import pytest +from fastapi.testclient import TestClient + +from app.config import get_settings +from app.db import _session_factory, get_engine + + +def _clear_caches() -> None: + get_settings.cache_clear() + get_engine.cache_clear() + _session_factory.cache_clear() + + +@pytest.fixture +def static_dir(tmp_path): + """Directory for the built frontend; empty by default (no SPA routes).""" + path = tmp_path / "static" + path.mkdir() + return path + + +@pytest.fixture +def client(tmp_path, static_dir, monkeypatch) -> Iterator[TestClient]: + monkeypatch.setenv("DATA_DIR", str(tmp_path / "data")) + monkeypatch.setenv("STATIC_DIR", str(static_dir)) + _clear_caches() + + from app.main import create_app + + with TestClient(create_app()) as test_client: + yield test_client + + get_engine().dispose() + _clear_caches() diff --git a/backend/tests/test_frontend.py b/backend/tests/test_frontend.py new file mode 100644 index 0000000..a65f9ce --- /dev/null +++ b/backend/tests/test_frontend.py @@ -0,0 +1,38 @@ +import pytest + + +@pytest.fixture +def spa_client(tmp_path, static_dir, client): + (static_dir / "assets").mkdir() + (static_dir / "index.html").write_text("spa") + (static_dir / "assets" / "app.js").write_text("console.log('x')") + (tmp_path / "secret.txt").write_text("secret") + return client + + +def test_serves_index_at_root(spa_client): + response = spa_client.get("/") + assert response.status_code == 200 + assert "spa" in response.text + + +def test_serves_static_asset(spa_client): + response = spa_client.get("/assets/app.js") + assert response.status_code == 200 + assert "console.log" in response.text + + +def test_client_route_falls_back_to_index(spa_client): + response = spa_client.get("/clips/123") + assert response.status_code == 200 + assert "spa" in response.text + + +def test_path_traversal_is_blocked(spa_client): + response = spa_client.get("/..%2Fsecret.txt") + assert "secret" not in response.text + + +def test_api_paths_are_not_swallowed_by_spa(spa_client): + assert spa_client.get("/api/unknown").status_code == 404 + assert spa_client.get("/api/health").json()["status"] == "ok" diff --git a/backend/tests/test_health.py b/backend/tests/test_health.py new file mode 100644 index 0000000..6d7c62c --- /dev/null +++ b/backend/tests/test_health.py @@ -0,0 +1,23 @@ +from sqlalchemy import text + +from app import __version__ +from app.db import get_engine + + +def test_health_ok(client): + response = client.get("/api/health") + + assert response.status_code == 200 + assert response.json() == {"status": "ok", "version": __version__, "db": "ok"} + + +def test_sqlite_uses_wal(client): + client.get("/api/health") + + with get_engine().connect() as conn: + assert conn.execute(text("PRAGMA journal_mode")).scalar() == "wal" + assert conn.execute(text("PRAGMA foreign_keys")).scalar() == 1 + + +def test_unknown_api_path_returns_404(client): + assert client.get("/api/does-not-exist").status_code == 404