diff --git a/aurweb/asgi.py b/aurweb/asgi.py index b172626f..b6578f33 100644 --- a/aurweb/asgi.py +++ b/aurweb/asgi.py @@ -38,6 +38,8 @@ logger = aur_logging.get_logger(__name__) # Setup the FastAPI app. app = FastAPI() +session_secret = aurweb.config.get("fastapi", "session_secret") + # Instrument routes with the prometheus-fastapi-instrumentator # library with custom collectors and expose /metrics. instrumentator().add(prometheus.http_api_requests_total()) @@ -68,7 +70,6 @@ async def app_startup(): f"Supported backends: {str(aurweb.db.DRIVERS.keys())}" ) - session_secret = aurweb.config.get("fastapi", "session_secret") if not session_secret: raise Exception("[fastapi] session_secret must not be empty") @@ -84,10 +85,6 @@ async def app_startup(): "/static/images", StaticFiles(directory="web/html/images"), name="static_images" ) - # Add application middlewares. - app.add_middleware(AuthenticationMiddleware, backend=BasicAuthBackend()) - app.add_middleware(SessionMiddleware, secret_key=session_secret) - # Add application routes. def add_router(module): app.include_router(module.router) @@ -320,3 +317,8 @@ async def id_redirect_middleware(request: Request, call_next: typing.Callable): return RedirectResponse(f"{path}/{id}{qs}") return await util.error_or_result(call_next, request) + + +# Add application middlewares. +app.add_middleware(AuthenticationMiddleware, backend=BasicAuthBackend()) +app.add_middleware(SessionMiddleware, secret_key=session_secret) diff --git a/test/test_asgi.py b/test/test_asgi.py index 3b794c76..840e6608 100644 --- a/test/test_asgi.py +++ b/test/test_asgi.py @@ -68,12 +68,19 @@ async def test_asgi_startup_session_secret_exception(monkeypatch): @pytest.mark.asyncio -async def test_asgi_startup_exception(monkeypatch): - with mock.patch.dict(os.environ, {"AUR_CONFIG": "conf/config.defaults"}): - aurweb.config.rehash() - with pytest.raises(Exception): - await aurweb.asgi.app_startup() - aurweb.config.rehash() +async def test_asgi_startup_exception(): + # save proper session secret + prev_secret = aurweb.asgi.session_secret + + # remove secret + aurweb.asgi.session_secret = None + + # startup should fail + with pytest.raises(Exception): + await aurweb.asgi.app_startup() + + # restore previous session secret after test + aurweb.asgi.session_secret = prev_secret @pytest.mark.asyncio