Fix setup_service to mark setup_complete only after successful runtime DB init

This commit is contained in:
2026-04-12 20:30:22 +02:00
parent e6df045e5e
commit 8e43ef9ad2
4 changed files with 758 additions and 26 deletions

View File

@@ -7,19 +7,27 @@ enforcing the rule that setup can only run once.
from __future__ import annotations
import asyncio
from app.utils.async_utils import run_blocking
from pathlib import Path
from typing import TYPE_CHECKING
import bcrypt
import structlog
if TYPE_CHECKING:
import aiosqlite
from app.db import init_db, open_db
from app.repositories import settings_repo
from app.utils.async_utils import run_blocking
from app.utils.setup_utils import (
get_map_color_thresholds as util_get_map_color_thresholds,
)
from app.utils.setup_utils import (
get_password_hash as util_get_password_hash,
)
from app.utils.setup_utils import (
set_map_color_thresholds as util_set_map_color_thresholds,
)
if TYPE_CHECKING:
import aiosqlite
log: structlog.stdlib.BoundLogger = structlog.get_logger()
@@ -89,22 +97,28 @@ async def run_setup(
await settings_repo.set_setting(db, _KEY_DATABASE_PATH, database_path)
runtime_initialized = await _ensure_database_initialized(database_path)
if not runtime_initialized:
log.error(
"bangui_setup_failed",
reason="runtime_database_initialization_failed",
database_path=database_path,
)
raise RuntimeError("Runtime database could not be initialized.")
runtime_db: aiosqlite.Connection | None = None
try:
if runtime_initialized:
runtime_db = await open_db(database_path)
await settings_repo.set_setting(runtime_db, _KEY_PASSWORD_HASH, hashed)
await settings_repo.set_setting(runtime_db, _KEY_DATABASE_PATH, database_path)
await settings_repo.set_setting(runtime_db, _KEY_FAIL2BAN_SOCKET, fail2ban_socket)
await settings_repo.set_setting(runtime_db, _KEY_TIMEZONE, timezone)
await settings_repo.set_setting(
runtime_db, _KEY_SESSION_DURATION, str(session_duration_minutes)
)
await settings_repo.set_setting(runtime_db, _KEY_MAP_COLOR_THRESHOLD_HIGH, "100")
await settings_repo.set_setting(runtime_db, _KEY_MAP_COLOR_THRESHOLD_MEDIUM, "50")
await settings_repo.set_setting(runtime_db, _KEY_MAP_COLOR_THRESHOLD_LOW, "20")
await settings_repo.set_setting(runtime_db, _KEY_SETUP_DONE, "1")
runtime_db = await open_db(database_path)
await settings_repo.set_setting(runtime_db, _KEY_PASSWORD_HASH, hashed)
await settings_repo.set_setting(runtime_db, _KEY_DATABASE_PATH, database_path)
await settings_repo.set_setting(runtime_db, _KEY_FAIL2BAN_SOCKET, fail2ban_socket)
await settings_repo.set_setting(runtime_db, _KEY_TIMEZONE, timezone)
await settings_repo.set_setting(
runtime_db, _KEY_SESSION_DURATION, str(session_duration_minutes)
)
await settings_repo.set_setting(runtime_db, _KEY_MAP_COLOR_THRESHOLD_HIGH, "100")
await settings_repo.set_setting(runtime_db, _KEY_MAP_COLOR_THRESHOLD_MEDIUM, "50")
await settings_repo.set_setting(runtime_db, _KEY_MAP_COLOR_THRESHOLD_LOW, "20")
await settings_repo.set_setting(runtime_db, _KEY_SETUP_DONE, "1")
finally:
if runtime_db is not None:
await runtime_db.close()
@@ -115,13 +129,6 @@ async def run_setup(
log.info("bangui_setup_completed")
from app.utils.setup_utils import (
get_map_color_thresholds as util_get_map_color_thresholds,
get_password_hash as util_get_password_hash,
set_map_color_thresholds as util_set_map_color_thresholds,
)
async def get_password_hash(db: aiosqlite.Connection) -> str | None:
"""Return the stored bcrypt password hash, or ``None`` if not set."""
return await util_get_password_hash(db)

View File

@@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
import inspect
from pathlib import Path
from unittest.mock import AsyncMock
import aiosqlite
import pytest
@@ -133,6 +134,31 @@ class TestRunSetup:
with pytest.raises(RuntimeError, match="already been completed"):
await setup_service.run_setup(db, **kwargs) # type: ignore[arg-type]
async def test_does_not_mark_setup_complete_on_runtime_db_failure(
self, db: aiosqlite.Connection, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""run_setup() must not mark setup complete when runtime DB init fails."""
monkeypatch.setattr(
setup_service,
"_ensure_database_initialized",
AsyncMock(return_value=False),
)
with pytest.raises(RuntimeError, match="Runtime database could not be initialized"):
await setup_service.run_setup(
db,
master_password="mypassword1",
database_path=str(tmp_path / "runtime.db"),
fail2ban_socket="/var/run/fail2ban/fail2ban.sock",
timezone="UTC",
session_duration_minutes=60,
)
assert await setup_service.is_setup_complete(db) is False
bootstrap_settings = await settings_repo.get_all_settings(db)
assert "setup_completed" not in bootstrap_settings
assert not (tmp_path / "runtime.db").exists()
async def test_initializes_map_color_thresholds_with_defaults(
self, db: aiosqlite.Connection, tmp_path: Path
) -> None: