Compare commits
75 Commits
refactorin
...
v0.9.15
| Author | SHA1 | Date | |
|---|---|---|---|
| 470c29443c | |||
| 6f15e1fa24 | |||
| 487cb171f2 | |||
| 7789353690 | |||
| ccfcbc82c5 | |||
| 7626c9cb60 | |||
| ac4fd967aa | |||
| 9f05da2d4d | |||
| 876af46955 | |||
| 0d4a2a3311 | |||
| f555b1b0a2 | |||
| a30b92471a | |||
| 9e43282bbc | |||
| 2ea4a8304f | |||
| e99920e616 | |||
| 670ff3e8a2 | |||
| f6672d0d16 | |||
| d909f93efc | |||
| 965cdd765b | |||
| 0663740b08 | |||
| 29587f2353 | |||
| 798ed08ddd | |||
| ed184f1c84 | |||
| 8e1b4fa978 | |||
| e604e3aadf | |||
| cf721513e8 | |||
| a32cc82851 | |||
| 26af69e2a3 | |||
| 00e702a2c0 | |||
| ee73373111 | |||
| a1f97bd78f | |||
| 99fbddb0e7 | |||
| b15629a078 | |||
| 136f21ecbe | |||
| bf2abda595 | |||
| 335f89c554 | |||
| 05dc9fa1e3 | |||
| 471eed9664 | |||
| 1f272dc348 | |||
| f9cec2a975 | |||
| cc235b95c6 | |||
| 29415da421 | |||
| 8a6bcc4d94 | |||
| a442836c5c | |||
| 3aba2b6446 | |||
| 28a7610276 | |||
| d30d138146 | |||
| 8c4fe767de | |||
| 52b0936200 | |||
| 1c0bac1353 | |||
| bdcdd5d672 | |||
| 482399c9e2 | |||
| ce59a66973 | |||
| dfbe126368 | |||
| c9e688cc52 | |||
| 1ce5da9e23 | |||
| 93f0feabde | |||
| 376c13370d | |||
| fb6d0e588f | |||
| e44caccb3c | |||
| 15e4a5434e | |||
| 1cc9968d31 | |||
| 80a6bac33e | |||
| 133ab2e82c | |||
| 60f2f35b25 | |||
| 59da34dc3b | |||
| 90f54cf39c | |||
| 93d26e3c60 | |||
| 954dcf7ea6 | |||
| bf8144916a | |||
| 481daa4e1a | |||
| 889976c7ee | |||
| d3d2cb0915 | |||
| bf82e38b6e | |||
| e98fd1de93 |
@@ -1 +1 @@
|
|||||||
v0.9.4
|
v0.9.15
|
||||||
|
|||||||
@@ -18,8 +18,8 @@ logpath = /dev/null
|
|||||||
backend = auto
|
backend = auto
|
||||||
maxretry = 1
|
maxretry = 1
|
||||||
findtime = 1d
|
findtime = 1d
|
||||||
# Block imported IPs for one week.
|
# Block imported IPs for 24 hours.
|
||||||
bantime = 1w
|
bantime = 86400
|
||||||
|
|
||||||
# Never ban the Docker bridge network or localhost.
|
# Never ban the Docker bridge network or localhost.
|
||||||
ignoreip = 127.0.0.0/8 ::1 172.16.0.0/12
|
ignoreip = 127.0.0.0/8 ::1 172.16.0.0/12
|
||||||
|
|||||||
@@ -56,11 +56,8 @@ echo " Registry : ${REGISTRY}"
|
|||||||
echo " Tag : ${TAG}"
|
echo " Tag : ${TAG}"
|
||||||
echo "============================================"
|
echo "============================================"
|
||||||
|
|
||||||
if [[ "${ENGINE}" == "podman" ]]; then
|
log "Logging in to ${REGISTRY}"
|
||||||
if ! podman login --get-login "${REGISTRY}" &>/dev/null; then
|
"${ENGINE}" login "${REGISTRY}"
|
||||||
err "Not logged in. Run:\n podman login ${REGISTRY}"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Build
|
# Build
|
||||||
|
|||||||
@@ -68,19 +68,34 @@ FRONT_PKG="${SCRIPT_DIR}/../frontend/package.json"
|
|||||||
sed -i "s/\"version\": \"[^\"]*\"/\"version\": \"${FRONT_VERSION}\"/" "${FRONT_PKG}"
|
sed -i "s/\"version\": \"[^\"]*\"/\"version\": \"${FRONT_VERSION}\"/" "${FRONT_PKG}"
|
||||||
echo "frontend/package.json version updated → ${FRONT_VERSION}"
|
echo "frontend/package.json version updated → ${FRONT_VERSION}"
|
||||||
|
|
||||||
|
# Keep backend/pyproject.toml in sync so app.__version__ matches Docker/VERSION in the runtime container.
|
||||||
|
BACKEND_PYPROJECT="${SCRIPT_DIR}/../backend/pyproject.toml"
|
||||||
|
if [[ -f "${BACKEND_PYPROJECT}" ]]; then
|
||||||
|
sed -i "s/^version = \".*\"/version = \"${FRONT_VERSION}\"/" "${BACKEND_PYPROJECT}"
|
||||||
|
echo "backend/pyproject.toml version updated → ${FRONT_VERSION}"
|
||||||
|
else
|
||||||
|
echo "Warning: backend/pyproject.toml not found, skipping backend version sync" >&2
|
||||||
|
fi
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Git tag
|
# Push containers
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
bash "${SCRIPT_DIR}/push.sh" "${NEW_TAG}"
|
||||||
|
bash "${SCRIPT_DIR}/push.sh"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Git tag (local only; push after container build)
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
cd "${SCRIPT_DIR}/.."
|
cd "${SCRIPT_DIR}/.."
|
||||||
git add Docker/VERSION frontend/package.json
|
git add Docker/VERSION frontend/package.json
|
||||||
git commit -m "chore: release ${NEW_TAG}"
|
git commit -m "chore: release ${NEW_TAG}"
|
||||||
git tag -a "${NEW_TAG}" -m "Release ${NEW_TAG}"
|
git tag -a "${NEW_TAG}" -m "Release ${NEW_TAG}"
|
||||||
git push origin HEAD
|
echo "Local git commit + tag ${NEW_TAG} created."
|
||||||
git push origin "${NEW_TAG}"
|
|
||||||
echo "Git tag ${NEW_TAG} created and pushed."
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Push
|
# Push git commits & tag
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
bash "${SCRIPT_DIR}/push.sh" "${NEW_TAG}"
|
git push origin HEAD
|
||||||
bash "${SCRIPT_DIR}/push.sh"
|
git push origin "${NEW_TAG}"
|
||||||
|
echo "Git commit and tag ${NEW_TAG} pushed."
|
||||||
|
|||||||
@@ -259,6 +259,17 @@ A view for exploring historical ban data stored in the fail2ban database.
|
|||||||
- Select any IP to see its full ban timeline: every ban event, which jail triggered it, when it started, and how long it lasted.
|
- Select any IP to see its full ban timeline: every ban event, which jail triggered it, when it started, and how long it lasted.
|
||||||
- Merged view showing total failures and matched log lines aggregated across all bans for that IP.
|
- Merged view showing total failures and matched log lines aggregated across all bans for that IP.
|
||||||
|
|
||||||
|
### Persistent Historical Archive
|
||||||
|
|
||||||
|
- BanGUI stores a separate long-term historical ban archive in its own application database, independent from fail2ban's database retention settings.
|
||||||
|
- On each configured sync cycle (default every 5 minutes), BanGUI reads latest entries from fail2ban `bans` table and appends any new events to BanGUI history storage.
|
||||||
|
- Supports both `ban` and `unban` events; audit record includes: `timestamp`, `ip`, `jail`, `action`, `duration`, `origin` (manual, auto, blocklist, etc.), `failures`, `matches`, and optional `country` / `ASN` enrichment.
|
||||||
|
- Includes incremental import logic with dedupe: using unique constraint on (ip, jail, action, timeofban) to prevent duplication across sync cycles.
|
||||||
|
- Provides backfill mode for initial startup: import last N days (configurable, default 7 days) of existing fail2ban history into BanGUI to avoid dark gaps after restart.
|
||||||
|
- Includes configurable archive purge policy in BanGUI (default 365 days), separate from fail2ban `dbpurgeage`, to keep app storage bounded while preserving audit data.
|
||||||
|
- Expose API endpoints for querying persistent history, with filters for timeframe, jail, origin, IP, and current ban status.
|
||||||
|
- On fail2ban connectivity failure, BanGUI continues serving historical data; next successful sync resumes ingestion without data loss.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 8. External Blocklist Importer
|
## 8. External Blocklist Importer
|
||||||
|
|||||||
@@ -7,3 +7,57 @@ Reference: `Docs/Refactoring.md` for full analysis of each issue.
|
|||||||
---
|
---
|
||||||
|
|
||||||
## Open Issues
|
## Open Issues
|
||||||
|
|
||||||
|
### History page filters and behavior (frontend)
|
||||||
|
|
||||||
|
1. [x] Time range filter currently not working
|
||||||
|
- Scope: frontend `history` page state/logic (likely in `frontend/src` route or component for history table)
|
||||||
|
- Expected behavior: selecting start/end timestamps (or presets) should filter history rows by event timestamp in the backend query or local data, then rerender filtered results immediately.
|
||||||
|
- Investigation:
|
||||||
|
- check component(s) handling time range input, change handlers, and query construction.
|
||||||
|
- confirm backend API supports `startTime`/`endTime` parameters for history endpoint (`/api/history` or similar).
|
||||||
|
- confirm values are passed as ISO strings/epoch and matched in backend.
|
||||||
|
- Fix should include:
|
||||||
|
- wiring the time range inputs to the filtering state.
|
||||||
|
- constructing API query with time range params.
|
||||||
|
- verifying with unit/integration tests plus manual through UI.
|
||||||
|
|
||||||
|
2. [x] Global filter (All | Blocklist | Selfblock) not working
|
||||||
|
- Scope: frontend `history` page filter chips or select control.
|
||||||
|
- Expected behavior: choosing `All`, `Blocklist`, `Selfblock` should apply corresponding filter in same history query (no results for unmatched types).
|
||||||
|
- Tasks:
|
||||||
|
- locate filter control component and event handlers.
|
||||||
|
- validate value mapping semantics (`all`=>no filter, `blocklist`=>source=blocklist, `selfblock`=>source=selfblock or equivalent).
|
||||||
|
- ensure filter value is merged with time range + jail/ip filters in API call.
|
||||||
|
- add tests for each filter option to confirm behavior.
|
||||||
|
|
||||||
|
3. [x] Jail and IP address filters UX alignment with time range
|
||||||
|
- Scope: frontend `history` page layout/CSS component; likely `HistoryFilters` container.
|
||||||
|
- Expected behavior:
|
||||||
|
- Jail filter and IP address filter should be same look (input/select style and spacing) as time range widget.
|
||||||
|
- Place Jail/IP filters next to time range controls in same row.
|
||||||
|
- Should be responsive and consistent.
|
||||||
|
- Tasks:
|
||||||
|
- modify the `history` filter container markup so time range, jail, ip filter are co-located.
|
||||||
|
- apply matching CSS classes/styles to Jail/IP as existing time range control.
|
||||||
|
- verify cross-browser/responsive display with storybook/test if exists.
|
||||||
|
|
||||||
|
4. [x] Remove “Apply” and “Clear” buttons; auto-apply on field change
|
||||||
|
- Scope: frontend `history` filter form behavior.
|
||||||
|
- Expected behavior:
|
||||||
|
- Any filter field change (time range, type, jail, IP) triggers immediate query update (debounced 150-300 ms if needed).
|
||||||
|
- Remove explicit “Apply” and “Clear” buttons from UI.
|
||||||
|
- Clear can be replaced by resetting fields automatically or via a small “reset” icon if needed.
|
||||||
|
- Implementation steps:
|
||||||
|
- remove button UI elements and event bindings from history page component.
|
||||||
|
- make each filter input onChange call the shared `applyFilters` logic with current state.
|
||||||
|
- add debounce to avoid 100% rapid API churn.
|
||||||
|
- for clear semantics, ensure default/empty state on filter input binds to default query (All).
|
||||||
|
- add tests to verify no apply/clear buttons present and updates via input change.
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
- On `history` page, time range selection + filter chips + jail/ip are functional and produce filtered results.
|
||||||
|
- Time range, jail/IP inputs are styled consistently and in same filter row.
|
||||||
|
- No apply/clear buttons are visible and filter updates occur on value change (with optional debounce).
|
||||||
|
- Relevant tests added/updated in frontend test suite.
|
||||||
|
|
||||||
|
|||||||
@@ -210,7 +210,7 @@ Use Fluent UI React components as the building blocks. The following mapping sho
|
|||||||
|
|
||||||
| Element | Fluent component | Notes |
|
| Element | Fluent component | Notes |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Data tables | `DetailsList` | All ban tables, jail overviews, history tables. Enable column sorting, selection, and shimmer loading. |
|
| Data tables | `DetailsList` | All ban tables, jail overviews, history tables. Enable column sorting, selection, and shimmer loading. Use clear pagination controls (page number + prev/next) and a page-size selector (25/50/100) for large result sets. |
|
||||||
| Stat cards | `DocumentCard` or custom `Stack` card | Dashboard status bar — server status, total bans, active jails. Use `Depth 4`. |
|
| Stat cards | `DocumentCard` or custom `Stack` card | Dashboard status bar — server status, total bans, active jails. Use `Depth 4`. |
|
||||||
| Status indicators | `Badge` / `Icon` + colour | Server online/offline, jail running/stopped/idle. |
|
| Status indicators | `Badge` / `Icon` + colour | Server online/offline, jail running/stopped/idle. |
|
||||||
| Country labels | Monospaced text + flag emoji or icon | Geo data next to IP addresses. |
|
| Country labels | Monospaced text + flag emoji or icon | Geo data next to IP addresses. |
|
||||||
|
|||||||
@@ -1,224 +0,0 @@
|
|||||||
# Config File Service Extraction Summary
|
|
||||||
|
|
||||||
## ✓ Extraction Complete
|
|
||||||
|
|
||||||
Three new service modules have been created by extracting functions from `config_file_service.py`.
|
|
||||||
|
|
||||||
### Files Created
|
|
||||||
|
|
||||||
| File | Lines | Status |
|
|
||||||
|------|-------|--------|
|
|
||||||
| [jail_config_service.py](jail_config_service.py) | 991 | ✓ Created |
|
|
||||||
| [filter_config_service.py](filter_config_service.py) | 765 | ✓ Created |
|
|
||||||
| [action_config_service.py](action_config_service.py) | 988 | ✓ Created |
|
|
||||||
| **Total** | **2,744** | **✓ Verified** |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. JAIL_CONFIG Service (`jail_config_service.py`)
|
|
||||||
|
|
||||||
### Public Functions (7)
|
|
||||||
- `list_inactive_jails(config_dir, socket_path)` → InactiveJailListResponse
|
|
||||||
- `activate_jail(config_dir, socket_path, name, req)` → JailActivationResponse
|
|
||||||
- `deactivate_jail(config_dir, socket_path, name)` → JailActivationResponse
|
|
||||||
- `delete_jail_local_override(config_dir, socket_path, name)` → None
|
|
||||||
- `validate_jail_config(config_dir, name)` → JailValidationResult
|
|
||||||
- `rollback_jail(config_dir, socket_path, name, start_cmd_parts)` → RollbackResponse
|
|
||||||
- `_rollback_activation_async(config_dir, name, socket_path, original_content)` → bool
|
|
||||||
|
|
||||||
### Helper Functions (5)
|
|
||||||
- `_write_local_override_sync()` - Atomic write of jail.d/{name}.local
|
|
||||||
- `_restore_local_file_sync()` - Restore or delete .local file during rollback
|
|
||||||
- `_validate_regex_patterns()` - Validate failregex/ignoreregex patterns
|
|
||||||
- `_set_jail_local_key_sync()` - Update single key in jail section
|
|
||||||
- `_validate_jail_config_sync()` - Synchronous validation (filter/action files, patterns, logpath)
|
|
||||||
|
|
||||||
### Custom Exceptions (3)
|
|
||||||
- `JailNotFoundInConfigError`
|
|
||||||
- `JailAlreadyActiveError`
|
|
||||||
- `JailAlreadyInactiveError`
|
|
||||||
|
|
||||||
### Shared Dependencies Imported
|
|
||||||
- `_safe_jail_name()` - From config_file_service
|
|
||||||
- `_parse_jails_sync()` - From config_file_service
|
|
||||||
- `_build_inactive_jail()` - From config_file_service
|
|
||||||
- `_get_active_jail_names()` - From config_file_service
|
|
||||||
- `_probe_fail2ban_running()` - From config_file_service
|
|
||||||
- `wait_for_fail2ban()` - From config_file_service
|
|
||||||
- `start_daemon()` - From config_file_service
|
|
||||||
- `_resolve_filter()` - From config_file_service
|
|
||||||
- `_parse_multiline()` - From config_file_service
|
|
||||||
- `_SOCKET_TIMEOUT`, `_META_SECTIONS` - Constants
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. FILTER_CONFIG Service (`filter_config_service.py`)
|
|
||||||
|
|
||||||
### Public Functions (6)
|
|
||||||
- `list_filters(config_dir, socket_path)` → FilterListResponse
|
|
||||||
- `get_filter(config_dir, socket_path, name)` → FilterConfig
|
|
||||||
- `update_filter(config_dir, socket_path, name, req, do_reload=False)` → FilterConfig
|
|
||||||
- `create_filter(config_dir, socket_path, req, do_reload=False)` → FilterConfig
|
|
||||||
- `delete_filter(config_dir, name)` → None
|
|
||||||
- `assign_filter_to_jail(config_dir, socket_path, jail_name, req, do_reload=False)` → None
|
|
||||||
|
|
||||||
### Helper Functions (4)
|
|
||||||
- `_extract_filter_base_name(filter_raw)` - Extract base name from filter string
|
|
||||||
- `_build_filter_to_jails_map()` - Map filters to jails using them
|
|
||||||
- `_parse_filters_sync()` - Scan filter.d/ and return tuples
|
|
||||||
- `_write_filter_local_sync()` - Atomic write of filter.d/{name}.local
|
|
||||||
- `_validate_regex_patterns()` - Validate regex patterns (shared with jail_config)
|
|
||||||
|
|
||||||
### Custom Exceptions (5)
|
|
||||||
- `FilterNotFoundError`
|
|
||||||
- `FilterAlreadyExistsError`
|
|
||||||
- `FilterReadonlyError`
|
|
||||||
- `FilterInvalidRegexError`
|
|
||||||
- `FilterNameError` (re-exported from config_file_service)
|
|
||||||
|
|
||||||
### Shared Dependencies Imported
|
|
||||||
- `_safe_filter_name()` - From config_file_service
|
|
||||||
- `_safe_jail_name()` - From config_file_service
|
|
||||||
- `_parse_jails_sync()` - From config_file_service
|
|
||||||
- `_get_active_jail_names()` - From config_file_service
|
|
||||||
- `_resolve_filter()` - From config_file_service
|
|
||||||
- `_parse_multiline()` - From config_file_service
|
|
||||||
- `_SAFE_FILTER_NAME_RE` - Constant pattern
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. ACTION_CONFIG Service (`action_config_service.py`)
|
|
||||||
|
|
||||||
### Public Functions (7)
|
|
||||||
- `list_actions(config_dir, socket_path)` → ActionListResponse
|
|
||||||
- `get_action(config_dir, socket_path, name)` → ActionConfig
|
|
||||||
- `update_action(config_dir, socket_path, name, req, do_reload=False)` → ActionConfig
|
|
||||||
- `create_action(config_dir, socket_path, req, do_reload=False)` → ActionConfig
|
|
||||||
- `delete_action(config_dir, name)` → None
|
|
||||||
- `assign_action_to_jail(config_dir, socket_path, jail_name, req, do_reload=False)` → None
|
|
||||||
- `remove_action_from_jail(config_dir, socket_path, jail_name, action_name, do_reload=False)` → None
|
|
||||||
|
|
||||||
### Helper Functions (5)
|
|
||||||
- `_safe_action_name(name)` - Validate action name
|
|
||||||
- `_extract_action_base_name()` - Extract base name from action string
|
|
||||||
- `_build_action_to_jails_map()` - Map actions to jails using them
|
|
||||||
- `_parse_actions_sync()` - Scan action.d/ and return tuples
|
|
||||||
- `_append_jail_action_sync()` - Append action to jail.d/{name}.local
|
|
||||||
- `_remove_jail_action_sync()` - Remove action from jail.d/{name}.local
|
|
||||||
- `_write_action_local_sync()` - Atomic write of action.d/{name}.local
|
|
||||||
|
|
||||||
### Custom Exceptions (4)
|
|
||||||
- `ActionNotFoundError`
|
|
||||||
- `ActionAlreadyExistsError`
|
|
||||||
- `ActionReadonlyError`
|
|
||||||
- `ActionNameError`
|
|
||||||
|
|
||||||
### Shared Dependencies Imported
|
|
||||||
- `_safe_jail_name()` - From config_file_service
|
|
||||||
- `_parse_jails_sync()` - From config_file_service
|
|
||||||
- `_get_active_jail_names()` - From config_file_service
|
|
||||||
- `_build_parser()` - From config_file_service
|
|
||||||
- `_SAFE_ACTION_NAME_RE` - Constant pattern
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. SHARED Utilities (remain in `config_file_service.py`)
|
|
||||||
|
|
||||||
### Utility Functions (14)
|
|
||||||
- `_safe_jail_name(name)` → str
|
|
||||||
- `_safe_filter_name(name)` → str
|
|
||||||
- `_ordered_config_files(config_dir)` → list[Path]
|
|
||||||
- `_build_parser()` → configparser.RawConfigParser
|
|
||||||
- `_is_truthy(value)` → bool
|
|
||||||
- `_parse_int_safe(value)` → int | None
|
|
||||||
- `_parse_time_to_seconds(value, default)` → int
|
|
||||||
- `_parse_multiline(raw)` → list[str]
|
|
||||||
- `_resolve_filter(raw_filter, jail_name, mode)` → str
|
|
||||||
- `_parse_jails_sync(config_dir)` → tuple
|
|
||||||
- `_build_inactive_jail(name, settings, source_file, config_dir=None)` → InactiveJail
|
|
||||||
- `_get_active_jail_names(socket_path)` → set[str]
|
|
||||||
- `_probe_fail2ban_running(socket_path)` → bool
|
|
||||||
- `wait_for_fail2ban(socket_path, max_wait_seconds, poll_interval)` → bool
|
|
||||||
- `start_daemon(start_cmd_parts)` → bool
|
|
||||||
|
|
||||||
### Shared Exceptions (3)
|
|
||||||
- `JailNameError`
|
|
||||||
- `FilterNameError`
|
|
||||||
- `ConfigWriteError`
|
|
||||||
|
|
||||||
### Constants (7)
|
|
||||||
- `_SOCKET_TIMEOUT`
|
|
||||||
- `_SAFE_JAIL_NAME_RE`
|
|
||||||
- `_META_SECTIONS`
|
|
||||||
- `_TRUE_VALUES`
|
|
||||||
- `_FALSE_VALUES`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Import Dependencies
|
|
||||||
|
|
||||||
### jail_config_service imports:
|
|
||||||
```python
|
|
||||||
config_file_service: (shared utilities + private functions)
|
|
||||||
jail_service.reload_all()
|
|
||||||
Fail2BanConnectionError
|
|
||||||
```
|
|
||||||
|
|
||||||
### filter_config_service imports:
|
|
||||||
```python
|
|
||||||
config_file_service: (shared utilities + _set_jail_local_key_sync)
|
|
||||||
jail_service.reload_all()
|
|
||||||
conffile_parser: (parse/merge/serialize filter functions)
|
|
||||||
jail_config_service: (JailNotFoundInConfigError - lazy import)
|
|
||||||
```
|
|
||||||
|
|
||||||
### action_config_service imports:
|
|
||||||
```python
|
|
||||||
config_file_service: (shared utilities + _build_parser)
|
|
||||||
jail_service.reload_all()
|
|
||||||
conffile_parser: (parse/merge/serialize action functions)
|
|
||||||
jail_config_service: (JailNotFoundInConfigError - lazy import)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Cross-Service Dependencies
|
|
||||||
|
|
||||||
**Circular imports handled via lazy imports:**
|
|
||||||
- `filter_config_service` imports `JailNotFoundInConfigError` from `jail_config_service` inside function
|
|
||||||
- `action_config_service` imports `JailNotFoundInConfigError` from `jail_config_service` inside function
|
|
||||||
|
|
||||||
**Shared functions re-used:**
|
|
||||||
- `_set_jail_local_key_sync()` exported from `jail_config_service`, used by `filter_config_service`
|
|
||||||
- `_append_jail_action_sync()` and `_remove_jail_action_sync()` internal to `action_config_service`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Verification Results
|
|
||||||
|
|
||||||
✓ **Syntax Check:** All three files compile without errors
|
|
||||||
✓ **Import Verification:** All imports resolved correctly
|
|
||||||
✓ **Total Lines:** 2,744 lines across three new files
|
|
||||||
✓ **Function Coverage:** 100% of specified functions extracted
|
|
||||||
✓ **Type Hints:** Preserved throughout
|
|
||||||
✓ **Docstrings:** All preserved with full documentation
|
|
||||||
✓ **Comments:** All inline comments preserved
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Next Steps (if needed)
|
|
||||||
|
|
||||||
1. **Update router imports** - Point from config_file_service to specific service modules:
|
|
||||||
- `jail_config_service` for jail operations
|
|
||||||
- `filter_config_service` for filter operations
|
|
||||||
- `action_config_service` for action operations
|
|
||||||
|
|
||||||
2. **Update config_file_service.py** - Remove all extracted functions (optional cleanup)
|
|
||||||
- Optionally keep it as a facade/aggregator
|
|
||||||
- Or reduce it to only the shared utilities module
|
|
||||||
|
|
||||||
3. **Add __all__ exports** to each new module for cleaner public API
|
|
||||||
|
|
||||||
4. **Update type hints** in models if needed for cross-service usage
|
|
||||||
|
|
||||||
5. **Testing** - Run existing tests to ensure no regressions
|
|
||||||
@@ -1 +1,68 @@
|
|||||||
"""BanGUI backend application package."""
|
"""BanGUI backend application package.
|
||||||
|
|
||||||
|
This package exposes the application version based on the project metadata.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Final
|
||||||
|
|
||||||
|
import importlib.metadata
|
||||||
|
import tomllib
|
||||||
|
|
||||||
|
PACKAGE_NAME: Final[str] = "bangui-backend"
|
||||||
|
|
||||||
|
|
||||||
|
def _read_pyproject_version() -> str:
|
||||||
|
"""Read the project version from ``pyproject.toml``.
|
||||||
|
|
||||||
|
This is used as a fallback when the package metadata is not available (e.g.
|
||||||
|
when running directly from a source checkout without installing the package).
|
||||||
|
"""
|
||||||
|
|
||||||
|
project_root = Path(__file__).resolve().parents[1]
|
||||||
|
pyproject_path = project_root / "pyproject.toml"
|
||||||
|
if not pyproject_path.exists():
|
||||||
|
raise FileNotFoundError(f"pyproject.toml not found at {pyproject_path}")
|
||||||
|
|
||||||
|
data = tomllib.loads(pyproject_path.read_text(encoding="utf-8"))
|
||||||
|
return str(data["project"]["version"])
|
||||||
|
|
||||||
|
|
||||||
|
def _read_docker_version() -> str:
|
||||||
|
"""Read the project version from ``Docker/VERSION``.
|
||||||
|
|
||||||
|
This file is the single source of truth for release scripts and must not be
|
||||||
|
out of sync with the frontend and backend versions.
|
||||||
|
"""
|
||||||
|
|
||||||
|
repo_root = Path(__file__).resolve().parents[2]
|
||||||
|
version_path = repo_root / "Docker" / "VERSION"
|
||||||
|
if not version_path.exists():
|
||||||
|
raise FileNotFoundError(f"Docker/VERSION not found at {version_path}")
|
||||||
|
|
||||||
|
version = version_path.read_text(encoding="utf-8").strip()
|
||||||
|
return version.lstrip("v")
|
||||||
|
|
||||||
|
|
||||||
|
def _read_version() -> str:
|
||||||
|
"""Return the current package version.
|
||||||
|
|
||||||
|
Prefer the release artifact in ``Docker/VERSION`` when available so the
|
||||||
|
backend version always matches what the release tooling publishes.
|
||||||
|
|
||||||
|
If that file is missing (e.g. in a production wheel or a local checkout),
|
||||||
|
fall back to ``pyproject.toml`` and finally installed package metadata.
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
return _read_docker_version()
|
||||||
|
except FileNotFoundError:
|
||||||
|
try:
|
||||||
|
return _read_pyproject_version()
|
||||||
|
except FileNotFoundError:
|
||||||
|
return importlib.metadata.version(PACKAGE_NAME)
|
||||||
|
|
||||||
|
|
||||||
|
__version__ = _read_version()
|
||||||
|
|||||||
@@ -75,6 +75,20 @@ CREATE TABLE IF NOT EXISTS geo_cache (
|
|||||||
);
|
);
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
_CREATE_HISTORY_ARCHIVE: str = """
|
||||||
|
CREATE TABLE IF NOT EXISTS history_archive (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
jail TEXT NOT NULL,
|
||||||
|
ip TEXT NOT NULL,
|
||||||
|
timeofban INTEGER NOT NULL,
|
||||||
|
bancount INTEGER NOT NULL,
|
||||||
|
data TEXT NOT NULL,
|
||||||
|
action TEXT NOT NULL CHECK(action IN ('ban', 'unban')),
|
||||||
|
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
||||||
|
UNIQUE(ip, jail, action, timeofban)
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
|
||||||
# Ordered list of DDL statements to execute on initialisation.
|
# Ordered list of DDL statements to execute on initialisation.
|
||||||
_SCHEMA_STATEMENTS: list[str] = [
|
_SCHEMA_STATEMENTS: list[str] = [
|
||||||
_CREATE_SETTINGS,
|
_CREATE_SETTINGS,
|
||||||
@@ -83,6 +97,7 @@ _SCHEMA_STATEMENTS: list[str] = [
|
|||||||
_CREATE_BLOCKLIST_SOURCES,
|
_CREATE_BLOCKLIST_SOURCES,
|
||||||
_CREATE_IMPORT_LOG,
|
_CREATE_IMPORT_LOG,
|
||||||
_CREATE_GEO_CACHE,
|
_CREATE_GEO_CACHE,
|
||||||
|
_CREATE_HISTORY_ARCHIVE,
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ from fastapi.middleware.cors import CORSMiddleware
|
|||||||
from fastapi.responses import JSONResponse, RedirectResponse
|
from fastapi.responses import JSONResponse, RedirectResponse
|
||||||
from starlette.middleware.base import BaseHTTPMiddleware
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
|
|
||||||
|
from app import __version__
|
||||||
from app.config import Settings, get_settings
|
from app.config import Settings, get_settings
|
||||||
from app.db import init_db
|
from app.db import init_db
|
||||||
from app.routers import (
|
from app.routers import (
|
||||||
@@ -47,7 +48,7 @@ from app.routers import (
|
|||||||
server,
|
server,
|
||||||
setup,
|
setup,
|
||||||
)
|
)
|
||||||
from app.tasks import blocklist_import, geo_cache_flush, geo_re_resolve, health_check
|
from app.tasks import blocklist_import, geo_cache_flush, geo_re_resolve, health_check, history_sync
|
||||||
from app.utils.fail2ban_client import Fail2BanConnectionError, Fail2BanProtocolError
|
from app.utils.fail2ban_client import Fail2BanConnectionError, Fail2BanProtocolError
|
||||||
from app.utils.jail_config import ensure_jail_configs
|
from app.utils.jail_config import ensure_jail_configs
|
||||||
|
|
||||||
@@ -182,6 +183,9 @@ async def _lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
|||||||
# --- Periodic re-resolve of NULL-country geo entries ---
|
# --- Periodic re-resolve of NULL-country geo entries ---
|
||||||
geo_re_resolve.register(app)
|
geo_re_resolve.register(app)
|
||||||
|
|
||||||
|
# --- Periodic history sync from fail2ban into BanGUI archive ---
|
||||||
|
history_sync.register(app)
|
||||||
|
|
||||||
log.info("bangui_started")
|
log.info("bangui_started")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -361,7 +365,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
|||||||
app: FastAPI = FastAPI(
|
app: FastAPI = FastAPI(
|
||||||
title="BanGUI",
|
title="BanGUI",
|
||||||
description="Web interface for monitoring, managing, and configuring fail2ban.",
|
description="Web interface for monitoring, managing, and configuring fail2ban.",
|
||||||
version="0.1.0",
|
version=__version__,
|
||||||
lifespan=_lifespan,
|
lifespan=_lifespan,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1001,7 +1001,7 @@ class ServiceStatusResponse(BaseModel):
|
|||||||
model_config = ConfigDict(strict=True)
|
model_config = ConfigDict(strict=True)
|
||||||
|
|
||||||
online: bool = Field(..., description="Whether fail2ban is reachable via its socket.")
|
online: bool = Field(..., description="Whether fail2ban is reachable via its socket.")
|
||||||
version: str | None = Field(default=None, description="fail2ban version string, or None when offline.")
|
version: str | None = Field(default=None, description="BanGUI application version (or None when offline).")
|
||||||
jail_count: int = Field(default=0, ge=0, description="Number of currently active jails.")
|
jail_count: int = Field(default=0, ge=0, description="Number of currently active jails.")
|
||||||
total_bans: int = Field(default=0, ge=0, description="Aggregated current ban count across all jails.")
|
total_bans: int = Field(default=0, ge=0, description="Aggregated current ban count across all jails.")
|
||||||
total_failures: int = Field(default=0, ge=0, description="Aggregated current failure count across all jails.")
|
total_failures: int = Field(default=0, ge=0, description="Aggregated current failure count across all jails.")
|
||||||
|
|||||||
@@ -56,3 +56,7 @@ class ServerSettingsResponse(BaseModel):
|
|||||||
model_config = ConfigDict(strict=True)
|
model_config = ConfigDict(strict=True)
|
||||||
|
|
||||||
settings: ServerSettings
|
settings: ServerSettings
|
||||||
|
warnings: dict[str, bool] = Field(
|
||||||
|
default_factory=dict,
|
||||||
|
description="Warnings highlighting potentially unsafe settings.",
|
||||||
|
)
|
||||||
|
|||||||
@@ -294,6 +294,7 @@ async def get_history_page(
|
|||||||
since: int | None = None,
|
since: int | None = None,
|
||||||
jail: str | None = None,
|
jail: str | None = None,
|
||||||
ip_filter: str | None = None,
|
ip_filter: str | None = None,
|
||||||
|
origin: BanOrigin | None = None,
|
||||||
page: int = 1,
|
page: int = 1,
|
||||||
page_size: int = 100,
|
page_size: int = 100,
|
||||||
) -> tuple[list[HistoryRecord], int]:
|
) -> tuple[list[HistoryRecord], int]:
|
||||||
@@ -314,6 +315,12 @@ async def get_history_page(
|
|||||||
wheres.append("ip LIKE ?")
|
wheres.append("ip LIKE ?")
|
||||||
params.append(f"{ip_filter}%")
|
params.append(f"{ip_filter}%")
|
||||||
|
|
||||||
|
origin_clause, origin_params = _origin_sql_filter(origin)
|
||||||
|
if origin_clause:
|
||||||
|
origin_clause_clean = origin_clause.removeprefix(" AND ")
|
||||||
|
wheres.append(origin_clause_clean)
|
||||||
|
params.extend(origin_params)
|
||||||
|
|
||||||
where_sql: str = ("WHERE " + " AND ".join(wheres)) if wheres else ""
|
where_sql: str = ("WHERE " + " AND ".join(wheres)) if wheres else ""
|
||||||
|
|
||||||
effective_page_size: int = page_size
|
effective_page_size: int = page_size
|
||||||
|
|||||||
148
backend/app/repositories/history_archive_repo.py
Normal file
148
backend/app/repositories/history_archive_repo.py
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
"""Ban history archive repository.
|
||||||
|
|
||||||
|
Provides persistence APIs for the BanGUI archival history table in the
|
||||||
|
application database.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from app.models.ban import BLOCKLIST_JAIL, BanOrigin
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
import aiosqlite
|
||||||
|
|
||||||
|
|
||||||
|
async def archive_ban_event(
|
||||||
|
db: aiosqlite.Connection,
|
||||||
|
jail: str,
|
||||||
|
ip: str,
|
||||||
|
timeofban: int,
|
||||||
|
bancount: int,
|
||||||
|
data: str,
|
||||||
|
action: str = "ban",
|
||||||
|
) -> bool:
|
||||||
|
"""Insert a new archived ban/unban event, ignoring duplicates."""
|
||||||
|
async with db.execute(
|
||||||
|
"""INSERT OR IGNORE INTO history_archive
|
||||||
|
(jail, ip, timeofban, bancount, data, action)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)""",
|
||||||
|
(jail, ip, timeofban, bancount, data, action),
|
||||||
|
) as cursor:
|
||||||
|
inserted = cursor.rowcount == 1
|
||||||
|
await db.commit()
|
||||||
|
return inserted
|
||||||
|
|
||||||
|
|
||||||
|
async def get_archived_history(
|
||||||
|
db: aiosqlite.Connection,
|
||||||
|
since: int | None = None,
|
||||||
|
jail: str | None = None,
|
||||||
|
ip_filter: str | None = None,
|
||||||
|
origin: BanOrigin | None = None,
|
||||||
|
action: str | None = None,
|
||||||
|
page: int = 1,
|
||||||
|
page_size: int = 100,
|
||||||
|
) -> tuple[list[dict], int]:
|
||||||
|
"""Return a paginated archived history result set."""
|
||||||
|
wheres: list[str] = []
|
||||||
|
params: list[object] = []
|
||||||
|
|
||||||
|
if since is not None:
|
||||||
|
wheres.append("timeofban >= ?")
|
||||||
|
params.append(since)
|
||||||
|
|
||||||
|
if jail is not None:
|
||||||
|
wheres.append("jail = ?")
|
||||||
|
params.append(jail)
|
||||||
|
|
||||||
|
if ip_filter is not None:
|
||||||
|
wheres.append("ip LIKE ?")
|
||||||
|
params.append(f"{ip_filter}%")
|
||||||
|
|
||||||
|
if origin == "blocklist":
|
||||||
|
wheres.append("jail = ?")
|
||||||
|
params.append(BLOCKLIST_JAIL)
|
||||||
|
elif origin == "selfblock":
|
||||||
|
wheres.append("jail != ?")
|
||||||
|
params.append(BLOCKLIST_JAIL)
|
||||||
|
|
||||||
|
if action is not None:
|
||||||
|
wheres.append("action = ?")
|
||||||
|
params.append(action)
|
||||||
|
|
||||||
|
where_sql = "WHERE " + " AND ".join(wheres) if wheres else ""
|
||||||
|
offset = (page - 1) * page_size
|
||||||
|
|
||||||
|
async with db.execute(f"SELECT COUNT(*) FROM history_archive {where_sql}", params) as cur:
|
||||||
|
row = await cur.fetchone()
|
||||||
|
total = int(row[0]) if row is not None and row[0] is not None else 0
|
||||||
|
|
||||||
|
async with db.execute(
|
||||||
|
"SELECT jail, ip, timeofban, bancount, data, action "
|
||||||
|
"FROM history_archive "
|
||||||
|
f"{where_sql} "
|
||||||
|
"ORDER BY timeofban DESC LIMIT ? OFFSET ?",
|
||||||
|
[*params, page_size, offset],
|
||||||
|
) as cur:
|
||||||
|
rows = await cur.fetchall()
|
||||||
|
|
||||||
|
records = [
|
||||||
|
{
|
||||||
|
"jail": str(r[0]),
|
||||||
|
"ip": str(r[1]),
|
||||||
|
"timeofban": int(r[2]),
|
||||||
|
"bancount": int(r[3]),
|
||||||
|
"data": str(r[4]),
|
||||||
|
"action": str(r[5]),
|
||||||
|
}
|
||||||
|
for r in rows
|
||||||
|
]
|
||||||
|
|
||||||
|
return records, total
|
||||||
|
|
||||||
|
|
||||||
|
async def get_all_archived_history(
|
||||||
|
db: aiosqlite.Connection,
|
||||||
|
since: int | None = None,
|
||||||
|
jail: str | None = None,
|
||||||
|
ip_filter: str | None = None,
|
||||||
|
origin: BanOrigin | None = None,
|
||||||
|
action: str | None = None,
|
||||||
|
) -> list[dict]:
|
||||||
|
"""Return all archived history rows for the given filters."""
|
||||||
|
page: int = 1
|
||||||
|
page_size: int = 500
|
||||||
|
all_rows: list[dict] = []
|
||||||
|
|
||||||
|
while True:
|
||||||
|
rows, total = await get_archived_history(
|
||||||
|
db=db,
|
||||||
|
since=since,
|
||||||
|
jail=jail,
|
||||||
|
ip_filter=ip_filter,
|
||||||
|
origin=origin,
|
||||||
|
action=action,
|
||||||
|
page=page,
|
||||||
|
page_size=page_size,
|
||||||
|
)
|
||||||
|
all_rows.extend(rows)
|
||||||
|
if len(rows) < page_size:
|
||||||
|
break
|
||||||
|
page += 1
|
||||||
|
|
||||||
|
return all_rows
|
||||||
|
|
||||||
|
|
||||||
|
async def purge_archived_history(db: aiosqlite.Connection, age_seconds: int) -> int:
|
||||||
|
"""Purge archived entries older than *age_seconds*; return rows deleted."""
|
||||||
|
threshold = int(datetime.datetime.now(datetime.UTC).timestamp()) - age_seconds
|
||||||
|
async with db.execute(
|
||||||
|
"DELETE FROM history_archive WHERE timeofban < ?",
|
||||||
|
(threshold,),
|
||||||
|
) as cursor:
|
||||||
|
deleted = cursor.rowcount
|
||||||
|
await db.commit()
|
||||||
|
return deleted
|
||||||
@@ -19,6 +19,7 @@ if TYPE_CHECKING:
|
|||||||
|
|
||||||
from fastapi import APIRouter, Query, Request
|
from fastapi import APIRouter, Query, Request
|
||||||
|
|
||||||
|
from app import __version__
|
||||||
from app.dependencies import AuthDep
|
from app.dependencies import AuthDep
|
||||||
from app.models.ban import (
|
from app.models.ban import (
|
||||||
BanOrigin,
|
BanOrigin,
|
||||||
@@ -69,6 +70,7 @@ async def get_server_status(
|
|||||||
"server_status",
|
"server_status",
|
||||||
ServerStatus(online=False),
|
ServerStatus(online=False),
|
||||||
)
|
)
|
||||||
|
cached.version = __version__
|
||||||
return ServerStatusResponse(status=cached)
|
return ServerStatusResponse(status=cached)
|
||||||
|
|
||||||
|
|
||||||
@@ -81,6 +83,7 @@ async def get_dashboard_bans(
|
|||||||
request: Request,
|
request: Request,
|
||||||
_auth: AuthDep,
|
_auth: AuthDep,
|
||||||
range: TimeRange = Query(default=_DEFAULT_RANGE, description="Time-range preset."),
|
range: TimeRange = Query(default=_DEFAULT_RANGE, description="Time-range preset."),
|
||||||
|
source: str = Query(default="fail2ban", description="Data source: 'fail2ban' or 'archive'."),
|
||||||
page: int = Query(default=1, ge=1, description="1-based page number."),
|
page: int = Query(default=1, ge=1, description="1-based page number."),
|
||||||
page_size: int = Query(default=_DEFAULT_PAGE_SIZE, ge=1, le=500, description="Items per page."),
|
page_size: int = Query(default=_DEFAULT_PAGE_SIZE, ge=1, le=500, description="Items per page."),
|
||||||
origin: BanOrigin | None = Query(
|
origin: BanOrigin | None = Query(
|
||||||
@@ -115,10 +118,11 @@ async def get_dashboard_bans(
|
|||||||
return await ban_service.list_bans(
|
return await ban_service.list_bans(
|
||||||
socket_path,
|
socket_path,
|
||||||
range,
|
range,
|
||||||
|
source=source,
|
||||||
page=page,
|
page=page,
|
||||||
page_size=page_size,
|
page_size=page_size,
|
||||||
http_session=http_session,
|
http_session=http_session,
|
||||||
app_db=None,
|
app_db=request.app.state.db,
|
||||||
geo_batch_lookup=geo_service.lookup_batch,
|
geo_batch_lookup=geo_service.lookup_batch,
|
||||||
origin=origin,
|
origin=origin,
|
||||||
)
|
)
|
||||||
@@ -133,6 +137,7 @@ async def get_bans_by_country(
|
|||||||
request: Request,
|
request: Request,
|
||||||
_auth: AuthDep,
|
_auth: AuthDep,
|
||||||
range: TimeRange = Query(default=_DEFAULT_RANGE, description="Time-range preset."),
|
range: TimeRange = Query(default=_DEFAULT_RANGE, description="Time-range preset."),
|
||||||
|
source: str = Query(default="fail2ban", description="Data source: 'fail2ban' or 'archive'."),
|
||||||
origin: BanOrigin | None = Query(
|
origin: BanOrigin | None = Query(
|
||||||
default=None,
|
default=None,
|
||||||
description="Filter by ban origin: 'blocklist' or 'selfblock'. Omit for all.",
|
description="Filter by ban origin: 'blocklist' or 'selfblock'. Omit for all.",
|
||||||
@@ -162,10 +167,11 @@ async def get_bans_by_country(
|
|||||||
return await ban_service.bans_by_country(
|
return await ban_service.bans_by_country(
|
||||||
socket_path,
|
socket_path,
|
||||||
range,
|
range,
|
||||||
|
source=source,
|
||||||
http_session=http_session,
|
http_session=http_session,
|
||||||
geo_cache_lookup=geo_service.lookup_cached_only,
|
geo_cache_lookup=geo_service.lookup_cached_only,
|
||||||
geo_batch_lookup=geo_service.lookup_batch,
|
geo_batch_lookup=geo_service.lookup_batch,
|
||||||
app_db=None,
|
app_db=request.app.state.db,
|
||||||
origin=origin,
|
origin=origin,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -179,6 +185,7 @@ async def get_ban_trend(
|
|||||||
request: Request,
|
request: Request,
|
||||||
_auth: AuthDep,
|
_auth: AuthDep,
|
||||||
range: TimeRange = Query(default=_DEFAULT_RANGE, description="Time-range preset."),
|
range: TimeRange = Query(default=_DEFAULT_RANGE, description="Time-range preset."),
|
||||||
|
source: str = Query(default="fail2ban", description="Data source: 'fail2ban' or 'archive'."),
|
||||||
origin: BanOrigin | None = Query(
|
origin: BanOrigin | None = Query(
|
||||||
default=None,
|
default=None,
|
||||||
description="Filter by ban origin: 'blocklist' or 'selfblock'. Omit for all.",
|
description="Filter by ban origin: 'blocklist' or 'selfblock'. Omit for all.",
|
||||||
@@ -210,7 +217,13 @@ async def get_ban_trend(
|
|||||||
"""
|
"""
|
||||||
socket_path: str = request.app.state.settings.fail2ban_socket
|
socket_path: str = request.app.state.settings.fail2ban_socket
|
||||||
|
|
||||||
return await ban_service.ban_trend(socket_path, range, origin=origin)
|
return await ban_service.ban_trend(
|
||||||
|
socket_path,
|
||||||
|
range,
|
||||||
|
source=source,
|
||||||
|
app_db=request.app.state.db,
|
||||||
|
origin=origin,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
@@ -222,6 +235,7 @@ async def get_bans_by_jail(
|
|||||||
request: Request,
|
request: Request,
|
||||||
_auth: AuthDep,
|
_auth: AuthDep,
|
||||||
range: TimeRange = Query(default=_DEFAULT_RANGE, description="Time-range preset."),
|
range: TimeRange = Query(default=_DEFAULT_RANGE, description="Time-range preset."),
|
||||||
|
source: str = Query(default="fail2ban", description="Data source: 'fail2ban' or 'archive'."),
|
||||||
origin: BanOrigin | None = Query(
|
origin: BanOrigin | None = Query(
|
||||||
default=None,
|
default=None,
|
||||||
description="Filter by ban origin: 'blocklist' or 'selfblock'. Omit for all.",
|
description="Filter by ban origin: 'blocklist' or 'selfblock'. Omit for all.",
|
||||||
@@ -246,4 +260,10 @@ async def get_bans_by_jail(
|
|||||||
"""
|
"""
|
||||||
socket_path: str = request.app.state.settings.fail2ban_socket
|
socket_path: str = request.app.state.settings.fail2ban_socket
|
||||||
|
|
||||||
return await ban_service.bans_by_jail(socket_path, range, origin=origin)
|
return await ban_service.bans_by_jail(
|
||||||
|
socket_path,
|
||||||
|
range,
|
||||||
|
source=source,
|
||||||
|
app_db=request.app.state.db,
|
||||||
|
origin=origin,
|
||||||
|
)
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ if TYPE_CHECKING:
|
|||||||
from fastapi import APIRouter, HTTPException, Query, Request
|
from fastapi import APIRouter, HTTPException, Query, Request
|
||||||
|
|
||||||
from app.dependencies import AuthDep
|
from app.dependencies import AuthDep
|
||||||
from app.models.ban import TimeRange
|
from app.models.ban import BanOrigin, TimeRange
|
||||||
from app.models.history import HistoryListResponse, IpDetailResponse
|
from app.models.history import HistoryListResponse, IpDetailResponse
|
||||||
from app.services import geo_service, history_service
|
from app.services import geo_service, history_service
|
||||||
|
|
||||||
@@ -52,6 +52,14 @@ async def get_history(
|
|||||||
default=None,
|
default=None,
|
||||||
description="Restrict results to IPs matching this prefix.",
|
description="Restrict results to IPs matching this prefix.",
|
||||||
),
|
),
|
||||||
|
origin: BanOrigin | None = Query(
|
||||||
|
default=None,
|
||||||
|
description="Filter by ban origin: 'blocklist' or 'selfblock'. Omit for all.",
|
||||||
|
),
|
||||||
|
source: str = Query(
|
||||||
|
default="fail2ban",
|
||||||
|
description="Data source: 'fail2ban' or 'archive'.",
|
||||||
|
),
|
||||||
page: int = Query(default=1, ge=1, description="1-based page number."),
|
page: int = Query(default=1, ge=1, description="1-based page number."),
|
||||||
page_size: int = Query(
|
page_size: int = Query(
|
||||||
default=_DEFAULT_PAGE_SIZE,
|
default=_DEFAULT_PAGE_SIZE,
|
||||||
@@ -89,9 +97,48 @@ async def get_history(
|
|||||||
range_=range,
|
range_=range,
|
||||||
jail=jail,
|
jail=jail,
|
||||||
ip_filter=ip,
|
ip_filter=ip,
|
||||||
|
origin=origin,
|
||||||
|
source=source,
|
||||||
page=page,
|
page=page,
|
||||||
page_size=page_size,
|
page_size=page_size,
|
||||||
geo_enricher=_enricher,
|
geo_enricher=_enricher,
|
||||||
|
db=request.app.state.db,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/archive",
|
||||||
|
response_model=HistoryListResponse,
|
||||||
|
summary="Return a paginated list of archived historical bans",
|
||||||
|
)
|
||||||
|
async def get_history_archive(
|
||||||
|
request: Request,
|
||||||
|
_auth: AuthDep,
|
||||||
|
range: TimeRange | None = Query(
|
||||||
|
default=None,
|
||||||
|
description="Optional time-range filter. Omit for all-time.",
|
||||||
|
),
|
||||||
|
jail: str | None = Query(default=None, description="Restrict results to this jail name."),
|
||||||
|
ip: str | None = Query(default=None, description="Restrict results to IPs matching this prefix."),
|
||||||
|
page: int = Query(default=1, ge=1, description="1-based page number."),
|
||||||
|
page_size: int = Query(default=_DEFAULT_PAGE_SIZE, ge=1, le=500, description="Items per page (max 500)."),
|
||||||
|
) -> HistoryListResponse:
|
||||||
|
socket_path: str = request.app.state.settings.fail2ban_socket
|
||||||
|
http_session: aiohttp.ClientSession = request.app.state.http_session
|
||||||
|
|
||||||
|
async def _enricher(addr: str) -> geo_service.GeoInfo | None:
|
||||||
|
return await geo_service.lookup(addr, http_session)
|
||||||
|
|
||||||
|
return await history_service.list_history(
|
||||||
|
socket_path,
|
||||||
|
range_=range,
|
||||||
|
jail=jail,
|
||||||
|
ip_filter=ip,
|
||||||
|
source="archive",
|
||||||
|
page=page,
|
||||||
|
page_size=page_size,
|
||||||
|
geo_enricher=_enricher,
|
||||||
|
db=request.app.state.db,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -112,6 +112,7 @@ async def list_bans(
|
|||||||
socket_path: str,
|
socket_path: str,
|
||||||
range_: TimeRange,
|
range_: TimeRange,
|
||||||
*,
|
*,
|
||||||
|
source: str = "fail2ban",
|
||||||
page: int = 1,
|
page: int = 1,
|
||||||
page_size: int = _DEFAULT_PAGE_SIZE,
|
page_size: int = _DEFAULT_PAGE_SIZE,
|
||||||
http_session: aiohttp.ClientSession | None = None,
|
http_session: aiohttp.ClientSession | None = None,
|
||||||
@@ -160,24 +161,41 @@ async def list_bans(
|
|||||||
since: int = _since_unix(range_)
|
since: int = _since_unix(range_)
|
||||||
effective_page_size: int = min(page_size, _MAX_PAGE_SIZE)
|
effective_page_size: int = min(page_size, _MAX_PAGE_SIZE)
|
||||||
offset: int = (page - 1) * effective_page_size
|
offset: int = (page - 1) * effective_page_size
|
||||||
origin_clause, origin_params = _origin_sql_filter(origin)
|
|
||||||
|
|
||||||
db_path: str = await get_fail2ban_db_path(socket_path)
|
if source not in ("fail2ban", "archive"):
|
||||||
log.info(
|
raise ValueError(f"Unsupported source: {source!r}")
|
||||||
"ban_service_list_bans",
|
|
||||||
db_path=db_path,
|
|
||||||
since=since,
|
|
||||||
range=range_,
|
|
||||||
origin=origin,
|
|
||||||
)
|
|
||||||
|
|
||||||
rows, total = await fail2ban_db_repo.get_currently_banned(
|
if source == "archive":
|
||||||
db_path=db_path,
|
if app_db is None:
|
||||||
since=since,
|
raise ValueError("app_db must be provided when source is 'archive'")
|
||||||
origin=origin,
|
|
||||||
limit=effective_page_size,
|
from app.repositories.history_archive_repo import get_archived_history
|
||||||
offset=offset,
|
|
||||||
)
|
rows, total = await get_archived_history(
|
||||||
|
db=app_db,
|
||||||
|
since=since,
|
||||||
|
origin=origin,
|
||||||
|
action="ban",
|
||||||
|
page=page,
|
||||||
|
page_size=effective_page_size,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
db_path: str = await get_fail2ban_db_path(socket_path)
|
||||||
|
log.info(
|
||||||
|
"ban_service_list_bans",
|
||||||
|
db_path=db_path,
|
||||||
|
since=since,
|
||||||
|
range=range_,
|
||||||
|
origin=origin,
|
||||||
|
)
|
||||||
|
|
||||||
|
rows, total = await fail2ban_db_repo.get_currently_banned(
|
||||||
|
db_path=db_path,
|
||||||
|
since=since,
|
||||||
|
origin=origin,
|
||||||
|
limit=effective_page_size,
|
||||||
|
offset=offset,
|
||||||
|
)
|
||||||
|
|
||||||
# Batch-resolve geo data for all IPs on this page in a single API call.
|
# Batch-resolve geo data for all IPs on this page in a single API call.
|
||||||
# This avoids hitting the 45 req/min single-IP rate limit when the
|
# This avoids hitting the 45 req/min single-IP rate limit when the
|
||||||
@@ -192,11 +210,19 @@ async def list_bans(
|
|||||||
|
|
||||||
items: list[DashboardBanItem] = []
|
items: list[DashboardBanItem] = []
|
||||||
for row in rows:
|
for row in rows:
|
||||||
jail: str = row.jail
|
if source == "archive":
|
||||||
ip: str = row.ip
|
jail = str(row["jail"])
|
||||||
banned_at: str = ts_to_iso(row.timeofban)
|
ip = str(row["ip"])
|
||||||
ban_count: int = row.bancount
|
banned_at = ts_to_iso(int(row["timeofban"]))
|
||||||
matches, _ = parse_data_json(row.data)
|
ban_count = int(row["bancount"])
|
||||||
|
matches, _ = parse_data_json(row["data"])
|
||||||
|
else:
|
||||||
|
jail = row.jail
|
||||||
|
ip = row.ip
|
||||||
|
banned_at = ts_to_iso(row.timeofban)
|
||||||
|
ban_count = row.bancount
|
||||||
|
matches, _ = parse_data_json(row.data)
|
||||||
|
|
||||||
service: str | None = matches[0] if matches else None
|
service: str | None = matches[0] if matches else None
|
||||||
|
|
||||||
country_code: str | None = None
|
country_code: str | None = None
|
||||||
@@ -256,6 +282,8 @@ _MAX_COMPANION_BANS: int = 200
|
|||||||
async def bans_by_country(
|
async def bans_by_country(
|
||||||
socket_path: str,
|
socket_path: str,
|
||||||
range_: TimeRange,
|
range_: TimeRange,
|
||||||
|
*,
|
||||||
|
source: str = "fail2ban",
|
||||||
http_session: aiohttp.ClientSession | None = None,
|
http_session: aiohttp.ClientSession | None = None,
|
||||||
geo_cache_lookup: GeoCacheLookup | None = None,
|
geo_cache_lookup: GeoCacheLookup | None = None,
|
||||||
geo_batch_lookup: GeoBatchLookup | None = None,
|
geo_batch_lookup: GeoBatchLookup | None = None,
|
||||||
@@ -300,41 +328,80 @@ async def bans_by_country(
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
since: int = _since_unix(range_)
|
since: int = _since_unix(range_)
|
||||||
origin_clause, origin_params = _origin_sql_filter(origin)
|
|
||||||
db_path: str = await get_fail2ban_db_path(socket_path)
|
|
||||||
log.info(
|
|
||||||
"ban_service_bans_by_country",
|
|
||||||
db_path=db_path,
|
|
||||||
since=since,
|
|
||||||
range=range_,
|
|
||||||
origin=origin,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Total count and companion rows reuse the same SQL query logic.
|
if source not in ("fail2ban", "archive"):
|
||||||
# Passing limit=0 returns only the total from the count query.
|
raise ValueError(f"Unsupported source: {source!r}")
|
||||||
_, total = await fail2ban_db_repo.get_currently_banned(
|
|
||||||
db_path=db_path,
|
|
||||||
since=since,
|
|
||||||
origin=origin,
|
|
||||||
limit=0,
|
|
||||||
offset=0,
|
|
||||||
)
|
|
||||||
|
|
||||||
agg_rows = await fail2ban_db_repo.get_ban_event_counts(
|
if source == "archive":
|
||||||
db_path=db_path,
|
if app_db is None:
|
||||||
since=since,
|
raise ValueError("app_db must be provided when source is 'archive'")
|
||||||
origin=origin,
|
|
||||||
)
|
|
||||||
|
|
||||||
companion_rows, _ = await fail2ban_db_repo.get_currently_banned(
|
from app.repositories.history_archive_repo import (
|
||||||
db_path=db_path,
|
get_all_archived_history,
|
||||||
since=since,
|
get_archived_history,
|
||||||
origin=origin,
|
)
|
||||||
limit=_MAX_COMPANION_BANS,
|
|
||||||
offset=0,
|
|
||||||
)
|
|
||||||
|
|
||||||
unique_ips: list[str] = [r.ip for r in agg_rows]
|
all_rows = await get_all_archived_history(
|
||||||
|
db=app_db,
|
||||||
|
since=since,
|
||||||
|
origin=origin,
|
||||||
|
action="ban",
|
||||||
|
)
|
||||||
|
|
||||||
|
total = len(all_rows)
|
||||||
|
|
||||||
|
# companion rows for the table should be most recent
|
||||||
|
companion_rows, _ = await get_archived_history(
|
||||||
|
db=app_db,
|
||||||
|
since=since,
|
||||||
|
origin=origin,
|
||||||
|
action="ban",
|
||||||
|
page=1,
|
||||||
|
page_size=_MAX_COMPANION_BANS,
|
||||||
|
)
|
||||||
|
|
||||||
|
agg_rows = {}
|
||||||
|
for row in all_rows:
|
||||||
|
ip = str(row["ip"])
|
||||||
|
agg_rows[ip] = agg_rows.get(ip, 0) + 1
|
||||||
|
|
||||||
|
unique_ips = list(agg_rows.keys())
|
||||||
|
else:
|
||||||
|
origin_clause, origin_params = _origin_sql_filter(origin)
|
||||||
|
db_path: str = await get_fail2ban_db_path(socket_path)
|
||||||
|
log.info(
|
||||||
|
"ban_service_bans_by_country",
|
||||||
|
db_path=db_path,
|
||||||
|
since=since,
|
||||||
|
range=range_,
|
||||||
|
origin=origin,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Total count and companion rows reuse the same SQL query logic.
|
||||||
|
# Passing limit=0 returns only the total from the count query.
|
||||||
|
_, total = await fail2ban_db_repo.get_currently_banned(
|
||||||
|
db_path=db_path,
|
||||||
|
since=since,
|
||||||
|
origin=origin,
|
||||||
|
limit=0,
|
||||||
|
offset=0,
|
||||||
|
)
|
||||||
|
|
||||||
|
agg_rows = await fail2ban_db_repo.get_ban_event_counts(
|
||||||
|
db_path=db_path,
|
||||||
|
since=since,
|
||||||
|
origin=origin,
|
||||||
|
)
|
||||||
|
|
||||||
|
companion_rows, _ = await fail2ban_db_repo.get_currently_banned(
|
||||||
|
db_path=db_path,
|
||||||
|
since=since,
|
||||||
|
origin=origin,
|
||||||
|
limit=_MAX_COMPANION_BANS,
|
||||||
|
offset=0,
|
||||||
|
)
|
||||||
|
|
||||||
|
unique_ips = [r.ip for r in agg_rows]
|
||||||
geo_map: dict[str, GeoInfo] = {}
|
geo_map: dict[str, GeoInfo] = {}
|
||||||
|
|
||||||
if http_session is not None and unique_ips and geo_cache_lookup is not None:
|
if http_session is not None and unique_ips and geo_cache_lookup is not None:
|
||||||
@@ -371,12 +438,28 @@ async def bans_by_country(
|
|||||||
countries: dict[str, int] = {}
|
countries: dict[str, int] = {}
|
||||||
country_names: dict[str, str] = {}
|
country_names: dict[str, str] = {}
|
||||||
|
|
||||||
for agg_row in agg_rows:
|
if source == "archive":
|
||||||
ip: str = agg_row.ip
|
agg_items = [
|
||||||
|
{
|
||||||
|
"ip": ip,
|
||||||
|
"event_count": count,
|
||||||
|
}
|
||||||
|
for ip, count in agg_rows.items()
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
agg_items = agg_rows
|
||||||
|
|
||||||
|
for agg_row in agg_items:
|
||||||
|
if source == "archive":
|
||||||
|
ip = agg_row["ip"]
|
||||||
|
event_count = agg_row["event_count"]
|
||||||
|
else:
|
||||||
|
ip = agg_row.ip
|
||||||
|
event_count = agg_row.event_count
|
||||||
|
|
||||||
geo = geo_map.get(ip)
|
geo = geo_map.get(ip)
|
||||||
cc: str | None = geo.country_code if geo else None
|
cc: str | None = geo.country_code if geo else None
|
||||||
cn: str | None = geo.country_name if geo else None
|
cn: str | None = geo.country_name if geo else None
|
||||||
event_count: int = agg_row.event_count
|
|
||||||
|
|
||||||
if cc:
|
if cc:
|
||||||
countries[cc] = countries.get(cc, 0) + event_count
|
countries[cc] = countries.get(cc, 0) + event_count
|
||||||
@@ -386,26 +469,38 @@ async def bans_by_country(
|
|||||||
# Build companion table from recent rows (geo already cached from batch step).
|
# Build companion table from recent rows (geo already cached from batch step).
|
||||||
bans: list[DashboardBanItem] = []
|
bans: list[DashboardBanItem] = []
|
||||||
for companion_row in companion_rows:
|
for companion_row in companion_rows:
|
||||||
ip = companion_row.ip
|
if source == "archive":
|
||||||
|
ip = companion_row["ip"]
|
||||||
|
jail = companion_row["jail"]
|
||||||
|
banned_at = ts_to_iso(int(companion_row["timeofban"]))
|
||||||
|
ban_count = int(companion_row["bancount"])
|
||||||
|
service = None
|
||||||
|
else:
|
||||||
|
ip = companion_row.ip
|
||||||
|
jail = companion_row.jail
|
||||||
|
banned_at = ts_to_iso(companion_row.timeofban)
|
||||||
|
ban_count = companion_row.bancount
|
||||||
|
matches, _ = parse_data_json(companion_row.data)
|
||||||
|
service = matches[0] if matches else None
|
||||||
|
|
||||||
geo = geo_map.get(ip)
|
geo = geo_map.get(ip)
|
||||||
cc = geo.country_code if geo else None
|
cc = geo.country_code if geo else None
|
||||||
cn = geo.country_name if geo else None
|
cn = geo.country_name if geo else None
|
||||||
asn: str | None = geo.asn if geo else None
|
asn: str | None = geo.asn if geo else None
|
||||||
org: str | None = geo.org if geo else None
|
org: str | None = geo.org if geo else None
|
||||||
matches, _ = parse_data_json(companion_row.data)
|
|
||||||
|
|
||||||
bans.append(
|
bans.append(
|
||||||
DashboardBanItem(
|
DashboardBanItem(
|
||||||
ip=ip,
|
ip=ip,
|
||||||
jail=companion_row.jail,
|
jail=jail,
|
||||||
banned_at=ts_to_iso(companion_row.timeofban),
|
banned_at=banned_at,
|
||||||
service=matches[0] if matches else None,
|
service=service,
|
||||||
country_code=cc,
|
country_code=cc,
|
||||||
country_name=cn,
|
country_name=cn,
|
||||||
asn=asn,
|
asn=asn,
|
||||||
org=org,
|
org=org,
|
||||||
ban_count=companion_row.bancount,
|
ban_count=ban_count,
|
||||||
origin=_derive_origin(companion_row.jail),
|
origin=_derive_origin(jail),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -426,6 +521,8 @@ async def ban_trend(
|
|||||||
socket_path: str,
|
socket_path: str,
|
||||||
range_: TimeRange,
|
range_: TimeRange,
|
||||||
*,
|
*,
|
||||||
|
source: str = "fail2ban",
|
||||||
|
app_db: aiosqlite.Connection | None = None,
|
||||||
origin: BanOrigin | None = None,
|
origin: BanOrigin | None = None,
|
||||||
) -> BanTrendResponse:
|
) -> BanTrendResponse:
|
||||||
"""Return ban counts aggregated into equal-width time buckets.
|
"""Return ban counts aggregated into equal-width time buckets.
|
||||||
@@ -457,26 +554,58 @@ async def ban_trend(
|
|||||||
since: int = _since_unix(range_)
|
since: int = _since_unix(range_)
|
||||||
bucket_secs: int = BUCKET_SECONDS[range_]
|
bucket_secs: int = BUCKET_SECONDS[range_]
|
||||||
num_buckets: int = bucket_count(range_)
|
num_buckets: int = bucket_count(range_)
|
||||||
origin_clause, origin_params = _origin_sql_filter(origin)
|
|
||||||
|
|
||||||
db_path: str = await get_fail2ban_db_path(socket_path)
|
if source not in ("fail2ban", "archive"):
|
||||||
log.info(
|
raise ValueError(f"Unsupported source: {source!r}")
|
||||||
"ban_service_ban_trend",
|
|
||||||
db_path=db_path,
|
|
||||||
since=since,
|
|
||||||
range=range_,
|
|
||||||
origin=origin,
|
|
||||||
bucket_secs=bucket_secs,
|
|
||||||
num_buckets=num_buckets,
|
|
||||||
)
|
|
||||||
|
|
||||||
counts = await fail2ban_db_repo.get_ban_counts_by_bucket(
|
if source == "archive":
|
||||||
db_path=db_path,
|
if app_db is None:
|
||||||
since=since,
|
raise ValueError("app_db must be provided when source is 'archive'")
|
||||||
bucket_secs=bucket_secs,
|
|
||||||
num_buckets=num_buckets,
|
from app.repositories.history_archive_repo import get_all_archived_history
|
||||||
origin=origin,
|
|
||||||
)
|
all_rows = await get_all_archived_history(
|
||||||
|
db=app_db,
|
||||||
|
since=since,
|
||||||
|
origin=origin,
|
||||||
|
action="ban",
|
||||||
|
)
|
||||||
|
|
||||||
|
counts: list[int] = [0] * num_buckets
|
||||||
|
for row in all_rows:
|
||||||
|
timeofban = int(row["timeofban"])
|
||||||
|
bucket_index = int((timeofban - since) / bucket_secs)
|
||||||
|
if 0 <= bucket_index < num_buckets:
|
||||||
|
counts[bucket_index] += 1
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
"ban_service_ban_trend",
|
||||||
|
source=source,
|
||||||
|
since=since,
|
||||||
|
range=range_,
|
||||||
|
origin=origin,
|
||||||
|
bucket_secs=bucket_secs,
|
||||||
|
num_buckets=num_buckets,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
db_path: str = await get_fail2ban_db_path(socket_path)
|
||||||
|
log.info(
|
||||||
|
"ban_service_ban_trend",
|
||||||
|
db_path=db_path,
|
||||||
|
since=since,
|
||||||
|
range=range_,
|
||||||
|
origin=origin,
|
||||||
|
bucket_secs=bucket_secs,
|
||||||
|
num_buckets=num_buckets,
|
||||||
|
)
|
||||||
|
|
||||||
|
counts = await fail2ban_db_repo.get_ban_counts_by_bucket(
|
||||||
|
db_path=db_path,
|
||||||
|
since=since,
|
||||||
|
bucket_secs=bucket_secs,
|
||||||
|
num_buckets=num_buckets,
|
||||||
|
origin=origin,
|
||||||
|
)
|
||||||
|
|
||||||
buckets: list[BanTrendBucket] = [
|
buckets: list[BanTrendBucket] = [
|
||||||
BanTrendBucket(
|
BanTrendBucket(
|
||||||
@@ -501,6 +630,8 @@ async def bans_by_jail(
|
|||||||
socket_path: str,
|
socket_path: str,
|
||||||
range_: TimeRange,
|
range_: TimeRange,
|
||||||
*,
|
*,
|
||||||
|
source: str = "fail2ban",
|
||||||
|
app_db: aiosqlite.Connection | None = None,
|
||||||
origin: BanOrigin | None = None,
|
origin: BanOrigin | None = None,
|
||||||
) -> BansByJailResponse:
|
) -> BansByJailResponse:
|
||||||
"""Return ban counts aggregated per jail for the selected time window.
|
"""Return ban counts aggregated per jail for the selected time window.
|
||||||
@@ -522,38 +653,75 @@ async def bans_by_jail(
|
|||||||
sorted descending and the total ban count.
|
sorted descending and the total ban count.
|
||||||
"""
|
"""
|
||||||
since: int = _since_unix(range_)
|
since: int = _since_unix(range_)
|
||||||
origin_clause, origin_params = _origin_sql_filter(origin)
|
|
||||||
|
|
||||||
db_path: str = await get_fail2ban_db_path(socket_path)
|
if source not in ("fail2ban", "archive"):
|
||||||
log.debug(
|
raise ValueError(f"Unsupported source: {source!r}")
|
||||||
"ban_service_bans_by_jail",
|
|
||||||
db_path=db_path,
|
|
||||||
since=since,
|
|
||||||
since_iso=ts_to_iso(since),
|
|
||||||
range=range_,
|
|
||||||
origin=origin,
|
|
||||||
)
|
|
||||||
|
|
||||||
total, jail_counts = await fail2ban_db_repo.get_bans_by_jail(
|
if source == "archive":
|
||||||
db_path=db_path,
|
if app_db is None:
|
||||||
since=since,
|
raise ValueError("app_db must be provided when source is 'archive'")
|
||||||
origin=origin,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Diagnostic guard: if zero results were returned, check whether the table
|
from app.repositories.history_archive_repo import get_all_archived_history
|
||||||
# has *any* rows and log a warning with min/max timeofban so operators can
|
|
||||||
# diagnose timezone or filter mismatches from logs.
|
all_rows = await get_all_archived_history(
|
||||||
if total == 0:
|
db=app_db,
|
||||||
table_row_count, min_timeofban, max_timeofban = await fail2ban_db_repo.get_bans_table_summary(db_path)
|
since=since,
|
||||||
if table_row_count > 0:
|
origin=origin,
|
||||||
log.warning(
|
action="ban",
|
||||||
"ban_service_bans_by_jail_empty_despite_data",
|
)
|
||||||
table_row_count=table_row_count,
|
|
||||||
min_timeofban=min_timeofban,
|
jail_counter: dict[str, int] = {}
|
||||||
max_timeofban=max_timeofban,
|
for row in all_rows:
|
||||||
since=since,
|
jail_name = str(row["jail"])
|
||||||
range=range_,
|
jail_counter[jail_name] = jail_counter.get(jail_name, 0) + 1
|
||||||
)
|
|
||||||
|
total = sum(jail_counter.values())
|
||||||
|
jail_counts = [
|
||||||
|
JailBanCountModel(jail=jail_name, count=count)
|
||||||
|
for jail_name, count in sorted(jail_counter.items(), key=lambda x: x[1], reverse=True)
|
||||||
|
]
|
||||||
|
|
||||||
|
log.debug(
|
||||||
|
"ban_service_bans_by_jail",
|
||||||
|
source=source,
|
||||||
|
since=since,
|
||||||
|
since_iso=ts_to_iso(since),
|
||||||
|
range=range_,
|
||||||
|
origin=origin,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
origin_clause, origin_params = _origin_sql_filter(origin)
|
||||||
|
|
||||||
|
db_path: str = await get_fail2ban_db_path(socket_path)
|
||||||
|
log.debug(
|
||||||
|
"ban_service_bans_by_jail",
|
||||||
|
db_path=db_path,
|
||||||
|
since=since,
|
||||||
|
since_iso=ts_to_iso(since),
|
||||||
|
range=range_,
|
||||||
|
origin=origin,
|
||||||
|
)
|
||||||
|
|
||||||
|
total, jail_counts = await fail2ban_db_repo.get_bans_by_jail(
|
||||||
|
db_path=db_path,
|
||||||
|
since=since,
|
||||||
|
origin=origin,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Diagnostic guard: if zero results were returned, check whether the table
|
||||||
|
# has *any* rows and log a warning with min/max timeofban so operators can
|
||||||
|
# diagnose timezone or filter mismatches from logs.
|
||||||
|
if total == 0:
|
||||||
|
table_row_count, min_timeofban, max_timeofban = await fail2ban_db_repo.get_bans_table_summary(db_path)
|
||||||
|
if table_row_count > 0:
|
||||||
|
log.warning(
|
||||||
|
"ban_service_bans_by_jail_empty_despite_data",
|
||||||
|
table_row_count=table_row_count,
|
||||||
|
min_timeofban=min_timeofban,
|
||||||
|
max_timeofban=max_timeofban,
|
||||||
|
since=since,
|
||||||
|
range=range_,
|
||||||
|
)
|
||||||
|
|
||||||
log.debug(
|
log.debug(
|
||||||
"ban_service_bans_by_jail_result",
|
"ban_service_bans_by_jail_result",
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ from __future__ import annotations
|
|||||||
import asyncio
|
import asyncio
|
||||||
import contextlib
|
import contextlib
|
||||||
import re
|
import re
|
||||||
from collections.abc import Awaitable, Callable
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import TYPE_CHECKING, TypeVar, cast
|
from typing import TYPE_CHECKING, TypeVar, cast
|
||||||
|
|
||||||
@@ -24,8 +23,12 @@ import structlog
|
|||||||
from app.utils.fail2ban_client import Fail2BanCommand, Fail2BanResponse, Fail2BanToken
|
from app.utils.fail2ban_client import Fail2BanCommand, Fail2BanResponse, Fail2BanToken
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Awaitable, Callable
|
||||||
|
|
||||||
import aiosqlite
|
import aiosqlite
|
||||||
|
|
||||||
|
from app import __version__
|
||||||
|
from app.exceptions import ConfigOperationError, ConfigValidationError, JailNotFoundError
|
||||||
from app.models.config import (
|
from app.models.config import (
|
||||||
AddLogPathRequest,
|
AddLogPathRequest,
|
||||||
BantimeEscalation,
|
BantimeEscalation,
|
||||||
@@ -44,11 +47,13 @@ from app.models.config import (
|
|||||||
RegexTestResponse,
|
RegexTestResponse,
|
||||||
ServiceStatusResponse,
|
ServiceStatusResponse,
|
||||||
)
|
)
|
||||||
from app.exceptions import ConfigOperationError, ConfigValidationError, JailNotFoundError
|
|
||||||
from app.utils.fail2ban_client import Fail2BanClient
|
from app.utils.fail2ban_client import Fail2BanClient
|
||||||
from app.utils.log_utils import preview_log as util_preview_log, test_regex as util_test_regex
|
from app.utils.log_utils import preview_log as util_preview_log
|
||||||
|
from app.utils.log_utils import test_regex as util_test_regex
|
||||||
from app.utils.setup_utils import (
|
from app.utils.setup_utils import (
|
||||||
get_map_color_thresholds as util_get_map_color_thresholds,
|
get_map_color_thresholds as util_get_map_color_thresholds,
|
||||||
|
)
|
||||||
|
from app.utils.setup_utils import (
|
||||||
set_map_color_thresholds as util_set_map_color_thresholds,
|
set_map_color_thresholds as util_set_map_color_thresholds,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -346,8 +351,8 @@ async def update_jail_config(
|
|||||||
await _set("datepattern", update.date_pattern)
|
await _set("datepattern", update.date_pattern)
|
||||||
if update.dns_mode is not None:
|
if update.dns_mode is not None:
|
||||||
await _set("usedns", update.dns_mode)
|
await _set("usedns", update.dns_mode)
|
||||||
if update.backend is not None:
|
# backend is managed by fail2ban and cannot be changed at runtime by API.
|
||||||
await _set("backend", update.backend)
|
# This field is therefore ignored during updates.
|
||||||
if update.log_encoding is not None:
|
if update.log_encoding is not None:
|
||||||
await _set("logencoding", update.log_encoding)
|
await _set("logencoding", update.log_encoding)
|
||||||
if update.prefregex is not None:
|
if update.prefregex is not None:
|
||||||
@@ -814,7 +819,7 @@ async def get_service_status(
|
|||||||
|
|
||||||
return ServiceStatusResponse(
|
return ServiceStatusResponse(
|
||||||
online=server_status.online,
|
online=server_status.online,
|
||||||
version=server_status.version,
|
version=__version__,
|
||||||
jail_count=server_status.active_jails,
|
jail_count=server_status.active_jails,
|
||||||
total_bans=server_status.total_bans,
|
total_bans=server_status.total_bans,
|
||||||
total_failures=server_status.total_failures,
|
total_failures=server_status.total_failures,
|
||||||
|
|||||||
@@ -17,16 +17,21 @@ from pathlib import Path
|
|||||||
|
|
||||||
import structlog
|
import structlog
|
||||||
|
|
||||||
|
from app.exceptions import FilterInvalidRegexError
|
||||||
from app.models.config import (
|
from app.models.config import (
|
||||||
|
AssignFilterRequest,
|
||||||
FilterConfig,
|
FilterConfig,
|
||||||
FilterConfigUpdate,
|
FilterConfigUpdate,
|
||||||
FilterCreateRequest,
|
FilterCreateRequest,
|
||||||
FilterListResponse,
|
FilterListResponse,
|
||||||
FilterUpdateRequest,
|
FilterUpdateRequest,
|
||||||
AssignFilterRequest,
|
|
||||||
)
|
)
|
||||||
from app.exceptions import FilterInvalidRegexError, JailNotFoundError
|
from app.services.config_file_service import _TRUE_VALUES, ConfigWriteError, JailNotFoundInConfigError
|
||||||
from app.utils import conffile_parser
|
from app.utils import conffile_parser
|
||||||
|
from app.utils.config_file_utils import (
|
||||||
|
_get_active_jail_names,
|
||||||
|
_parse_jails_sync,
|
||||||
|
)
|
||||||
from app.utils.jail_utils import reload_jails
|
from app.utils.jail_utils import reload_jails
|
||||||
|
|
||||||
log: structlog.stdlib.BoundLogger = structlog.get_logger()
|
log: structlog.stdlib.BoundLogger = structlog.get_logger()
|
||||||
@@ -90,6 +95,7 @@ class JailNameError(Exception):
|
|||||||
"""Raised when a jail name contains invalid characters."""
|
"""Raised when a jail name contains invalid characters."""
|
||||||
|
|
||||||
|
|
||||||
|
_SAFE_FILTER_NAME_RE: re.Pattern[str] = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
||||||
_SAFE_JAIL_NAME_RE: re.Pattern[str] = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
_SAFE_JAIL_NAME_RE: re.Pattern[str] = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -16,9 +16,11 @@ from typing import TYPE_CHECKING
|
|||||||
import structlog
|
import structlog
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
|
import aiosqlite
|
||||||
|
|
||||||
from app.models.geo import GeoEnricher
|
from app.models.geo import GeoEnricher
|
||||||
|
|
||||||
from app.models.ban import TIME_RANGE_SECONDS, TimeRange
|
from app.models.ban import TIME_RANGE_SECONDS, BanOrigin, TimeRange
|
||||||
from app.models.history import (
|
from app.models.history import (
|
||||||
HistoryBanItem,
|
HistoryBanItem,
|
||||||
HistoryListResponse,
|
HistoryListResponse,
|
||||||
@@ -62,9 +64,12 @@ async def list_history(
|
|||||||
range_: TimeRange | None = None,
|
range_: TimeRange | None = None,
|
||||||
jail: str | None = None,
|
jail: str | None = None,
|
||||||
ip_filter: str | None = None,
|
ip_filter: str | None = None,
|
||||||
|
origin: BanOrigin | None = None,
|
||||||
|
source: str = "fail2ban",
|
||||||
page: int = 1,
|
page: int = 1,
|
||||||
page_size: int = _DEFAULT_PAGE_SIZE,
|
page_size: int = _DEFAULT_PAGE_SIZE,
|
||||||
geo_enricher: GeoEnricher | None = None,
|
geo_enricher: GeoEnricher | None = None,
|
||||||
|
db: aiosqlite.Connection | None = None,
|
||||||
) -> HistoryListResponse:
|
) -> HistoryListResponse:
|
||||||
"""Return a paginated list of historical ban records with optional filters.
|
"""Return a paginated list of historical ban records with optional filters.
|
||||||
|
|
||||||
@@ -103,54 +108,111 @@ async def list_history(
|
|||||||
page=page,
|
page=page,
|
||||||
)
|
)
|
||||||
|
|
||||||
rows, total = await fail2ban_db_repo.get_history_page(
|
|
||||||
db_path=db_path,
|
|
||||||
since=since,
|
|
||||||
jail=jail,
|
|
||||||
ip_filter=ip_filter,
|
|
||||||
page=page,
|
|
||||||
page_size=effective_page_size,
|
|
||||||
)
|
|
||||||
|
|
||||||
items: list[HistoryBanItem] = []
|
items: list[HistoryBanItem] = []
|
||||||
for row in rows:
|
total: int
|
||||||
jail_name: str = row.jail
|
|
||||||
ip: str = row.ip
|
|
||||||
banned_at: str = ts_to_iso(row.timeofban)
|
|
||||||
ban_count: int = row.bancount
|
|
||||||
matches, failures = parse_data_json(row.data)
|
|
||||||
|
|
||||||
country_code: str | None = None
|
if source == "archive":
|
||||||
country_name: str | None = None
|
if db is None:
|
||||||
asn: str | None = None
|
raise ValueError("db must be provided when source is 'archive'")
|
||||||
org: str | None = None
|
|
||||||
|
|
||||||
if geo_enricher is not None:
|
from app.repositories.history_archive_repo import get_archived_history
|
||||||
try:
|
|
||||||
geo = await geo_enricher(ip)
|
|
||||||
if geo is not None:
|
|
||||||
country_code = geo.country_code
|
|
||||||
country_name = geo.country_name
|
|
||||||
asn = geo.asn
|
|
||||||
org = geo.org
|
|
||||||
except Exception: # noqa: BLE001
|
|
||||||
log.warning("history_service_geo_lookup_failed", ip=ip)
|
|
||||||
|
|
||||||
items.append(
|
archived_rows, total = await get_archived_history(
|
||||||
HistoryBanItem(
|
db=db,
|
||||||
ip=ip,
|
since=since,
|
||||||
jail=jail_name,
|
jail=jail,
|
||||||
banned_at=banned_at,
|
ip_filter=ip_filter,
|
||||||
ban_count=ban_count,
|
page=page,
|
||||||
failures=failures,
|
page_size=effective_page_size,
|
||||||
matches=matches,
|
|
||||||
country_code=country_code,
|
|
||||||
country_name=country_name,
|
|
||||||
asn=asn,
|
|
||||||
org=org,
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
for row in archived_rows:
|
||||||
|
jail_name = row["jail"]
|
||||||
|
ip = row["ip"]
|
||||||
|
banned_at = ts_to_iso(int(row["timeofban"]))
|
||||||
|
ban_count = int(row["bancount"])
|
||||||
|
matches, failures = parse_data_json(row["data"])
|
||||||
|
# archive records may include actions; we treat all as history
|
||||||
|
|
||||||
|
country_code = None
|
||||||
|
country_name = None
|
||||||
|
asn = None
|
||||||
|
org = None
|
||||||
|
|
||||||
|
if geo_enricher is not None:
|
||||||
|
try:
|
||||||
|
geo = await geo_enricher(ip)
|
||||||
|
if geo is not None:
|
||||||
|
country_code = geo.country_code
|
||||||
|
country_name = geo.country_name
|
||||||
|
asn = geo.asn
|
||||||
|
org = geo.org
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
log.warning("history_service_geo_lookup_failed", ip=ip)
|
||||||
|
|
||||||
|
items.append(
|
||||||
|
HistoryBanItem(
|
||||||
|
ip=ip,
|
||||||
|
jail=jail_name,
|
||||||
|
banned_at=banned_at,
|
||||||
|
ban_count=ban_count,
|
||||||
|
failures=failures,
|
||||||
|
matches=matches,
|
||||||
|
country_code=country_code,
|
||||||
|
country_name=country_name,
|
||||||
|
asn=asn,
|
||||||
|
org=org,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
rows, total = await fail2ban_db_repo.get_history_page(
|
||||||
|
db_path=db_path,
|
||||||
|
since=since,
|
||||||
|
jail=jail,
|
||||||
|
ip_filter=ip_filter,
|
||||||
|
origin=origin,
|
||||||
|
page=page,
|
||||||
|
page_size=effective_page_size,
|
||||||
|
)
|
||||||
|
|
||||||
|
for row in rows:
|
||||||
|
jail_name: str = row.jail
|
||||||
|
ip: str = row.ip
|
||||||
|
banned_at: str = ts_to_iso(row.timeofban)
|
||||||
|
ban_count: int = row.bancount
|
||||||
|
matches, failures = parse_data_json(row.data)
|
||||||
|
|
||||||
|
country_code: str | None = None
|
||||||
|
country_name: str | None = None
|
||||||
|
asn: str | None = None
|
||||||
|
org: str | None = None
|
||||||
|
|
||||||
|
if geo_enricher is not None:
|
||||||
|
try:
|
||||||
|
geo = await geo_enricher(ip)
|
||||||
|
if geo is not None:
|
||||||
|
country_code = geo.country_code
|
||||||
|
country_name = geo.country_name
|
||||||
|
asn = geo.asn
|
||||||
|
org = geo.org
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
log.warning("history_service_geo_lookup_failed", ip=ip)
|
||||||
|
|
||||||
|
items.append(
|
||||||
|
HistoryBanItem(
|
||||||
|
ip=ip,
|
||||||
|
jail=jail_name,
|
||||||
|
banned_at=banned_at,
|
||||||
|
ban_count=ban_count,
|
||||||
|
failures=failures,
|
||||||
|
matches=matches,
|
||||||
|
country_code=country_code,
|
||||||
|
country_name=country_name,
|
||||||
|
asn=asn,
|
||||||
|
org=org,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
return HistoryListResponse(
|
return HistoryListResponse(
|
||||||
items=items,
|
items=items,
|
||||||
total=total,
|
total=total,
|
||||||
|
|||||||
@@ -26,22 +26,17 @@ from app.models.config import (
|
|||||||
InactiveJail,
|
InactiveJail,
|
||||||
InactiveJailListResponse,
|
InactiveJailListResponse,
|
||||||
JailActivationResponse,
|
JailActivationResponse,
|
||||||
JailValidationIssue,
|
|
||||||
JailValidationResult,
|
JailValidationResult,
|
||||||
RollbackResponse,
|
RollbackResponse,
|
||||||
)
|
)
|
||||||
from app.utils.config_file_utils import (
|
from app.utils.config_file_utils import (
|
||||||
_build_inactive_jail,
|
_build_inactive_jail,
|
||||||
_ordered_config_files,
|
_get_active_jail_names,
|
||||||
_parse_jails_sync,
|
_parse_jails_sync,
|
||||||
_validate_jail_config_sync,
|
_validate_jail_config_sync,
|
||||||
)
|
)
|
||||||
|
from app.utils.fail2ban_client import Fail2BanClient
|
||||||
from app.utils.jail_utils import reload_jails
|
from app.utils.jail_utils import reload_jails
|
||||||
from app.utils.fail2ban_client import (
|
|
||||||
Fail2BanClient,
|
|
||||||
Fail2BanConnectionError,
|
|
||||||
Fail2BanResponse,
|
|
||||||
)
|
|
||||||
|
|
||||||
log: structlog.stdlib.BoundLogger = structlog.get_logger()
|
log: structlog.stdlib.BoundLogger = structlog.get_logger()
|
||||||
|
|
||||||
|
|||||||
@@ -160,8 +160,12 @@ async def get_settings(socket_path: str) -> ServerSettingsResponse:
|
|||||||
db_max_matches=db_max_matches,
|
db_max_matches=db_max_matches,
|
||||||
)
|
)
|
||||||
|
|
||||||
log.info("server_settings_fetched")
|
warnings: dict[str, bool] = {
|
||||||
return ServerSettingsResponse(settings=settings)
|
"db_purge_age_too_low": db_purge_age < 86400,
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("server_settings_fetched", db_purge_age=db_purge_age, warnings=warnings)
|
||||||
|
return ServerSettingsResponse(settings=settings, warnings=warnings)
|
||||||
|
|
||||||
|
|
||||||
async def update_settings(socket_path: str, update: ServerSettingsUpdate) -> None:
|
async def update_settings(socket_path: str, update: ServerSettingsUpdate) -> None:
|
||||||
|
|||||||
109
backend/app/tasks/history_sync.py
Normal file
109
backend/app/tasks/history_sync.py
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
"""History sync background task.
|
||||||
|
|
||||||
|
Periodically copies new records from the fail2ban sqlite database into the
|
||||||
|
BanGUI application archive table to prevent gaps when fail2ban purges old rows.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
import structlog
|
||||||
|
|
||||||
|
from app.repositories import fail2ban_db_repo
|
||||||
|
from app.utils.fail2ban_db_utils import get_fail2ban_db_path
|
||||||
|
|
||||||
|
if TYPE_CHECKING: # pragma: no cover
|
||||||
|
from fastapi import FastAPI
|
||||||
|
|
||||||
|
log: structlog.stdlib.BoundLogger = structlog.get_logger()
|
||||||
|
|
||||||
|
#: Stable APScheduler job id.
|
||||||
|
JOB_ID: str = "history_sync"
|
||||||
|
|
||||||
|
#: Interval in seconds between sync runs.
|
||||||
|
HISTORY_SYNC_INTERVAL: int = 300
|
||||||
|
|
||||||
|
#: Backfill window when archive is empty (seconds).
|
||||||
|
BACKFILL_WINDOW: int = 7 * 86400
|
||||||
|
|
||||||
|
|
||||||
|
async def _get_last_archive_ts(db) -> int | None:
|
||||||
|
async with db.execute("SELECT MAX(timeofban) FROM history_archive") as cur:
|
||||||
|
row = await cur.fetchone()
|
||||||
|
if row is None or row[0] is None:
|
||||||
|
return None
|
||||||
|
return int(row[0])
|
||||||
|
|
||||||
|
|
||||||
|
async def _run_sync(app: FastAPI) -> None:
|
||||||
|
db = app.state.db
|
||||||
|
socket_path: str = app.state.settings.fail2ban_socket
|
||||||
|
|
||||||
|
try:
|
||||||
|
last_ts = await _get_last_archive_ts(db)
|
||||||
|
now_ts = int(datetime.datetime.now(datetime.UTC).timestamp())
|
||||||
|
|
||||||
|
if last_ts is None:
|
||||||
|
last_ts = now_ts - BACKFILL_WINDOW
|
||||||
|
log.info("history_sync_backfill", window_seconds=BACKFILL_WINDOW)
|
||||||
|
|
||||||
|
per_page = 500
|
||||||
|
next_since = last_ts
|
||||||
|
total_synced = 0
|
||||||
|
|
||||||
|
while True:
|
||||||
|
fail2ban_db_path = await get_fail2ban_db_path(socket_path)
|
||||||
|
rows, total = await fail2ban_db_repo.get_history_page(
|
||||||
|
db_path=fail2ban_db_path,
|
||||||
|
since=next_since,
|
||||||
|
page=1,
|
||||||
|
page_size=per_page,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not rows:
|
||||||
|
break
|
||||||
|
|
||||||
|
from app.repositories.history_archive_repo import archive_ban_event
|
||||||
|
|
||||||
|
for row in rows:
|
||||||
|
await archive_ban_event(
|
||||||
|
db=db,
|
||||||
|
jail=row.jail,
|
||||||
|
ip=row.ip,
|
||||||
|
timeofban=row.timeofban,
|
||||||
|
bancount=row.bancount,
|
||||||
|
data=row.data,
|
||||||
|
action="ban",
|
||||||
|
)
|
||||||
|
total_synced += 1
|
||||||
|
|
||||||
|
# Continue where we left off by max timeofban + 1.
|
||||||
|
max_time = max(row.timeofban for row in rows)
|
||||||
|
next_since = max_time + 1
|
||||||
|
|
||||||
|
if len(rows) < per_page:
|
||||||
|
break
|
||||||
|
|
||||||
|
log.info("history_sync_complete", synced=total_synced)
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
log.exception("history_sync_failed")
|
||||||
|
|
||||||
|
|
||||||
|
def register(app: FastAPI) -> None:
|
||||||
|
"""Register the history sync periodic job.
|
||||||
|
|
||||||
|
Should be called after scheduler startup, from the lifespan handler.
|
||||||
|
"""
|
||||||
|
app.state.scheduler.add_job(
|
||||||
|
_run_sync,
|
||||||
|
trigger="interval",
|
||||||
|
seconds=HISTORY_SYNC_INTERVAL,
|
||||||
|
kwargs={"app": app},
|
||||||
|
id=JOB_ID,
|
||||||
|
replace_existing=True,
|
||||||
|
next_run_time=datetime.datetime.now(tz=datetime.UTC),
|
||||||
|
)
|
||||||
|
log.info("history_sync_scheduled", interval_seconds=HISTORY_SYNC_INTERVAL)
|
||||||
@@ -49,7 +49,7 @@ logpath = /dev/null
|
|||||||
backend = auto
|
backend = auto
|
||||||
maxretry = 1
|
maxretry = 1
|
||||||
findtime = 1d
|
findtime = 1d
|
||||||
bantime = 1w
|
bantime = 86400
|
||||||
ignoreip = 127.0.0.0/8 ::1 172.16.0.0/12
|
ignoreip = 127.0.0.0/8 ::1 172.16.0.0/12
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "bangui-backend"
|
name = "bangui-backend"
|
||||||
version = "0.9.0"
|
version = "0.9.14"
|
||||||
description = "BanGUI backend — fail2ban web management interface"
|
description = "BanGUI backend — fail2ban web management interface"
|
||||||
requires-python = ">=3.12"
|
requires-python = ">=3.12"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
|||||||
276
backend/tests/test_regression_500s.py
Normal file
276
backend/tests/test_regression_500s.py
Normal file
@@ -0,0 +1,276 @@
|
|||||||
|
"""Regression tests for the four 500-error bugs discovered on 2026-03-22.
|
||||||
|
|
||||||
|
Each test targets the exact code path that caused a 500 Internal Server Error.
|
||||||
|
These tests call the **real** service/repository functions (not the router)
|
||||||
|
so they fail even if the route layer is mocked in router-level tests.
|
||||||
|
|
||||||
|
Bugs covered:
|
||||||
|
1. ``list_history`` rejected the ``origin`` keyword argument (TypeError).
|
||||||
|
2. ``jail_config_service`` used ``_get_active_jail_names`` without importing it.
|
||||||
|
3. ``filter_config_service`` used ``_parse_jails_sync`` / ``_get_active_jail_names``
|
||||||
|
without importing them.
|
||||||
|
4. ``config_service.get_service_status`` omitted the required ``bangui_version``
|
||||||
|
field from the ``ServiceStatusResponse`` constructor (Pydantic ValidationError).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import inspect
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
from unittest.mock import AsyncMock, patch
|
||||||
|
|
||||||
|
import aiosqlite
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
# ── Bug 1 ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestHistoryOriginParameter:
|
||||||
|
"""Bug 1: ``origin`` parameter must be threaded through service → repo."""
|
||||||
|
|
||||||
|
# -- Service layer --
|
||||||
|
|
||||||
|
async def test_list_history_accepts_origin_kwarg(self) -> None:
|
||||||
|
"""``history_service.list_history()`` must accept an ``origin`` keyword."""
|
||||||
|
from app.services import history_service
|
||||||
|
|
||||||
|
sig = inspect.signature(history_service.list_history)
|
||||||
|
assert "origin" in sig.parameters, (
|
||||||
|
"list_history() is missing the 'origin' parameter — "
|
||||||
|
"the router passes origin=… which would cause a TypeError"
|
||||||
|
)
|
||||||
|
|
||||||
|
async def test_list_history_forwards_origin_to_repo(
|
||||||
|
self, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""``list_history(origin='blocklist')`` must forward origin to the DB repo."""
|
||||||
|
from app.services import history_service
|
||||||
|
|
||||||
|
db_path = str(tmp_path / "f2b.db")
|
||||||
|
async with aiosqlite.connect(db_path) as db:
|
||||||
|
await db.execute(
|
||||||
|
"CREATE TABLE jails (name TEXT, enabled INTEGER DEFAULT 1)"
|
||||||
|
)
|
||||||
|
await db.execute(
|
||||||
|
"CREATE TABLE bans "
|
||||||
|
"(jail TEXT, ip TEXT, timeofban INTEGER, bantime INTEGER, "
|
||||||
|
"bancount INTEGER DEFAULT 1, data JSON)"
|
||||||
|
)
|
||||||
|
await db.execute(
|
||||||
|
"INSERT INTO bans VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
("blocklist-import", "10.0.0.1", int(time.time()), 3600, 1, "{}"),
|
||||||
|
)
|
||||||
|
await db.execute(
|
||||||
|
"INSERT INTO bans VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
("sshd", "10.0.0.2", int(time.time()), 3600, 1, "{}"),
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"app.services.history_service.get_fail2ban_db_path",
|
||||||
|
new=AsyncMock(return_value=db_path),
|
||||||
|
):
|
||||||
|
result = await history_service.list_history(
|
||||||
|
"fake_socket", origin="blocklist"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert all(
|
||||||
|
item.jail == "blocklist-import" for item in result.items
|
||||||
|
), "origin='blocklist' must filter to blocklist-import jail only"
|
||||||
|
|
||||||
|
# -- Repository layer --
|
||||||
|
|
||||||
|
async def test_get_history_page_accepts_origin_kwarg(self) -> None:
|
||||||
|
"""``fail2ban_db_repo.get_history_page()`` must accept ``origin``."""
|
||||||
|
from app.repositories import fail2ban_db_repo
|
||||||
|
|
||||||
|
sig = inspect.signature(fail2ban_db_repo.get_history_page)
|
||||||
|
assert "origin" in sig.parameters, (
|
||||||
|
"get_history_page() is missing the 'origin' parameter"
|
||||||
|
)
|
||||||
|
|
||||||
|
async def test_get_history_page_filters_by_origin(
|
||||||
|
self, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""``get_history_page(origin='selfblock')`` excludes blocklist-import."""
|
||||||
|
from app.repositories import fail2ban_db_repo
|
||||||
|
|
||||||
|
db_path = str(tmp_path / "f2b.db")
|
||||||
|
async with aiosqlite.connect(db_path) as db:
|
||||||
|
await db.execute(
|
||||||
|
"CREATE TABLE bans "
|
||||||
|
"(jail TEXT, ip TEXT, timeofban INTEGER, bancount INTEGER, data TEXT)"
|
||||||
|
)
|
||||||
|
await db.executemany(
|
||||||
|
"INSERT INTO bans VALUES (?, ?, ?, ?, ?)",
|
||||||
|
[
|
||||||
|
("blocklist-import", "10.0.0.1", 100, 1, "{}"),
|
||||||
|
("sshd", "10.0.0.2", 200, 1, "{}"),
|
||||||
|
("sshd", "10.0.0.3", 300, 1, "{}"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
rows, total = await fail2ban_db_repo.get_history_page(
|
||||||
|
db_path=db_path, origin="selfblock"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert total == 2
|
||||||
|
assert all(r.jail != "blocklist-import" for r in rows)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Bug 2 ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestJailConfigImports:
|
||||||
|
"""Bug 2: ``jail_config_service`` must import ``_get_active_jail_names``."""
|
||||||
|
|
||||||
|
async def test_get_active_jail_names_is_importable(self) -> None:
|
||||||
|
"""The module must successfully import ``_get_active_jail_names``."""
|
||||||
|
import app.services.jail_config_service as mod
|
||||||
|
|
||||||
|
assert hasattr(mod, "_get_active_jail_names") or callable(
|
||||||
|
getattr(mod, "_get_active_jail_names", None)
|
||||||
|
), (
|
||||||
|
"_get_active_jail_names is not available in jail_config_service — "
|
||||||
|
"any call site will raise NameError → 500"
|
||||||
|
)
|
||||||
|
|
||||||
|
async def test_list_inactive_jails_does_not_raise_name_error(
|
||||||
|
self, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""``list_inactive_jails`` must not crash with NameError."""
|
||||||
|
from app.services import jail_config_service
|
||||||
|
|
||||||
|
config_dir = str(tmp_path / "fail2ban")
|
||||||
|
Path(config_dir).mkdir()
|
||||||
|
(Path(config_dir) / "jail.conf").write_text("[DEFAULT]\n")
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"app.services.jail_config_service._get_active_jail_names",
|
||||||
|
new=AsyncMock(return_value=set()),
|
||||||
|
):
|
||||||
|
result = await jail_config_service.list_inactive_jails(
|
||||||
|
config_dir, "/fake/socket"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.total >= 0
|
||||||
|
|
||||||
|
|
||||||
|
# ── Bug 3 ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestFilterConfigImports:
|
||||||
|
"""Bug 3: ``filter_config_service`` must import ``_parse_jails_sync``
|
||||||
|
and ``_get_active_jail_names``."""
|
||||||
|
|
||||||
|
async def test_parse_jails_sync_is_available(self) -> None:
|
||||||
|
"""``_parse_jails_sync`` must be resolvable at module scope."""
|
||||||
|
import app.services.filter_config_service as mod
|
||||||
|
|
||||||
|
assert hasattr(mod, "_parse_jails_sync"), (
|
||||||
|
"_parse_jails_sync is not available in filter_config_service — "
|
||||||
|
"list_filters() will raise NameError → 500"
|
||||||
|
)
|
||||||
|
|
||||||
|
async def test_get_active_jail_names_is_available(self) -> None:
|
||||||
|
"""``_get_active_jail_names`` must be resolvable at module scope."""
|
||||||
|
import app.services.filter_config_service as mod
|
||||||
|
|
||||||
|
assert hasattr(mod, "_get_active_jail_names"), (
|
||||||
|
"_get_active_jail_names is not available in filter_config_service — "
|
||||||
|
"list_filters() will raise NameError → 500"
|
||||||
|
)
|
||||||
|
|
||||||
|
async def test_list_filters_does_not_raise_name_error(
|
||||||
|
self, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
"""``list_filters`` must not crash with NameError."""
|
||||||
|
from app.services import filter_config_service
|
||||||
|
|
||||||
|
config_dir = str(tmp_path / "fail2ban")
|
||||||
|
filter_d = Path(config_dir) / "filter.d"
|
||||||
|
filter_d.mkdir(parents=True)
|
||||||
|
|
||||||
|
# Create a minimal filter file so _parse_filters_sync has something to scan.
|
||||||
|
(filter_d / "sshd.conf").write_text(
|
||||||
|
"[Definition]\nfailregex = ^Failed password\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
with (
|
||||||
|
patch(
|
||||||
|
"app.services.filter_config_service._parse_jails_sync",
|
||||||
|
return_value=({}, {}),
|
||||||
|
),
|
||||||
|
patch(
|
||||||
|
"app.services.filter_config_service._get_active_jail_names",
|
||||||
|
new=AsyncMock(return_value=set()),
|
||||||
|
),
|
||||||
|
):
|
||||||
|
result = await filter_config_service.list_filters(
|
||||||
|
config_dir, "/fake/socket"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.total >= 0
|
||||||
|
|
||||||
|
|
||||||
|
# ── Bug 4 ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestServiceStatusBanguiVersion:
|
||||||
|
"""Bug 4: ``get_service_status`` must include application version
|
||||||
|
in the ``version`` field of the ``ServiceStatusResponse``."""
|
||||||
|
|
||||||
|
async def test_online_response_contains_bangui_version(self) -> None:
|
||||||
|
"""The returned model must contain the ``bangui_version`` field."""
|
||||||
|
from app.models.server import ServerStatus
|
||||||
|
from app.services import config_service
|
||||||
|
import app
|
||||||
|
|
||||||
|
online_status = ServerStatus(
|
||||||
|
online=True,
|
||||||
|
version="1.0.0",
|
||||||
|
active_jails=2,
|
||||||
|
total_bans=5,
|
||||||
|
total_failures=3,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def _send(command: list[Any]) -> Any:
|
||||||
|
key = "|".join(str(c) for c in command)
|
||||||
|
if key == "get|loglevel":
|
||||||
|
return (0, "INFO")
|
||||||
|
if key == "get|logtarget":
|
||||||
|
return (0, "/var/log/fail2ban.log")
|
||||||
|
return (0, None)
|
||||||
|
|
||||||
|
class _FakeClient:
|
||||||
|
def __init__(self, **_kw: Any) -> None:
|
||||||
|
self.send = AsyncMock(side_effect=_send)
|
||||||
|
|
||||||
|
with patch("app.services.config_service.Fail2BanClient", _FakeClient):
|
||||||
|
result = await config_service.get_service_status(
|
||||||
|
"/fake/socket",
|
||||||
|
probe_fn=AsyncMock(return_value=online_status),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.version == app.__version__, (
|
||||||
|
"ServiceStatusResponse must expose BanGUI version in version field"
|
||||||
|
)
|
||||||
|
|
||||||
|
async def test_offline_response_contains_bangui_version(self) -> None:
|
||||||
|
"""Even when fail2ban is offline, ``bangui_version`` must be present."""
|
||||||
|
from app.models.server import ServerStatus
|
||||||
|
from app.services import config_service
|
||||||
|
import app
|
||||||
|
|
||||||
|
offline_status = ServerStatus(online=False)
|
||||||
|
|
||||||
|
result = await config_service.get_service_status(
|
||||||
|
"/fake/socket",
|
||||||
|
probe_fn=AsyncMock(return_value=offline_status),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.version == app.__version__
|
||||||
@@ -136,3 +136,32 @@ async def test_get_history_page_and_for_ip(tmp_path: Path) -> None:
|
|||||||
history_for_ip = await fail2ban_db_repo.get_history_for_ip(db_path=db_path, ip="2.2.2.2")
|
history_for_ip = await fail2ban_db_repo.get_history_for_ip(db_path=db_path, ip="2.2.2.2")
|
||||||
assert len(history_for_ip) == 1
|
assert len(history_for_ip) == 1
|
||||||
assert history_for_ip[0].ip == "2.2.2.2"
|
assert history_for_ip[0].ip == "2.2.2.2"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_get_history_page_origin_filter(tmp_path: Path) -> None:
|
||||||
|
db_path = str(tmp_path / "fail2ban.db")
|
||||||
|
async with aiosqlite.connect(db_path) as db:
|
||||||
|
await _create_bans_table(db)
|
||||||
|
await db.executemany(
|
||||||
|
"INSERT INTO bans (jail, ip, timeofban, bancount, data) VALUES (?, ?, ?, ?, ?)",
|
||||||
|
[
|
||||||
|
("jail1", "1.1.1.1", 100, 1, "{}"),
|
||||||
|
("blocklist-import", "2.2.2.2", 200, 1, "{}"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
page, total = await fail2ban_db_repo.get_history_page(
|
||||||
|
db_path=db_path,
|
||||||
|
since=None,
|
||||||
|
jail=None,
|
||||||
|
ip_filter=None,
|
||||||
|
origin="selfblock",
|
||||||
|
page=1,
|
||||||
|
page_size=10,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert total == 1
|
||||||
|
assert len(page) == 1
|
||||||
|
assert page[0].ip == "1.1.1.1"
|
||||||
|
|||||||
60
backend/tests/test_repositories/test_history_archive_repo.py
Normal file
60
backend/tests/test_repositories/test_history_archive_repo.py
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
"""Tests for history_archive_repo."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import aiosqlite
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.db import init_db
|
||||||
|
from app.repositories.history_archive_repo import archive_ban_event, get_archived_history, purge_archived_history
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
async def app_db(tmp_path: Path) -> str:
|
||||||
|
path = str(tmp_path / "app.db")
|
||||||
|
async with aiosqlite.connect(path) as db:
|
||||||
|
db.row_factory = aiosqlite.Row
|
||||||
|
await init_db(db)
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_archive_ban_event_deduplication(app_db: str) -> None:
|
||||||
|
async with aiosqlite.connect(app_db) as db:
|
||||||
|
# first insert should add
|
||||||
|
inserted = await archive_ban_event(db, "sshd", "1.1.1.1", 1000, 1, "{}", "ban")
|
||||||
|
assert inserted
|
||||||
|
|
||||||
|
# duplicate event is ignored
|
||||||
|
inserted = await archive_ban_event(db, "sshd", "1.1.1.1", 1000, 1, "{}", "ban")
|
||||||
|
assert not inserted
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_get_archived_history_filtering_and_pagination(app_db: str) -> None:
|
||||||
|
async with aiosqlite.connect(app_db) as db:
|
||||||
|
await archive_ban_event(db, "sshd", "1.1.1.1", 1000, 1, "{}", "ban")
|
||||||
|
await archive_ban_event(db, "nginx", "2.2.2.2", 2000, 1, "{}", "ban")
|
||||||
|
|
||||||
|
rows, total = await get_archived_history(db, jail="sshd")
|
||||||
|
assert total == 1
|
||||||
|
assert rows[0]["ip"] == "1.1.1.1"
|
||||||
|
|
||||||
|
rows, total = await get_archived_history(db, page=1, page_size=1)
|
||||||
|
assert total == 2
|
||||||
|
assert len(rows) == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_purge_archived_history(app_db: str) -> None:
|
||||||
|
now = int(time.time())
|
||||||
|
async with aiosqlite.connect(app_db) as db:
|
||||||
|
await archive_ban_event(db, "sshd", "1.1.1.1", now - 3000, 1, "{}", "ban")
|
||||||
|
await archive_ban_event(db, "sshd", "1.1.1.2", now - 1000, 1, "{}", "ban")
|
||||||
|
deleted = await purge_archived_history(db, age_seconds=2000)
|
||||||
|
assert deleted == 1
|
||||||
|
rows, total = await get_archived_history(db)
|
||||||
|
assert total == 1
|
||||||
@@ -9,6 +9,8 @@ import aiosqlite
|
|||||||
import pytest
|
import pytest
|
||||||
from httpx import ASGITransport, AsyncClient
|
from httpx import ASGITransport, AsyncClient
|
||||||
|
|
||||||
|
import app
|
||||||
|
|
||||||
from app.config import Settings
|
from app.config import Settings
|
||||||
from app.db import init_db
|
from app.db import init_db
|
||||||
from app.main import create_app
|
from app.main import create_app
|
||||||
@@ -1999,7 +2001,7 @@ class TestGetServiceStatus:
|
|||||||
def _mock_status(self, online: bool = True) -> ServiceStatusResponse:
|
def _mock_status(self, online: bool = True) -> ServiceStatusResponse:
|
||||||
return ServiceStatusResponse(
|
return ServiceStatusResponse(
|
||||||
online=online,
|
online=online,
|
||||||
version="1.0.0" if online else None,
|
version=app.__version__,
|
||||||
jail_count=2 if online else 0,
|
jail_count=2 if online else 0,
|
||||||
total_bans=10 if online else 0,
|
total_bans=10 if online else 0,
|
||||||
total_failures=3 if online else 0,
|
total_failures=3 if online else 0,
|
||||||
@@ -2018,6 +2020,7 @@ class TestGetServiceStatus:
|
|||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
assert data["online"] is True
|
assert data["online"] is True
|
||||||
|
assert data["version"] == app.__version__
|
||||||
assert data["jail_count"] == 2
|
assert data["jail_count"] == 2
|
||||||
assert data["log_level"] == "INFO"
|
assert data["log_level"] == "INFO"
|
||||||
|
|
||||||
@@ -2031,6 +2034,7 @@ class TestGetServiceStatus:
|
|||||||
|
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
|
assert data["version"] == app.__version__
|
||||||
assert data["online"] is False
|
assert data["online"] is False
|
||||||
assert data["log_level"] == "UNKNOWN"
|
assert data["log_level"] == "UNKNOWN"
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import aiosqlite
|
|||||||
import pytest
|
import pytest
|
||||||
from httpx import ASGITransport, AsyncClient
|
from httpx import ASGITransport, AsyncClient
|
||||||
|
|
||||||
|
import app
|
||||||
|
|
||||||
from app.config import Settings
|
from app.config import Settings
|
||||||
from app.db import init_db
|
from app.db import init_db
|
||||||
from app.main import create_app
|
from app.main import create_app
|
||||||
@@ -151,6 +153,7 @@ class TestDashboardStatus:
|
|||||||
body = response.json()
|
body = response.json()
|
||||||
|
|
||||||
assert "status" in body
|
assert "status" in body
|
||||||
|
|
||||||
status = body["status"]
|
status = body["status"]
|
||||||
assert "online" in status
|
assert "online" in status
|
||||||
assert "version" in status
|
assert "version" in status
|
||||||
@@ -163,10 +166,11 @@ class TestDashboardStatus:
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""Endpoint returns the exact values from ``app.state.server_status``."""
|
"""Endpoint returns the exact values from ``app.state.server_status``."""
|
||||||
response = await dashboard_client.get("/api/dashboard/status")
|
response = await dashboard_client.get("/api/dashboard/status")
|
||||||
status = response.json()["status"]
|
body = response.json()
|
||||||
|
status = body["status"]
|
||||||
|
|
||||||
assert status["online"] is True
|
assert status["online"] is True
|
||||||
assert status["version"] == "1.0.2"
|
assert status["version"] == app.__version__
|
||||||
assert status["active_jails"] == 2
|
assert status["active_jails"] == 2
|
||||||
assert status["total_bans"] == 10
|
assert status["total_bans"] == 10
|
||||||
assert status["total_failures"] == 5
|
assert status["total_failures"] == 5
|
||||||
@@ -177,10 +181,11 @@ class TestDashboardStatus:
|
|||||||
"""Endpoint returns online=False when the cache holds an offline snapshot."""
|
"""Endpoint returns online=False when the cache holds an offline snapshot."""
|
||||||
response = await offline_dashboard_client.get("/api/dashboard/status")
|
response = await offline_dashboard_client.get("/api/dashboard/status")
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
status = response.json()["status"]
|
body = response.json()
|
||||||
|
status = body["status"]
|
||||||
|
|
||||||
assert status["online"] is False
|
assert status["online"] is False
|
||||||
assert status["version"] is None
|
assert status["version"] == app.__version__
|
||||||
assert status["active_jails"] == 0
|
assert status["active_jails"] == 0
|
||||||
assert status["total_bans"] == 0
|
assert status["total_bans"] == 0
|
||||||
assert status["total_failures"] == 0
|
assert status["total_failures"] == 0
|
||||||
@@ -285,6 +290,17 @@ class TestDashboardBans:
|
|||||||
called_range = mock_list.call_args[0][1]
|
called_range = mock_list.call_args[0][1]
|
||||||
assert called_range == "7d"
|
assert called_range == "7d"
|
||||||
|
|
||||||
|
async def test_accepts_source_param(
|
||||||
|
self, dashboard_client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
"""The ``source`` query parameter is forwarded to ban_service."""
|
||||||
|
mock_list = AsyncMock(return_value=_make_ban_list_response())
|
||||||
|
with patch("app.routers.dashboard.ban_service.list_bans", new=mock_list):
|
||||||
|
await dashboard_client.get("/api/dashboard/bans?source=archive")
|
||||||
|
|
||||||
|
called_source = mock_list.call_args[1]["source"]
|
||||||
|
assert called_source == "archive"
|
||||||
|
|
||||||
async def test_empty_ban_list_returns_zero_total(
|
async def test_empty_ban_list_returns_zero_total(
|
||||||
self, dashboard_client: AsyncClient
|
self, dashboard_client: AsyncClient
|
||||||
) -> None:
|
) -> None:
|
||||||
@@ -487,6 +503,16 @@ class TestDashboardBansOriginField:
|
|||||||
origins = {ban["origin"] for ban in bans}
|
origins = {ban["origin"] for ban in bans}
|
||||||
assert origins == {"blocklist", "selfblock"}
|
assert origins == {"blocklist", "selfblock"}
|
||||||
|
|
||||||
|
async def test_bans_by_country_source_param_forwarded(
|
||||||
|
self, dashboard_client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
"""The ``source`` query parameter is forwarded to bans_by_country."""
|
||||||
|
mock_fn = AsyncMock(return_value=_make_bans_by_country_response())
|
||||||
|
with patch("app.routers.dashboard.ban_service.bans_by_country", new=mock_fn):
|
||||||
|
await dashboard_client.get("/api/dashboard/bans/by-country?source=archive")
|
||||||
|
|
||||||
|
assert mock_fn.call_args[1]["source"] == "archive"
|
||||||
|
|
||||||
async def test_blocklist_origin_serialised_correctly(
|
async def test_blocklist_origin_serialised_correctly(
|
||||||
self, dashboard_client: AsyncClient
|
self, dashboard_client: AsyncClient
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|||||||
@@ -213,6 +213,44 @@ class TestHistoryList:
|
|||||||
_args, kwargs = mock_fn.call_args
|
_args, kwargs = mock_fn.call_args
|
||||||
assert kwargs.get("range_") == "7d"
|
assert kwargs.get("range_") == "7d"
|
||||||
|
|
||||||
|
async def test_forwards_origin_filter(self, history_client: AsyncClient) -> None:
|
||||||
|
"""The ``origin`` query parameter is forwarded to the service."""
|
||||||
|
mock_fn = AsyncMock(return_value=_make_history_list(n=0))
|
||||||
|
with patch(
|
||||||
|
"app.routers.history.history_service.list_history",
|
||||||
|
new=mock_fn,
|
||||||
|
):
|
||||||
|
await history_client.get("/api/history?origin=blocklist")
|
||||||
|
|
||||||
|
_args, kwargs = mock_fn.call_args
|
||||||
|
assert kwargs.get("origin") == "blocklist"
|
||||||
|
|
||||||
|
async def test_forwards_source_filter(self, history_client: AsyncClient) -> None:
|
||||||
|
"""The ``source`` query parameter is forwarded to the service."""
|
||||||
|
mock_fn = AsyncMock(return_value=_make_history_list(n=0))
|
||||||
|
with patch(
|
||||||
|
"app.routers.history.history_service.list_history",
|
||||||
|
new=mock_fn,
|
||||||
|
):
|
||||||
|
await history_client.get("/api/history?source=archive")
|
||||||
|
|
||||||
|
_args, kwargs = mock_fn.call_args
|
||||||
|
assert kwargs.get("source") == "archive"
|
||||||
|
|
||||||
|
async def test_archive_route_forces_source_archive(
|
||||||
|
self, history_client: AsyncClient
|
||||||
|
) -> None:
|
||||||
|
"""GET /api/history/archive should call list_history with source='archive'."""
|
||||||
|
mock_fn = AsyncMock(return_value=_make_history_list(n=0))
|
||||||
|
with patch(
|
||||||
|
"app.routers.history.history_service.list_history",
|
||||||
|
new=mock_fn,
|
||||||
|
):
|
||||||
|
await history_client.get("/api/history/archive")
|
||||||
|
|
||||||
|
_args, kwargs = mock_fn.call_args
|
||||||
|
assert kwargs.get("source") == "archive"
|
||||||
|
|
||||||
async def test_empty_result(self, history_client: AsyncClient) -> None:
|
async def test_empty_result(self, history_client: AsyncClient) -> None:
|
||||||
"""An empty history returns items=[] and total=0."""
|
"""An empty history returns items=[] and total=0."""
|
||||||
with patch(
|
with patch(
|
||||||
|
|||||||
@@ -68,7 +68,8 @@ def _make_settings() -> ServerSettingsResponse:
|
|||||||
db_path="/var/lib/fail2ban/fail2ban.sqlite3",
|
db_path="/var/lib/fail2ban/fail2ban.sqlite3",
|
||||||
db_purge_age=86400,
|
db_purge_age=86400,
|
||||||
db_max_matches=10,
|
db_max_matches=10,
|
||||||
)
|
),
|
||||||
|
warnings={"db_purge_age_too_low": False},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -93,6 +94,7 @@ class TestGetServerSettings:
|
|||||||
data = resp.json()
|
data = resp.json()
|
||||||
assert data["settings"]["log_level"] == "INFO"
|
assert data["settings"]["log_level"] == "INFO"
|
||||||
assert data["settings"]["db_purge_age"] == 86400
|
assert data["settings"]["db_purge_age"] == 86400
|
||||||
|
assert data["warnings"]["db_purge_age_too_low"] is False
|
||||||
|
|
||||||
async def test_401_when_unauthenticated(self, server_client: AsyncClient) -> None:
|
async def test_401_when_unauthenticated(self, server_client: AsyncClient) -> None:
|
||||||
"""GET /api/server/settings returns 401 without session."""
|
"""GET /api/server/settings returns 401 without session."""
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from unittest.mock import AsyncMock, patch
|
|||||||
import aiosqlite
|
import aiosqlite
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from app.db import init_db
|
||||||
from app.services import ban_service
|
from app.services import ban_service
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -143,6 +144,29 @@ async def empty_f2b_db_path(tmp_path: Path) -> str:
|
|||||||
return path
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
async def app_db_with_archive(tmp_path: Path) -> aiosqlite.Connection:
|
||||||
|
"""Return an app database connection pre-populated with archived ban rows."""
|
||||||
|
db_path = str(tmp_path / "app_archive.db")
|
||||||
|
db = await aiosqlite.connect(db_path)
|
||||||
|
db.row_factory = aiosqlite.Row
|
||||||
|
await init_db(db)
|
||||||
|
|
||||||
|
await db.execute(
|
||||||
|
"INSERT INTO history_archive (jail, ip, timeofban, bancount, data, action) VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
("sshd", "1.2.3.4", _ONE_HOUR_AGO, 1, '{"matches": ["fail"], "failures": 1}', "ban"),
|
||||||
|
)
|
||||||
|
await db.execute(
|
||||||
|
"INSERT INTO history_archive (jail, ip, timeofban, bancount, data, action) VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
("nginx", "5.6.7.8", _ONE_HOUR_AGO, 1, '{"matches": ["fail"], "failures": 2}', "ban"),
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
yield db
|
||||||
|
|
||||||
|
await db.close()
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# list_bans — happy path
|
# list_bans — happy path
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -233,6 +257,20 @@ class TestListBansHappyPath:
|
|||||||
|
|
||||||
assert result.total == 3
|
assert result.total == 3
|
||||||
|
|
||||||
|
async def test_source_archive_reads_from_archive(
|
||||||
|
self, app_db_with_archive: aiosqlite.Connection
|
||||||
|
) -> None:
|
||||||
|
"""Using source='archive' reads from the BanGUI archive table."""
|
||||||
|
result = await ban_service.list_bans(
|
||||||
|
"/fake/sock",
|
||||||
|
"24h",
|
||||||
|
source="archive",
|
||||||
|
app_db=app_db_with_archive,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.total == 2
|
||||||
|
assert {item.ip for item in result.items} == {"1.2.3.4", "5.6.7.8"}
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# list_bans — geo enrichment
|
# list_bans — geo enrichment
|
||||||
@@ -616,6 +654,20 @@ class TestOriginFilter:
|
|||||||
|
|
||||||
assert result.total == 3
|
assert result.total == 3
|
||||||
|
|
||||||
|
async def test_bans_by_country_source_archive_reads_archive(
|
||||||
|
self, app_db_with_archive: aiosqlite.Connection
|
||||||
|
) -> None:
|
||||||
|
"""``bans_by_country`` accepts source='archive' and reads archived rows."""
|
||||||
|
result = await ban_service.bans_by_country(
|
||||||
|
"/fake/sock",
|
||||||
|
"24h",
|
||||||
|
source="archive",
|
||||||
|
app_db=app_db_with_archive,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.total == 2
|
||||||
|
assert len(result.bans) == 2
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# bans_by_country — background geo resolution (Task 3)
|
# bans_by_country — background geo resolution (Task 3)
|
||||||
@@ -802,6 +854,19 @@ class TestBanTrend:
|
|||||||
timestamps = [b.timestamp for b in result.buckets]
|
timestamps = [b.timestamp for b in result.buckets]
|
||||||
assert timestamps == sorted(timestamps)
|
assert timestamps == sorted(timestamps)
|
||||||
|
|
||||||
|
async def test_ban_trend_source_archive_reads_archive(
|
||||||
|
self, app_db_with_archive: aiosqlite.Connection
|
||||||
|
) -> None:
|
||||||
|
"""``ban_trend`` accepts source='archive' and uses archived rows."""
|
||||||
|
result = await ban_service.ban_trend(
|
||||||
|
"/fake/sock",
|
||||||
|
"24h",
|
||||||
|
source="archive",
|
||||||
|
app_db=app_db_with_archive,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert sum(b.count for b in result.buckets) == 2
|
||||||
|
|
||||||
async def test_bans_counted_in_correct_bucket(self, tmp_path: Path) -> None:
|
async def test_bans_counted_in_correct_bucket(self, tmp_path: Path) -> None:
|
||||||
"""A ban at a known time appears in the expected bucket."""
|
"""A ban at a known time appears in the expected bucket."""
|
||||||
import time as _time
|
import time as _time
|
||||||
@@ -1018,6 +1083,20 @@ class TestBansByJail:
|
|||||||
assert result.total == 3
|
assert result.total == 3
|
||||||
assert len(result.jails) == 3
|
assert len(result.jails) == 3
|
||||||
|
|
||||||
|
async def test_bans_by_jail_source_archive_reads_archive(
|
||||||
|
self, app_db_with_archive: aiosqlite.Connection
|
||||||
|
) -> None:
|
||||||
|
"""``bans_by_jail`` accepts source='archive' and aggregates archived rows."""
|
||||||
|
result = await ban_service.bans_by_jail(
|
||||||
|
"/fake/sock",
|
||||||
|
"24h",
|
||||||
|
source="archive",
|
||||||
|
app_db=app_db_with_archive,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.total == 2
|
||||||
|
assert any(j.jail == "sshd" for j in result.jails)
|
||||||
|
|
||||||
async def test_diagnostic_warning_when_zero_results_despite_data(
|
async def test_diagnostic_warning_when_zero_results_despite_data(
|
||||||
self, tmp_path: Path
|
self, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from unittest.mock import AsyncMock, patch
|
from unittest.mock import AsyncMock, patch
|
||||||
|
|
||||||
@@ -256,6 +257,27 @@ class TestUpdateJailConfig:
|
|||||||
assert "bantime" in keys
|
assert "bantime" in keys
|
||||||
assert "maxretry" in keys
|
assert "maxretry" in keys
|
||||||
|
|
||||||
|
async def test_ignores_backend_field(self) -> None:
|
||||||
|
"""update_jail_config does not send a set command for backend."""
|
||||||
|
sent_commands: list[list[Any]] = []
|
||||||
|
|
||||||
|
async def _send(command: list[Any]) -> Any:
|
||||||
|
sent_commands.append(command)
|
||||||
|
return (0, "OK")
|
||||||
|
|
||||||
|
class _FakeClient:
|
||||||
|
def __init__(self, **_kw: Any) -> None:
|
||||||
|
self.send = AsyncMock(side_effect=_send)
|
||||||
|
|
||||||
|
from app.models.config import JailConfigUpdate
|
||||||
|
|
||||||
|
update = JailConfigUpdate(backend="polling")
|
||||||
|
with patch("app.services.config_service.Fail2BanClient", _FakeClient):
|
||||||
|
await config_service.update_jail_config(_SOCKET, "sshd", update)
|
||||||
|
|
||||||
|
keys = [cmd[2] for cmd in sent_commands if len(cmd) >= 3 and cmd[0] == "set"]
|
||||||
|
assert "backend" not in keys
|
||||||
|
|
||||||
async def test_raises_validation_error_on_bad_regex(self) -> None:
|
async def test_raises_validation_error_on_bad_regex(self) -> None:
|
||||||
"""update_jail_config raises ConfigValidationError for invalid regex."""
|
"""update_jail_config raises ConfigValidationError for invalid regex."""
|
||||||
from app.models.config import JailConfigUpdate
|
from app.models.config import JailConfigUpdate
|
||||||
@@ -727,8 +749,10 @@ class TestGetServiceStatus:
|
|||||||
probe_fn=AsyncMock(return_value=online_status),
|
probe_fn=AsyncMock(return_value=online_status),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
from app import __version__
|
||||||
|
|
||||||
assert result.online is True
|
assert result.online is True
|
||||||
assert result.version == "1.0.0"
|
assert result.version == __version__
|
||||||
assert result.jail_count == 2
|
assert result.jail_count == 2
|
||||||
assert result.total_bans == 5
|
assert result.total_bans == 5
|
||||||
assert result.total_failures == 3
|
assert result.total_failures == 3
|
||||||
@@ -750,3 +774,62 @@ class TestGetServiceStatus:
|
|||||||
assert result.jail_count == 0
|
assert result.jail_count == 0
|
||||||
assert result.log_level == "UNKNOWN"
|
assert result.log_level == "UNKNOWN"
|
||||||
assert result.log_target == "UNKNOWN"
|
assert result.log_target == "UNKNOWN"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
class TestConfigModuleIntegration:
|
||||||
|
async def test_jail_config_service_list_inactive_jails_uses_imports(self, tmp_path: Any) -> None:
|
||||||
|
from app.services.jail_config_service import list_inactive_jails
|
||||||
|
|
||||||
|
# Arrange: fake parse_jails output with one active and one inactive
|
||||||
|
def fake_parse_jails_sync(path: Path) -> tuple[dict[str, dict[str, str]], dict[str, str]]:
|
||||||
|
return (
|
||||||
|
{
|
||||||
|
"sshd": {
|
||||||
|
"enabled": "true",
|
||||||
|
"filter": "sshd",
|
||||||
|
"logpath": "/var/log/auth.log",
|
||||||
|
},
|
||||||
|
"apache-auth": {
|
||||||
|
"enabled": "false",
|
||||||
|
"filter": "apache-auth",
|
||||||
|
"logpath": "/var/log/apache2/error.log",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sshd": str(path / "jail.conf"),
|
||||||
|
"apache-auth": str(path / "jail.conf"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"app.services.jail_config_service._parse_jails_sync",
|
||||||
|
new=fake_parse_jails_sync,
|
||||||
|
), patch(
|
||||||
|
"app.services.jail_config_service._get_active_jail_names",
|
||||||
|
new=AsyncMock(return_value={"sshd"}),
|
||||||
|
):
|
||||||
|
result = await list_inactive_jails(str(tmp_path), "/fake.sock")
|
||||||
|
|
||||||
|
names = {j.name for j in result.jails}
|
||||||
|
assert "apache-auth" in names
|
||||||
|
assert "sshd" not in names
|
||||||
|
|
||||||
|
async def test_filter_config_service_list_filters_uses_imports(self, tmp_path: Any) -> None:
|
||||||
|
from app.services.filter_config_service import list_filters
|
||||||
|
|
||||||
|
# Arrange minimal filter and jail config files
|
||||||
|
filter_d = tmp_path / "filter.d"
|
||||||
|
filter_d.mkdir(parents=True)
|
||||||
|
(filter_d / "sshd.conf").write_text("[Definition]\nfailregex = ^%(__prefix_line)s.*$\n")
|
||||||
|
(tmp_path / "jail.conf").write_text("[sshd]\nfilter = sshd\nenabled = true\n")
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"app.services.filter_config_service._get_active_jail_names",
|
||||||
|
new=AsyncMock(return_value={"sshd"}),
|
||||||
|
):
|
||||||
|
result = await list_filters(str(tmp_path), "/fake.sock")
|
||||||
|
|
||||||
|
assert result.total == 1
|
||||||
|
assert result.filters[0].name == "sshd"
|
||||||
|
assert result.filters[0].active is True
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from unittest.mock import AsyncMock, patch
|
|||||||
import aiosqlite
|
import aiosqlite
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from app.db import init_db
|
||||||
from app.services import history_service
|
from app.services import history_service
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -179,6 +180,19 @@ class TestListHistory:
|
|||||||
# 2 sshd bans for 1.2.3.4
|
# 2 sshd bans for 1.2.3.4
|
||||||
assert result.total == 2
|
assert result.total == 2
|
||||||
|
|
||||||
|
async def test_origin_filter_selfblock(self, f2b_db_path: str) -> None:
|
||||||
|
"""Origin filter should include only selfblock entries."""
|
||||||
|
with patch(
|
||||||
|
"app.services.history_service.get_fail2ban_db_path",
|
||||||
|
new=AsyncMock(return_value=f2b_db_path),
|
||||||
|
):
|
||||||
|
result = await history_service.list_history(
|
||||||
|
"fake_socket", origin="selfblock"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.total == 4
|
||||||
|
assert all(item.jail != "blocklist-import" for item in result.items)
|
||||||
|
|
||||||
async def test_unknown_ip_returns_empty(self, f2b_db_path: str) -> None:
|
async def test_unknown_ip_returns_empty(self, f2b_db_path: str) -> None:
|
||||||
"""Filtering by a non-existent IP returns an empty result set."""
|
"""Filtering by a non-existent IP returns an empty result set."""
|
||||||
with patch(
|
with patch(
|
||||||
@@ -251,6 +265,31 @@ class TestListHistory:
|
|||||||
assert result.page == 1
|
assert result.page == 1
|
||||||
assert result.page_size == 2
|
assert result.page_size == 2
|
||||||
|
|
||||||
|
async def test_source_archive_reads_from_archive(self, f2b_db_path: str, tmp_path: Path) -> None:
|
||||||
|
"""Using source='archive' reads from the BanGUI archive table."""
|
||||||
|
app_db_path = str(tmp_path / "app_archive.db")
|
||||||
|
async with aiosqlite.connect(app_db_path) as db:
|
||||||
|
db.row_factory = aiosqlite.Row
|
||||||
|
await init_db(db)
|
||||||
|
await db.execute(
|
||||||
|
"INSERT INTO history_archive (jail, ip, timeofban, bancount, data, action) VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
("sshd", "10.0.0.1", _ONE_HOUR_AGO, 1, '{"matches": [], "failures": 0}', "ban"),
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"app.services.history_service.get_fail2ban_db_path",
|
||||||
|
new=AsyncMock(return_value=f2b_db_path),
|
||||||
|
):
|
||||||
|
result = await history_service.list_history(
|
||||||
|
"fake_socket",
|
||||||
|
source="archive",
|
||||||
|
db=db,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.total == 1
|
||||||
|
assert result.items[0].ip == "10.0.0.1"
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# get_ip_detail tests
|
# get_ip_detail tests
|
||||||
|
|||||||
@@ -63,6 +63,16 @@ class TestGetSettings:
|
|||||||
assert result.settings.log_target == "/var/log/fail2ban.log"
|
assert result.settings.log_target == "/var/log/fail2ban.log"
|
||||||
assert result.settings.db_purge_age == 86400
|
assert result.settings.db_purge_age == 86400
|
||||||
assert result.settings.db_max_matches == 10
|
assert result.settings.db_max_matches == 10
|
||||||
|
assert result.warnings == {"db_purge_age_too_low": False}
|
||||||
|
|
||||||
|
async def test_db_purge_age_warning_when_below_minimum(self) -> None:
|
||||||
|
"""get_settings sets warning when db_purge_age is below 86400 seconds."""
|
||||||
|
responses = {**_DEFAULT_RESPONSES, "get|dbpurgeage": (0, 3600)}
|
||||||
|
with _patch_client(responses):
|
||||||
|
result = await server_service.get_settings(_SOCKET)
|
||||||
|
|
||||||
|
assert result.settings.db_purge_age == 3600
|
||||||
|
assert result.warnings == {"db_purge_age_too_low": True}
|
||||||
|
|
||||||
async def test_db_path_parsed(self) -> None:
|
async def test_db_path_parsed(self) -> None:
|
||||||
"""get_settings returns the correct database file path."""
|
"""get_settings returns the correct database file path."""
|
||||||
|
|||||||
29
backend/tests/test_tasks/test_history_sync.py
Normal file
29
backend/tests/test_tasks/test_history_sync.py
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
"""Tests for history_sync task registration."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
from app.tasks import history_sync
|
||||||
|
|
||||||
|
|
||||||
|
class TestHistorySyncTask:
|
||||||
|
async def test_register_schedules_job(self) -> None:
|
||||||
|
fake_scheduler = MagicMock()
|
||||||
|
class FakeState:
|
||||||
|
pass
|
||||||
|
|
||||||
|
class FakeSettings:
|
||||||
|
fail2ban_socket = "/tmp/fake.sock"
|
||||||
|
|
||||||
|
app = type("FakeApp", (), {})()
|
||||||
|
app.state = FakeState()
|
||||||
|
app.state.scheduler = fake_scheduler
|
||||||
|
app.state.settings = FakeSettings()
|
||||||
|
|
||||||
|
history_sync.register(app)
|
||||||
|
|
||||||
|
fake_scheduler.add_job.assert_called_once()
|
||||||
|
called_args, called_kwargs = fake_scheduler.add_job.call_args
|
||||||
|
assert called_kwargs["id"] == history_sync.JOB_ID
|
||||||
|
assert called_kwargs["kwargs"]["app"] == app
|
||||||
@@ -65,6 +65,10 @@ class TestEnsureJailConfigs:
|
|||||||
content = _read(jail_d, conf_file)
|
content = _read(jail_d, conf_file)
|
||||||
assert "enabled = false" in content
|
assert "enabled = false" in content
|
||||||
|
|
||||||
|
# Blocklist-import jail must have a 24-hour ban time
|
||||||
|
blocklist_conf = _read(jail_d, _BLOCKLIST_CONF)
|
||||||
|
assert "bantime = 86400" in blocklist_conf
|
||||||
|
|
||||||
# .local files must set enabled = true and nothing else
|
# .local files must set enabled = true and nothing else
|
||||||
for local_file in (_MANUAL_LOCAL, _BLOCKLIST_LOCAL):
|
for local_file in (_MANUAL_LOCAL, _BLOCKLIST_LOCAL):
|
||||||
content = _read(jail_d, local_file)
|
content = _read(jail_d, local_file)
|
||||||
|
|||||||
28
backend/tests/test_version.py
Normal file
28
backend/tests/test_version.py
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
|
||||||
|
import app
|
||||||
|
|
||||||
|
|
||||||
|
def test_app_version_matches_docker_version() -> None:
|
||||||
|
"""The backend version should match the signed off Docker release version."""
|
||||||
|
|
||||||
|
repo_root = Path(__file__).resolve().parents[2]
|
||||||
|
version_file = repo_root / "Docker" / "VERSION"
|
||||||
|
expected = version_file.read_text(encoding="utf-8").strip().lstrip("v")
|
||||||
|
|
||||||
|
assert app.__version__ == expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_backend_pyproject_version_matches_docker_version() -> None:
|
||||||
|
repo_root = Path(__file__).resolve().parents[2]
|
||||||
|
version_file = repo_root / "Docker" / "VERSION"
|
||||||
|
expected = version_file.read_text(encoding="utf-8").strip().lstrip("v")
|
||||||
|
|
||||||
|
pyproject_file = repo_root / "backend" / "pyproject.toml"
|
||||||
|
text = pyproject_file.read_text(encoding="utf-8")
|
||||||
|
match = re.search(r"^version\s*=\s*\"([^\"]+)\"", text, re.MULTILINE)
|
||||||
|
assert match is not None, "backend/pyproject.toml must contain a version entry"
|
||||||
|
assert match.group(1) == expected
|
||||||
4
frontend/package-lock.json
generated
4
frontend/package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "bangui-frontend",
|
"name": "bangui-frontend",
|
||||||
"version": "0.9.4",
|
"version": "0.9.14",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "bangui-frontend",
|
"name": "bangui-frontend",
|
||||||
"version": "0.9.4",
|
"version": "0.9.14",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fluentui/react-components": "^9.55.0",
|
"@fluentui/react-components": "^9.55.0",
|
||||||
"@fluentui/react-icons": "^2.0.257",
|
"@fluentui/react-icons": "^2.0.257",
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "bangui-frontend",
|
"name": "bangui-frontend",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.9.4",
|
"version": "0.9.15",
|
||||||
"description": "BanGUI frontend — fail2ban web management interface",
|
"description": "BanGUI frontend — fail2ban web management interface",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ export async function fetchHistory(
|
|||||||
): Promise<HistoryListResponse> {
|
): Promise<HistoryListResponse> {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
if (query.range) params.set("range", query.range);
|
if (query.range) params.set("range", query.range);
|
||||||
|
if (query.origin) params.set("origin", query.origin);
|
||||||
if (query.jail) params.set("jail", query.jail);
|
if (query.jail) params.set("jail", query.jail);
|
||||||
if (query.ip) params.set("ip", query.ip);
|
if (query.ip) params.set("ip", query.ip);
|
||||||
if (query.page !== undefined) params.set("page", String(query.page));
|
if (query.page !== undefined) params.set("page", String(query.page));
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ export function ServerStatusBar(): React.JSX.Element {
|
|||||||
{/* Version */}
|
{/* Version */}
|
||||||
{/* ---------------------------------------------------------------- */}
|
{/* ---------------------------------------------------------------- */}
|
||||||
{status?.version != null && (
|
{status?.version != null && (
|
||||||
<Tooltip content="fail2ban daemon version" relationship="description">
|
<Tooltip content="BanGUI version" relationship="description">
|
||||||
<Text size={200} className={styles.statValue}>
|
<Text size={200} className={styles.statValue}>
|
||||||
v{status.version}
|
v{status.version}
|
||||||
</Text>
|
</Text>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
* country filters the companion table.
|
* country filters the companion table.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
import { useCallback, useState } from "react";
|
import { useCallback, useState } from "react";
|
||||||
import { ComposableMap, ZoomableGroup, Geography, useGeographies } from "react-simple-maps";
|
import { ComposableMap, ZoomableGroup, Geography, useGeographies } from "react-simple-maps";
|
||||||
import { Button, makeStyles, tokens } from "@fluentui/react-components";
|
import { Button, makeStyles, tokens } from "@fluentui/react-components";
|
||||||
@@ -48,6 +49,28 @@ const useStyles = makeStyles({
|
|||||||
gap: tokens.spacingVerticalXS,
|
gap: tokens.spacingVerticalXS,
|
||||||
zIndex: 10,
|
zIndex: 10,
|
||||||
},
|
},
|
||||||
|
tooltip: {
|
||||||
|
position: "fixed",
|
||||||
|
zIndex: 9999,
|
||||||
|
pointerEvents: "none",
|
||||||
|
backgroundColor: tokens.colorNeutralBackground1,
|
||||||
|
border: `1px solid ${tokens.colorNeutralStroke2}`,
|
||||||
|
borderRadius: tokens.borderRadiusSmall,
|
||||||
|
padding: `${tokens.spacingVerticalXS} ${tokens.spacingHorizontalS}`,
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
gap: tokens.spacingVerticalXXS,
|
||||||
|
boxShadow: tokens.shadow4,
|
||||||
|
},
|
||||||
|
tooltipCountry: {
|
||||||
|
fontSize: tokens.fontSizeBase200,
|
||||||
|
fontWeight: tokens.fontWeightSemibold,
|
||||||
|
color: tokens.colorNeutralForeground1,
|
||||||
|
},
|
||||||
|
tooltipCount: {
|
||||||
|
fontSize: tokens.fontSizeBase200,
|
||||||
|
color: tokens.colorNeutralForeground2,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -56,6 +79,7 @@ const useStyles = makeStyles({
|
|||||||
|
|
||||||
interface GeoLayerProps {
|
interface GeoLayerProps {
|
||||||
countries: Record<string, number>;
|
countries: Record<string, number>;
|
||||||
|
countryNames?: Record<string, string>;
|
||||||
selectedCountry: string | null;
|
selectedCountry: string | null;
|
||||||
onSelectCountry: (cc: string | null) => void;
|
onSelectCountry: (cc: string | null) => void;
|
||||||
thresholdLow: number;
|
thresholdLow: number;
|
||||||
@@ -65,6 +89,7 @@ interface GeoLayerProps {
|
|||||||
|
|
||||||
function GeoLayer({
|
function GeoLayer({
|
||||||
countries,
|
countries,
|
||||||
|
countryNames,
|
||||||
selectedCountry,
|
selectedCountry,
|
||||||
onSelectCountry,
|
onSelectCountry,
|
||||||
thresholdLow,
|
thresholdLow,
|
||||||
@@ -74,6 +99,17 @@ function GeoLayer({
|
|||||||
const styles = useStyles();
|
const styles = useStyles();
|
||||||
const { geographies, path } = useGeographies({ geography: GEO_URL });
|
const { geographies, path } = useGeographies({ geography: GEO_URL });
|
||||||
|
|
||||||
|
const [tooltip, setTooltip] = useState<
|
||||||
|
| {
|
||||||
|
cc: string;
|
||||||
|
count: number;
|
||||||
|
name: string;
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
}
|
||||||
|
| null
|
||||||
|
>(null);
|
||||||
|
|
||||||
const handleClick = useCallback(
|
const handleClick = useCallback(
|
||||||
(cc: string | null): void => {
|
(cc: string | null): void => {
|
||||||
onSelectCountry(selectedCountry === cc ? null : cc);
|
onSelectCountry(selectedCountry === cc ? null : cc);
|
||||||
@@ -96,7 +132,7 @@ function GeoLayer({
|
|||||||
const cc: string | null = ISO_NUMERIC_TO_ALPHA2[numericId] ?? null;
|
const cc: string | null = ISO_NUMERIC_TO_ALPHA2[numericId] ?? null;
|
||||||
const count: number = cc !== null ? (countries[cc] ?? 0) : 0;
|
const count: number = cc !== null ? (countries[cc] ?? 0) : 0;
|
||||||
const isSelected = cc !== null && selectedCountry === cc;
|
const isSelected = cc !== null && selectedCountry === cc;
|
||||||
|
|
||||||
// Compute the fill color based on ban count
|
// Compute the fill color based on ban count
|
||||||
const fillColor = getBanCountColor(
|
const fillColor = getBanCountColor(
|
||||||
count,
|
count,
|
||||||
@@ -104,7 +140,7 @@ function GeoLayer({
|
|||||||
thresholdMedium,
|
thresholdMedium,
|
||||||
thresholdHigh,
|
thresholdHigh,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Only calculate centroid if path is available
|
// Only calculate centroid if path is available
|
||||||
let cx: number | undefined;
|
let cx: number | undefined;
|
||||||
let cy: number | undefined;
|
let cy: number | undefined;
|
||||||
@@ -114,16 +150,18 @@ function GeoLayer({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<g
|
<g key={geo.rsmKey} style={{ cursor: cc ? "pointer" : "default" }}>
|
||||||
key={geo.rsmKey}
|
<Geography
|
||||||
style={{ cursor: cc ? "pointer" : "default" }}
|
geography={geo}
|
||||||
role={cc ? "button" : undefined}
|
role={cc ? "button" : undefined}
|
||||||
tabIndex={cc ? 0 : undefined}
|
tabIndex={cc ? 0 : undefined}
|
||||||
aria-label={cc
|
aria-label={
|
||||||
? `${cc}: ${String(count)} ban${count !== 1 ? "s" : ""}${
|
cc
|
||||||
isSelected ? " (selected)" : ""
|
? `${cc}: ${String(count)} ban${count !== 1 ? "s" : ""}${
|
||||||
}`
|
isSelected ? " (selected)" : ""
|
||||||
: undefined}
|
}`
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
aria-pressed={isSelected || undefined}
|
aria-pressed={isSelected || undefined}
|
||||||
onClick={(): void => {
|
onClick={(): void => {
|
||||||
if (cc) handleClick(cc);
|
if (cc) handleClick(cc);
|
||||||
@@ -134,49 +172,86 @@ function GeoLayer({
|
|||||||
handleClick(cc);
|
handleClick(cc);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
>
|
onMouseEnter={(e): void => {
|
||||||
<Geography
|
if (!cc) return;
|
||||||
geography={geo}
|
setTooltip({
|
||||||
style={{
|
cc,
|
||||||
default: {
|
count,
|
||||||
fill: isSelected ? tokens.colorBrandBackground : fillColor,
|
name: countryNames?.[cc] ?? cc,
|
||||||
stroke: tokens.colorNeutralStroke2,
|
x: e.clientX,
|
||||||
strokeWidth: 0.75,
|
y: e.clientY,
|
||||||
outline: "none",
|
});
|
||||||
},
|
}}
|
||||||
hover: {
|
onMouseMove={(e): void => {
|
||||||
fill: isSelected
|
setTooltip((current) =>
|
||||||
? tokens.colorBrandBackgroundHover
|
current
|
||||||
: cc && count > 0
|
? {
|
||||||
? tokens.colorNeutralBackground3
|
...current,
|
||||||
: fillColor,
|
x: e.clientX,
|
||||||
stroke: tokens.colorNeutralStroke1,
|
y: e.clientY,
|
||||||
strokeWidth: 1,
|
}
|
||||||
outline: "none",
|
: current,
|
||||||
},
|
);
|
||||||
pressed: {
|
}}
|
||||||
fill: cc ? tokens.colorBrandBackgroundPressed : fillColor,
|
onMouseLeave={(): void => {
|
||||||
stroke: tokens.colorBrandStroke1,
|
setTooltip(null);
|
||||||
strokeWidth: 1,
|
}}
|
||||||
outline: "none",
|
style={{
|
||||||
},
|
default: {
|
||||||
}}
|
fill: isSelected ? tokens.colorBrandBackground : fillColor,
|
||||||
/>
|
stroke: tokens.colorNeutralStroke2,
|
||||||
{count > 0 && cx !== undefined && cy !== undefined && isFinite(cx) && isFinite(cy) && (
|
strokeWidth: 0.75,
|
||||||
<text
|
outline: "none",
|
||||||
x={cx}
|
},
|
||||||
y={cy}
|
hover: {
|
||||||
textAnchor="middle"
|
fill: isSelected
|
||||||
dominantBaseline="central"
|
? tokens.colorBrandBackgroundHover
|
||||||
className={styles.countLabel}
|
: cc && count > 0
|
||||||
>
|
? tokens.colorNeutralBackground3
|
||||||
{count}
|
: fillColor,
|
||||||
</text>
|
stroke: tokens.colorNeutralStroke1,
|
||||||
)}
|
strokeWidth: 1,
|
||||||
</g>
|
outline: "none",
|
||||||
|
},
|
||||||
|
pressed: {
|
||||||
|
fill: cc ? tokens.colorBrandBackgroundPressed : fillColor,
|
||||||
|
stroke: tokens.colorBrandStroke1,
|
||||||
|
strokeWidth: 1,
|
||||||
|
outline: "none",
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{count > 0 && cx !== undefined && cy !== undefined && isFinite(cx) && isFinite(cy) && (
|
||||||
|
<text
|
||||||
|
x={cx}
|
||||||
|
y={cy}
|
||||||
|
textAnchor="middle"
|
||||||
|
dominantBaseline="central"
|
||||||
|
className={styles.countLabel}
|
||||||
|
>
|
||||||
|
{count}
|
||||||
|
</text>
|
||||||
|
)}
|
||||||
|
</g>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{tooltip &&
|
||||||
|
createPortal(
|
||||||
|
<div
|
||||||
|
className={styles.tooltip}
|
||||||
|
style={{ left: tooltip.x + 12, top: tooltip.y + 12 }}
|
||||||
|
role="tooltip"
|
||||||
|
aria-live="polite"
|
||||||
|
>
|
||||||
|
<span className={styles.tooltipCountry}>{tooltip.name}</span>
|
||||||
|
<span className={styles.tooltipCount}>
|
||||||
|
{tooltip.count.toLocaleString()} ban{tooltip.count !== 1 ? "s" : ""}
|
||||||
|
</span>
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -188,6 +263,8 @@ function GeoLayer({
|
|||||||
export interface WorldMapProps {
|
export interface WorldMapProps {
|
||||||
/** ISO alpha-2 country code → ban count. */
|
/** ISO alpha-2 country code → ban count. */
|
||||||
countries: Record<string, number>;
|
countries: Record<string, number>;
|
||||||
|
/** Optional mapping from country code to display name. */
|
||||||
|
countryNames?: Record<string, string>;
|
||||||
/** Currently selected country filter (null means no filter). */
|
/** Currently selected country filter (null means no filter). */
|
||||||
selectedCountry: string | null;
|
selectedCountry: string | null;
|
||||||
/** Called when the user clicks a country or deselects. */
|
/** Called when the user clicks a country or deselects. */
|
||||||
@@ -202,6 +279,7 @@ export interface WorldMapProps {
|
|||||||
|
|
||||||
export function WorldMap({
|
export function WorldMap({
|
||||||
countries,
|
countries,
|
||||||
|
countryNames,
|
||||||
selectedCountry,
|
selectedCountry,
|
||||||
onSelectCountry,
|
onSelectCountry,
|
||||||
thresholdLow = 20,
|
thresholdLow = 20,
|
||||||
@@ -285,6 +363,7 @@ export function WorldMap({
|
|||||||
>
|
>
|
||||||
<GeoLayer
|
<GeoLayer
|
||||||
countries={countries}
|
countries={countries}
|
||||||
|
countryNames={countryNames}
|
||||||
selectedCountry={selectedCountry}
|
selectedCountry={selectedCountry}
|
||||||
onSelectCountry={onSelectCountry}
|
onSelectCountry={onSelectCountry}
|
||||||
thresholdLow={thresholdLow}
|
thresholdLow={thresholdLow}
|
||||||
|
|||||||
@@ -101,6 +101,23 @@ describe("ServerStatusBar", () => {
|
|||||||
expect(screen.getByText("v1.2.3")).toBeInTheDocument();
|
expect(screen.getByText("v1.2.3")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("does not render a separate BanGUI version badge", () => {
|
||||||
|
mockedUseServerStatus.mockReturnValue({
|
||||||
|
status: {
|
||||||
|
online: true,
|
||||||
|
version: "1.2.3",
|
||||||
|
active_jails: 1,
|
||||||
|
total_bans: 0,
|
||||||
|
total_failures: 0,
|
||||||
|
},
|
||||||
|
loading: false,
|
||||||
|
error: null,
|
||||||
|
refresh: vi.fn(),
|
||||||
|
});
|
||||||
|
renderBar();
|
||||||
|
expect(screen.queryByText("BanGUI v9.9.9")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
it("does not render the version element when version is null", () => {
|
it("does not render the version element when version is null", () => {
|
||||||
mockedUseServerStatus.mockReturnValue({
|
mockedUseServerStatus.mockReturnValue({
|
||||||
status: {
|
status: {
|
||||||
|
|||||||
54
frontend/src/components/__tests__/WorldMap.test.tsx
Normal file
54
frontend/src/components/__tests__/WorldMap.test.tsx
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
/**
|
||||||
|
* Tests for WorldMap component.
|
||||||
|
*
|
||||||
|
* Verifies that hovering a country shows a tooltip with the country name and ban count.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { fireEvent, render, screen } from "@testing-library/react";
|
||||||
|
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
|
||||||
|
|
||||||
|
// Mock react-simple-maps to avoid fetching real TopoJSON and to control geometry.
|
||||||
|
vi.mock("react-simple-maps", () => ({
|
||||||
|
ComposableMap: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||||
|
ZoomableGroup: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||||
|
Geography: ({ children, ...props }: { children?: React.ReactNode } & Record<string, unknown>) => <g {...props}>{children}</g>,
|
||||||
|
useGeographies: () => ({
|
||||||
|
geographies: [{ rsmKey: "geo-1", id: 840 }],
|
||||||
|
path: { centroid: () => [10, 10] },
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { WorldMap } from "../WorldMap";
|
||||||
|
|
||||||
|
describe("WorldMap", () => {
|
||||||
|
it("shows a tooltip with country name and ban count on hover", () => {
|
||||||
|
render(
|
||||||
|
<FluentProvider theme={webLightTheme}>
|
||||||
|
<WorldMap
|
||||||
|
countries={{ US: 42 }}
|
||||||
|
countryNames={{ US: "United States" }}
|
||||||
|
selectedCountry={null}
|
||||||
|
onSelectCountry={vi.fn()}
|
||||||
|
/>
|
||||||
|
</FluentProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Tooltip should not be present initially
|
||||||
|
expect(screen.queryByRole("tooltip")).toBeNull();
|
||||||
|
|
||||||
|
// Country map area is exposed as an accessible button with an accurate label
|
||||||
|
const countryButton = screen.getByRole("button", { name: "US: 42 bans" });
|
||||||
|
expect(countryButton).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.mouseEnter(countryButton, { clientX: 10, clientY: 10 });
|
||||||
|
|
||||||
|
const tooltip = screen.getByRole("tooltip");
|
||||||
|
expect(tooltip).toHaveTextContent("United States");
|
||||||
|
expect(tooltip).toHaveTextContent("42 bans");
|
||||||
|
expect(tooltip).toHaveStyle({ left: "22px", top: "22px" });
|
||||||
|
|
||||||
|
fireEvent.mouseLeave(countryButton);
|
||||||
|
expect(screen.queryByRole("tooltip")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -216,7 +216,6 @@ function JailConfigDetail({
|
|||||||
ignore_regex: ignoreRegex,
|
ignore_regex: ignoreRegex,
|
||||||
date_pattern: datePattern !== "" ? datePattern : null,
|
date_pattern: datePattern !== "" ? datePattern : null,
|
||||||
dns_mode: dnsMode,
|
dns_mode: dnsMode,
|
||||||
backend,
|
|
||||||
log_encoding: logEncoding,
|
log_encoding: logEncoding,
|
||||||
prefregex: prefRegex !== "" ? prefRegex : null,
|
prefregex: prefRegex !== "" ? prefRegex : null,
|
||||||
bantime_escalation: {
|
bantime_escalation: {
|
||||||
@@ -231,7 +230,7 @@ function JailConfigDetail({
|
|||||||
}),
|
}),
|
||||||
[
|
[
|
||||||
banTime, findTime, maxRetry, failRegex, ignoreRegex, datePattern,
|
banTime, findTime, maxRetry, failRegex, ignoreRegex, datePattern,
|
||||||
dnsMode, backend, logEncoding, prefRegex, escEnabled, escFactor,
|
dnsMode, logEncoding, prefRegex, escEnabled, escFactor,
|
||||||
escFormula, escMultipliers, escMaxTime, escRndTime, escOverallJails,
|
escFormula, escMultipliers, escMaxTime, escRndTime, escOverallJails,
|
||||||
jail.ban_time, jail.find_time, jail.max_retry,
|
jail.ban_time, jail.find_time, jail.max_retry,
|
||||||
],
|
],
|
||||||
@@ -758,7 +757,12 @@ function InactiveJailDetail({
|
|||||||
*
|
*
|
||||||
* @returns JSX element.
|
* @returns JSX element.
|
||||||
*/
|
*/
|
||||||
export function JailsTab(): React.JSX.Element {
|
interface JailsTabProps {
|
||||||
|
/** Jail name to pre-select when the component mounts. */
|
||||||
|
initialJail?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function JailsTab({ initialJail }: JailsTabProps): React.JSX.Element {
|
||||||
const styles = useConfigStyles();
|
const styles = useConfigStyles();
|
||||||
const { jails, loading, error, refresh, updateJail } =
|
const { jails, loading, error, refresh, updateJail } =
|
||||||
useJailConfigs();
|
useJailConfigs();
|
||||||
@@ -819,6 +823,13 @@ export function JailsTab(): React.JSX.Element {
|
|||||||
return [...activeItems, ...inactiveItems];
|
return [...activeItems, ...inactiveItems];
|
||||||
}, [jails, inactiveJails]);
|
}, [jails, inactiveJails]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!initialJail || selectedName) return;
|
||||||
|
if (listItems.some((item) => item.name === initialJail)) {
|
||||||
|
setSelectedName(initialJail);
|
||||||
|
}
|
||||||
|
}, [initialJail, listItems, selectedName]);
|
||||||
|
|
||||||
const activeJailMap = useMemo(
|
const activeJailMap = useMemo(
|
||||||
() => new Map(jails.map((j) => [j.name, j])),
|
() => new Map(jails.map((j) => [j.name, j])),
|
||||||
[jails],
|
[jails],
|
||||||
|
|||||||
84
frontend/src/components/config/__tests__/JailsTab.test.tsx
Normal file
84
frontend/src/components/config/__tests__/JailsTab.test.tsx
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { render } from "@testing-library/react";
|
||||||
|
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
|
||||||
|
|
||||||
|
import { JailsTab } from "../JailsTab";
|
||||||
|
import type { JailConfig } from "../../../types/config";
|
||||||
|
import { useAutoSave } from "../../../hooks/useAutoSave";
|
||||||
|
import { useJailConfigs } from "../../../hooks/useConfig";
|
||||||
|
import { useConfigActiveStatus } from "../../../hooks/useConfigActiveStatus";
|
||||||
|
|
||||||
|
vi.mock("../../../hooks/useAutoSave");
|
||||||
|
vi.mock("../../../hooks/useConfig");
|
||||||
|
vi.mock("../../../hooks/useConfigActiveStatus");
|
||||||
|
vi.mock("../../../api/config", () => ({
|
||||||
|
fetchInactiveJails: vi.fn().mockResolvedValue({ jails: [] }),
|
||||||
|
deactivateJail: vi.fn(),
|
||||||
|
deleteJailLocalOverride: vi.fn(),
|
||||||
|
addLogPath: vi.fn(),
|
||||||
|
deleteLogPath: vi.fn(),
|
||||||
|
fetchJailConfigFileContent: vi.fn(),
|
||||||
|
updateJailConfigFile: vi.fn(),
|
||||||
|
validateJailConfig: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockUseAutoSave = vi.mocked(useAutoSave);
|
||||||
|
const mockUseJailConfigs = vi.mocked(useJailConfigs);
|
||||||
|
const mockUseConfigActiveStatus = vi.mocked(useConfigActiveStatus);
|
||||||
|
|
||||||
|
const basicJail: JailConfig = {
|
||||||
|
name: "sshd",
|
||||||
|
ban_time: 600,
|
||||||
|
max_retry: 5,
|
||||||
|
find_time: 600,
|
||||||
|
fail_regex: [],
|
||||||
|
ignore_regex: [],
|
||||||
|
log_paths: [],
|
||||||
|
date_pattern: null,
|
||||||
|
log_encoding: "auto",
|
||||||
|
backend: "polling",
|
||||||
|
use_dns: "warn",
|
||||||
|
prefregex: "",
|
||||||
|
actions: [],
|
||||||
|
bantime_escalation: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("JailsTab", () => {
|
||||||
|
it("does not include backend in auto-save payload", () => {
|
||||||
|
const autoSavePayloads: Array<Record<string, unknown>> = [];
|
||||||
|
mockUseAutoSave.mockImplementation((value) => {
|
||||||
|
autoSavePayloads.push(value as Record<string, unknown>);
|
||||||
|
return { status: "idle", errorText: null, retry: vi.fn() };
|
||||||
|
});
|
||||||
|
|
||||||
|
mockUseJailConfigs.mockReturnValue({
|
||||||
|
jails: [basicJail],
|
||||||
|
total: 1,
|
||||||
|
loading: false,
|
||||||
|
error: null,
|
||||||
|
refresh: vi.fn(),
|
||||||
|
updateJail: vi.fn(),
|
||||||
|
reloadAll: vi.fn(),
|
||||||
|
});
|
||||||
|
|
||||||
|
mockUseConfigActiveStatus.mockReturnValue({
|
||||||
|
activeJails: new Set<string>(),
|
||||||
|
activeFilters: new Set<string>(),
|
||||||
|
activeActions: new Set<string>(),
|
||||||
|
loading: false,
|
||||||
|
error: null,
|
||||||
|
refresh: vi.fn(),
|
||||||
|
});
|
||||||
|
|
||||||
|
render(
|
||||||
|
<FluentProvider theme={webLightTheme}>
|
||||||
|
<JailsTab initialJail="sshd" />
|
||||||
|
</FluentProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(autoSavePayloads.length).toBeGreaterThan(0);
|
||||||
|
const lastPayload = autoSavePayloads[autoSavePayloads.length - 1];
|
||||||
|
|
||||||
|
expect(lastPayload).not.toHaveProperty("backend");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
|
||||||
|
import { ServerHealthSection } from "../ServerHealthSection";
|
||||||
|
|
||||||
|
vi.mock("../../../api/config");
|
||||||
|
|
||||||
|
import { fetchFail2BanLog, fetchServiceStatus } from "../../../api/config";
|
||||||
|
|
||||||
|
const mockedFetchServiceStatus = vi.mocked(fetchServiceStatus);
|
||||||
|
const mockedFetchFail2BanLog = vi.mocked(fetchFail2BanLog);
|
||||||
|
|
||||||
|
describe("ServerHealthSection", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows the version in the service health panel", async () => {
|
||||||
|
mockedFetchServiceStatus.mockResolvedValue({
|
||||||
|
online: true,
|
||||||
|
version: "1.2.3",
|
||||||
|
jail_count: 2,
|
||||||
|
total_bans: 5,
|
||||||
|
total_failures: 1,
|
||||||
|
log_level: "INFO",
|
||||||
|
log_target: "STDOUT",
|
||||||
|
});
|
||||||
|
|
||||||
|
mockedFetchFail2BanLog.mockResolvedValue({
|
||||||
|
log_path: "/var/log/fail2ban.log",
|
||||||
|
lines: ["2026-01-01 fail2ban[123]: INFO Test"],
|
||||||
|
total_lines: 1,
|
||||||
|
log_level: "INFO",
|
||||||
|
log_target: "STDOUT",
|
||||||
|
});
|
||||||
|
|
||||||
|
render(
|
||||||
|
<FluentProvider theme={webLightTheme}>
|
||||||
|
<ServerHealthSection />
|
||||||
|
</FluentProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
// The service health panel should render and include the version.
|
||||||
|
const versionLabel = await screen.findByText("Version");
|
||||||
|
expect(versionLabel).toBeInTheDocument();
|
||||||
|
|
||||||
|
const versionCard = versionLabel.closest("div");
|
||||||
|
expect(versionCard).toHaveTextContent("1.2.3");
|
||||||
|
});
|
||||||
|
});
|
||||||
74
frontend/src/hooks/__tests__/useActionConfig.test.ts
Normal file
74
frontend/src/hooks/__tests__/useActionConfig.test.ts
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
import { renderHook, act } from "@testing-library/react";
|
||||||
|
import * as configApi from "../../api/config";
|
||||||
|
import { useActionConfig } from "../useActionConfig";
|
||||||
|
|
||||||
|
vi.mock("../../api/config");
|
||||||
|
|
||||||
|
describe("useActionConfig", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
vi.mocked(configApi.fetchAction).mockResolvedValue({
|
||||||
|
name: "iptables",
|
||||||
|
filename: "iptables.conf",
|
||||||
|
source_file: "/etc/fail2ban/action.d/iptables.conf",
|
||||||
|
active: false,
|
||||||
|
used_by_jails: [],
|
||||||
|
before: null,
|
||||||
|
after: null,
|
||||||
|
actionstart: "",
|
||||||
|
actionstop: "",
|
||||||
|
actioncheck: "",
|
||||||
|
actionban: "",
|
||||||
|
actionunban: "",
|
||||||
|
actionflush: "",
|
||||||
|
definition_vars: {},
|
||||||
|
init_vars: {},
|
||||||
|
has_local_override: false,
|
||||||
|
});
|
||||||
|
vi.mocked(configApi.updateAction).mockResolvedValue(undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("calls fetchAction exactly once for stable name and rerenders", async () => {
|
||||||
|
const { rerender } = renderHook(
|
||||||
|
({ name }) => useActionConfig(name),
|
||||||
|
{ initialProps: { name: "iptables" } },
|
||||||
|
);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(configApi.fetchAction).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
// Rerender with the same action name; fetch should not be called again.
|
||||||
|
rerender({ name: "iptables" });
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(configApi.fetchAction).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("calls fetchAction again when name changes", async () => {
|
||||||
|
const { rerender } = renderHook(
|
||||||
|
({ name }) => useActionConfig(name),
|
||||||
|
{ initialProps: { name: "iptables" } },
|
||||||
|
);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(configApi.fetchAction).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
rerender({ name: "ssh" });
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(configApi.fetchAction).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
72
frontend/src/hooks/__tests__/useFilterConfig.test.ts
Normal file
72
frontend/src/hooks/__tests__/useFilterConfig.test.ts
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
import { renderHook, act } from "@testing-library/react";
|
||||||
|
import * as configApi from "../../api/config";
|
||||||
|
import { useFilterConfig } from "../useFilterConfig";
|
||||||
|
|
||||||
|
vi.mock("../../api/config");
|
||||||
|
|
||||||
|
describe("useFilterConfig", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
vi.mocked(configApi.fetchParsedFilter).mockResolvedValue({
|
||||||
|
name: "sshd",
|
||||||
|
filename: "sshd.conf",
|
||||||
|
source_file: "/etc/fail2ban/filter.d/sshd.conf",
|
||||||
|
active: false,
|
||||||
|
used_by_jails: [],
|
||||||
|
before: null,
|
||||||
|
after: null,
|
||||||
|
variables: {},
|
||||||
|
prefregex: null,
|
||||||
|
failregex: [],
|
||||||
|
ignoreregex: [],
|
||||||
|
maxlines: null,
|
||||||
|
datepattern: null,
|
||||||
|
journalmatch: null,
|
||||||
|
has_local_override: false,
|
||||||
|
});
|
||||||
|
vi.mocked(configApi.updateParsedFilter).mockResolvedValue(undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("calls fetchParsedFilter only once for stable name", async () => {
|
||||||
|
const { rerender } = renderHook(
|
||||||
|
({ name }) => useFilterConfig(name),
|
||||||
|
{ initialProps: { name: "sshd" } },
|
||||||
|
);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(configApi.fetchParsedFilter).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
rerender({ name: "sshd" });
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(configApi.fetchParsedFilter).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("calls fetchParsedFilter again when name changes", async () => {
|
||||||
|
const { rerender } = renderHook(
|
||||||
|
({ name }) => useFilterConfig(name),
|
||||||
|
{ initialProps: { name: "sshd" } },
|
||||||
|
);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(configApi.fetchParsedFilter).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
rerender({ name: "apache-auth" });
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(configApi.fetchParsedFilter).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -36,7 +36,7 @@ describe("useJailDetail control methods", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("calls start() and refetches jail data", async () => {
|
it("calls start() and refetches jail data", async () => {
|
||||||
vi.mocked(jailsApi.startJail).mockResolvedValue(undefined);
|
vi.mocked(jailsApi.startJail).mockResolvedValue({ message: "jail started", jail: "sshd" });
|
||||||
|
|
||||||
const { result } = renderHook(() => useJailDetail("sshd"));
|
const { result } = renderHook(() => useJailDetail("sshd"));
|
||||||
|
|
||||||
@@ -58,7 +58,7 @@ describe("useJailDetail control methods", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("calls stop() and refetches jail data", async () => {
|
it("calls stop() and refetches jail data", async () => {
|
||||||
vi.mocked(jailsApi.stopJail).mockResolvedValue(undefined);
|
vi.mocked(jailsApi.stopJail).mockResolvedValue({ message: "jail stopped", jail: "sshd" });
|
||||||
|
|
||||||
const { result } = renderHook(() => useJailDetail("sshd"));
|
const { result } = renderHook(() => useJailDetail("sshd"));
|
||||||
|
|
||||||
@@ -77,7 +77,7 @@ describe("useJailDetail control methods", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("calls reload() and refetches jail data", async () => {
|
it("calls reload() and refetches jail data", async () => {
|
||||||
vi.mocked(jailsApi.reloadJail).mockResolvedValue(undefined);
|
vi.mocked(jailsApi.reloadJail).mockResolvedValue({ message: "jail reloaded", jail: "sshd" });
|
||||||
|
|
||||||
const { result } = renderHook(() => useJailDetail("sshd"));
|
const { result } = renderHook(() => useJailDetail("sshd"));
|
||||||
|
|
||||||
@@ -96,7 +96,7 @@ describe("useJailDetail control methods", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("calls setIdle() with correct parameter and refetches jail data", async () => {
|
it("calls setIdle() with correct parameter and refetches jail data", async () => {
|
||||||
vi.mocked(jailsApi.setJailIdle).mockResolvedValue(undefined);
|
vi.mocked(jailsApi.setJailIdle).mockResolvedValue({ message: "jail idle toggled", jail: "sshd" });
|
||||||
|
|
||||||
const { result } = renderHook(() => useJailDetail("sshd"));
|
const { result } = renderHook(() => useJailDetail("sshd"));
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
* React hook for loading and updating a single parsed action config.
|
* React hook for loading and updating a single parsed action config.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { useCallback } from "react";
|
||||||
import { useConfigItem } from "./useConfigItem";
|
import { useConfigItem } from "./useConfigItem";
|
||||||
import { fetchAction, updateAction } from "../api/config";
|
import { fetchAction, updateAction } from "../api/config";
|
||||||
import type { ActionConfig, ActionConfigUpdate } from "../types/config";
|
import type { ActionConfig, ActionConfigUpdate } from "../types/config";
|
||||||
@@ -23,12 +24,18 @@ export interface UseActionConfigResult {
|
|||||||
* @param name - Action base name (e.g. ``"iptables"``).
|
* @param name - Action base name (e.g. ``"iptables"``).
|
||||||
*/
|
*/
|
||||||
export function useActionConfig(name: string): UseActionConfigResult {
|
export function useActionConfig(name: string): UseActionConfigResult {
|
||||||
|
const fetchFn = useCallback(() => fetchAction(name), [name]);
|
||||||
|
const saveFn = useCallback(
|
||||||
|
(update: ActionConfigUpdate) => updateAction(name, update),
|
||||||
|
[name],
|
||||||
|
);
|
||||||
|
|
||||||
const { data, loading, error, saving, saveError, refresh, save } = useConfigItem<
|
const { data, loading, error, saving, saveError, refresh, save } = useConfigItem<
|
||||||
ActionConfig,
|
ActionConfig,
|
||||||
ActionConfigUpdate
|
ActionConfigUpdate
|
||||||
>({
|
>({
|
||||||
fetchFn: () => fetchAction(name),
|
fetchFn,
|
||||||
saveFn: (update) => updateAction(name, update),
|
saveFn,
|
||||||
mergeOnSave: (prev, update) =>
|
mergeOnSave: (prev, update) =>
|
||||||
prev
|
prev
|
||||||
? {
|
? {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
* React hook for loading and updating a single parsed filter config.
|
* React hook for loading and updating a single parsed filter config.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { useCallback } from "react";
|
||||||
import { useConfigItem } from "./useConfigItem";
|
import { useConfigItem } from "./useConfigItem";
|
||||||
import { fetchParsedFilter, updateParsedFilter } from "../api/config";
|
import { fetchParsedFilter, updateParsedFilter } from "../api/config";
|
||||||
import type { FilterConfig, FilterConfigUpdate } from "../types/config";
|
import type { FilterConfig, FilterConfigUpdate } from "../types/config";
|
||||||
@@ -23,12 +24,18 @@ export interface UseFilterConfigResult {
|
|||||||
* @param name - Filter base name (e.g. ``"sshd"``).
|
* @param name - Filter base name (e.g. ``"sshd"``).
|
||||||
*/
|
*/
|
||||||
export function useFilterConfig(name: string): UseFilterConfigResult {
|
export function useFilterConfig(name: string): UseFilterConfigResult {
|
||||||
|
const fetchFn = useCallback(() => fetchParsedFilter(name), [name]);
|
||||||
|
const saveFn = useCallback(
|
||||||
|
(update: FilterConfigUpdate) => updateParsedFilter(name, update),
|
||||||
|
[name],
|
||||||
|
);
|
||||||
|
|
||||||
const { data, loading, error, saving, saveError, refresh, save } = useConfigItem<
|
const { data, loading, error, saving, saveError, refresh, save } = useConfigItem<
|
||||||
FilterConfig,
|
FilterConfig,
|
||||||
FilterConfigUpdate
|
FilterConfigUpdate
|
||||||
>({
|
>({
|
||||||
fetchFn: () => fetchParsedFilter(name),
|
fetchFn,
|
||||||
saveFn: (update) => updateParsedFilter(name, update),
|
saveFn,
|
||||||
mergeOnSave: (prev, update) =>
|
mergeOnSave: (prev, update) =>
|
||||||
prev
|
prev
|
||||||
? {
|
? {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
* React hook for loading and updating a single parsed jail.d config file.
|
* React hook for loading and updating a single parsed jail.d config file.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { useCallback } from "react";
|
||||||
import { useConfigItem } from "./useConfigItem";
|
import { useConfigItem } from "./useConfigItem";
|
||||||
import { fetchParsedJailFile, updateParsedJailFile } from "../api/config";
|
import { fetchParsedJailFile, updateParsedJailFile } from "../api/config";
|
||||||
import type { JailFileConfig, JailFileConfigUpdate } from "../types/config";
|
import type { JailFileConfig, JailFileConfigUpdate } from "../types/config";
|
||||||
@@ -21,12 +22,18 @@ export interface UseJailFileConfigResult {
|
|||||||
* @param filename - Filename including extension (e.g. ``"sshd.conf"``).
|
* @param filename - Filename including extension (e.g. ``"sshd.conf"``).
|
||||||
*/
|
*/
|
||||||
export function useJailFileConfig(filename: string): UseJailFileConfigResult {
|
export function useJailFileConfig(filename: string): UseJailFileConfigResult {
|
||||||
|
const fetchFn = useCallback(() => fetchParsedJailFile(filename), [filename]);
|
||||||
|
const saveFn = useCallback(
|
||||||
|
(update: JailFileConfigUpdate) => updateParsedJailFile(filename, update),
|
||||||
|
[filename],
|
||||||
|
);
|
||||||
|
|
||||||
const { data, loading, error, refresh, save } = useConfigItem<
|
const { data, loading, error, refresh, save } = useConfigItem<
|
||||||
JailFileConfig,
|
JailFileConfig,
|
||||||
JailFileConfigUpdate
|
JailFileConfigUpdate
|
||||||
>({
|
>({
|
||||||
fetchFn: () => fetchParsedJailFile(filename),
|
fetchFn,
|
||||||
saveFn: (update) => updateParsedJailFile(filename, update),
|
saveFn,
|
||||||
mergeOnSave: (prev, update) =>
|
mergeOnSave: (prev, update) =>
|
||||||
update.jails != null && prev
|
update.jails != null && prev
|
||||||
? { ...prev, jails: { ...prev.jails, ...update.jails } }
|
? { ...prev, jails: { ...prev.jails, ...update.jails } }
|
||||||
|
|||||||
@@ -97,3 +97,21 @@ export function useMapData(
|
|||||||
refresh: load,
|
refresh: load,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test helper: returns arguments most recently used to call `useMapData`.
|
||||||
|
*
|
||||||
|
* This helper is only intended for test use with a mock implementation.
|
||||||
|
*/
|
||||||
|
export function getLastArgs(): { range: string; origin: string } {
|
||||||
|
throw new Error("getLastArgs is only available in tests with a mocked useMapData");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test helper: mutates mocked map data state.
|
||||||
|
*
|
||||||
|
* This helper is only intended for test use with a mock implementation.
|
||||||
|
*/
|
||||||
|
export function setMapData(_: Partial<UseMapDataResult>): void {
|
||||||
|
throw new Error("setMapData is only available in tests with a mocked useMapData");
|
||||||
|
}
|
||||||
|
|||||||
@@ -313,7 +313,7 @@ export function MainLayout(): React.JSX.Element {
|
|||||||
<div className={styles.sidebarFooter}>
|
<div className={styles.sidebarFooter}>
|
||||||
{!collapsed && (
|
{!collapsed && (
|
||||||
<Text className={styles.versionText}>
|
<Text className={styles.versionText}>
|
||||||
BanGUI v{__APP_VERSION__}
|
BanGUI
|
||||||
</Text>
|
</Text>
|
||||||
)}
|
)}
|
||||||
<Tooltip
|
<Tooltip
|
||||||
|
|||||||
@@ -63,16 +63,16 @@ describe("MainLayout", () => {
|
|||||||
expect(screen.getByRole("navigation", { name: "Main navigation" })).toBeInTheDocument();
|
expect(screen.getByRole("navigation", { name: "Main navigation" })).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("shows the BanGUI version in the sidebar footer when expanded", () => {
|
it("does not show the BanGUI application version in the sidebar footer", () => {
|
||||||
renderLayout();
|
renderLayout();
|
||||||
// __APP_VERSION__ is stubbed to "0.0.0-test" via vitest.config.ts define.
|
// __APP_VERSION__ is stubbed to "0.0.0-test" via vitest.config.ts define.
|
||||||
expect(screen.getByText("BanGUI v0.0.0-test")).toBeInTheDocument();
|
expect(screen.queryByText(/BanGUI v/)).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("hides the BanGUI version text when the sidebar is collapsed", async () => {
|
it("hides the logo text when the sidebar is collapsed", async () => {
|
||||||
renderLayout();
|
renderLayout();
|
||||||
const toggleButton = screen.getByRole("button", { name: /collapse sidebar/i });
|
const toggleButton = screen.getByRole("button", { name: /collapse sidebar/i });
|
||||||
await userEvent.click(toggleButton);
|
await userEvent.click(toggleButton);
|
||||||
expect(screen.queryByText("BanGUI v0.0.0-test")).not.toBeInTheDocument();
|
expect(screen.queryByText("BanGUI")).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
import { useCallback, useState } from "react";
|
import { useCallback, useState } from "react";
|
||||||
import { Button, MessageBar, MessageBarBody, Text } from "@fluentui/react-components";
|
import { Button, MessageBar, MessageBarBody, Text } from "@fluentui/react-components";
|
||||||
import { useBlocklistStyles } from "../theme/commonStyles";
|
import { useBlocklistStyles } from "../components/blocklist/blocklistStyles";
|
||||||
|
|
||||||
import { BlocklistSourcesSection } from "../components/blocklist/BlocklistSourcesSection";
|
import { BlocklistSourcesSection } from "../components/blocklist/BlocklistSourcesSection";
|
||||||
import { BlocklistScheduleSection } from "../components/blocklist/BlocklistScheduleSection";
|
import { BlocklistScheduleSection } from "../components/blocklist/BlocklistScheduleSection";
|
||||||
|
|||||||
@@ -13,7 +13,8 @@
|
|||||||
* Export — raw file editors for jail, filter, and action files
|
* Export — raw file editors for jail, filter, and action files
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import { useLocation } from "react-router-dom";
|
||||||
import { Tab, TabList, Text, makeStyles, tokens } from "@fluentui/react-components";
|
import { Tab, TabList, Text, makeStyles, tokens } from "@fluentui/react-components";
|
||||||
import {
|
import {
|
||||||
ActionsTab,
|
ActionsTab,
|
||||||
@@ -58,8 +59,16 @@ type TabValue =
|
|||||||
|
|
||||||
export function ConfigPage(): React.JSX.Element {
|
export function ConfigPage(): React.JSX.Element {
|
||||||
const styles = useStyles();
|
const styles = useStyles();
|
||||||
|
const location = useLocation();
|
||||||
const [tab, setTab] = useState<TabValue>("jails");
|
const [tab, setTab] = useState<TabValue>("jails");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const state = location.state as { tab?: string; jail?: string } | null;
|
||||||
|
if (state?.tab === "jails") {
|
||||||
|
setTab("jails");
|
||||||
|
}
|
||||||
|
}, [location.state]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.page}>
|
<div className={styles.page}>
|
||||||
<div className={styles.header}>
|
<div className={styles.header}>
|
||||||
@@ -86,7 +95,11 @@ export function ConfigPage(): React.JSX.Element {
|
|||||||
</TabList>
|
</TabList>
|
||||||
|
|
||||||
<div className={styles.tabContent} key={tab}>
|
<div className={styles.tabContent} key={tab}>
|
||||||
{tab === "jails" && <JailsTab />}
|
{tab === "jails" && (
|
||||||
|
<JailsTab
|
||||||
|
initialJail={(location.state as { jail?: string } | null)?.jail}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{tab === "filters" && <FiltersTab />}
|
{tab === "filters" && <FiltersTab />}
|
||||||
{tab === "actions" && <ActionsTab />}
|
{tab === "actions" && <ActionsTab />}
|
||||||
{tab === "server" && <ServerTab />}
|
{tab === "server" && <ServerTab />}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
* Rows with repeatedly-banned IPs are highlighted in amber.
|
* Rows with repeatedly-banned IPs are highlighted in amber.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { useCallback, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import {
|
import {
|
||||||
Badge,
|
Badge,
|
||||||
Button,
|
Button,
|
||||||
@@ -19,7 +19,6 @@ import {
|
|||||||
Input,
|
Input,
|
||||||
MessageBar,
|
MessageBar,
|
||||||
MessageBarBody,
|
MessageBarBody,
|
||||||
Select,
|
|
||||||
Spinner,
|
Spinner,
|
||||||
Table,
|
Table,
|
||||||
TableBody,
|
TableBody,
|
||||||
@@ -43,8 +42,10 @@ import {
|
|||||||
ChevronLeftRegular,
|
ChevronLeftRegular,
|
||||||
ChevronRightRegular,
|
ChevronRightRegular,
|
||||||
} from "@fluentui/react-icons";
|
} from "@fluentui/react-icons";
|
||||||
|
import { DashboardFilterBar } from "../components/DashboardFilterBar";
|
||||||
import { useHistory, useIpHistory } from "../hooks/useHistory";
|
import { useHistory, useIpHistory } from "../hooks/useHistory";
|
||||||
import type { HistoryBanItem, HistoryQuery, TimeRange } from "../types/history";
|
import type { HistoryBanItem, HistoryQuery, TimeRange } from "../types/history";
|
||||||
|
import type { BanOriginFilter } from "../types/ban";
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Constants
|
// Constants
|
||||||
@@ -55,13 +56,6 @@ const HIGH_BAN_THRESHOLD = 5;
|
|||||||
|
|
||||||
const PAGE_SIZE = 50;
|
const PAGE_SIZE = 50;
|
||||||
|
|
||||||
const TIME_RANGE_OPTIONS: { label: string; value: TimeRange }[] = [
|
|
||||||
{ label: "Last 24 hours", value: "24h" },
|
|
||||||
{ label: "Last 7 days", value: "7d" },
|
|
||||||
{ label: "Last 30 days", value: "30d" },
|
|
||||||
{ label: "Last 365 days", value: "365d" },
|
|
||||||
];
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Styles
|
// Styles
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -142,6 +136,24 @@ const useStyles = makeStyles({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Utilities
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function areHistoryQueriesEqual(
|
||||||
|
a: HistoryQuery,
|
||||||
|
b: HistoryQuery,
|
||||||
|
): boolean {
|
||||||
|
return (
|
||||||
|
a.range === b.range &&
|
||||||
|
a.origin === b.origin &&
|
||||||
|
a.jail === b.jail &&
|
||||||
|
a.ip === b.ip &&
|
||||||
|
a.page === b.page &&
|
||||||
|
a.page_size === b.page_size
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Column definitions for the main history table
|
// Column definitions for the main history table
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -378,9 +390,11 @@ function IpDetailView({ ip, onBack }: IpDetailViewProps): React.JSX.Element {
|
|||||||
|
|
||||||
export function HistoryPage(): React.JSX.Element {
|
export function HistoryPage(): React.JSX.Element {
|
||||||
const styles = useStyles();
|
const styles = useStyles();
|
||||||
|
const cardStyles = useCardStyles();
|
||||||
|
|
||||||
// Filter state
|
// Filter state
|
||||||
const [range, setRange] = useState<TimeRange | undefined>(undefined);
|
const [range, setRange] = useState<TimeRange>("24h");
|
||||||
|
const [originFilter, setOriginFilter] = useState<BanOriginFilter>("all");
|
||||||
const [jailFilter, setJailFilter] = useState("");
|
const [jailFilter, setJailFilter] = useState("");
|
||||||
const [ipFilter, setIpFilter] = useState("");
|
const [ipFilter, setIpFilter] = useState("");
|
||||||
const [appliedQuery, setAppliedQuery] = useState<HistoryQuery>({
|
const [appliedQuery, setAppliedQuery] = useState<HistoryQuery>({
|
||||||
@@ -393,14 +407,23 @@ export function HistoryPage(): React.JSX.Element {
|
|||||||
const { items, total, page, loading, error, setPage, refresh } =
|
const { items, total, page, loading, error, setPage, refresh } =
|
||||||
useHistory(appliedQuery);
|
useHistory(appliedQuery);
|
||||||
|
|
||||||
const applyFilters = useCallback((): void => {
|
useEffect((): void => {
|
||||||
setAppliedQuery({
|
const nextQuery: HistoryQuery = {
|
||||||
range: range,
|
range,
|
||||||
|
origin: originFilter !== "all" ? originFilter : undefined,
|
||||||
jail: jailFilter.trim() || undefined,
|
jail: jailFilter.trim() || undefined,
|
||||||
ip: ipFilter.trim() || undefined,
|
ip: ipFilter.trim() || undefined,
|
||||||
|
page: 1,
|
||||||
page_size: PAGE_SIZE,
|
page_size: PAGE_SIZE,
|
||||||
});
|
};
|
||||||
}, [range, jailFilter, ipFilter]);
|
|
||||||
|
if (areHistoryQueriesEqual(nextQuery, appliedQuery)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setPage(1);
|
||||||
|
setAppliedQuery(nextQuery);
|
||||||
|
}, [range, originFilter, jailFilter, ipFilter, setPage, appliedQuery]);
|
||||||
|
|
||||||
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
|
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
|
||||||
|
|
||||||
@@ -451,26 +474,18 @@ export function HistoryPage(): React.JSX.Element {
|
|||||||
{/* Filter bar */}
|
{/* Filter bar */}
|
||||||
{/* ---------------------------------------------------------------- */}
|
{/* ---------------------------------------------------------------- */}
|
||||||
<div className={styles.filterRow}>
|
<div className={styles.filterRow}>
|
||||||
<div className={styles.filterLabel}>
|
<DashboardFilterBar
|
||||||
<Text size={200}>Time range</Text>
|
timeRange={range}
|
||||||
<Select
|
onTimeRangeChange={(value) => {
|
||||||
aria-label="Time range"
|
setRange(value);
|
||||||
value={range ?? ""}
|
}}
|
||||||
onChange={(_ev, data): void => {
|
originFilter={originFilter}
|
||||||
setRange(data.value === "" ? undefined : (data.value as TimeRange));
|
onOriginFilterChange={(value) => {
|
||||||
}}
|
setOriginFilter(value);
|
||||||
size="small"
|
}}
|
||||||
>
|
/>
|
||||||
<option value="">All time</option>
|
|
||||||
{TIME_RANGE_OPTIONS.map((o) => (
|
|
||||||
<option key={o.value} value={o.value}>
|
|
||||||
{o.label}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className={styles.filterLabel}>
|
<div className={`${styles.filterLabel} ${cardStyles.card}`}>
|
||||||
<Text size={200}>Jail</Text>
|
<Text size={200}>Jail</Text>
|
||||||
<Input
|
<Input
|
||||||
placeholder="e.g. sshd"
|
placeholder="e.g. sshd"
|
||||||
@@ -482,7 +497,7 @@ export function HistoryPage(): React.JSX.Element {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className={styles.filterLabel}>
|
<div className={`${styles.filterLabel} ${cardStyles.card}`}>
|
||||||
<Text size={200}>IP Address</Text>
|
<Text size={200}>IP Address</Text>
|
||||||
<Input
|
<Input
|
||||||
placeholder="e.g. 192.168"
|
placeholder="e.g. 192.168"
|
||||||
@@ -491,28 +506,9 @@ export function HistoryPage(): React.JSX.Element {
|
|||||||
setIpFilter(data.value);
|
setIpFilter(data.value);
|
||||||
}}
|
}}
|
||||||
size="small"
|
size="small"
|
||||||
onKeyDown={(e): void => {
|
|
||||||
if (e.key === "Enter") applyFilters();
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button appearance="primary" size="small" onClick={applyFilters}>
|
|
||||||
Apply
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
appearance="subtle"
|
|
||||||
size="small"
|
|
||||||
onClick={(): void => {
|
|
||||||
setRange(undefined);
|
|
||||||
setJailFilter("");
|
|
||||||
setIpFilter("");
|
|
||||||
setAppliedQuery({ page_size: PAGE_SIZE });
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Clear
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* ---------------------------------------------------------------- */}
|
{/* ---------------------------------------------------------------- */}
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import {
|
|||||||
Button,
|
Button,
|
||||||
MessageBar,
|
MessageBar,
|
||||||
MessageBarBody,
|
MessageBarBody,
|
||||||
Select,
|
|
||||||
Spinner,
|
Spinner,
|
||||||
Table,
|
Table,
|
||||||
TableBody,
|
TableBody,
|
||||||
@@ -22,19 +21,22 @@ import {
|
|||||||
TableHeaderCell,
|
TableHeaderCell,
|
||||||
TableRow,
|
TableRow,
|
||||||
Text,
|
Text,
|
||||||
Toolbar,
|
|
||||||
ToolbarButton,
|
|
||||||
Tooltip,
|
Tooltip,
|
||||||
makeStyles,
|
makeStyles,
|
||||||
tokens,
|
tokens,
|
||||||
} from "@fluentui/react-components";
|
} from "@fluentui/react-components";
|
||||||
import { ArrowCounterclockwiseRegular, DismissRegular } from "@fluentui/react-icons";
|
import {
|
||||||
|
ArrowCounterclockwiseRegular,
|
||||||
|
ChevronLeftRegular,
|
||||||
|
ChevronRightRegular,
|
||||||
|
DismissRegular,
|
||||||
|
} from "@fluentui/react-icons";
|
||||||
|
import { DashboardFilterBar } from "../components/DashboardFilterBar";
|
||||||
import { WorldMap } from "../components/WorldMap";
|
import { WorldMap } from "../components/WorldMap";
|
||||||
import { useMapData } from "../hooks/useMapData";
|
import { useMapData } from "../hooks/useMapData";
|
||||||
import { useMapColorThresholds } from "../hooks/useMapColorThresholds";
|
import { useMapColorThresholds } from "../hooks/useMapColorThresholds";
|
||||||
import type { TimeRange } from "../types/map";
|
import type { TimeRange } from "../types/map";
|
||||||
import type { BanOriginFilter } from "../types/ban";
|
import type { BanOriginFilter } from "../types/ban";
|
||||||
import { BAN_ORIGIN_FILTER_LABELS } from "../types/ban";
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Styles
|
// Styles
|
||||||
@@ -56,34 +58,32 @@ const useStyles = makeStyles({
|
|||||||
flexWrap: "wrap",
|
flexWrap: "wrap",
|
||||||
gap: tokens.spacingHorizontalM,
|
gap: tokens.spacingHorizontalM,
|
||||||
},
|
},
|
||||||
filterBar: {
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: tokens.spacingHorizontalM,
|
|
||||||
padding: `${tokens.spacingVerticalS} ${tokens.spacingHorizontalM}`,
|
|
||||||
background: tokens.colorNeutralBackground3,
|
|
||||||
borderRadius: tokens.borderRadiusMedium,
|
|
||||||
border: `1px solid ${tokens.colorNeutralStroke2}`,
|
|
||||||
},
|
|
||||||
tableWrapper: {
|
tableWrapper: {
|
||||||
overflow: "auto",
|
overflow: "auto",
|
||||||
maxHeight: "420px",
|
maxHeight: "420px",
|
||||||
borderRadius: tokens.borderRadiusMedium,
|
borderRadius: tokens.borderRadiusMedium,
|
||||||
border: `1px solid ${tokens.colorNeutralStroke1}`,
|
border: `1px solid ${tokens.colorNeutralStroke1}`,
|
||||||
},
|
},
|
||||||
|
filterBar: {
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
gap: tokens.spacingHorizontalM,
|
||||||
|
padding: tokens.spacingVerticalS,
|
||||||
|
borderRadius: tokens.borderRadiusMedium,
|
||||||
|
backgroundColor: tokens.colorNeutralBackground2,
|
||||||
|
},
|
||||||
|
pagination: {
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
gap: tokens.spacingHorizontalS,
|
||||||
|
padding: `${tokens.spacingVerticalS} ${tokens.spacingHorizontalM}`,
|
||||||
|
borderTop: `1px solid ${tokens.colorNeutralStroke2}`,
|
||||||
|
backgroundColor: tokens.colorNeutralBackground2,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Time-range options
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
const TIME_RANGE_OPTIONS: { label: string; value: TimeRange }[] = [
|
|
||||||
{ label: "Last 24 hours", value: "24h" },
|
|
||||||
{ label: "Last 7 days", value: "7d" },
|
|
||||||
{ label: "Last 30 days", value: "30d" },
|
|
||||||
{ label: "Last 365 days", value: "365d" },
|
|
||||||
];
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// MapPage
|
// MapPage
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -93,6 +93,10 @@ export function MapPage(): React.JSX.Element {
|
|||||||
const [range, setRange] = useState<TimeRange>("24h");
|
const [range, setRange] = useState<TimeRange>("24h");
|
||||||
const [originFilter, setOriginFilter] = useState<BanOriginFilter>("all");
|
const [originFilter, setOriginFilter] = useState<BanOriginFilter>("all");
|
||||||
const [selectedCountry, setSelectedCountry] = useState<string | null>(null);
|
const [selectedCountry, setSelectedCountry] = useState<string | null>(null);
|
||||||
|
const [page, setPage] = useState<number>(1);
|
||||||
|
const [pageSize, setPageSize] = useState<number>(100);
|
||||||
|
|
||||||
|
const PAGE_SIZE_OPTIONS = [25, 50, 100] as const;
|
||||||
|
|
||||||
const { countries, countryNames, bans, total, loading, error, refresh } =
|
const { countries, countryNames, bans, total, loading, error, refresh } =
|
||||||
useMapData(range, originFilter);
|
useMapData(range, originFilter);
|
||||||
@@ -113,6 +117,10 @@ export function MapPage(): React.JSX.Element {
|
|||||||
}
|
}
|
||||||
}, [mapThresholdError]);
|
}, [mapThresholdError]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setPage(1);
|
||||||
|
}, [range, originFilter, selectedCountry, bans, pageSize]);
|
||||||
|
|
||||||
/** Bans visible in the companion table (filtered by selected country). */
|
/** Bans visible in the companion table (filtered by selected country). */
|
||||||
const visibleBans = useMemo(() => {
|
const visibleBans = useMemo(() => {
|
||||||
if (!selectedCountry) return bans;
|
if (!selectedCountry) return bans;
|
||||||
@@ -123,6 +131,15 @@ export function MapPage(): React.JSX.Element {
|
|||||||
? (countryNames[selectedCountry] ?? selectedCountry)
|
? (countryNames[selectedCountry] ?? selectedCountry)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
|
const totalPages = Math.max(1, Math.ceil(visibleBans.length / pageSize));
|
||||||
|
const hasPrev = page > 1;
|
||||||
|
const hasNext = page < totalPages;
|
||||||
|
|
||||||
|
const pageBans = useMemo(() => {
|
||||||
|
const start = (page - 1) * pageSize;
|
||||||
|
return visibleBans.slice(start, start + pageSize);
|
||||||
|
}, [visibleBans, page, pageSize]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.root}>
|
<div className={styles.root}>
|
||||||
{/* ---------------------------------------------------------------- */}
|
{/* ---------------------------------------------------------------- */}
|
||||||
@@ -133,41 +150,20 @@ export function MapPage(): React.JSX.Element {
|
|||||||
World Map
|
World Map
|
||||||
</Text>
|
</Text>
|
||||||
|
|
||||||
<Toolbar size="small">
|
<div style={{ display: "flex", alignItems: "center", gap: tokens.spacingHorizontalM, flexWrap: "wrap" }}>
|
||||||
<Select
|
<DashboardFilterBar
|
||||||
aria-label="Time range"
|
timeRange={range}
|
||||||
value={range}
|
onTimeRangeChange={(value) => {
|
||||||
onChange={(_ev, data): void => {
|
setRange(value);
|
||||||
setRange(data.value as TimeRange);
|
|
||||||
setSelectedCountry(null);
|
setSelectedCountry(null);
|
||||||
}}
|
}}
|
||||||
size="small"
|
originFilter={originFilter}
|
||||||
>
|
onOriginFilterChange={(value) => {
|
||||||
{TIME_RANGE_OPTIONS.map((o) => (
|
setOriginFilter(value);
|
||||||
<option key={o.value} value={o.value}>
|
|
||||||
{o.label}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
|
|
||||||
{/* Origin filter */}
|
|
||||||
<Select
|
|
||||||
aria-label="Origin filter"
|
|
||||||
value={originFilter}
|
|
||||||
onChange={(_ev, data): void => {
|
|
||||||
setOriginFilter(data.value as BanOriginFilter);
|
|
||||||
setSelectedCountry(null);
|
setSelectedCountry(null);
|
||||||
}}
|
}}
|
||||||
size="small"
|
/>
|
||||||
>
|
<Button
|
||||||
{(["all", "blocklist", "selfblock"] as BanOriginFilter[]).map((f) => (
|
|
||||||
<option key={f} value={f}>
|
|
||||||
{BAN_ORIGIN_FILTER_LABELS[f]}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
|
|
||||||
<ToolbarButton
|
|
||||||
icon={<ArrowCounterclockwiseRegular />}
|
icon={<ArrowCounterclockwiseRegular />}
|
||||||
onClick={(): void => {
|
onClick={(): void => {
|
||||||
refresh();
|
refresh();
|
||||||
@@ -175,7 +171,7 @@ export function MapPage(): React.JSX.Element {
|
|||||||
disabled={loading}
|
disabled={loading}
|
||||||
title="Refresh"
|
title="Refresh"
|
||||||
/>
|
/>
|
||||||
</Toolbar>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* ---------------------------------------------------------------- */}
|
{/* ---------------------------------------------------------------- */}
|
||||||
@@ -199,6 +195,7 @@ export function MapPage(): React.JSX.Element {
|
|||||||
{!loading && !error && (
|
{!loading && !error && (
|
||||||
<WorldMap
|
<WorldMap
|
||||||
countries={countries}
|
countries={countries}
|
||||||
|
countryNames={countryNames}
|
||||||
selectedCountry={selectedCountry}
|
selectedCountry={selectedCountry}
|
||||||
onSelectCountry={setSelectedCountry}
|
onSelectCountry={setSelectedCountry}
|
||||||
thresholdLow={thresholdLow}
|
thresholdLow={thresholdLow}
|
||||||
@@ -269,7 +266,7 @@ export function MapPage(): React.JSX.Element {
|
|||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
) : (
|
) : (
|
||||||
visibleBans.map((ban) => (
|
pageBans.map((ban) => (
|
||||||
<TableRow key={`${ban.ip}-${ban.banned_at}`}>
|
<TableRow key={`${ban.ip}-${ban.banned_at}`}>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<TableCellLayout>{ban.ip}</TableCellLayout>
|
<TableCellLayout>{ban.ip}</TableCellLayout>
|
||||||
@@ -316,6 +313,53 @@ export function MapPage(): React.JSX.Element {
|
|||||||
)}
|
)}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
|
<div className={styles.pagination}>
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: tokens.spacingHorizontalS }}>
|
||||||
|
<Text size={200} style={{ color: tokens.colorNeutralForeground3 }}>
|
||||||
|
Showing {pageBans.length} of {visibleBans.length} filtered ban{visibleBans.length !== 1 ? "s" : ""}
|
||||||
|
{" · "}Page {page} of {totalPages}
|
||||||
|
</Text>
|
||||||
|
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: tokens.spacingHorizontalS }}>
|
||||||
|
<Text size={200} style={{ color: tokens.colorNeutralForeground3 }}>
|
||||||
|
Page size
|
||||||
|
</Text>
|
||||||
|
<select
|
||||||
|
aria-label="Page size"
|
||||||
|
value={pageSize}
|
||||||
|
onChange={(event): void => {
|
||||||
|
setPageSize(Number(event.target.value));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{PAGE_SIZE_OPTIONS.map((option) => (
|
||||||
|
<option key={option} value={option}>
|
||||||
|
{option}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: "flex", gap: tokens.spacingHorizontalXS }}>
|
||||||
|
<Button
|
||||||
|
icon={<ChevronLeftRegular />}
|
||||||
|
appearance="subtle"
|
||||||
|
disabled={!hasPrev}
|
||||||
|
onClick={(): void => {
|
||||||
|
setPage(page - 1);
|
||||||
|
}}
|
||||||
|
aria-label="Previous page"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
icon={<ChevronRightRegular />}
|
||||||
|
appearance="subtle"
|
||||||
|
disabled={!hasNext}
|
||||||
|
onClick={(): void => {
|
||||||
|
setPage(page + 1);
|
||||||
|
}}
|
||||||
|
aria-label="Next page"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,7 +6,11 @@ import { ConfigPage } from "../ConfigPage";
|
|||||||
|
|
||||||
// Mock all tab components to avoid deep render trees and API calls.
|
// Mock all tab components to avoid deep render trees and API calls.
|
||||||
vi.mock("../../components/config", () => ({
|
vi.mock("../../components/config", () => ({
|
||||||
JailsTab: () => <div data-testid="jails-tab">JailsTab</div>,
|
JailsTab: ({ initialJail }: { initialJail?: string }) => (
|
||||||
|
<div data-testid="jails-tab" data-initial-jail={initialJail}>
|
||||||
|
JailsTab
|
||||||
|
</div>
|
||||||
|
),
|
||||||
FiltersTab: () => <div data-testid="filters-tab">FiltersTab</div>,
|
FiltersTab: () => <div data-testid="filters-tab">FiltersTab</div>,
|
||||||
ActionsTab: () => <div data-testid="actions-tab">ActionsTab</div>,
|
ActionsTab: () => <div data-testid="actions-tab">ActionsTab</div>,
|
||||||
ServerTab: () => <div data-testid="server-tab">ServerTab</div>,
|
ServerTab: () => <div data-testid="server-tab">ServerTab</div>,
|
||||||
@@ -53,4 +57,22 @@ describe("ConfigPage", () => {
|
|||||||
renderPage();
|
renderPage();
|
||||||
expect(screen.getByRole("heading", { name: /configuration/i })).toBeInTheDocument();
|
expect(screen.getByRole("heading", { name: /configuration/i })).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("selects the Jails tab based on location state", () => {
|
||||||
|
render(
|
||||||
|
<MemoryRouter
|
||||||
|
initialEntries={[
|
||||||
|
{ pathname: "/config", state: { tab: "jails", jail: "sshd" } },
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<FluentProvider theme={webLightTheme}>
|
||||||
|
<ConfigPage />
|
||||||
|
</FluentProvider>
|
||||||
|
</MemoryRouter>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const jailsTab = screen.getByTestId("jails-tab");
|
||||||
|
expect(jailsTab).toBeInTheDocument();
|
||||||
|
expect(jailsTab).toHaveAttribute("data-initial-jail", "sshd");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
76
frontend/src/pages/__tests__/HistoryPage.test.tsx
Normal file
76
frontend/src/pages/__tests__/HistoryPage.test.tsx
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { render, screen, waitFor } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
|
||||||
|
|
||||||
|
let lastQuery: Record<string, unknown> | null = null;
|
||||||
|
const mockUseHistory = vi.fn((query: Record<string, unknown>) => {
|
||||||
|
console.log("mockUseHistory called", query);
|
||||||
|
lastQuery = query;
|
||||||
|
return {
|
||||||
|
items: [],
|
||||||
|
total: 0,
|
||||||
|
page: 1,
|
||||||
|
loading: false,
|
||||||
|
error: null,
|
||||||
|
setPage: vi.fn(),
|
||||||
|
refresh: vi.fn(),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock("../../hooks/useHistory", () => ({
|
||||||
|
useHistory: (query: Record<string, unknown>) => mockUseHistory(query),
|
||||||
|
useIpHistory: () => ({ detail: null, loading: false, error: null, refresh: vi.fn() }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../../components/WorldMap", () => ({
|
||||||
|
WorldMap: () => <div data-testid="world-map" />,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../../api/config", () => ({
|
||||||
|
fetchMapColorThresholds: async () => ({
|
||||||
|
threshold_low: 10,
|
||||||
|
threshold_medium: 50,
|
||||||
|
threshold_high: 100,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { HistoryPage } from "../HistoryPage";
|
||||||
|
|
||||||
|
describe("HistoryPage", () => {
|
||||||
|
it("auto-applies filters on change and hides apply/clear actions", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
|
||||||
|
render(
|
||||||
|
<FluentProvider theme={webLightTheme}>
|
||||||
|
<HistoryPage />
|
||||||
|
</FluentProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Initial load should include the auto-applied default query.
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(lastQuery).toEqual({
|
||||||
|
range: "24h",
|
||||||
|
origin: undefined,
|
||||||
|
jail: undefined,
|
||||||
|
ip: undefined,
|
||||||
|
page: 1,
|
||||||
|
page_size: 50,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(screen.queryByRole("button", { name: /apply/i })).toBeNull();
|
||||||
|
expect(screen.queryByRole("button", { name: /clear/i })).toBeNull();
|
||||||
|
|
||||||
|
// Time-range and origin updates should be applied automatically.
|
||||||
|
await user.click(screen.getByRole("button", { name: /Last 7 days/i }));
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(lastQuery).toMatchObject({ range: "7d" });
|
||||||
|
});
|
||||||
|
|
||||||
|
await user.click(screen.getByRole("button", { name: /Blocklist/i }));
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(lastQuery).toMatchObject({ origin: "blocklist" });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
74
frontend/src/pages/__tests__/JailsPage.test.tsx
Normal file
74
frontend/src/pages/__tests__/JailsPage.test.tsx
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
|
||||||
|
import { MemoryRouter } from "react-router-dom";
|
||||||
|
import { JailsPage } from "../JailsPage";
|
||||||
|
import type { JailSummary } from "../../types/jail";
|
||||||
|
|
||||||
|
const mockNavigate = vi.fn();
|
||||||
|
|
||||||
|
vi.mock("react-router-dom", async () => {
|
||||||
|
const actual = (await vi.importActual<typeof import("react-router-dom")>(
|
||||||
|
"react-router-dom",
|
||||||
|
)) as unknown as Record<string, unknown>;
|
||||||
|
return {
|
||||||
|
...actual,
|
||||||
|
useNavigate: () => mockNavigate,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock("../hooks/useJails", () => ({
|
||||||
|
useJails: () => ({
|
||||||
|
jails: [
|
||||||
|
{
|
||||||
|
name: "sshd",
|
||||||
|
enabled: true,
|
||||||
|
running: true,
|
||||||
|
idle: false,
|
||||||
|
backend: "systemd",
|
||||||
|
find_time: 600,
|
||||||
|
ban_time: 3600,
|
||||||
|
max_retry: 5,
|
||||||
|
status: {
|
||||||
|
currently_banned: 1,
|
||||||
|
total_banned: 10,
|
||||||
|
currently_failed: 0,
|
||||||
|
total_failed: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
] as JailSummary[],
|
||||||
|
total: 1,
|
||||||
|
loading: false,
|
||||||
|
error: null,
|
||||||
|
refresh: vi.fn(),
|
||||||
|
startJail: vi.fn().mockResolvedValue(undefined),
|
||||||
|
stopJail: vi.fn().mockResolvedValue(undefined),
|
||||||
|
setIdle: vi.fn().mockResolvedValue(undefined),
|
||||||
|
reloadJail: vi.fn().mockResolvedValue(undefined),
|
||||||
|
reloadAll: vi.fn().mockResolvedValue(undefined),
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
function renderPage() {
|
||||||
|
return render(
|
||||||
|
<MemoryRouter>
|
||||||
|
<FluentProvider theme={webLightTheme}>
|
||||||
|
<JailsPage />
|
||||||
|
</FluentProvider>
|
||||||
|
</MemoryRouter>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("JailsPage", () => {
|
||||||
|
it("navigates to Configuration → Jails when a jail is clicked", async () => {
|
||||||
|
renderPage();
|
||||||
|
const user = userEvent.setup();
|
||||||
|
|
||||||
|
await user.click(screen.getByText("sshd"));
|
||||||
|
|
||||||
|
expect(mockNavigate).toHaveBeenCalledWith("/config", {
|
||||||
|
state: { tab: "jails", jail: "sshd" },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
114
frontend/src/pages/__tests__/MapPage.test.tsx
Normal file
114
frontend/src/pages/__tests__/MapPage.test.tsx
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
|
||||||
|
import { getLastArgs, setMapData } from "../../hooks/useMapData";
|
||||||
|
import { MapPage } from "../MapPage";
|
||||||
|
|
||||||
|
vi.mock("../../hooks/useMapData", () => {
|
||||||
|
let lastArgs: { range: string; origin: string } = { range: "", origin: "" };
|
||||||
|
let dataState = {
|
||||||
|
countries: {},
|
||||||
|
countryNames: {},
|
||||||
|
bans: [],
|
||||||
|
total: 0,
|
||||||
|
loading: false,
|
||||||
|
error: null,
|
||||||
|
refresh: () => {},
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
useMapData: (range: string, origin: string) => {
|
||||||
|
lastArgs = { range, origin };
|
||||||
|
return { ...dataState };
|
||||||
|
},
|
||||||
|
setMapData: (newState: Partial<typeof dataState>) => {
|
||||||
|
dataState = { ...dataState, ...newState };
|
||||||
|
},
|
||||||
|
getLastArgs: () => lastArgs,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock("../../api/config", () => ({
|
||||||
|
fetchMapColorThresholds: vi.fn(async () => ({
|
||||||
|
threshold_low: 10,
|
||||||
|
threshold_medium: 50,
|
||||||
|
threshold_high: 100,
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../../components/WorldMap", () => ({
|
||||||
|
WorldMap: () => <div data-testid="world-map" />,
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe("MapPage", () => {
|
||||||
|
it("renders DashboardFilterBar and updates data when filters change", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
|
||||||
|
render(
|
||||||
|
<FluentProvider theme={webLightTheme}>
|
||||||
|
<MapPage />
|
||||||
|
</FluentProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Initial load should call useMapData with default filters.
|
||||||
|
expect(getLastArgs()).toEqual({ range: "24h", origin: "all" });
|
||||||
|
|
||||||
|
await user.click(screen.getByRole("button", { name: /Last 7 days/i }));
|
||||||
|
expect(getLastArgs().range).toBe("7d");
|
||||||
|
|
||||||
|
await user.click(screen.getByRole("button", { name: /Blocklist/i }));
|
||||||
|
expect(getLastArgs().origin).toBe("blocklist");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("supports pagination with 100 items per page and reset on filter changes", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
|
||||||
|
const bans: import("../../types/map").MapBanItem[] = Array.from({ length: 120 }, (_, index) => ({
|
||||||
|
ip: `192.0.2.${index}`,
|
||||||
|
jail: "ssh",
|
||||||
|
banned_at: new Date(Date.now() - index * 1000).toISOString(),
|
||||||
|
service: null,
|
||||||
|
country_code: "US",
|
||||||
|
country_name: "United States",
|
||||||
|
asn: null,
|
||||||
|
org: null,
|
||||||
|
ban_count: 1,
|
||||||
|
origin: "selfblock",
|
||||||
|
}));
|
||||||
|
|
||||||
|
setMapData({
|
||||||
|
countries: { US: 120 },
|
||||||
|
countryNames: { US: "United States" },
|
||||||
|
bans,
|
||||||
|
total: 120,
|
||||||
|
loading: false,
|
||||||
|
error: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
render(
|
||||||
|
<FluentProvider theme={webLightTheme}>
|
||||||
|
<MapPage />
|
||||||
|
</FluentProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(await screen.findByText(/Page 1 of 2/i)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/Showing 100 of 120 filtered bans/i)).toBeInTheDocument();
|
||||||
|
|
||||||
|
await user.click(screen.getByRole("button", { name: /Next page/i }));
|
||||||
|
expect(await screen.findByText(/Page 2 of 2/i)).toBeInTheDocument();
|
||||||
|
|
||||||
|
await user.click(screen.getByRole("button", { name: /Previous page/i }));
|
||||||
|
expect(await screen.findByText(/Page 1 of 2/i)).toBeInTheDocument();
|
||||||
|
|
||||||
|
// Page size selector should adjust pagination
|
||||||
|
await user.selectOptions(screen.getByRole("combobox", { name: /Page size/i }), "25");
|
||||||
|
expect(await screen.findByText(/Page 1 of 5/i)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/Showing 25 of 120 filtered bans/i)).toBeInTheDocument();
|
||||||
|
|
||||||
|
// Changing filter keeps page reset to 1
|
||||||
|
await user.click(screen.getByRole("button", { name: /Blocklist/i }));
|
||||||
|
expect(getLastArgs().origin).toBe("blocklist");
|
||||||
|
expect(await screen.findByText(/Page 1 of 5/i)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -659,7 +659,7 @@ export interface Fail2BanLogResponse {
|
|||||||
export interface ServiceStatusResponse {
|
export interface ServiceStatusResponse {
|
||||||
/** Whether fail2ban is reachable via its socket. */
|
/** Whether fail2ban is reachable via its socket. */
|
||||||
online: boolean;
|
online: boolean;
|
||||||
/** fail2ban version string, or null when offline. */
|
/** BanGUI application version (or null when offline). */
|
||||||
version: string | null;
|
version: string | null;
|
||||||
/** Number of currently active jails. */
|
/** Number of currently active jails. */
|
||||||
jail_count: number;
|
jail_count: number;
|
||||||
|
|||||||
@@ -50,8 +50,11 @@ export interface IpDetailResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Query parameters supported by GET /api/history */
|
/** Query parameters supported by GET /api/history */
|
||||||
|
import type { BanOriginFilter } from "./ban";
|
||||||
|
|
||||||
export interface HistoryQuery {
|
export interface HistoryQuery {
|
||||||
range?: TimeRange;
|
range?: TimeRange;
|
||||||
|
origin?: BanOriginFilter;
|
||||||
jail?: string;
|
jail?: string;
|
||||||
ip?: string;
|
ip?: string;
|
||||||
page?: number;
|
page?: number;
|
||||||
|
|||||||
@@ -1,18 +1,22 @@
|
|||||||
import { defineConfig } from "vite";
|
import { defineConfig } from "vite";
|
||||||
import react from "@vitejs/plugin-react";
|
import react from "@vitejs/plugin-react";
|
||||||
import { resolve } from "path";
|
import { resolve } from "path";
|
||||||
import { readFileSync } from "node:fs";
|
import { readFileSync, existsSync } from "node:fs";
|
||||||
|
|
||||||
const pkg = JSON.parse(
|
let appVersion = "0.0.0";
|
||||||
readFileSync(resolve(__dirname, "package.json"), "utf-8"),
|
const versionFile = resolve(__dirname, "../Docker/VERSION");
|
||||||
) as { version: string };
|
if (existsSync(versionFile)) {
|
||||||
|
appVersion = readFileSync(versionFile, "utf-8")
|
||||||
|
.trim()
|
||||||
|
.replace(/^v/, "");
|
||||||
|
}
|
||||||
|
|
||||||
// https://vitejs.dev/config/
|
// https://vitejs.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [react()],
|
plugins: [react()],
|
||||||
define: {
|
define: {
|
||||||
/** BanGUI application version injected at build time from package.json. */
|
/** BanGUI application version injected at build time from Docker/VERSION. */
|
||||||
__APP_VERSION__: JSON.stringify(pkg.version),
|
__APP_VERSION__: JSON.stringify(appVersion),
|
||||||
},
|
},
|
||||||
resolve: {
|
resolve: {
|
||||||
alias: {
|
alias: {
|
||||||
|
|||||||
10
pytest.ini
Normal file
10
pytest.ini
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
[pytest]
|
||||||
|
# Ensure pytest-asyncio is in auto mode for async tests without explicit markers.
|
||||||
|
asyncio_mode = auto
|
||||||
|
|
||||||
|
# Run the backend test suite from the repository root.
|
||||||
|
testpaths = backend/tests
|
||||||
|
pythonpath = backend
|
||||||
|
|
||||||
|
# Keep coverage output consistent with backend/pyproject.toml settings.
|
||||||
|
addopts = --cov=backend/app --cov-report=term-missing
|
||||||
Reference in New Issue
Block a user