83b1aeb97c
Adds a shared-token auth dependency for the viewing API (Task 2.9). Trust model: when API_TOKEN is empty (the default) auth is disabled — we trust the network boundary (local/intranet tool). When set, every request must present the token via `Authorization: Bearer <token>` or `?token=<token>`, else 401. `/api/health` is exempt so liveness probes work without the token. - app/config.py: add `api_token: str = ""` to Settings. - app/api/auth.py: `require_auth` dependency (secrets.compare_digest, reads get_settings() per-request so token rotation via cache_clear() works). - app/api/main.py: apply the dependency globally; document the trust model. - .env.example: document API_TOKEN. - tests/test_api_auth.py: 8 tests covering disabled/correct/missing/wrong/ malformed-header/query-param/health-exempt paths. Co-Authored-By: Claude <noreply@anthropic.com>
48 lines
1.5 KiB
Python
48 lines
1.5 KiB
Python
"""FastAPI app for the yunke data-mirror viewing API.
|
|
|
|
Run locally with::
|
|
|
|
uvicorn app.api.main:app --reload
|
|
|
|
Includes:
|
|
* ``GET /api/health`` -> ``{"status": "ok"}`` liveness probe.
|
|
* ``GET /api/customers`` (see :mod:`app.api.routers.customer`).
|
|
* ``GET /api/media/{media_hash}`` (see :mod:`app.api.routers.media`).
|
|
|
|
CORS is configured permissively (wildcard origin, no credentials) so the local
|
|
frontend can call the API during development.
|
|
|
|
Auth (Task 2.9): a single shared-token dependency (:func:`app.api.auth.require_auth`)
|
|
is applied globally on the app. Trust model: when ``Settings.api_token`` is
|
|
empty (the default) auth is disabled — we trust the network boundary (this is a
|
|
local/intranet tool). When a token is configured, every request must present it
|
|
via ``Authorization: Bearer <token>`` or ``?token=``. ``/api/health`` is exempt
|
|
so liveness probes work without the token. See :mod:`app.api.auth`.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from fastapi import Depends, FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
from app.api.auth import require_auth
|
|
from app.api.routers import customer, media
|
|
|
|
app = FastAPI(title="yunke data mirror", dependencies=[Depends(require_auth)])
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
app.include_router(customer.router)
|
|
app.include_router(media.router)
|
|
|
|
|
|
@app.get("/api/health")
|
|
async def health() -> dict[str, str]:
|
|
"""Trivial liveness probe."""
|
|
return {"status": "ok"}
|