"""Token międzywarstwowy (LOG-32). Warstwa logiczna oddaje treść baz, więc musi odrzucać żądania z pominięciem UI. """ import pytest from fastapi import FastAPI from starlette.testclient import TestClient from app import security TOKEN = "tajny-token-testowy" def _app() -> FastAPI: app = FastAPI() security.install(app, "testowa") @app.get("/health") def health(): return {"status": "ok"} @app.get("/secret") def secret(): return {"rows": ["treść z bazy"]} return app @pytest.fixture def guarded(monkeypatch): monkeypatch.setenv("INTERNAL_TOKEN", TOKEN) return TestClient(_app()) @pytest.fixture def open_app(monkeypatch): monkeypatch.delenv("INTERNAL_TOKEN", raising=False) return TestClient(_app()) def test_rejects_request_without_token(guarded): assert guarded.get("/secret").status_code == 401 def test_rejects_wrong_token(guarded): r = guarded.get("/secret", headers={security.HEADER: "zly"}) assert r.status_code == 401 assert "treść z bazy" not in r.text def test_accepts_correct_token(guarded): r = guarded.get("/secret", headers={security.HEADER: TOKEN}) assert r.status_code == 200 assert r.json()["rows"] == ["treść z bazy"] def test_health_stays_public(guarded): """Sonda k8s nie zna tokenu — /health musi działać bez niego.""" assert guarded.get("/health").status_code == 200 def test_disabled_when_token_unset(open_app): """Brak konfiguracji = zgodność wstecz (dev), nie blokada.""" assert not security.enabled() assert open_app.get("/secret").status_code == 200