- Task 1: Mark imported blocklist IP addresses
- Add BanOrigin type and _derive_origin() to ban.py model
- Populate origin field in ban_service list_bans() and bans_by_country()
- BanTable and MapPage companion table show origin badge column
- Tests: origin derivation in test_ban_service.py and test_dashboard.py
- Task 2: Add origin filter to dashboard and world map
- ban_service: _origin_sql_filter() helper; origin param on list_bans()
and bans_by_country()
- dashboard router: optional origin query param forwarded to service
- Frontend: BanOriginFilter type + BAN_ORIGIN_FILTER_LABELS in ban.ts
- fetchBans / fetchBansByCountry forward origin to API
- useBans / useMapData accept and pass origin; page resets on change
- BanTable accepts origin prop; DashboardPage adds segmented filter
- MapPage adds origin Select next to time-range picker
- Tests: origin filter assertions in test_ban_service and test_dashboard
537 lines
19 KiB
Python
537 lines
19 KiB
Python
"""Tests for the config router endpoints."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import aiosqlite
|
|
import pytest
|
|
from httpx import ASGITransport, AsyncClient
|
|
|
|
from app.config import Settings
|
|
from app.db import init_db
|
|
from app.main import create_app
|
|
from app.models.config import (
|
|
GlobalConfigResponse,
|
|
JailConfig,
|
|
JailConfigListResponse,
|
|
JailConfigResponse,
|
|
RegexTestResponse,
|
|
)
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Fixtures
|
|
# ---------------------------------------------------------------------------
|
|
|
|
_SETUP_PAYLOAD = {
|
|
"master_password": "testpassword1",
|
|
"database_path": "bangui.db",
|
|
"fail2ban_socket": "/var/run/fail2ban/fail2ban.sock",
|
|
"timezone": "UTC",
|
|
"session_duration_minutes": 60,
|
|
}
|
|
|
|
|
|
@pytest.fixture
|
|
async def config_client(tmp_path: Path) -> AsyncClient: # type: ignore[misc]
|
|
"""Provide an authenticated ``AsyncClient`` for config endpoint tests."""
|
|
settings = Settings(
|
|
database_path=str(tmp_path / "config_test.db"),
|
|
fail2ban_socket="/tmp/fake.sock",
|
|
session_secret="test-config-secret",
|
|
session_duration_minutes=60,
|
|
timezone="UTC",
|
|
log_level="debug",
|
|
)
|
|
app = create_app(settings=settings)
|
|
|
|
db: aiosqlite.Connection = await aiosqlite.connect(settings.database_path)
|
|
db.row_factory = aiosqlite.Row
|
|
await init_db(db)
|
|
app.state.db = db
|
|
app.state.http_session = MagicMock()
|
|
|
|
transport = ASGITransport(app=app)
|
|
async with AsyncClient(transport=transport, base_url="http://test") as ac:
|
|
await ac.post("/api/setup", json=_SETUP_PAYLOAD)
|
|
login = await ac.post(
|
|
"/api/auth/login",
|
|
json={"password": _SETUP_PAYLOAD["master_password"]},
|
|
)
|
|
assert login.status_code == 200
|
|
yield ac
|
|
|
|
await db.close()
|
|
|
|
|
|
def _make_jail_config(name: str = "sshd") -> JailConfig:
|
|
return JailConfig(
|
|
name=name,
|
|
ban_time=600,
|
|
max_retry=5,
|
|
find_time=600,
|
|
fail_regex=["regex1"],
|
|
ignore_regex=[],
|
|
log_paths=["/var/log/auth.log"],
|
|
date_pattern=None,
|
|
log_encoding="UTF-8",
|
|
backend="polling",
|
|
actions=["iptables"],
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# GET /api/config/jails
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestGetJailConfigs:
|
|
"""Tests for ``GET /api/config/jails``."""
|
|
|
|
async def test_200_returns_jail_list(self, config_client: AsyncClient) -> None:
|
|
"""GET /api/config/jails returns 200 with JailConfigListResponse."""
|
|
mock_response = JailConfigListResponse(
|
|
jails=[_make_jail_config("sshd")], total=1
|
|
)
|
|
with patch(
|
|
"app.routers.config.config_service.list_jail_configs",
|
|
AsyncMock(return_value=mock_response),
|
|
):
|
|
resp = await config_client.get("/api/config/jails")
|
|
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["total"] == 1
|
|
assert data["jails"][0]["name"] == "sshd"
|
|
|
|
async def test_401_when_unauthenticated(self, config_client: AsyncClient) -> None:
|
|
"""GET /api/config/jails returns 401 without a valid session."""
|
|
resp = await AsyncClient(
|
|
transport=ASGITransport(app=config_client._transport.app), # type: ignore[attr-defined]
|
|
base_url="http://test",
|
|
).get("/api/config/jails")
|
|
assert resp.status_code == 401
|
|
|
|
async def test_502_on_connection_error(self, config_client: AsyncClient) -> None:
|
|
"""GET /api/config/jails returns 502 when fail2ban is unreachable."""
|
|
from app.utils.fail2ban_client import Fail2BanConnectionError
|
|
|
|
with patch(
|
|
"app.routers.config.config_service.list_jail_configs",
|
|
AsyncMock(side_effect=Fail2BanConnectionError("down", "/tmp/fake.sock")),
|
|
):
|
|
resp = await config_client.get("/api/config/jails")
|
|
|
|
assert resp.status_code == 502
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# GET /api/config/jails/{name}
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestGetJailConfig:
|
|
"""Tests for ``GET /api/config/jails/{name}``."""
|
|
|
|
async def test_200_returns_jail_config(self, config_client: AsyncClient) -> None:
|
|
"""GET /api/config/jails/sshd returns 200 with JailConfigResponse."""
|
|
mock_response = JailConfigResponse(jail=_make_jail_config("sshd"))
|
|
with patch(
|
|
"app.routers.config.config_service.get_jail_config",
|
|
AsyncMock(return_value=mock_response),
|
|
):
|
|
resp = await config_client.get("/api/config/jails/sshd")
|
|
|
|
assert resp.status_code == 200
|
|
assert resp.json()["jail"]["name"] == "sshd"
|
|
assert resp.json()["jail"]["ban_time"] == 600
|
|
|
|
async def test_404_for_unknown_jail(self, config_client: AsyncClient) -> None:
|
|
"""GET /api/config/jails/missing returns 404."""
|
|
from app.services.config_service import JailNotFoundError
|
|
|
|
with patch(
|
|
"app.routers.config.config_service.get_jail_config",
|
|
AsyncMock(side_effect=JailNotFoundError("missing")),
|
|
):
|
|
resp = await config_client.get("/api/config/jails/missing")
|
|
|
|
assert resp.status_code == 404
|
|
|
|
async def test_401_when_unauthenticated(self, config_client: AsyncClient) -> None:
|
|
"""GET /api/config/jails/sshd returns 401 without session."""
|
|
resp = await AsyncClient(
|
|
transport=ASGITransport(app=config_client._transport.app), # type: ignore[attr-defined]
|
|
base_url="http://test",
|
|
).get("/api/config/jails/sshd")
|
|
assert resp.status_code == 401
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# PUT /api/config/jails/{name}
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestUpdateJailConfig:
|
|
"""Tests for ``PUT /api/config/jails/{name}``."""
|
|
|
|
async def test_204_on_success(self, config_client: AsyncClient) -> None:
|
|
"""PUT /api/config/jails/sshd returns 204 on success."""
|
|
with patch(
|
|
"app.routers.config.config_service.update_jail_config",
|
|
AsyncMock(return_value=None),
|
|
):
|
|
resp = await config_client.put(
|
|
"/api/config/jails/sshd",
|
|
json={"ban_time": 3600},
|
|
)
|
|
|
|
assert resp.status_code == 204
|
|
|
|
async def test_404_for_unknown_jail(self, config_client: AsyncClient) -> None:
|
|
"""PUT /api/config/jails/missing returns 404."""
|
|
from app.services.config_service import JailNotFoundError
|
|
|
|
with patch(
|
|
"app.routers.config.config_service.update_jail_config",
|
|
AsyncMock(side_effect=JailNotFoundError("missing")),
|
|
):
|
|
resp = await config_client.put(
|
|
"/api/config/jails/missing",
|
|
json={"ban_time": 3600},
|
|
)
|
|
|
|
assert resp.status_code == 404
|
|
|
|
async def test_422_on_invalid_regex(self, config_client: AsyncClient) -> None:
|
|
"""PUT /api/config/jails/sshd returns 422 for invalid regex pattern."""
|
|
from app.services.config_service import ConfigValidationError
|
|
|
|
with patch(
|
|
"app.routers.config.config_service.update_jail_config",
|
|
AsyncMock(side_effect=ConfigValidationError("bad regex")),
|
|
):
|
|
resp = await config_client.put(
|
|
"/api/config/jails/sshd",
|
|
json={"fail_regex": ["[bad"]},
|
|
)
|
|
|
|
assert resp.status_code == 422
|
|
|
|
async def test_400_on_config_operation_error(self, config_client: AsyncClient) -> None:
|
|
"""PUT /api/config/jails/sshd returns 400 when set command fails."""
|
|
from app.services.config_service import ConfigOperationError
|
|
|
|
with patch(
|
|
"app.routers.config.config_service.update_jail_config",
|
|
AsyncMock(side_effect=ConfigOperationError("set failed")),
|
|
):
|
|
resp = await config_client.put(
|
|
"/api/config/jails/sshd",
|
|
json={"ban_time": 3600},
|
|
)
|
|
|
|
assert resp.status_code == 400
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# GET /api/config/global
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestGetGlobalConfig:
|
|
"""Tests for ``GET /api/config/global``."""
|
|
|
|
async def test_200_returns_global_config(self, config_client: AsyncClient) -> None:
|
|
"""GET /api/config/global returns 200 with GlobalConfigResponse."""
|
|
mock_response = GlobalConfigResponse(
|
|
log_level="WARNING",
|
|
log_target="/var/log/fail2ban.log",
|
|
db_purge_age=86400,
|
|
db_max_matches=10,
|
|
)
|
|
with patch(
|
|
"app.routers.config.config_service.get_global_config",
|
|
AsyncMock(return_value=mock_response),
|
|
):
|
|
resp = await config_client.get("/api/config/global")
|
|
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["log_level"] == "WARNING"
|
|
assert data["db_purge_age"] == 86400
|
|
|
|
async def test_401_when_unauthenticated(self, config_client: AsyncClient) -> None:
|
|
"""GET /api/config/global returns 401 without session."""
|
|
resp = await AsyncClient(
|
|
transport=ASGITransport(app=config_client._transport.app), # type: ignore[attr-defined]
|
|
base_url="http://test",
|
|
).get("/api/config/global")
|
|
assert resp.status_code == 401
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# PUT /api/config/global
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestUpdateGlobalConfig:
|
|
"""Tests for ``PUT /api/config/global``."""
|
|
|
|
async def test_204_on_success(self, config_client: AsyncClient) -> None:
|
|
"""PUT /api/config/global returns 204 on success."""
|
|
with patch(
|
|
"app.routers.config.config_service.update_global_config",
|
|
AsyncMock(return_value=None),
|
|
):
|
|
resp = await config_client.put(
|
|
"/api/config/global",
|
|
json={"log_level": "DEBUG"},
|
|
)
|
|
|
|
assert resp.status_code == 204
|
|
|
|
async def test_400_on_operation_error(self, config_client: AsyncClient) -> None:
|
|
"""PUT /api/config/global returns 400 when set command fails."""
|
|
from app.services.config_service import ConfigOperationError
|
|
|
|
with patch(
|
|
"app.routers.config.config_service.update_global_config",
|
|
AsyncMock(side_effect=ConfigOperationError("set failed")),
|
|
):
|
|
resp = await config_client.put(
|
|
"/api/config/global",
|
|
json={"log_level": "INFO"},
|
|
)
|
|
|
|
assert resp.status_code == 400
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# POST /api/config/reload
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestReloadFail2ban:
|
|
"""Tests for ``POST /api/config/reload``."""
|
|
|
|
async def test_204_on_success(self, config_client: AsyncClient) -> None:
|
|
"""POST /api/config/reload returns 204 on success."""
|
|
with patch(
|
|
"app.routers.config.jail_service.reload_all",
|
|
AsyncMock(return_value=None),
|
|
):
|
|
resp = await config_client.post("/api/config/reload")
|
|
|
|
assert resp.status_code == 204
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# POST /api/config/regex-test
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestRegexTest:
|
|
"""Tests for ``POST /api/config/regex-test``."""
|
|
|
|
async def test_200_matched(self, config_client: AsyncClient) -> None:
|
|
"""POST /api/config/regex-test returns matched=true for a valid match."""
|
|
mock_response = RegexTestResponse(matched=True, groups=["1.2.3.4"], error=None)
|
|
with patch(
|
|
"app.routers.config.config_service.test_regex",
|
|
return_value=mock_response,
|
|
):
|
|
resp = await config_client.post(
|
|
"/api/config/regex-test",
|
|
json={
|
|
"log_line": "fail from 1.2.3.4",
|
|
"fail_regex": r"(\d+\.\d+\.\d+\.\d+)",
|
|
},
|
|
)
|
|
|
|
assert resp.status_code == 200
|
|
assert resp.json()["matched"] is True
|
|
|
|
async def test_200_not_matched(self, config_client: AsyncClient) -> None:
|
|
"""POST /api/config/regex-test returns matched=false for no match."""
|
|
mock_response = RegexTestResponse(matched=False, groups=[], error=None)
|
|
with patch(
|
|
"app.routers.config.config_service.test_regex",
|
|
return_value=mock_response,
|
|
):
|
|
resp = await config_client.post(
|
|
"/api/config/regex-test",
|
|
json={"log_line": "ok line", "fail_regex": r"FAIL"},
|
|
)
|
|
|
|
assert resp.status_code == 200
|
|
assert resp.json()["matched"] is False
|
|
|
|
async def test_401_when_unauthenticated(self, config_client: AsyncClient) -> None:
|
|
"""POST /api/config/regex-test returns 401 without session."""
|
|
resp = await AsyncClient(
|
|
transport=ASGITransport(app=config_client._transport.app), # type: ignore[attr-defined]
|
|
base_url="http://test",
|
|
).post(
|
|
"/api/config/regex-test",
|
|
json={"log_line": "test", "fail_regex": "test"},
|
|
)
|
|
assert resp.status_code == 401
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# POST /api/config/jails/{name}/logpath
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestAddLogPath:
|
|
"""Tests for ``POST /api/config/jails/{name}/logpath``."""
|
|
|
|
async def test_204_on_success(self, config_client: AsyncClient) -> None:
|
|
"""POST /api/config/jails/sshd/logpath returns 204 on success."""
|
|
with patch(
|
|
"app.routers.config.config_service.add_log_path",
|
|
AsyncMock(return_value=None),
|
|
):
|
|
resp = await config_client.post(
|
|
"/api/config/jails/sshd/logpath",
|
|
json={"log_path": "/var/log/specific.log", "tail": True},
|
|
)
|
|
|
|
assert resp.status_code == 204
|
|
|
|
async def test_404_for_unknown_jail(self, config_client: AsyncClient) -> None:
|
|
"""POST /api/config/jails/missing/logpath returns 404."""
|
|
from app.services.config_service import JailNotFoundError
|
|
|
|
with patch(
|
|
"app.routers.config.config_service.add_log_path",
|
|
AsyncMock(side_effect=JailNotFoundError("missing")),
|
|
):
|
|
resp = await config_client.post(
|
|
"/api/config/jails/missing/logpath",
|
|
json={"log_path": "/var/log/test.log"},
|
|
)
|
|
|
|
assert resp.status_code == 404
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# POST /api/config/preview-log
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestPreviewLog:
|
|
"""Tests for ``POST /api/config/preview-log``."""
|
|
|
|
async def test_200_returns_preview(self, config_client: AsyncClient) -> None:
|
|
"""POST /api/config/preview-log returns 200 with LogPreviewResponse."""
|
|
from app.models.config import LogPreviewLine, LogPreviewResponse
|
|
|
|
mock_response = LogPreviewResponse(
|
|
lines=[LogPreviewLine(line="fail line", matched=True, groups=[])],
|
|
total_lines=1,
|
|
matched_count=1,
|
|
)
|
|
with patch(
|
|
"app.routers.config.config_service.preview_log",
|
|
AsyncMock(return_value=mock_response),
|
|
):
|
|
resp = await config_client.post(
|
|
"/api/config/preview-log",
|
|
json={"log_path": "/var/log/test.log", "fail_regex": "fail"},
|
|
)
|
|
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["total_lines"] == 1
|
|
assert data["matched_count"] == 1
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# GET /api/config/map-color-thresholds
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestGetMapColorThresholds:
|
|
"""Tests for ``GET /api/config/map-color-thresholds``."""
|
|
|
|
async def test_200_returns_thresholds(self, config_client: AsyncClient) -> None:
|
|
"""GET /api/config/map-color-thresholds returns 200 with current values."""
|
|
resp = await config_client.get("/api/config/map-color-thresholds")
|
|
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert "threshold_high" in data
|
|
assert "threshold_medium" in data
|
|
assert "threshold_low" in data
|
|
# Should return defaults after setup
|
|
assert data["threshold_high"] == 100
|
|
assert data["threshold_medium"] == 50
|
|
assert data["threshold_low"] == 20
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# PUT /api/config/map-color-thresholds
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestUpdateMapColorThresholds:
|
|
"""Tests for ``PUT /api/config/map-color-thresholds``."""
|
|
|
|
async def test_200_updates_thresholds(self, config_client: AsyncClient) -> None:
|
|
"""PUT /api/config/map-color-thresholds returns 200 and updates settings."""
|
|
update_payload = {
|
|
"threshold_high": 200,
|
|
"threshold_medium": 80,
|
|
"threshold_low": 30,
|
|
}
|
|
resp = await config_client.put(
|
|
"/api/config/map-color-thresholds", json=update_payload
|
|
)
|
|
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["threshold_high"] == 200
|
|
assert data["threshold_medium"] == 80
|
|
assert data["threshold_low"] == 30
|
|
|
|
# Verify the values persist
|
|
get_resp = await config_client.get("/api/config/map-color-thresholds")
|
|
assert get_resp.status_code == 200
|
|
get_data = get_resp.json()
|
|
assert get_data["threshold_high"] == 200
|
|
assert get_data["threshold_medium"] == 80
|
|
assert get_data["threshold_low"] == 30
|
|
|
|
async def test_400_for_invalid_order(self, config_client: AsyncClient) -> None:
|
|
"""PUT /api/config/map-color-thresholds returns 400 if thresholds are misordered."""
|
|
invalid_payload = {
|
|
"threshold_high": 50,
|
|
"threshold_medium": 50,
|
|
"threshold_low": 20,
|
|
}
|
|
resp = await config_client.put(
|
|
"/api/config/map-color-thresholds", json=invalid_payload
|
|
)
|
|
|
|
assert resp.status_code == 400
|
|
assert "high > medium > low" in resp.json()["detail"]
|
|
|
|
async def test_400_for_non_positive_values(
|
|
self, config_client: AsyncClient
|
|
) -> None:
|
|
"""PUT /api/config/map-color-thresholds returns 422 for non-positive values (Pydantic validation)."""
|
|
invalid_payload = {
|
|
"threshold_high": 100,
|
|
"threshold_medium": 50,
|
|
"threshold_low": 0,
|
|
}
|
|
resp = await config_client.put(
|
|
"/api/config/map-color-thresholds", json=invalid_payload
|
|
)
|
|
|
|
# Pydantic validates ge=1 constraint before our service code runs
|
|
assert resp.status_code == 422
|