Enforce repository boundary: Remove DbDep from routers

This commit enforces the repository boundary by eliminating direct database connection
dependencies (DbDep) from all routers. Routers now depend on service context dependencies
that combine the database connection with the related repositories.

Changes:
- Add 5 service context dependencies in dependencies.py:
  * SessionServiceContext: db + session_repo
  * BlocklistServiceContext: db + blocklist_repo + import_log_repo + settings_repo
  * SettingsServiceContext: db + settings_repo
  * BanServiceContext: db + fail2ban_db_repo
  * HistoryServiceContext: db + fail2ban_db_repo + history_archive_repo

- Refactor all 9 routers (auth, bans, blocklist, config_misc, dashboard, geo,
  history, jails, setup) to use service contexts instead of DbDep.

- Update Backend-Development.md with clear examples of the new pattern and
  documentation of available service contexts.

Rationale:
- Enforces the repository boundary through the dependency system
- Makes database operations explicit and auditable
- Improves testability by allowing service contexts to be mocked
- Prevents accidental direct database access from routers

The deprecated DbDep remains available for backward compatibility with
services that have not yet been refactored, but routers can no longer import it.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-04-28 07:35:23 +02:00
parent 813cf09bed
commit 507f153ab9
11 changed files with 318 additions and 105 deletions

View File

@@ -14,7 +14,7 @@ from fastapi import APIRouter, Request, status
from app.dependencies import (
AuthDep,
DbDep,
BanServiceContextDep,
Fail2BanSocketDep,
GeoCacheDep,
HttpSessionDep,
@@ -34,7 +34,7 @@ router: APIRouter = APIRouter(prefix="/api/bans", tags=["Bans"])
async def get_active_bans(
request: Request,
_auth: AuthDep,
db: DbDep,
ban_ctx: BanServiceContextDep,
socket_path: Fail2BanSocketDep,
http_session: HttpSessionDep,
geo_cache: GeoCacheDep,
@@ -47,6 +47,10 @@ async def get_active_bans(
Args:
request: Incoming request (used to access ``app.state``).
_auth: Validated session — enforces authentication.
ban_ctx: Ban service context containing db and repository.
socket_path: Path to fail2ban Unix domain socket.
http_session: Shared HTTP session for geolocation.
geo_cache: Geolocation cache instance.
Returns:
:class:`~app.models.ban.ActiveBanListResponse` with all active bans.
@@ -58,7 +62,7 @@ async def get_active_bans(
socket_path,
geo_cache=geo_cache,
http_session=http_session,
app_db=db,
app_db=ban_ctx.db,
)