Feat: Gate API docs endpoints behind API_DOCS_ENABLED env var

When API_DOCS_ENABLED=false, FastAPI registers no routes for /docs,
/redoc, or /openapi.json, returning 404 for all three. Default is true
for backwards compatibility. Invalid values fall back to true (FR-007).

Fix: Remove tests/ and alembic/ from api/.dockerignore so the test
Dockerfile (which uses COPY . .) includes the test suite; Dockerfile.prod
is unaffected as it only copies app/ explicitly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-07 20:40:48 +00:00
parent 1b3468b72d
commit 602648ef56
13 changed files with 582 additions and 4 deletions

View File

@@ -0,0 +1,48 @@
import importlib
from starlette.testclient import TestClient
from app.config import get_settings
_BASE_ENV = {
"DATABASE_URL": "postgresql+asyncpg://u:p@localhost/db",
"JWT_SECRET_KEY": "test-secret",
"OWNER_USERNAME": "admin",
"OWNER_PASSWORD": "password",
"S3_ENDPOINT_URL": "http://localhost:9000",
"S3_BUCKET_NAME": "test-bucket",
"S3_ACCESS_KEY_ID": "key",
"S3_SECRET_ACCESS_KEY": "secret",
}
def _set_env(monkeypatch, extra=None):
for k, v in {**_BASE_ENV, **(extra or {})}.items():
monkeypatch.setenv(k, v)
def test_docs_hidden_when_flag_disabled(monkeypatch):
_set_env(monkeypatch, {"API_DOCS_ENABLED": "false"})
get_settings.cache_clear()
import app.main as m
importlib.reload(m)
client = TestClient(m.app, raise_server_exceptions=False)
assert client.get("/docs").status_code == 404
assert client.get("/redoc").status_code == 404
assert client.get("/openapi.json").status_code == 404
assert client.get("/api/v1/health").status_code == 200
get_settings.cache_clear()
def test_docs_visible_when_flag_enabled(monkeypatch):
_set_env(monkeypatch, {"API_DOCS_ENABLED": "true"})
get_settings.cache_clear()
import app.main as m
importlib.reload(m)
client = TestClient(m.app, raise_server_exceptions=False)
assert client.get("/docs").status_code == 200
assert client.get("/redoc").status_code == 200
assert client.get("/openapi.json").status_code == 200
get_settings.cache_clear()

View File

@@ -59,3 +59,39 @@ def test_settings_jwt_expiry_override(monkeypatch):
s = config_module.Settings()
assert s.jwt_expiry_seconds == 3600
def test_api_docs_enabled_default(monkeypatch):
_apply_env(monkeypatch)
import importlib
import app.config as config_module
importlib.reload(config_module)
s = config_module.Settings()
assert s.api_docs_enabled is True
def test_api_docs_enabled_false(monkeypatch):
_apply_env(monkeypatch, {"API_DOCS_ENABLED": "false"})
import importlib
import app.config as config_module
importlib.reload(config_module)
s = config_module.Settings()
assert s.api_docs_enabled is False
def test_api_docs_invalid_value_defaults_to_enabled(monkeypatch):
_apply_env(monkeypatch, {"API_DOCS_ENABLED": "not-a-bool"})
import importlib
import app.config as config_module
importlib.reload(config_module)
s = config_module.Settings()
assert s.api_docs_enabled is True