chore: initialize repository skeleton and engineering baseline

This commit is contained in:
Ilgiz Kalmetyev 2026-04-06 21:13:57 +05:00
commit 3f75d7d64e
117 changed files with 12145 additions and 0 deletions

3
.env.example Normal file
View File

@ -0,0 +1,3 @@
# Copy to .env and adjust for local development.
APP_ENV=development

3
.env.test.example Normal file
View File

@ -0,0 +1,3 @@
# Copy to .env.test for test-specific overrides.
APP_ENV=test

32
.gitignore vendored Normal file
View File

@ -0,0 +1,32 @@
# Python bytecode
__pycache__/
*.py[cod]
*.pyd
# Build artifacts
build/
dist/
*.egg-info/
# Virtual environments
.venv/
venv/
env/
# Test and tooling caches
.pytest_cache/
.mypy_cache/
.ruff_cache/
.coverage
htmlcov/
# Editor settings
.idea/
.vscode/
# Local env files
.env
.env.*
!.env.example
!.env.test.example

1501
AGENTS.md Normal file

File diff suppressed because it is too large Load Diff

36
README.md Normal file
View File

@ -0,0 +1,36 @@
# wifi-agent
Linux/Python Wi-Fi telemetry and command agent.
This repository is currently at the bootstrap stage:
- repository skeleton is in place;
- packaging is configured for Python 3.12+;
- a smoke test verifies the `app` package imports;
- feature work will be added in later steps.
## Layout
```text
wifi-agent/
app/
docs/
tests/
pyproject.toml
```
## Quick start
1. Create and activate a Python 3.12+ virtual environment.
2. Install the project with test dependencies:
```bash
pip install -e .[test]
```
3. Run the test suite:
```bash
pytest
```

2
app/__init__.py Normal file
View File

@ -0,0 +1,2 @@
"""wifi-agent application package."""

2
app/adapters/__init__.py Normal file
View File

@ -0,0 +1,2 @@
"""Adapter layer."""

2
app/api/__init__.py Normal file
View File

@ -0,0 +1,2 @@
"""API layer."""

View File

@ -0,0 +1,2 @@
"""Application bootstrap and wiring."""

2
app/commands/__init__.py Normal file
View File

@ -0,0 +1,2 @@
"""Command domain and execution support."""

2
app/core/__init__.py Normal file
View File

@ -0,0 +1,2 @@
"""Core infrastructure primitives."""

View File

@ -0,0 +1,2 @@
"""Correlation helpers."""

2
app/delivery/__init__.py Normal file
View File

@ -0,0 +1,2 @@
"""Northbound delivery layer."""

2
app/domain/__init__.py Normal file
View File

@ -0,0 +1,2 @@
"""Domain models and contracts."""

View File

@ -0,0 +1,2 @@
"""Ingestion backbone."""

View File

@ -0,0 +1,2 @@
"""Monitoring and health reporting."""

View File

@ -0,0 +1,2 @@
"""Validation and normalization layer."""

2
app/services/__init__.py Normal file
View File

@ -0,0 +1,2 @@
"""Application services."""

2
app/storage/__init__.py Normal file
View File

@ -0,0 +1,2 @@
"""Persistence layer."""

2
app/workers/__init__.py Normal file
View File

@ -0,0 +1,2 @@
"""Background workers."""

1
docs/.gitkeep Normal file
View File

@ -0,0 +1 @@
# Keep docs/ in the repository.

188
proto/dbus-agent/README.md Normal file
View File

@ -0,0 +1,188 @@
# dbus-agent
`dbus-agent` - Python-демон для наблюдения за `wpa_supplicant` через system D-Bus, хранения событий в SQLite и предоставления локального REST API и CLI.
## Архитектура
```mermaid
flowchart LR
main[main.py] --> runtime[runtime.py]
runtime --> config[config.py]
runtime --> store[storage.py]
runtime --> client[dbus_client.py]
runtime --> supervisor[supervisor.py]
supervisor --> client
supervisor --> store
api[api.py] --> supervisor
api --> store
api --> client
cli[cli.py] --> http[REST API]
```
Приложение собирается как цепочка слоев:
- `main.py` читает путь к YAML-конфигу и `.env`, создает runtime и запускает Uvicorn.
- `runtime.py` связывает конфиг, SQLite-хранилище, D-Bus-клиент и supervisor.
- `supervisor.py` ведет heartbeat, reconnect/backoff и retention.
- `dbus_client.py` общается с `fi.w1.wpa_supplicant1` на system bus.
- `api.py` экспортирует HTTP-слой поверх уже собранного runtime.
- `cli.py` не ходит в D-Bus напрямую, а работает только через REST API.
## Ключевые компоненты
- `config.py`
- Загружает YAML-конфиг и `.env`, затем накладывает переменные окружения.
- Сводит настройки интерфейса, D-Bus, SQLite, API, heartbeat и retention в `AgentConfig`.
- `runtime.py`
- Собирает готовые объекты приложения.
- Подписывает ingest-колбэк на D-Bus события и обновления scan results после `ScanDone`.
- `supervisor.py`
- Запускает и останавливает фоновые циклы.
- Отвечает за health-снимок, heartbeat и повторное подключение к D-Bus.
- Запускает retention sweep для старых событий.
- `dbus_client.py`
- Реализует чтение состояния интерфейса и вызовы D-Bus команд `Scan`, `Disconnect`, `Reattach`, `Reconnect`, `EAPLogoff`, `EAPLogon`, `SignalPoll`, `SubscribeProbeReq`, `UnsubscribeProbeReq`, `AddNetwork`.
- Нормализует D-Bus значения в структуры, пригодные для JSON.
- `storage.py`
- Хранит события, состояние интерфейса и кэш результатов сканирования в SQLite.
- `api.py`
- Экспортирует REST API.
- Транслирует ошибки D-Bus и storage в HTTP-коды.
- `cli.py`
- Обеспечивает консольный клиент для health/state/events/scan-results/command.
- Использует `httpx` и не дублирует бизнес-логику.
## Основные потоки данных
1. Старт сервиса
- `main.py` вызывает `build_runtime()`.
- `runtime.py` загружает конфиг, открывает SQLite, создает D-Bus клиент и supervisor.
- `api.py` получает уже собранные объекты и монтирует FastAPI-приложение.
2. События из D-Bus в SQLite
- `dbus_client.py` подписывается на события `wpa_supplicant`.
- `runtime.py` записывает каждое событие в `events` и обновляет `interface_state`.
- При `ScanDone` сервис может перечитать scan results и обновить кэш `scan_results`.
3. Heartbeat, reconnect и retention
- `supervisor.py` регулярно делает `ping()` к D-Bus.
- При ошибке соединение помечается unhealthy, клиент отключается и переподключается с backoff.
- Отдельный retention-loop удаляет устаревшие события по TTL из конфигурации.
4. HTTP/API и CLI
- `api.py` обслуживает read-only запросы и D-Bus команды интерфейса.
- `cli.py` вызывает REST API через `httpx`, поэтому вся доменная логика остается на сервере.
## Технические решения
- Конфигурация разделена на YAML и `.env`.
- YAML удобен для структурных и повторяемых настроек.
- `.env` и переменные окружения нужны для локальных переопределений и секретов.
- Приоритет: environment > `.env` > YAML.
- Хранилище - SQLite.
- Подходит для локального демона и не требует отдельного сервера БД.
- Используется для событий, состояния интерфейса и кэша scan results.
- Для кеша событий можно задать allowlist по `event_filter.allowed_event_types`.
- Неразрешенные типы не попадают в `events`, но `ScanDone`-обновления кеша сканов продолжают работать.
- Пример допустимых типов событий:
- `InterfaceAdded`
- `InterfaceRemoved`
- `PropertiesChanged`
- `ScanDone`
- `BSSAdded`
- `BSSRemoved`
- `NetworkAdded`
- `NetworkRemoved`
- `NetworkSelected`
- Полный пример конфигурации см. в [config/example.yaml](config/example.yaml).
- REST API построен на FastAPI.
- OpenAPI доступен через `/docs`.
- Swagger UI поставляется как bundled static assets в репозитории.
- D-Bus доступ реализован через `dbus-next`.
- Демон работает с system bus и объектами `fi.w1.wpa_supplicant1`.
- CLI работает через `httpx`.
- Это упрощает поддержку: одна доменная логика на сервере, один HTTP-контракт для всех клиентов.
- Политика доступа
- Read-only и интерфейсные action endpoints локальны и без аутентификации.
- `POST /commands` требует API key.
## Обзор API
### Служебные endpoint-ы
- `GET /health`
- `GET /docs`
- `GET /docs/oauth2-redirect`
### Снимки состояния интерфейса
- `GET /interfaces/{ifname}/state`
- `GET /interfaces/{ifname}/current_bss`
- `GET /interfaces/{ifname}/current_network`
- `GET /interfaces/{ifname}/signal_poll`
### История и кэш
- `GET /interfaces/{ifname}/events` - список кешированных событий с `ttl_remaining_seconds`, показывающим остаток до удаления по retention
- `GET /interfaces/{ifname}/scan_results`
### Действия над интерфейсом
- `POST /interfaces/{ifname}/scan`
- `POST /interfaces/{ifname}/disconnect`
- `POST /interfaces/{ifname}/reattach`
- `POST /interfaces/{ifname}/reassociate`
- `POST /interfaces/{ifname}/reconnect`
- `POST /interfaces/{ifname}/eap_logoff`
- `POST /interfaces/{ifname}/eap_logon`
- `POST /interfaces/{ifname}/subscribe_probe_req`
- `POST /interfaces/{ifname}/unsubscribe_probe_req`
- `POST /interfaces/{ifname}/add_network`
### Управляющий канал
- `POST /commands`
- Требует API key.
- Сейчас остается stub и возвращает `501 Not Implemented`.
### Типовые ответы
- `scan`, `disconnect`, `reattach`, `reassociate`, `reconnect`, `eap_logoff`, `eap_logon`, `subscribe_probe_req`, `unsubscribe_probe_req` - `202 Accepted` и `{"interface": "...", "requested": true}`
- `events` - список событий с `ttl_remaining_seconds`
- `add_network` - `201 Created` и `{"interface": "...", "network": "..."}`
- `signal_poll` - `200 OK` и `{"interface": "...", "properties": {...}}`
- `current_bss`, `current_network` - `200 OK` и снимок соответствующего объекта
## Зависимости между модулями
| Модуль | Зависит от | Роль |
| --- | --- | --- |
| `main.py` | `runtime.py`, `api.py`, `uvicorn` | Точка входа процесса |
| `runtime.py` | `config.py`, `storage.py`, `dbus_client.py`, `supervisor.py` | Сборка и wiring приложения |
| `config.py` | `yaml`, `os.environ`, `models.py` | Загрузка и нормализация конфигурации |
| `supervisor.py` | `dbus_client.py`, `storage.py`, `models.py` | Heartbeat, reconnect, retention, health |
| `dbus_client.py` | `dbus-next`, `models.py` | D-Bus транспорт и преобразование данных |
| `storage.py` | `sqlite3`, `models.py` | Локальное хранение событий и состояния |
| `api.py` | `supervisor.py`, `storage.py`, `dbus_client.py`, `models.py` | REST слой и HTTP-маппинг ошибок |
| `cli.py` | `httpx` | CLI-клиент поверх REST API |
## Конфигурация и развёртывание
- Базовый YAML шаблон: [config/example.yaml](config/example.yaml)
- Подробности запуска и путей: [docs/deployment.md](docs/deployment.md)
- Примеры использования API и CLI: [docs/usage.md](docs/usage.md)
По умолчанию `dbus-agent` запускается с:
- YAML: `/opt/dbus-agent/config.yaml`
- env file: `/etc/default/dbus-agent`
## Зависимости
Ключевые Python-зависимости:
- `fastapi`
- `dbus-next`
- `httpx`
- `PyYAML`
- `uvicorn`
Для тестов используется:
- `pytest`

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,35 @@
interface: wlan0
dbus:
service: fi.w1.wpa_supplicant1
object_path: /fi/w1/wpa_supplicant1
database:
path: /var/lib/dbus-agent/dbus-agent.sqlite3
api:
host: 127.0.0.1
port: 8080
heartbeat:
interval_seconds: 10
reconnect_initial_delay_seconds: 1
reconnect_max_delay_seconds: 30
retention:
record_ttl_seconds: 86400
event_filter:
# Empty list keeps all events in the cache.
allowed_event_types: []
# Example allowlist:
# allowed_event_types:
# - InterfaceAdded
# - InterfaceRemoved
# - PropertiesChanged
# - ScanDone
# - BSSAdded
# - BSSRemoved
# - NetworkAdded
# - NetworkRemoved
# - NetworkSelected

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,19 @@
[Unit]
Description=dbus-agent Wi-Fi D-Bus watcher
After=network-online.target dbus.service
Wants=network-online.target
[Service]
Type=simple
User=wifi-agent
Group=wifi-agent
WorkingDirectory=/opt/dbus-agent
EnvironmentFile=-/etc/default/dbus-agent
ExecStart=/opt/dbus-agent/.venv/bin/python -m dbus_agent.main --config /opt/dbus-agent/config.yaml --env-file /etc/default/dbus-agent
Restart=on-failure
RestartSec=3
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,48 @@
# dbus-agent deployment layout
## Runtime paths
- Application root: `/opt/dbus-agent`
- YAML config: `/opt/dbus-agent/config.yaml`
- Environment file: `/etc/default/dbus-agent`
- SQLite database: `/var/lib/dbus-agent/dbus-agent.sqlite3`
- systemd unit: `/etc/systemd/system/dbus-agent.service`
## Ownership
- Run the service as the dedicated system user `wifi-agent`.
- Create `/var/lib/dbus-agent` with `wifi-agent:wifi-agent` ownership.
- Keep `/opt/dbus-agent` readable by the service user and writable only where runtime files are stored.
- Install the project into `/opt/dbus-agent/.venv` and let systemd invoke that interpreter directly.
## Input templates
- `config/example.yaml` is the YAML template for the runtime config.
- `/etc/default/dbus-agent` is the environment file used by systemd at runtime.
- Common env overrides include `DBUS_AGENT_API_KEY`, `DBUS_AGENT_DATABASE_PATH`, `DBUS_AGENT_RECORD_TTL_SECONDS`, and `DBUS_AGENT_EVENT_FILTER_ALLOWED_EVENT_TYPES`.
## Service start
- The unit runs `/opt/dbus-agent/.venv/bin/python -m dbus_agent.main`.
- This avoids relying on `PATH` resolution for the `dbus-agent` console script.
## D-Bus policy for scan
- `POST /interfaces/{ifname}/scan` requires a system bus policy rule that allows the service user to call `fi.w1.wpa_supplicant1.Interface.Scan`.
- If the endpoint returns `403` with a D-Bus policy denial, install a policy file such as `/etc/dbus-1/system.d/dbus-agent-scan.conf`:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<policy user="wifi-agent">
<allow send_destination="fi.w1.wpa_supplicant1"
send_interface="fi.w1.wpa_supplicant1.Interface"
send_member="Scan"/>
</policy>
</busconfig>
```
- Adjust the `user="wifi-agent"` value if the service runs under a different account.
- Restart the system bus after installing the policy file, or reload it according to your distro's D-Bus service manager.
## CLI usage
- See [usage guide](usage.md) for day-to-day interaction with the HTTP API from the CLI.
- The CLI defaults to `http://127.0.0.1:8080` and can target a remote host with `--base-url`.
- Use `--api-key` and `--api-key-header` when calling authenticated endpoints such as `POST /commands`.

View File

@ -0,0 +1,121 @@
# dbus-agent phased execution plan
## Phase 1. Project Foundation
### Stage 1.1. Repository bootstrap
- Initialize repository metadata.
- Create the base project layout for `dbus-agent`.
- Add bootstrap files and placeholder directories.
### Stage 1.2. Plan and status tracking
- Keep the plan in a file in the repository.
- Keep a status file with phase, stage, step, state, timestamp, and note.
- Update status after every finished step.
### Stage 1.3. Commit discipline
- Commit every completed step before starting the next one.
- Use descriptive commit messages that include the phase and step.
## Phase 2. Core Service Skeleton
### Stage 2.1. Python application scaffold
- Add the Python package structure.
- Add the service entrypoint.
- Add config loading for YAML and `.env`.
### Stage 2.2. Runtime configuration
- Load the YAML config file.
- Load runtime parameters and API key from `.env`.
- Freeze the production paths for config and runtime files.
## Phase 3. D-Bus and Storage
### Stage 3.1. D-Bus connectivity
- Connect to system D-Bus.
- Select the interface from config.
- Subscribe to events for the selected interface only.
### Stage 3.2. Heartbeat and recovery
- Add a D-Bus heartbeat.
- Mark the connection unhealthy on failure.
- Reconnect with backoff.
### Stage 3.3. SQLite persistence
- Create the SQLite schema.
- Store raw events.
- Maintain the current interface state.
## Phase 4. REST API
### Stage 4.1. API layer
- Add a FastAPI REST API.
- Bind the API to `127.0.0.1`.
### Stage 4.2. Endpoints
- Add `GET /health`.
- Add `GET /interfaces/{ifname}/state`.
- Add `GET /interfaces/{ifname}/events`.
- Add `POST /commands` as a stub.
### Stage 4.3. API key policy
- Require the API key only on command endpoints.
- Keep read-only endpoints local and unauthenticated.
## Phase 5. System Integration
### Stage 5.1. systemd packaging
- Add a `systemd` unit.
- Run the service as `wifi-agent`.
- Load `.env` through the unit file.
### Stage 5.2. Deployment layout
- Fix the YAML and `.env` production paths.
- Keep the install layout explicit.
## Phase 6. Verification and Delivery
### Stage 6.1. Testing
- Add unit tests.
- Add integration tests with a mocked D-Bus source.
- Verify heartbeat and SQLite writes.
### Stage 6.2. Final validation
- Verify service startup.
- Verify REST API behavior.
- Verify commit history and status tracking.
## Phase 7. CLI Client
### Stage 7.1. CLI scaffold
- Add the `dbus-agent.cli` entrypoint.
- Move CLI-specific code into a dedicated module.
- Add CLI configuration for API base URL, API key, timeout, and output format.
### Stage 7.2. Console commands
- Add console commands for `health`, `state`, `events`, and `command`.
- Call the REST API directly without duplicating business logic.
- Reuse the same API key policy for mutating operations.
### Stage 7.3. Output and UX
- Default to human-readable terminal output.
- Add JSON output for automation.
- Return clear exit codes for transport, auth, not-found, and server errors.
### Stage 7.4. Testing
- Cover the CLI with mocked HTTP responses.
- Verify command-to-endpoint mapping and output formatting.
- Cover API-down, auth-failure, empty-response, and missing-interface scenarios.
## Phase 8. Persistence Retention
### Stage 8.1. Retention configuration
- Add record TTL to the YAML config and `.env` overrides.
- Define whether retention applies to event history only or to other persistence tables as well.
### Stage 8.2. Expiration worker
- Add a background retention worker for the persistence DB.
- Detect expired records based on configured TTL.
- Delete stale records without affecting the current interface state.
### Stage 8.3. Runtime counters
- Track `ingested` and `expired` record counters in application runtime state.
- Expose those counters through the runtime status payload and mirror them in the CLI health output.
- Keep counters monotonic for the current process lifetime.
### Stage 8.4. Testing
- Verify TTL parsing and config precedence.
- Verify expiration boundaries and deletion behavior.
- Verify counter updates for ingested and expired records.
- Verify status payloads and CLI output include the counters.

View File

@ -0,0 +1,245 @@
# dbus-agent usage guide
This guide covers the CLI client that talks to the `dbus-agent` REST API.
## Prerequisites
- The `dbus-agent` service must be running and reachable over HTTP.
- The CLI defaults to `http://127.0.0.1:8080`.
- If `/commands` is protected, provide the same API key that the service expects.
## CLI entrypoint
Use the installed console command:
```bash
dbus-agent.cli --help
```
If you are running from the source tree, the module entrypoint also works:
```bash
python -m dbus_agent.cli --help
```
## Global options
- `--base-url` sets the API root, for example `http://192.168.1.23:8080`.
- `--api-key` sends the API key for authenticated requests.
- `--api-key-header` changes the header name, default `X-API-Key`.
- `--timeout` sets the HTTP timeout in seconds.
- `--output` selects `text` or `json`.
The same options can also be provided through environment variables:
- `DBUS_AGENT_API_BASE_URL`
- `DBUS_AGENT_API_KEY`
- `DBUS_AGENT_API_KEY_HEADER`
- `DBUS_AGENT_API_TIMEOUT`
- `DBUS_AGENT_OUTPUT`
## Commands
### Health
Show daemon status and counters:
```bash
dbus-agent.cli health
```
Example JSON output:
```bash
dbus-agent.cli --output json health
```
### Interface state
Read the current state for the configured interface:
```bash
dbus-agent.cli state wlp3s0
```
Example against a remote host:
```bash
dbus-agent.cli --base-url http://192.168.1.23:8080 state wlp3s0
```
### Events
List recent events for an interface:
```bash
dbus-agent.cli events wlp3s0 --limit 20
```
Each event in the response includes `ttl_remaining_seconds`, which shows how much time remains before the cached record is removed by retention.
If `event_filter.allowed_event_types` is configured, only those event types are cached and returned here.
### Scan results
Read the current BSS list discovered by the latest scan:
```bash
dbus-agent.cli scan-results wlp3s0
```
This returns the cached scan snapshot for `Interface.BSSs`. The cache is refreshed automatically after `ScanDone`, and the service can fall back to a live read if the cache is still empty.
### Start scan
Trigger a scan on the configured interface:
```bash
curl -X POST http://127.0.0.1:8080/interfaces/wlp3s0/scan
```
The endpoint returns immediately with `202 Accepted`. Results appear later in `scan-results` after the `ScanDone` event refreshes the cache.
### Disconnect interface
Disconnect the configured interface from the current network:
```bash
curl -X POST http://127.0.0.1:8080/interfaces/wlp3s0/disconnect
```
The endpoint returns immediately with `202 Accepted`.
### Reattach interface
Attempt reassociation back to the current BSS:
```bash
curl -X POST http://127.0.0.1:8080/interfaces/wlp3s0/reattach
```
The endpoint returns `202 Accepted` when the interface accepts the request.
### Reassociate interface
Request reassociation on the configured interface:
```bash
curl -X POST http://127.0.0.1:8080/interfaces/wlp3s0/reassociate
```
The endpoint returns `202 Accepted` when the interface accepts the request.
### Reconnect interface
Request a reconnect on the configured interface:
```bash
curl -X POST http://127.0.0.1:8080/interfaces/wlp3s0/reconnect
```
The endpoint returns `202 Accepted` when the interface accepts the request.
### EAP logoff
Request EAP logoff on the configured interface:
```bash
curl -X POST http://127.0.0.1:8080/interfaces/wlp3s0/eap_logoff
```
The endpoint returns `202 Accepted` when the interface accepts the request.
### EAP logon
Request EAP logon on the configured interface:
```bash
curl -X POST http://127.0.0.1:8080/interfaces/wlp3s0/eap_logon
```
The endpoint returns `202 Accepted` when the interface accepts the request.
### Subscribe probe requests
Enable probe request subscriptions on the configured interface:
```bash
curl -X POST http://127.0.0.1:8080/interfaces/wlp3s0/subscribe_probe_req
```
The endpoint returns `202 Accepted` when the interface accepts the request.
### Unsubscribe probe requests
Disable probe request subscriptions on the configured interface:
```bash
curl -X POST http://127.0.0.1:8080/interfaces/wlp3s0/unsubscribe_probe_req
```
The endpoint returns `202 Accepted` when the interface accepts the request.
### Signal poll
Read the current signal snapshot for the configured interface:
```bash
curl http://127.0.0.1:8080/interfaces/wlp3s0/signal_poll
```
The endpoint returns the current `SignalPoll` properties as JSON.
### Add network
Create a new configured network on the interface:
```bash
curl -X POST http://127.0.0.1:8080/interfaces/wlp3s0/add_network \
-H 'Content-Type: application/json' \
-d '{"ssid":"example","priority":10,"scan_ssid":true,"key_mgmt":["wpa-psk"]}'
```
The endpoint returns `201 Created` with the D-Bus network object path.
### Command
Send a command payload to the API:
```bash
dbus-agent.cli command --payload '{"action":"scan"}'
```
If the endpoint requires authorization, pass the API key:
```bash
dbus-agent.cli --api-key secret --api-key-header X-Token command --payload '{"action":"scan"}'
```
## Output formats
- `text` is optimized for terminal reading.
- `json` returns machine-readable output and preserves the API payload shape.
Examples:
```bash
dbus-agent.cli --output text health
dbus-agent.cli --output json state wlp3s0
```
## Typical workflow
1. Check service health.
2. Read interface state.
3. Inspect recent events.
4. Read the latest scan results.
5. Send a command if the API exposes one.
Example:
```bash
dbus-agent.cli --base-url http://127.0.0.1:8080 health
dbus-agent.cli --base-url http://127.0.0.1:8080 state wlp3s0
dbus-agent.cli --base-url http://127.0.0.1:8080 events wlp3s0 --limit 10
dbus-agent.cli --base-url http://127.0.0.1:8080 scan-results wlp3s0
```

View File

@ -0,0 +1,36 @@
[build-system]
requires = ["setuptools>=69", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "dbus-agent"
version = "0.1.0"
description = "Wi-Fi D-Bus agent for wpa_supplicant"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"fastapi>=0.115",
"dbus-next>=0.2.3",
"httpx>=0.27",
"PyYAML>=6.0",
"uvicorn[standard]>=0.30",
]
[project.scripts]
dbus-agent = "dbus_agent.main:main"
"dbus-agent.cli" = "dbus_agent.cli:main"
[project.optional-dependencies]
test = [
"pytest>=8.0",
]
[tool.setuptools]
package-dir = {"" = "src"}
include-package-data = true
[tool.setuptools.packages.find]
where = ["src"]
[tool.setuptools.package-data]
dbus_agent = ["static/*"]

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,6 @@
"""dbus-agent package."""
__all__ = ["__version__"]
__version__ = "0.1.0"

View File

@ -0,0 +1,391 @@
from __future__ import annotations
import asyncio
import json
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from pathlib import Path
from fastapi import Body, FastAPI, HTTPException, Request, status
from fastapi.openapi.docs import get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html
from fastapi.staticfiles import StaticFiles
from .models import AgentConfig, EventRecord, InterfaceState
from .storage import SqliteStore
from .dbus_client import InterfaceConflictError
from .supervisor import ConnectionSupervisor
def _iso(value: datetime | None) -> str | None:
return value.isoformat() if value is not None else None
def _normalize_datetime(value: datetime) -> datetime:
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc)
def _ttl_remaining_seconds(
created_at: datetime,
ttl_seconds: float,
*,
now: datetime | None = None,
) -> float:
current = _normalize_datetime(now or datetime.now(timezone.utc))
created = _normalize_datetime(created_at)
remaining = ttl_seconds - (current - created).total_seconds()
return max(0.0, remaining)
def _event_to_payload(
event: EventRecord,
*,
ttl_seconds: float,
now: datetime | None = None,
) -> dict[str, object]:
return {
"interface": event.interface,
"event_type": event.event_type,
"payload": json.loads(event.payload_json),
"created_at": _iso(event.created_at),
"ttl_remaining_seconds": _ttl_remaining_seconds(event.created_at, ttl_seconds, now=now),
}
def _state_to_payload(state: InterfaceState) -> dict[str, object]:
return {
"interface": state.interface,
"status": state.status,
"last_event_at": _iso(state.last_event_at),
"last_heartbeat_at": _iso(state.last_heartbeat_at),
"details": json.loads(state.details_json or "{}"),
}
def _related_object_to_payload(interface: str, snapshot: dict[str, object]) -> dict[str, object]:
return {
"interface": interface,
**snapshot,
}
def _scan_results_to_payload(
interface: str,
results: list[dict[str, object]],
refreshed_at: datetime | None = None,
) -> dict[str, object]:
return {
"interface": interface,
"refreshed_at": _iso(refreshed_at),
"results": results,
}
def _static_dir() -> Path:
return Path(__file__).resolve().parent / "static"
def _require_api_key(config: AgentConfig, request: Request) -> None:
expected = config.api.api_key
if not expected:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="API key is not configured")
supplied = request.headers.get(config.api.api_key_header)
if supplied != expected:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API key")
def create_app(config: AgentConfig, store: SqliteStore, supervisor: ConnectionSupervisor) -> FastAPI:
@asynccontextmanager
async def lifespan(app: FastAPI):
await store.open()
app.state.supervisor_task = asyncio.create_task(supervisor.run())
try:
yield
finally:
await supervisor.stop()
task = app.state.supervisor_task
if task is not None:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
await store.close()
app = FastAPI(title="dbus-agent", version="0.1.0", lifespan=lifespan, docs_url=None, redoc_url=None)
app.mount("/static", StaticFiles(directory=_static_dir()), name="static")
app.state.config = config
app.state.store = store
app.state.supervisor = supervisor
app.state.supervisor_task = None
@app.get("/docs", include_in_schema=False)
async def docs():
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=f"{app.title} - Swagger UI",
swagger_js_url="/static/swagger-ui-bundle.js",
swagger_css_url="/static/swagger-ui.css",
swagger_favicon_url="/static/favicon-32x32.png",
oauth2_redirect_url="/docs/oauth2-redirect",
)
@app.get("/docs/oauth2-redirect", include_in_schema=False)
async def swagger_ui_redirect():
return get_swagger_ui_oauth2_redirect_html()
@app.get("/health")
async def health() -> dict[str, object]:
snapshot = supervisor.health
connection = supervisor.connection
return {
"process_up": snapshot.process_up,
"dbus_up": snapshot.dbus_up,
"dbus_connected": connection.connected,
"last_heartbeat_at": _iso(snapshot.last_heartbeat_at),
"ingested_records": snapshot.ingested_records,
"expired_records": snapshot.expired_records,
"message": snapshot.message,
}
@app.get("/interfaces/{ifname}/state")
async def get_state(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
try:
state = await supervisor.client.read_interface_state(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
await store.touch_interface(state)
return _state_to_payload(state)
@app.get("/interfaces/{ifname}/current_bss")
async def get_current_bss(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
try:
snapshot = await supervisor.client.read_current_bss(ifname)
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
if snapshot is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Current BSS not found")
return _related_object_to_payload(ifname, snapshot)
@app.get("/interfaces/{ifname}/current_network")
async def get_current_network(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
try:
snapshot = await supervisor.client.read_current_network(ifname)
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
if snapshot is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Current network not found")
return _related_object_to_payload(ifname, snapshot)
@app.get("/interfaces/{ifname}/signal_poll")
async def signal_poll(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
try:
properties = await supervisor.client.signal_poll(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except InterfaceConflictError as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
return {"interface": ifname, "properties": properties}
@app.post("/interfaces/{ifname}/scan", status_code=status.HTTP_202_ACCEPTED)
async def scan(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
try:
await supervisor.client.scan(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/disconnect", status_code=status.HTTP_202_ACCEPTED)
async def disconnect(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
try:
await supervisor.client.disconnect_interface(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/reattach", status_code=status.HTTP_202_ACCEPTED)
async def reattach(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
try:
await supervisor.client.reattach(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except InterfaceConflictError as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/reassociate", status_code=status.HTTP_202_ACCEPTED)
async def reassociate(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
try:
await supervisor.client.reassociate(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except InterfaceConflictError as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/reconnect", status_code=status.HTTP_202_ACCEPTED)
async def reconnect(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
try:
await supervisor.client.reconnect(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except InterfaceConflictError as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/eap_logoff", status_code=status.HTTP_202_ACCEPTED)
async def eap_logoff(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
try:
await supervisor.client.eap_logoff(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except InterfaceConflictError as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/eap_logon", status_code=status.HTTP_202_ACCEPTED)
async def eap_logon(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
try:
await supervisor.client.eap_logon(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except InterfaceConflictError as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/subscribe_probe_req", status_code=status.HTTP_202_ACCEPTED)
async def subscribe_probe_req(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
try:
await supervisor.client.subscribe_probe_req(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/unsubscribe_probe_req", status_code=status.HTTP_202_ACCEPTED)
async def unsubscribe_probe_req(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
try:
await supervisor.client.unsubscribe_probe_req(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/add_network", status_code=status.HTTP_201_CREATED)
async def add_network(ifname: str, payload: dict[str, object] = Body(default_factory=dict)) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
try:
network_path = await supervisor.client.add_network(ifname, payload)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
return {"interface": ifname, "network": network_path}
@app.get("/interfaces/{ifname}/scan_results")
async def get_scan_results(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
try:
cached = await store.get_scan_results(ifname)
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
if cached is None:
try:
results = await supervisor.client.read_scan_results(ifname)
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
await store.replace_scan_results(ifname, results)
return _scan_results_to_payload(ifname, results, None)
return _scan_results_to_payload(
ifname,
cached["results"],
cached.get("refreshed_at") if isinstance(cached.get("refreshed_at"), datetime) else None,
)
@app.get("/interfaces/{ifname}/events")
async def get_events(ifname: str, limit: int = 100) -> list[dict[str, object]]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
events = await store.list_events(ifname, limit=limit)
return [_event_to_payload(event, ttl_seconds=config.retention.record_ttl_seconds) for event in events]
@app.post("/commands")
async def commands(request: Request, payload: dict[str, object] = Body(default_factory=dict)) -> dict[str, object]:
_require_api_key(config, request)
raise HTTPException(
status_code=status.HTTP_501_NOT_IMPLEMENTED,
detail={"message": "Command execution is not implemented yet", "payload": payload},
)
return app

View File

@ -0,0 +1,297 @@
from __future__ import annotations
import argparse
import json
from dataclasses import dataclass
from os import getenv
import sys
from collections.abc import Callable
from typing import Any
import httpx
EXIT_SUCCESS = 0
EXIT_USAGE = 2
EXIT_TRANSPORT = 3
EXIT_AUTH = 4
EXIT_SERVER = 5
EXIT_NOT_FOUND = 6
@dataclass(slots=True)
class CliSettings:
base_url: str
api_key: str | None
timeout_seconds: float
output: str
api_key_header: str
@dataclass(slots=True)
class CliResult:
status_code: int
payload: Any
def _env(name: str, default: str | None = None) -> str | None:
value = getenv(name)
if value is None or value == "":
return default
return value
def load_cli_settings(namespace: argparse.Namespace) -> CliSettings:
return CliSettings(
base_url=str(namespace.base_url),
api_key=namespace.api_key or _env("DBUS_AGENT_API_KEY"),
timeout_seconds=float(namespace.timeout),
output=str(namespace.output),
api_key_header=str(namespace.api_key_header),
)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="dbus-agent.cli", description="Console client for dbus-agent REST API")
parser.add_argument("--base-url", default=_env("DBUS_AGENT_API_BASE_URL", "http://127.0.0.1:8080"))
parser.add_argument("--api-key", default=_env("DBUS_AGENT_API_KEY"))
parser.add_argument("--timeout", type=float, default=float(_env("DBUS_AGENT_API_TIMEOUT", "10")))
parser.add_argument("--output", choices=("text", "json"), default=_env("DBUS_AGENT_OUTPUT", "text"))
parser.add_argument(
"--api-key-header",
default=_env("DBUS_AGENT_API_KEY_HEADER", "X-API-Key"),
help="Header name used to send the API key.",
)
subparsers = parser.add_subparsers(dest="command", required=True)
subparsers.add_parser("health", help="Show daemon health")
state = subparsers.add_parser("state", help="Show interface state")
state.add_argument("ifname", help="Interface name")
events = subparsers.add_parser("events", help="Show interface events")
events.add_argument("ifname", help="Interface name")
events.add_argument("--limit", type=int, default=100)
scan_results = subparsers.add_parser("scan-results", help="Show scan results for an interface")
scan_results.add_argument("ifname", help="Interface name")
command = subparsers.add_parser("command", aliases=["commands"], help="Send a command payload")
command.add_argument("--payload", default="{}", help="JSON payload sent to POST /commands")
return parser
class ApiClient:
def __init__(self, settings: CliSettings, client: httpx.Client | None = None) -> None:
self._settings = settings
self._client = client or httpx.Client(base_url=settings.base_url, timeout=settings.timeout_seconds)
self._owns_client = client is None
def close(self) -> None:
if self._owns_client:
self._client.close()
def health(self) -> httpx.Response:
return self._client.get("/health")
def state(self, ifname: str) -> httpx.Response:
return self._client.get(f"/interfaces/{ifname}/state")
def events(self, ifname: str, limit: int) -> httpx.Response:
return self._client.get(f"/interfaces/{ifname}/events", params={"limit": limit})
def scan_results(self, ifname: str) -> httpx.Response:
return self._client.get(f"/interfaces/{ifname}/scan_results")
def command(self, payload: dict[str, Any]) -> httpx.Response:
headers = {}
if self._settings.api_key is not None:
headers[self._settings.api_key_header] = self._settings.api_key
return self._client.post("/commands", headers=headers, json=payload)
def _decode_payload(response: httpx.Response) -> Any:
if not response.content:
return None
return response.json()
def _run_command(namespace: argparse.Namespace, client: ApiClient) -> CliResult:
if namespace.command == "health":
response = client.health()
elif namespace.command == "state":
response = client.state(namespace.ifname)
elif namespace.command == "events":
response = client.events(namespace.ifname, namespace.limit)
elif namespace.command == "scan-results":
response = client.scan_results(namespace.ifname)
elif namespace.command in {"command", "commands"}:
try:
payload = json.loads(namespace.payload)
except json.JSONDecodeError as exc:
raise ValueError(f"Invalid JSON payload: {exc.msg}") from exc
if not isinstance(payload, dict):
raise ValueError("Command payload must be a JSON object")
response = client.command(payload)
else: # pragma: no cover - argparse prevents this branch
raise ValueError(f"Unknown command: {namespace.command}")
return CliResult(status_code=response.status_code, payload=_decode_payload(response))
def _scalar(value: Any) -> str:
if value is True:
return "yes"
if value is False:
return "no"
if value is None:
return "-"
return str(value)
def _text_lines(value: Any, indent: int = 0) -> list[str]:
prefix = " " * indent
lines: list[str] = []
if isinstance(value, dict):
for key, item in value.items():
if isinstance(item, (dict, list)):
lines.append(f"{prefix}{key}:")
lines.extend(_text_lines(item, indent + 1))
else:
lines.append(f"{prefix}{key}: {_scalar(item)}")
return lines
if isinstance(value, list):
for index, item in enumerate(value, start=1):
if isinstance(item, dict):
lines.append(f"{prefix}- item {index}:")
lines.extend(_text_lines(item, indent + 1))
else:
lines.append(f"{prefix}- {_scalar(item)}")
return lines
return [f"{prefix}{_scalar(value)}"]
def _render_text(command: str, payload: Any) -> str:
if payload is None:
return ""
if command == "events" and isinstance(payload, list):
if not payload:
return "No events found."
lines: list[str] = []
for index, event in enumerate(payload, start=1):
if not isinstance(event, dict):
lines.append(f"Event {index}: {_scalar(event)}")
continue
lines.append(f"Event {index}:")
for field in ("created_at", "event_type", "interface"):
if field in event:
lines.append(f" {field}: {_scalar(event[field])}")
if "ttl_remaining_seconds" in event:
lines.append(f" ttl_remaining_seconds: {_scalar(event['ttl_remaining_seconds'])}")
if "payload" in event:
lines.append(" payload:")
lines.extend(_text_lines(event["payload"], 2))
return "\n".join(lines)
if command == "scan-results" and isinstance(payload, dict):
results = payload.get("results")
if not isinstance(results, list) or not results:
return "No scan results found."
lines = []
interface = payload.get("interface")
if interface is not None:
lines.append(f"Interface: {_scalar(interface)}")
for index, item in enumerate(results, start=1):
if not isinstance(item, dict):
lines.append(f"Result {index}: {_scalar(item)}")
continue
lines.append(f"Result {index}:")
for field in ("path", "interface"):
if field in item:
lines.append(f" {field}: {_scalar(item[field])}")
if "properties" in item:
lines.append(" properties:")
lines.extend(_text_lines(item["properties"], 2))
return "\n".join(lines)
return "\n".join(_text_lines(payload))
def _render_json(payload: Any) -> str:
return json.dumps(payload, indent=2, sort_keys=True, ensure_ascii=False)
def _render_success(command: str, output: str, payload: Any) -> str:
if output == "json":
return _render_json(payload)
return _render_text(command, payload)
def _render_error(output: str, status_code: int, payload: Any) -> str:
if output == "json":
return _render_json({"status_code": status_code, "error": payload})
if isinstance(payload, dict):
detail = payload.get("detail", payload)
else:
detail = payload
if isinstance(detail, (dict, list)):
detail_text = _render_json(detail)
else:
detail_text = _scalar(detail)
return f"HTTP {status_code}: {detail_text}"
def _exit_code_for_status(status_code: int) -> int:
if 200 <= status_code < 300:
return EXIT_SUCCESS
if status_code in {401, 403}:
return EXIT_AUTH
if status_code == 404:
return EXIT_NOT_FOUND
if status_code >= 500:
return EXIT_SERVER
return EXIT_SERVER
def run(
argv: list[str] | None = None,
*,
client_factory: Callable[[CliSettings], ApiClient] | None = None,
stdout: Any = sys.stdout,
stderr: Any = sys.stderr,
) -> int:
parser = build_parser()
try:
namespace = parser.parse_args(argv)
settings = load_cli_settings(namespace)
client = client_factory(settings) if client_factory is not None else ApiClient(settings)
try:
result = _run_command(namespace, client)
finally:
client.close()
command_name = "command" if namespace.command == "commands" else namespace.command
if 200 <= result.status_code < 300:
print(_render_success(command_name, settings.output, result.payload), file=stdout)
return EXIT_SUCCESS
print(_render_error(settings.output, result.status_code, result.payload), file=stderr)
return _exit_code_for_status(result.status_code)
except ValueError as exc:
print(f"{parser.prog}: error: {exc}", file=stderr)
return EXIT_USAGE
except httpx.RequestError as exc:
print(f"Transport error: {exc}", file=stderr)
return EXIT_TRANSPORT
except httpx.TimeoutException as exc:
print(f"Transport timeout: {exc}", file=stderr)
return EXIT_TRANSPORT
except Exception as exc: # pragma: no cover - placeholder for future refinement
print(f"Unexpected error: {exc}", file=stderr)
return EXIT_SERVER
def main(argv: list[str] | None = None) -> int:
return run(argv)
if __name__ == "__main__": # pragma: no cover - manual invocation helper
raise SystemExit(main())

View File

@ -0,0 +1,164 @@
from __future__ import annotations
import os
from pathlib import Path
import yaml
from .models import (
AgentConfig,
ApiSettings,
DatabaseSettings,
DbusSettings,
EventFilterSettings,
HeartbeatSettings,
RetentionSettings,
)
def _strip_quotes(value: str) -> str:
if len(value) >= 2 and value[0] == value[-1] and value[0] in {'"', "'"}:
return value[1:-1]
return value
def load_env_file(path: Path) -> dict[str, str]:
values: dict[str, str] = {}
if not path.exists():
return values
for raw_line in path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[7:].strip()
if "=" not in line:
continue
key, value = line.split("=", 1)
values[key.strip()] = _strip_quotes(value.strip())
return values
def _as_int(value: str | int | None, default: int) -> int:
if value is None or value == "":
return default
return int(value)
def _as_float(value: str | float | None, default: float) -> float:
if value is None or value == "":
return default
return float(value)
def _as_positive_float(value: str | float | None, default: float) -> float:
parsed = _as_float(value, default)
if parsed <= 0:
raise ValueError("configuration values must be greater than zero")
return parsed
def _as_event_type_list(value: object | None, default: tuple[str, ...] = ()) -> tuple[str, ...]:
if value is None or value == "":
return default
if isinstance(value, str):
items = value.split(",")
elif isinstance(value, (list, tuple)):
items = [str(item) for item in value]
else:
raise TypeError("event_filter.allowed_event_types must be a string or a list")
normalized = []
seen: set[str] = set()
for item in items:
event_type = item.strip()
if not event_type or event_type in seen:
continue
normalized.append(event_type)
seen.add(event_type)
return tuple(normalized)
def load_agent_config(config_path: Path, env_path: Path | None = None) -> AgentConfig:
env_vars: dict[str, str] = {}
if env_path is not None:
env_vars.update(load_env_file(env_path))
env_vars.update(os.environ)
data = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}
interface = env_vars.get("DBUS_AGENT_INTERFACE") or data.get("interface")
if not interface:
raise ValueError("interface is required in the YAML config or in DBUS_AGENT_INTERFACE")
dbus_data = data.get("dbus", {}) or {}
database_data = data.get("database", {}) or {}
api_data = data.get("api", {}) or {}
heartbeat_data = data.get("heartbeat", {}) or {}
retention_data = data.get("retention", {}) or {}
event_filter_data = data.get("event_filter", {}) or {}
dbus = DbusSettings(
service=env_vars.get("DBUS_AGENT_DBUS_SERVICE", dbus_data.get("service", "fi.w1.wpa_supplicant1")),
object_path=env_vars.get(
"DBUS_AGENT_DBUS_OBJECT_PATH", dbus_data.get("object_path", "/fi/w1/wpa_supplicant1")
),
)
database_path = env_vars.get("DBUS_AGENT_DATABASE_PATH") or database_data.get("path")
if not database_path:
database_path = "/var/lib/dbus-agent/dbus-agent.sqlite3"
api = ApiSettings(
host=env_vars.get("DBUS_AGENT_API_HOST", api_data.get("host", "127.0.0.1")),
port=_as_int(env_vars.get("DBUS_AGENT_API_PORT", api_data.get("port", 8080)), 8080),
api_key_header=env_vars.get("DBUS_AGENT_API_KEY_HEADER", api_data.get("api_key_header", "X-API-Key")),
api_key=env_vars.get("DBUS_AGENT_API_KEY", api_data.get("api_key")),
)
heartbeat = HeartbeatSettings(
interval_seconds=_as_float(
env_vars.get("DBUS_AGENT_HEARTBEAT_INTERVAL", heartbeat_data.get("interval_seconds", 10.0)),
10.0,
),
reconnect_initial_delay_seconds=_as_float(
env_vars.get(
"DBUS_AGENT_RECONNECT_INITIAL_DELAY",
heartbeat_data.get("reconnect_initial_delay_seconds", 1.0),
),
1.0,
),
reconnect_max_delay_seconds=_as_float(
env_vars.get("DBUS_AGENT_RECONNECT_MAX_DELAY", heartbeat_data.get("reconnect_max_delay_seconds", 30.0)),
30.0,
),
)
retention = RetentionSettings(
record_ttl_seconds=_as_positive_float(
env_vars.get(
"DBUS_AGENT_RECORD_TTL_SECONDS",
retention_data.get("record_ttl_seconds", 86400.0),
),
86400.0,
)
)
event_filter = EventFilterSettings(
allowed_event_types=_as_event_type_list(
env_vars.get(
"DBUS_AGENT_EVENT_FILTER_ALLOWED_EVENT_TYPES",
event_filter_data.get("allowed_event_types", ()),
)
)
)
return AgentConfig(
interface=str(interface),
dbus=dbus,
database=DatabaseSettings(path=Path(database_path)),
api=api,
heartbeat=heartbeat,
retention=retention,
event_filter=event_filter,
)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,36 @@
from __future__ import annotations
import argparse
from pathlib import Path
import uvicorn
from .api import create_app
from .runtime import build_runtime
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="dbus-agent")
parser.add_argument(
"--config",
default="/opt/dbus-agent/config.yaml",
help="Path to the YAML configuration file.",
)
parser.add_argument(
"--env-file",
default="/etc/default/dbus-agent",
help="Path to the environment file used by systemd.",
)
return parser
def main() -> int:
args = build_parser().parse_args()
config, store, _client, supervisor = build_runtime(Path(args.config), Path(args.env_file))
app = create_app(config, store, supervisor)
uvicorn.run(app, host=config.api.host, port=config.api.port, log_level="info")
return 0
if __name__ == "__main__": # pragma: no cover - manual invocation helper
raise SystemExit(main())

View File

@ -0,0 +1,79 @@
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
@dataclass(slots=True)
class DbusSettings:
service: str = "fi.w1.wpa_supplicant1"
object_path: str = "/fi/w1/wpa_supplicant1"
@dataclass(slots=True)
class DatabaseSettings:
path: Path = Path("/var/lib/dbus-agent/dbus-agent.sqlite3")
@dataclass(slots=True)
class ApiSettings:
host: str = "127.0.0.1"
port: int = 8080
api_key_header: str = "X-API-Key"
api_key: str | None = None
@dataclass(slots=True)
class HeartbeatSettings:
interval_seconds: float = 10.0
reconnect_initial_delay_seconds: float = 1.0
reconnect_max_delay_seconds: float = 30.0
@dataclass(slots=True)
class RetentionSettings:
record_ttl_seconds: float = 86400.0
@dataclass(slots=True)
class EventFilterSettings:
allowed_event_types: tuple[str, ...] = ()
@dataclass(slots=True)
class AgentConfig:
interface: str
dbus: DbusSettings = field(default_factory=DbusSettings)
database: DatabaseSettings = field(default_factory=DatabaseSettings)
api: ApiSettings = field(default_factory=ApiSettings)
heartbeat: HeartbeatSettings = field(default_factory=HeartbeatSettings)
retention: RetentionSettings = field(default_factory=RetentionSettings)
event_filter: EventFilterSettings = field(default_factory=EventFilterSettings)
@dataclass(slots=True)
class EventRecord:
interface: str
event_type: str
payload_json: str
created_at: datetime
@dataclass(slots=True)
class InterfaceState:
interface: str
status: str
last_event_at: datetime | None = None
last_heartbeat_at: datetime | None = None
details_json: str = "{}"
@dataclass(slots=True)
class HealthSnapshot:
process_up: bool
dbus_up: bool
last_heartbeat_at: datetime | None
ingested_records: int = 0
expired_records: int = 0
message: str = ""

View File

@ -0,0 +1,50 @@
from __future__ import annotations
import json
from pathlib import Path
from .config import load_agent_config
from .dbus_client import WpaSupplicantDbusClient
from .models import AgentConfig, EventRecord, InterfaceState
from .storage import SqliteStore
from .supervisor import ConnectionSupervisor
def _interface_state_from_event(event: EventRecord) -> InterfaceState:
return InterfaceState(
interface=event.interface,
status="active",
last_event_at=event.created_at,
last_heartbeat_at=None,
details_json=event.payload_json,
)
def build_runtime(config_path: Path, env_path: Path | None = None) -> tuple[AgentConfig, SqliteStore, WpaSupplicantDbusClient, ConnectionSupervisor]:
config = load_agent_config(config_path, env_path)
store = SqliteStore(config.database.path)
client = WpaSupplicantDbusClient(config)
allowed_event_types = set(config.event_filter.allowed_event_types)
async def ingest_event(event) -> None:
if not allowed_event_types or event.event_type in allowed_event_types:
await store.record_event(event)
supervisor.record_ingested()
else:
await store.touch_interface(_interface_state_from_event(event))
if event.event_type == "ScanDone":
try:
payload = json.loads(event.payload_json)
except json.JSONDecodeError:
payload = {}
if payload.get("success") is True:
try:
results = await client.read_scan_results(event.interface)
await store.replace_scan_results(event.interface, results)
except Exception:
pass
client.add_callback(ingest_event)
supervisor = ConnectionSupervisor(config, client, store)
return config, store, client, supervisor

View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,2 @@
swagger-ui
Copyright 2020-2021 SmartBear Software Inc.

View File

@ -0,0 +1,40 @@
# Swagger UI Dist
[![NPM version](https://badge.fury.io/js/swagger-ui-dist.svg)](http://badge.fury.io/js/swagger-ui-dist)
## Anonymized analytics
SwaggerUI Dist uses [Scarf](https://scarf.sh/) to collect [anonymized installation analytics](https://github.com/scarf-sh/scarf-js?tab=readme-ov-file#as-a-user-of-a-package-using-scarf-js-what-information-does-scarf-js-send-about-me). These analytics help support the maintainers of this library and ONLY run during installation. To [opt out](https://github.com/scarf-sh/scarf-js?tab=readme-ov-file#as-a-user-of-a-package-using-scarf-js-how-can-i-opt-out-of-analytics), you can set the `scarfSettings.enabled` field to `false` in your project's `package.json`:
```
// package.json
{
// ...
"scarfSettings": {
"enabled": false
}
// ...
}
```
Alternatively, you can set the environment variable `SCARF_ANALYTICS` to `false` as part of the environment that installs your npm packages, e.g., `SCARF_ANALYTICS=false npm install`.
# API
This module, `swagger-ui-dist`, exposes Swagger-UI's entire dist folder as a dependency-free npm module.
Use `swagger-ui` instead, if you'd like to have npm install dependencies for you.
`SwaggerUIBundle` and `SwaggerUIStandalonePreset` can be imported:
```javascript
import { SwaggerUIBundle, SwaggerUIStandalonePreset } from "swagger-ui-dist"
```
To get an absolute path to this directory for static file serving, use the exported `getAbsoluteFSPath` method:
```javascript
const swaggerUiAssetPath = require("swagger-ui-dist").getAbsoluteFSPath()
// then instantiate server that serves files from the swaggerUiAssetPath
```
For anything else, check the [Swagger-UI](https://github.com/swagger-api/swagger-ui) repository.

View File

@ -0,0 +1,14 @@
/*
* getAbsoluteFSPath
* @return {string} When run in NodeJS env, returns the absolute path to the current directory
* When run outside of NodeJS, will return an error message
*/
const getAbsoluteFSPath = function () {
// detect whether we are running in a browser or nodejs
if (typeof module !== "undefined" && module.exports) {
return require("path").resolve(__dirname)
}
throw new Error('getAbsoluteFSPath can only be called within a Nodejs environment');
}
module.exports = getAbsoluteFSPath

Binary file not shown.

After

Width:  |  Height:  |  Size: 665 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 628 B

View File

@ -0,0 +1,16 @@
html {
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
margin: 0;
background: #fafafa;
}

View File

@ -0,0 +1,19 @@
<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" />
<link rel="stylesheet" type="text/css" href="index.css" />
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="./swagger-ui-bundle.js" charset="UTF-8"> </script>
<script src="./swagger-ui-standalone-preset.js" charset="UTF-8"> </script>
<script src="./swagger-initializer.js" charset="UTF-8"> </script>
</body>
</html>

View File

@ -0,0 +1,17 @@
try {
module.exports.SwaggerUIBundle = require("./swagger-ui-bundle.js")
module.exports.SwaggerUIStandalonePreset = require("./swagger-ui-standalone-preset.js")
} catch(e) {
// swallow the error if there's a problem loading the assets.
// allows this module to support providing the assets for browserish contexts,
// without exploding in a Node context.
//
// see https://github.com/swagger-api/swagger-ui/issues/3291#issuecomment-311195388
// for more information.
}
// `absolutePath` and `getAbsoluteFSPath` are both here because at one point,
// we documented having one and actually implemented the other.
// They were both retained so we don't break anyone's code.
module.exports.absolutePath = require("./absolute-path.js")
module.exports.getAbsoluteFSPath = require("./absolute-path.js")

View File

@ -0,0 +1,114 @@
ramda: 367.12 KB (5.37%)
lodash: 256.9 KB (3.76%)
ramda-adjunct: 255.04 KB (3.73%)
autolinker: 203.32 KB (2.98%)
@swagger-api/apidom-ns-openapi-3-0: 192.76 KB (2.82%)
swagger-client: 181.75 KB (2.66%)
@swagger-api/apidom-ns-openapi-3-1: 142.98 KB (2.09%)
immutable: 139.22 KB (2.04%)
react-dom: 129.93 KB (1.90%)
remarkable: 125.56 KB (1.84%)
highlight.js: 111.85 KB (1.64%)
js-yaml: 105.22 KB (1.54%)
@swagger-api/apidom-reference: 100.62 KB (1.47%)
readable-stream: 96.66 KB (1.41%)
core-js-pure: 83.37 KB (1.22%)
dompurify: 63.13 KB (0.924%)
minim: 57.35 KB (0.839%)
buffer: 56.99 KB (0.834%)
@swagger-api/apidom-core: 54.17 KB (0.793%)
@swagger-api/apidom-ast: 53.99 KB (0.790%)
@swagger-api/apidom-ns-json-schema-draft-4: 52.01 KB (0.761%)
react-syntax-highlighter: 40.38 KB (0.591%)
apg-lite: 38.54 KB (0.564%)
short-unique-id: 37.48 KB (0.548%)
react-redux: 36.62 KB (0.536%)
@swaggerexpert/cookie: 35.16 KB (0.515%)
@swagger-api/apidom-ns-json-schema-2019-09: 35.04 KB (0.513%)
fast-json-patch: 31.89 KB (0.467%)
@swaggerexpert/json-pointer: 30.48 KB (0.446%)
@swagger-api/apidom-ns-json-schema-draft-7: 23.62 KB (0.346%)
@swagger-api/apidom-ns-json-schema-2020-12: 22.4 KB (0.328%)
@swagger-api/apidom-ns-json-schema-draft-6: 21.63 KB (0.317%)
reselect: 21.47 KB (0.314%)
openapi-path-templating: 20.81 KB (0.305%)
neotraverse: 20.33 KB (0.298%)
sha.js: 18.92 KB (0.277%)
ts-mixer: 17.56 KB (0.257%)
tslib: 17.23 KB (0.252%)
redux: 16.37 KB (0.240%)
url-parse: 16.23 KB (0.238%)
events: 14.54 KB (0.213%)
openapi-server-url-templating: 14.38 KB (0.210%)
get-intrinsic: 14.02 KB (0.205%)
zenscroll: 12.31 KB (0.180%)
react-debounce-input: 11.95 KB (0.175%)
react-immutable-proptypes: 11.82 KB (0.173%)
ret: 10.82 KB (0.158%)
lodash.debounce: 10.53 KB (0.154%)
unraw: 9.9 KB (0.145%)
string_decoder: 9.24 KB (0.135%)
xml: 7.39 KB (0.108%)
react-copy-to-clipboard: 7.33 KB (0.107%)
react: 6.95 KB (0.102%)
randexp: 6.15 KB (0.0899%)
react-immutable-pure-component: 6.01 KB (0.0879%)
redux-immutable: 5.43 KB (0.0795%)
process: 5.29 KB (0.0774%)
drange: 4.8 KB (0.0703%)
lowlight: 4.42 KB (0.0647%)
scheduler: 4.33 KB (0.0634%)
deep-extend: 4.19 KB (0.0614%)
@babel/runtime: 3.99 KB (0.0584%)
deepmerge: 3.95 KB (0.0579%)
base64-js: 3.84 KB (0.0562%)
stream-browserify: 3.76 KB (0.0550%)
which-typed-array: 3.64 KB (0.0533%)
@swagger-api/apidom-error: 3.45 KB (0.0505%)
copy-to-clipboard: 3.29 KB (0.0481%)
format: 3.26 KB (0.0477%)
is-callable: 3.15 KB (0.0461%)
css.escape: 3.08 KB (0.0451%)
to-buffer: 3.03 KB (0.0444%)
serialize-error: 2.93 KB (0.0428%)
use-sync-external-store: 2.81 KB (0.0412%)
prop-types: 2.6 KB (0.0381%)
querystringify: 2.5 KB (0.0366%)
for-each: 2.32 KB (0.0339%)
has-symbols: 2.31 KB (0.0339%)
define-data-property: 2.28 KB (0.0334%)
xml-but-prettier: 2.17 KB (0.0317%)
function-bind: 2.12 KB (0.0310%)
ieee754: 2.1 KB (0.0308%)
safe-buffer: 1.63 KB (0.0239%)
util-deprecate: 1.58 KB (0.0231%)
randombytes: 1.54 KB (0.0225%)
js-file-download: 1.52 KB (0.0222%)
classnames: 1.49 KB (0.0219%)
call-bind-apply-helpers: 1.35 KB (0.0198%)
set-function-length: 1.24 KB (0.0182%)
repeat-string: 1.18 KB (0.0173%)
get-proto: 1.1 KB (0.0161%)
dunder-proto: 980 B (0.0140%)
@babel/runtime-corejs3: 781 B (0.0112%)
math-intrinsics: 781 B (0.0112%)
toggle-selection: 780 B (0.0111%)
requires-port: 753 B (0.0108%)
inherits: 753 B (0.0108%)
@swagger-api/apidom-json-pointer: 709 B (0.0101%)
fault: 691 B (0.00988%)
call-bound: 667 B (0.00953%)
call-bind: 643 B (0.00919%)
typed-array-buffer: 591 B (0.00845%)
has-property-descriptors: 588 B (0.00840%)
es-errors: 524 B (0.00749%)
available-typed-arrays: 475 B (0.00679%)
gopd: 303 B (0.00433%)
es-define-property: 288 B (0.00412%)
possible-typed-array-names: 264 B (0.00377%)
hasown: 206 B (0.00294%)
has-tostringtag: 189 B (0.00270%)
is-typed-array: 180 B (0.00257%)
isarray: 132 B (0.00189%)
es-object-atoms: 67 B (0.000958%)
<self>: 3.16 MB (47.3%)

View File

@ -0,0 +1,14 @@
readable-stream: 96.66 KB (5.58%)
buffer: 56.99 KB (3.29%)
sha.js: 18.92 KB (1.09%)
events: 14.54 KB (0.839%)
string_decoder: 9.24 KB (0.533%)
xml: 7.39 KB (0.426%)
process: 5.29 KB (0.305%)
deep-extend: 4.19 KB (0.242%)
stream-browserify: 3.76 KB (0.217%)
safe-buffer: 1.63 KB (0.0941%)
util-deprecate: 1.58 KB (0.0909%)
randombytes: 1.54 KB (0.0888%)
inherits: 753 B (0.0424%)
<self>: 1.48 MB (87.2%)

View File

@ -0,0 +1,114 @@
ramda: 367.12 KB (5.37%)
lodash: 256.9 KB (3.76%)
ramda-adjunct: 255.04 KB (3.73%)
autolinker: 203.32 KB (2.98%)
@swagger-api/apidom-ns-openapi-3-0: 192.76 KB (2.82%)
swagger-client: 181.75 KB (2.66%)
@swagger-api/apidom-ns-openapi-3-1: 142.98 KB (2.09%)
immutable: 139.22 KB (2.04%)
react-dom: 129.93 KB (1.90%)
remarkable: 125.56 KB (1.84%)
highlight.js: 111.85 KB (1.64%)
js-yaml: 105.22 KB (1.54%)
@swagger-api/apidom-reference: 100.62 KB (1.47%)
readable-stream: 96.66 KB (1.41%)
core-js-pure: 83.37 KB (1.22%)
dompurify: 63.13 KB (0.924%)
minim: 57.35 KB (0.839%)
buffer: 56.99 KB (0.834%)
@swagger-api/apidom-core: 54.17 KB (0.793%)
@swagger-api/apidom-ast: 53.99 KB (0.790%)
@swagger-api/apidom-ns-json-schema-draft-4: 52.01 KB (0.761%)
react-syntax-highlighter: 40.38 KB (0.591%)
apg-lite: 38.54 KB (0.564%)
short-unique-id: 37.48 KB (0.548%)
react-redux: 36.62 KB (0.536%)
@swaggerexpert/cookie: 35.16 KB (0.515%)
@swagger-api/apidom-ns-json-schema-2019-09: 35.04 KB (0.513%)
fast-json-patch: 31.89 KB (0.467%)
@swaggerexpert/json-pointer: 30.48 KB (0.446%)
@swagger-api/apidom-ns-json-schema-draft-7: 23.62 KB (0.346%)
@swagger-api/apidom-ns-json-schema-2020-12: 22.4 KB (0.328%)
@swagger-api/apidom-ns-json-schema-draft-6: 21.63 KB (0.317%)
reselect: 21.47 KB (0.314%)
openapi-path-templating: 20.81 KB (0.305%)
neotraverse: 20.33 KB (0.298%)
sha.js: 18.92 KB (0.277%)
ts-mixer: 17.56 KB (0.257%)
tslib: 17.23 KB (0.252%)
redux: 16.37 KB (0.240%)
url-parse: 16.23 KB (0.238%)
events: 14.54 KB (0.213%)
openapi-server-url-templating: 14.38 KB (0.210%)
get-intrinsic: 14.02 KB (0.205%)
zenscroll: 12.31 KB (0.180%)
react-debounce-input: 11.95 KB (0.175%)
react-immutable-proptypes: 11.82 KB (0.173%)
ret: 10.82 KB (0.158%)
lodash.debounce: 10.53 KB (0.154%)
unraw: 9.9 KB (0.145%)
string_decoder: 9.24 KB (0.135%)
xml: 7.39 KB (0.108%)
react-copy-to-clipboard: 7.33 KB (0.107%)
react: 6.95 KB (0.102%)
randexp: 6.15 KB (0.0899%)
react-immutable-pure-component: 6.01 KB (0.0879%)
redux-immutable: 5.43 KB (0.0795%)
process: 5.29 KB (0.0774%)
drange: 4.8 KB (0.0703%)
lowlight: 4.42 KB (0.0647%)
scheduler: 4.33 KB (0.0634%)
deep-extend: 4.19 KB (0.0614%)
@babel/runtime: 3.99 KB (0.0584%)
deepmerge: 3.95 KB (0.0579%)
base64-js: 3.84 KB (0.0562%)
stream-browserify: 3.76 KB (0.0550%)
which-typed-array: 3.64 KB (0.0533%)
@swagger-api/apidom-error: 3.45 KB (0.0505%)
copy-to-clipboard: 3.29 KB (0.0481%)
format: 3.26 KB (0.0477%)
is-callable: 3.15 KB (0.0461%)
css.escape: 3.08 KB (0.0451%)
to-buffer: 3.03 KB (0.0444%)
serialize-error: 2.93 KB (0.0428%)
use-sync-external-store: 2.81 KB (0.0412%)
prop-types: 2.6 KB (0.0381%)
querystringify: 2.5 KB (0.0366%)
for-each: 2.32 KB (0.0339%)
has-symbols: 2.31 KB (0.0339%)
define-data-property: 2.28 KB (0.0334%)
xml-but-prettier: 2.17 KB (0.0317%)
function-bind: 2.12 KB (0.0310%)
ieee754: 2.1 KB (0.0308%)
safe-buffer: 1.63 KB (0.0239%)
util-deprecate: 1.58 KB (0.0231%)
randombytes: 1.54 KB (0.0225%)
js-file-download: 1.52 KB (0.0222%)
classnames: 1.49 KB (0.0219%)
call-bind-apply-helpers: 1.35 KB (0.0198%)
set-function-length: 1.24 KB (0.0182%)
repeat-string: 1.18 KB (0.0173%)
get-proto: 1.1 KB (0.0161%)
dunder-proto: 980 B (0.0140%)
@babel/runtime-corejs3: 781 B (0.0112%)
math-intrinsics: 781 B (0.0112%)
toggle-selection: 780 B (0.0111%)
requires-port: 753 B (0.0108%)
inherits: 753 B (0.0108%)
@swagger-api/apidom-json-pointer: 709 B (0.0101%)
fault: 691 B (0.00988%)
call-bound: 667 B (0.00953%)
call-bind: 643 B (0.00919%)
typed-array-buffer: 591 B (0.00845%)
has-property-descriptors: 588 B (0.00840%)
es-errors: 524 B (0.00749%)
available-typed-arrays: 475 B (0.00679%)
gopd: 303 B (0.00433%)
es-define-property: 288 B (0.00412%)
possible-typed-array-names: 264 B (0.00377%)
hasown: 206 B (0.00294%)
has-tostringtag: 189 B (0.00270%)
is-typed-array: 180 B (0.00257%)
isarray: 132 B (0.00189%)
es-object-atoms: 67 B (0.000958%)
<self>: 3.16 MB (47.3%)

View File

@ -0,0 +1,6 @@
<!doctype html>
<html lang="en-US">
<body>
<script src="oauth2-redirect.js"></script>
</body>
</html>

View File

@ -0,0 +1 @@
"use strict";function run(){var e,r,t,a=window.opener.swaggerUIRedirectOauth2,o=a.state,n=a.redirectUrl;if((t=(r=/code|token|error/.test(window.location.hash)?window.location.hash.substring(1).replace("?","&"):location.search.substring(1)).split("&")).forEach((function(e,r,t){t[r]='"'+e.replace("=",'":"')+'"'})),e=(r=r?JSON.parse("{"+t.join()+"}",(function(e,r){return""===e?r:decodeURIComponent(r)})):{}).state===o,"accessCode"!==a.auth.schema.get("flow")&&"authorizationCode"!==a.auth.schema.get("flow")&&"authorization_code"!==a.auth.schema.get("flow")||a.auth.code)a.callback({auth:a.auth,token:r,isValid:e,redirectUrl:n});else if(e||a.errCb({authId:a.auth.name,source:"auth",level:"warning",message:"Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server"}),r.code)delete a.state,a.auth.code=r.code,a.callback({auth:a.auth,redirectUrl:n});else{let e;r.error&&(e="["+r.error+"]: "+(r.error_description?r.error_description+". ":"no accessCode received from the server. ")+(r.error_uri?"More info: "+r.error_uri:"")),a.errCb({authId:a.auth.name,source:"auth",level:"error",message:e||"[Authorization failed]: no accessCode received from the server"})}window.close()}"loading"!==document.readyState?run():document.addEventListener("DOMContentLoaded",(function(){run()}));

View File

@ -0,0 +1,20 @@
{
"name": "swagger-ui-dist",
"version": "5.32.1",
"main": "index.js",
"repository": "git@github.com:swagger-api/swagger-ui.git",
"contributors": [
"(in alphabetical order)",
"Anna Bodnia <anna.bodnia@gmail.com>",
"Buu Nguyen <buunguyen@gmail.com>",
"Josh Ponelat <jponelat@gmail.com>",
"Kyle Shockey <kyleshockey1@gmail.com>",
"Robert Barnwell <robert@robertismy.name>",
"Sahar Jafari <shr.jafari@gmail.com>"
],
"license": "Apache-2.0",
"dependencies": {
"@scarf/scarf": "=1.4.0"
},
"devDependencies": {}
}

View File

@ -0,0 +1,11 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<defs>
<linearGradient id="g" x1="0" x2="1" y1="0" y2="1">
<stop offset="0%" stop-color="#38bdf8"/>
<stop offset="100%" stop-color="#22c55e"/>
</linearGradient>
</defs>
<rect width="64" height="64" rx="14" fill="#0f172a"/>
<path d="M14 19h36v26H14z" fill="url(#g)"/>
<path d="M22 28h20v4H22zm0 8h14v4H22z" fill="#0f172a" opacity="0.9"/>
</svg>

After

Width:  |  Height:  |  Size: 435 B

View File

@ -0,0 +1,20 @@
window.onload = function() {
//<editor-fold desc="Changeable Configuration Block">
// the following lines will be replaced by docker/configurator, when it runs in a docker-container
window.ui = SwaggerUIBundle({
url: "https://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
});
//</editor-fold>
};

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,106 @@
/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/*!
* @description Recursive object extending
* @author Viacheslav Lotsmanov <lotsmanov89@gmail.com>
* @license MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2018 Viacheslav Lotsmanov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2021 Joachim Wester
* MIT license
*/
/*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2022 Joachim Wester
* MIT licensed
*/
/*!
* repeat-string <https://github.com/jonschlinkert/repeat-string>
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
/*! @license DOMPurify 3.3.2 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.2/LICENSE */
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
/*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
/**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* use-sync-external-store-with-selector.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,35 @@
/*!
* @description Recursive object extending
* @author Viacheslav Lotsmanov <lotsmanov89@gmail.com>
* @license MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2018 Viacheslav Lotsmanov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,106 @@
/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/*!
* @description Recursive object extending
* @author Viacheslav Lotsmanov <lotsmanov89@gmail.com>
* @license MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2018 Viacheslav Lotsmanov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2021 Joachim Wester
* MIT license
*/
/*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2022 Joachim Wester
* MIT licensed
*/
/*!
* repeat-string <https://github.com/jonschlinkert/repeat-string>
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
/*! @license DOMPurify 3.3.2 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.2/LICENSE */
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
/*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
/**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* use-sync-external-store-with-selector.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,22 @@
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
/*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
/**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,246 @@
from __future__ import annotations
from datetime import datetime, timezone
import json
from pathlib import Path
import sqlite3
from .models import EventRecord, InterfaceState
def _to_timestamp(value: datetime | None) -> str | None:
if value is None:
return None
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc).isoformat()
def _from_timestamp(value: str | None) -> datetime | None:
if value is None:
return None
parsed = datetime.fromisoformat(value)
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed
class SqliteStore:
def __init__(self, path: Path) -> None:
self._path = path
self._conn: sqlite3.Connection | None = None
@property
def path(self) -> Path:
return self._path
@property
def connection(self) -> sqlite3.Connection:
if self._conn is None:
raise RuntimeError("sqlite store is not open")
return self._conn
async def open(self) -> None:
self._path.parent.mkdir(parents=True, exist_ok=True)
self._conn = sqlite3.connect(self._path, check_same_thread=False)
self._conn.row_factory = sqlite3.Row
self.connection.execute("PRAGMA foreign_keys = ON")
self._ensure_schema()
async def close(self) -> None:
if self._conn is not None:
self._conn.close()
self._conn = None
def _ensure_schema(self) -> None:
self.connection.executescript(
"""
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
interface TEXT NOT NULL,
event_type TEXT NOT NULL,
payload_json TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_events_interface_created_at
ON events(interface, created_at DESC);
CREATE TABLE IF NOT EXISTS interface_state (
interface TEXT PRIMARY KEY,
status TEXT NOT NULL,
last_event_at TEXT,
last_heartbeat_at TEXT,
details_json TEXT NOT NULL DEFAULT '{}'
);
CREATE TABLE IF NOT EXISTS scan_results (
interface TEXT PRIMARY KEY,
refreshed_at TEXT NOT NULL,
results_json TEXT NOT NULL
);
"""
)
self.connection.commit()
async def record_event(self, event: EventRecord) -> None:
self.connection.execute(
"""
INSERT INTO events(interface, event_type, payload_json, created_at)
VALUES (?, ?, ?, ?)
""",
(event.interface, event.event_type, event.payload_json, _to_timestamp(event.created_at)),
)
await self.touch_interface(
InterfaceState(
interface=event.interface,
status="active",
last_event_at=event.created_at,
last_heartbeat_at=None,
details_json=event.payload_json,
)
)
self.connection.commit()
async def touch_interface(self, state: InterfaceState) -> None:
self.connection.execute(
"""
INSERT INTO interface_state(interface, status, last_event_at, last_heartbeat_at, details_json)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(interface) DO UPDATE SET
status = excluded.status,
last_event_at = COALESCE(excluded.last_event_at, interface_state.last_event_at),
last_heartbeat_at = COALESCE(excluded.last_heartbeat_at, interface_state.last_heartbeat_at),
details_json = excluded.details_json
""",
(
state.interface,
state.status,
_to_timestamp(state.last_event_at),
_to_timestamp(state.last_heartbeat_at),
state.details_json,
),
)
self.connection.commit()
async def mark_heartbeat(self, interface: str, heartbeat_at: datetime | None = None) -> None:
heartbeat_at = heartbeat_at or datetime.now(timezone.utc)
self.connection.execute(
"""
INSERT INTO interface_state(interface, status, last_heartbeat_at, details_json)
VALUES (?, ?, ?, ?)
ON CONFLICT(interface) DO UPDATE SET
last_heartbeat_at = excluded.last_heartbeat_at,
status = excluded.status
""",
(interface, "healthy", _to_timestamp(heartbeat_at), "{}"),
)
self.connection.commit()
async def get_state(self, interface: str) -> InterfaceState | None:
cursor = self.connection.execute(
"""
SELECT interface, status, last_event_at, last_heartbeat_at, details_json
FROM interface_state
WHERE interface = ?
""",
(interface,),
)
row = cursor.fetchone()
cursor.close()
if row is None:
return None
return InterfaceState(
interface=row["interface"],
status=row["status"],
last_event_at=_from_timestamp(row["last_event_at"]),
last_heartbeat_at=_from_timestamp(row["last_heartbeat_at"]),
details_json=row["details_json"],
)
async def list_events(self, interface: str, limit: int = 100) -> list[EventRecord]:
cursor = self.connection.execute(
"""
SELECT interface, event_type, payload_json, created_at
FROM events
WHERE interface = ?
ORDER BY created_at DESC, id DESC
LIMIT ?
""",
(interface, limit),
)
rows = cursor.fetchall()
cursor.close()
return [
EventRecord(
interface=row["interface"],
event_type=row["event_type"],
payload_json=row["payload_json"],
created_at=_from_timestamp(row["created_at"]) or datetime.now(timezone.utc),
)
for row in rows
]
async def purge_expired_events(self, expired_before: datetime) -> int:
cutoff = _to_timestamp(expired_before)
count_cursor = self.connection.execute(
"""
SELECT COUNT(*) AS count
FROM events
WHERE created_at <= ?
""",
(cutoff,),
)
row = count_cursor.fetchone()
count_cursor.close()
count = int(row["count"]) if row is not None else 0
if count == 0:
return 0
self.connection.execute(
"""
DELETE FROM events
WHERE created_at <= ?
""",
(cutoff,),
)
self.connection.commit()
return count
async def replace_scan_results(
self,
interface: str,
results: list[dict[str, object]],
refreshed_at: datetime | None = None,
) -> None:
refreshed_at = refreshed_at or datetime.now(timezone.utc)
self.connection.execute(
"""
INSERT INTO scan_results(interface, refreshed_at, results_json)
VALUES (?, ?, ?)
ON CONFLICT(interface) DO UPDATE SET
refreshed_at = excluded.refreshed_at,
results_json = excluded.results_json
""",
(interface, _to_timestamp(refreshed_at), json.dumps(results, sort_keys=True, default=str)),
)
self.connection.commit()
async def get_scan_results(self, interface: str) -> dict[str, object] | None:
cursor = self.connection.execute(
"""
SELECT interface, refreshed_at, results_json
FROM scan_results
WHERE interface = ?
""",
(interface,),
)
row = cursor.fetchone()
cursor.close()
if row is None:
return None
return {
"interface": row["interface"],
"refreshed_at": _from_timestamp(row["refreshed_at"]),
"results": json.loads(row["results_json"]),
}

View File

@ -0,0 +1,142 @@
from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from .dbus_client import DbusConnectionSnapshot, WpaSupplicantDbusClient
from .models import AgentConfig, HealthSnapshot
from .storage import SqliteStore
def _utcnow() -> datetime:
return datetime.now(timezone.utc)
@dataclass(slots=True)
class SupervisorState:
health: HealthSnapshot = field(
default_factory=lambda: HealthSnapshot(
process_up=True,
dbus_up=False,
last_heartbeat_at=None,
ingested_records=0,
expired_records=0,
message="starting",
)
)
reconnect_delay_seconds: float = 1.0
last_error: str = ""
class ConnectionSupervisor:
def __init__(self, config: AgentConfig, client: WpaSupplicantDbusClient, store: SqliteStore) -> None:
self._config = config
self._client = client
self._store = store
self._state = SupervisorState()
self._stop_event = asyncio.Event()
@property
def health(self) -> HealthSnapshot:
return self._state.health
@property
def connection(self) -> DbusConnectionSnapshot:
return self._client.snapshot
@property
def client(self) -> WpaSupplicantDbusClient:
return self._client
async def stop(self) -> None:
self._stop_event.set()
await self._client.disconnect()
async def run(self) -> None:
heartbeat_task = asyncio.create_task(self._heartbeat_loop())
retention_task = asyncio.create_task(self._retention_loop())
try:
await self._stop_event.wait()
finally:
for task in (heartbeat_task, retention_task):
task.cancel()
await asyncio.gather(heartbeat_task, retention_task, return_exceptions=True)
def record_ingested(self, count: int = 1) -> None:
if count <= 0:
return
self._state.health.ingested_records += count
def record_expired(self, count: int = 1) -> None:
if count <= 0:
return
self._state.health.expired_records += count
def _sync_health(
self,
*,
dbus_up: bool | None = None,
last_heartbeat_at: datetime | None = None,
message: str | None = None,
) -> None:
current = self._state.health
self._state.health = HealthSnapshot(
process_up=True,
dbus_up=current.dbus_up if dbus_up is None else dbus_up,
last_heartbeat_at=current.last_heartbeat_at if last_heartbeat_at is None else last_heartbeat_at,
ingested_records=current.ingested_records,
expired_records=current.expired_records,
message=current.message if message is None else message,
)
async def _heartbeat_loop(self) -> None:
while not self._stop_event.is_set():
try:
if not self._client.snapshot.connected:
await self._client.connect()
await self._client.ping()
self._state.reconnect_delay_seconds = self._config.heartbeat.reconnect_initial_delay_seconds
self._state.last_error = ""
self._sync_health(dbus_up=True, last_heartbeat_at=_utcnow(), message="dbus heartbeat ok")
await asyncio.wait_for(self._stop_event.wait(), timeout=self._config.heartbeat.interval_seconds)
except asyncio.TimeoutError:
continue
except asyncio.CancelledError:
raise
except Exception as exc: # pragma: no cover - exercised in integration scenarios
self._state.last_error = str(exc)
self._sync_health(dbus_up=False, message=str(exc))
await self._client.disconnect()
delay = self._state.reconnect_delay_seconds
self._state.reconnect_delay_seconds = min(
self._state.reconnect_delay_seconds * 2,
self._config.heartbeat.reconnect_max_delay_seconds,
)
try:
await asyncio.wait_for(self._stop_event.wait(), timeout=delay)
except asyncio.TimeoutError:
pass
async def _retention_loop(self) -> None:
sweep_seconds = max(0.1, min(60.0, self._config.retention.record_ttl_seconds / 10.0))
while not self._stop_event.is_set():
try:
cutoff = datetime.now(timezone.utc) - timedelta(seconds=self._config.retention.record_ttl_seconds)
expired = await self._store.purge_expired_events(cutoff)
if expired:
self.record_expired(expired)
self._sync_health(message="retention sweep completed")
await asyncio.wait_for(self._stop_event.wait(), timeout=sweep_seconds)
except asyncio.TimeoutError:
continue
except asyncio.CancelledError:
raise
except Exception as exc: # pragma: no cover - retention failures are handled in runtime status
self._state.last_error = str(exc)
self._sync_health(message=f"retention error: {exc}")
try:
await asyncio.wait_for(self._stop_event.wait(), timeout=sweep_seconds)
except asyncio.TimeoutError:
pass

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,12 @@
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "src"
if str(SRC) not in sys.path:
sys.path.insert(0, str(SRC))

View File

@ -0,0 +1,895 @@
from __future__ import annotations
import asyncio
from datetime import datetime, timedelta, timezone
from pathlib import Path
from fastapi.testclient import TestClient
from dbus_agent.api import _event_to_payload, _ttl_remaining_seconds, create_app
from dbus_agent import dbus_client
from dbus_agent.dbus_client import DbusConnectionSnapshot
from dbus_agent.models import AgentConfig, ApiSettings, DatabaseSettings, DbusSettings, EventRecord, HeartbeatSettings, InterfaceState
class FakeStore:
def __init__(self) -> None:
self.opened = False
self.closed = False
self.touched: InterfaceState | None = None
self.scan_results_cache: dict[str, dict[str, object]] = {
"wlan0": {
"interface": "wlan0",
"refreshed_at": datetime(2026, 3, 31, 8, 3, tzinfo=timezone.utc),
"results": [
{
"path": "/fi/w1/wpa_supplicant1/Interfaces/0/BSSs/0",
"interface": "fi.w1.wpa_supplicant1.BSS",
"properties": {
"BSSID": "00:01:02:03:04:05",
"Frequency": 2412,
"Signal": -42,
"SSID": "example",
},
},
{
"path": "/fi/w1/wpa_supplicant1/Interfaces/0/BSSs/1",
"interface": "fi.w1.wpa_supplicant1.BSS",
"properties": {
"BSSID": "00:01:02:03:04:06",
"Frequency": 5180,
"Signal": -55,
"SSID": "backup",
},
}
],
}
}
async def open(self) -> None:
self.opened = True
async def close(self) -> None:
self.closed = True
async def touch_interface(self, state: InterfaceState) -> None:
self.touched = state
async def get_state(self, interface: str) -> InterfaceState | None:
return InterfaceState(
interface=interface,
status="stale",
last_event_at=datetime(2026, 3, 31, 8, 0, tzinfo=timezone.utc),
last_heartbeat_at=datetime(2026, 3, 31, 8, 1, tzinfo=timezone.utc),
details_json='{"ssid":"stale"}',
)
async def list_events(self, interface: str, limit: int = 100) -> list[EventRecord]:
if interface != "wlan0":
return []
return [
EventRecord(
interface="wlan0",
event_type="PropertiesChanged",
payload_json='{"ssid":"example"}',
created_at=datetime(2026, 3, 31, 8, 0, tzinfo=timezone.utc),
)
]
async def get_scan_results(self, interface: str) -> dict[str, object] | None:
return self.scan_results_cache.get(interface)
async def replace_scan_results(
self,
interface: str,
results: list[dict[str, object]],
refreshed_at: datetime | None = None,
) -> None:
self.scan_results_cache[interface] = {
"interface": interface,
"refreshed_at": refreshed_at or datetime.now(timezone.utc),
"results": results,
}
class FakeSupervisor:
def __init__(self) -> None:
self.health = type(
"Health",
(),
{
"process_up": True,
"dbus_up": True,
"last_heartbeat_at": datetime(2026, 3, 31, 8, 1, tzinfo=timezone.utc),
"ingested_records": 12,
"expired_records": 3,
"message": "ok",
},
)()
self.connection = DbusConnectionSnapshot(connected=True, last_ping_at=datetime(2026, 3, 31, 8, 1, tzinfo=timezone.utc))
self.client = self
self._stop_event = asyncio.Event()
self.scan_calls: list[str] = []
self.disconnect_calls: list[str] = []
self.reattach_calls: list[str] = []
self.reassociate_calls: list[str] = []
self.reconnect_calls: list[str] = []
self.eap_logoff_calls: list[str] = []
self.eap_logon_calls: list[str] = []
self.subscribe_probe_req_calls: list[str] = []
self.unsubscribe_probe_req_calls: list[str] = []
self.signal_poll_calls: list[str] = []
self.add_network_calls: list[dict[str, object]] = []
async def run(self) -> None:
await self._stop_event.wait()
async def stop(self) -> None:
self._stop_event.set()
async def read_interface_state(self, interface: str) -> InterfaceState:
return InterfaceState(
interface=interface,
status="completed",
last_event_at=None,
last_heartbeat_at=datetime(2026, 3, 31, 8, 2, tzinfo=timezone.utc),
details_json='{"Scanning":false,"State":"completed"}',
)
async def read_current_bss(self, interface: str) -> dict[str, object]:
return {
"path": "/fi/w1/wpa_supplicant1/Interfaces/0/BSSs/0",
"dbus_interface": "fi.w1.wpa_supplicant1.BSS",
"properties": {
"BSSID": "00:01:02:03:04:05",
"Frequency": 2412,
"Signal": -42,
"SSID": "example",
},
}
async def read_current_network(self, interface: str) -> dict[str, object]:
return {
"path": "/fi/w1/wpa_supplicant1/Interfaces/0/Networks/0",
"dbus_interface": "fi.w1.wpa_supplicant1.Network",
"properties": {
"Enabled": True,
"Properties": {"psk": "secret", "ssid": "example"},
},
}
async def read_scan_results(self, interface: str) -> list[dict[str, object]]:
return [
{
"path": "/fi/w1/wpa_supplicant1/Interfaces/0/BSSs/0",
"interface": "fi.w1.wpa_supplicant1.BSS",
"properties": {
"BSSID": "00:01:02:03:04:05",
"Frequency": 2412,
"Signal": -42,
"SSID": "example",
},
},
{
"path": "/fi/w1/wpa_supplicant1/Interfaces/0/BSSs/1",
"interface": "fi.w1.wpa_supplicant1.BSS",
"properties": {
"BSSID": "00:01:02:03:04:06",
"Frequency": 5180,
"Signal": -55,
"SSID": "backup",
},
},
]
async def scan(self, interface: str) -> None:
self.scan_calls.append(interface)
async def disconnect_interface(self, interface: str) -> None:
self.disconnect_calls.append(interface)
async def reattach(self, interface: str) -> None:
self.reattach_calls.append(interface)
async def reassociate(self, interface: str) -> None:
self.reassociate_calls.append(interface)
async def reconnect(self, interface: str) -> None:
self.reconnect_calls.append(interface)
async def eap_logoff(self, interface: str) -> None:
self.eap_logoff_calls.append(interface)
async def eap_logon(self, interface: str) -> None:
self.eap_logon_calls.append(interface)
async def subscribe_probe_req(self, interface: str) -> None:
self.subscribe_probe_req_calls.append(interface)
async def unsubscribe_probe_req(self, interface: str) -> None:
self.unsubscribe_probe_req_calls.append(interface)
async def signal_poll(self, interface: str) -> dict[str, object]:
self.signal_poll_calls.append(interface)
return {"RSSI": -42, "Frequency": 2412, "Noise": -95}
async def add_network(self, interface: str, payload: dict[str, object]) -> str:
self.add_network_calls.append(payload)
return f"/fi/w1/wpa_supplicant1/Interfaces/{interface}/Networks/7"
def _config() -> AgentConfig:
return AgentConfig(
interface="wlan0",
dbus=DbusSettings(),
database=DatabaseSettings(path=Path("/tmp/dbus-agent.sqlite3")),
api=ApiSettings(host="127.0.0.1", port=8080, api_key_header="X-Token", api_key="secret"),
heartbeat=HeartbeatSettings(),
)
def test_api_health_state_events_and_commands() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
docs = client.get("/docs")
assert docs.status_code == 200
assert "cdn.jsdelivr.net" not in docs.text
assert "/static/swagger-ui-bundle.js" in docs.text
assert "/static/swagger-ui.css" in docs.text
assert "SwaggerUIBundle" in docs.text
assert client.get("/docs/oauth2-redirect").status_code == 200
bundle = client.get("/static/swagger-ui-bundle.js")
assert bundle.status_code == 200
assert len(bundle.content) > 1_000_000
css = client.get("/static/swagger-ui.css")
assert css.status_code == 200
health = client.get("/health")
assert health.status_code == 200
assert health.json()["dbus_up"] is True
assert health.json()["ingested_records"] == 12
assert health.json()["expired_records"] == 3
state = client.get("/interfaces/wlan0/state")
assert state.status_code == 200
assert state.json()["status"] == "completed"
assert state.json()["details"]["State"] == "completed"
assert "CurrentBSS" not in state.json()["details"]
assert "CurrentNetwork" not in state.json()["details"]
assert store.touched is not None
assert store.touched.status == "completed"
current_bss = client.get("/interfaces/wlan0/current_bss")
assert current_bss.status_code == 200
assert current_bss.json()["interface"] == "wlan0"
assert current_bss.json()["properties"]["Signal"] == -42
assert current_bss.json()["properties"]["BSSID"] == "00:01:02:03:04:05"
assert current_bss.json()["properties"]["SSID"] == "example"
current_network = client.get("/interfaces/wlan0/current_network")
assert current_network.status_code == 200
assert current_network.json()["interface"] == "wlan0"
assert current_network.json()["properties"]["Enabled"] is True
signal_poll = client.get("/interfaces/wlan0/signal_poll")
assert signal_poll.status_code == 200
assert signal_poll.json() == {
"interface": "wlan0",
"properties": {
"RSSI": -42,
"Frequency": 2412,
"Noise": -95,
},
}
assert supervisor.signal_poll_calls == ["wlan0"]
scan = client.post("/interfaces/wlan0/scan")
assert scan.status_code == 202
assert scan.json() == {"interface": "wlan0", "requested": True}
assert supervisor.scan_calls == ["wlan0"]
disconnect = client.post("/interfaces/wlan0/disconnect")
assert disconnect.status_code == 202
assert disconnect.json() == {"interface": "wlan0", "requested": True}
assert supervisor.disconnect_calls == ["wlan0"]
reattach = client.post("/interfaces/wlan0/reattach")
assert reattach.status_code == 202
assert reattach.json() == {"interface": "wlan0", "requested": True}
assert supervisor.reattach_calls == ["wlan0"]
reassociate = client.post("/interfaces/wlan0/reassociate")
assert reassociate.status_code == 202
assert reassociate.json() == {"interface": "wlan0", "requested": True}
assert supervisor.reassociate_calls == ["wlan0"]
reconnect = client.post("/interfaces/wlan0/reconnect")
assert reconnect.status_code == 202
assert reconnect.json() == {"interface": "wlan0", "requested": True}
assert supervisor.reconnect_calls == ["wlan0"]
eap_logoff = client.post("/interfaces/wlan0/eap_logoff")
assert eap_logoff.status_code == 202
assert eap_logoff.json() == {"interface": "wlan0", "requested": True}
assert supervisor.eap_logoff_calls == ["wlan0"]
eap_logon = client.post("/interfaces/wlan0/eap_logon")
assert eap_logon.status_code == 202
assert eap_logon.json() == {"interface": "wlan0", "requested": True}
assert supervisor.eap_logon_calls == ["wlan0"]
subscribe_probe_req = client.post("/interfaces/wlan0/subscribe_probe_req")
assert subscribe_probe_req.status_code == 202
assert subscribe_probe_req.json() == {"interface": "wlan0", "requested": True}
assert supervisor.subscribe_probe_req_calls == ["wlan0"]
unsubscribe_probe_req = client.post("/interfaces/wlan0/unsubscribe_probe_req")
assert unsubscribe_probe_req.status_code == 202
assert unsubscribe_probe_req.json() == {"interface": "wlan0", "requested": True}
assert supervisor.unsubscribe_probe_req_calls == ["wlan0"]
add_network = client.post(
"/interfaces/wlan0/add_network",
json={
"ssid": "example",
"priority": 10,
"scan_ssid": True,
"key_mgmt": ["wpa-psk"],
},
)
assert add_network.status_code == 201
assert add_network.json() == {
"interface": "wlan0",
"network": "/fi/w1/wpa_supplicant1/Interfaces/wlan0/Networks/7",
}
assert supervisor.add_network_calls == [
{
"ssid": "example",
"priority": 10,
"scan_ssid": True,
"key_mgmt": ["wpa-psk"],
}
]
scan_results = client.get("/interfaces/wlan0/scan_results")
assert scan_results.status_code == 200
assert scan_results.json()["interface"] == "wlan0"
assert len(scan_results.json()["results"]) == 2
assert scan_results.json()["results"][0]["properties"]["SSID"] == "example"
assert scan_results.json()["refreshed_at"] == "2026-03-31T08:03:00+00:00"
events = client.get("/interfaces/wlan0/events")
assert events.status_code == 200
assert events.json()[0]["event_type"] == "PropertiesChanged"
assert "ttl_remaining_seconds" in events.json()[0]
assert events.json()[0]["ttl_remaining_seconds"] >= 0
unauthorized = client.post("/commands", json={"action": "scan"})
assert unauthorized.status_code == 401
authorized = client.post("/commands", headers={"X-Token": "secret"}, json={"action": "scan"})
assert authorized.status_code == 501
def test_api_rejects_unconfigured_interface() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.get("/interfaces/wlp2s0/state")
assert response.status_code == 404
assert client.get("/interfaces/wlp2s0/current_bss").status_code == 404
assert client.get("/interfaces/wlp2s0/current_network").status_code == 404
assert client.get("/interfaces/wlp2s0/signal_poll").status_code == 404
assert client.post("/interfaces/wlp2s0/subscribe_probe_req").status_code == 404
assert client.post("/interfaces/wlp2s0/unsubscribe_probe_req").status_code == 404
assert client.post("/interfaces/wlp2s0/scan").status_code == 404
assert client.post("/interfaces/wlp2s0/disconnect").status_code == 404
assert client.post("/interfaces/wlp2s0/reattach").status_code == 404
assert client.post("/interfaces/wlp2s0/reassociate").status_code == 404
assert client.post("/interfaces/wlp2s0/reconnect").status_code == 404
assert client.post("/interfaces/wlp2s0/eap_logoff").status_code == 404
assert client.post("/interfaces/wlp2s0/eap_logon").status_code == 404
assert client.post("/interfaces/wlp2s0/add_network", json={"ssid": "example"}).status_code == 404
assert client.get("/interfaces/wlp2s0/scan_results").status_code == 404
assert client.get("/interface/wlp2s0/current_bss").status_code == 404
assert client.get("/interface/wlp2s0/current_network").status_code == 404
def test_api_scan_rejects_policy_denied_dbus_calls() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def denied_scan(interface: str) -> None:
raise PermissionError("D-Bus policy denied scan request for wlan0")
supervisor.scan = denied_scan # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/scan")
assert response.status_code == 403
assert "policy denied" in response.json()["detail"]
def test_api_signal_poll_rejects_policy_denied_dbus_calls() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def denied_signal_poll(interface: str) -> dict[str, object]:
raise PermissionError("D-Bus policy denied signal poll request for wlan0")
supervisor.signal_poll = denied_signal_poll # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.get("/interfaces/wlan0/signal_poll")
assert response.status_code == 403
assert "policy denied" in response.json()["detail"]
def test_event_ttl_remaining_seconds_helper() -> None:
now = datetime(2026, 3, 31, 8, 0, tzinfo=timezone.utc)
event = EventRecord(
interface="wlan0",
event_type="PropertiesChanged",
payload_json='{"ssid":"example"}',
created_at=now - timedelta(seconds=30),
)
assert _ttl_remaining_seconds(event.created_at, 120.0, now=now) == 90.0
assert _ttl_remaining_seconds(now, 120.0, now=now) == 120.0
assert _ttl_remaining_seconds(now - timedelta(seconds=120), 120.0, now=now) == 0.0
assert _ttl_remaining_seconds(now - timedelta(seconds=300), 120.0, now=now) == 0.0
payload = _event_to_payload(event, ttl_seconds=120.0, now=now)
assert payload["ttl_remaining_seconds"] == 90.0
assert payload["created_at"] == "2026-03-31T07:59:30+00:00"
def test_api_subscribe_probe_req_rejects_policy_denied_dbus_calls() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def denied_subscribe_probe_req(interface: str) -> None:
raise PermissionError("D-Bus policy denied subscribe probe request for wlan0")
supervisor.subscribe_probe_req = denied_subscribe_probe_req # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/subscribe_probe_req")
assert response.status_code == 403
assert "policy denied" in response.json()["detail"]
def test_api_unsubscribe_probe_req_rejects_policy_denied_dbus_calls() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def denied_unsubscribe_probe_req(interface: str) -> None:
raise PermissionError("D-Bus policy denied unsubscribe probe request for wlan0")
supervisor.unsubscribe_probe_req = denied_unsubscribe_probe_req # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/unsubscribe_probe_req")
assert response.status_code == 403
assert "policy denied" in response.json()["detail"]
def test_api_disconnect_rejects_policy_denied_dbus_calls() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def denied_disconnect(interface: str) -> None:
raise PermissionError("D-Bus policy denied disconnect request for wlan0")
supervisor.disconnect_interface = denied_disconnect # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/disconnect")
assert response.status_code == 403
assert "policy denied" in response.json()["detail"]
def test_api_reattach_rejects_state_conflicts() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def conflicted_reattach(interface: str) -> None:
raise dbus_client.InterfaceConflictError("interface wlan0 cannot be reattached in its current state: Interface is not connected to any network")
supervisor.reattach = conflicted_reattach # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/reattach")
assert response.status_code == 409
assert "cannot be reattached" in response.json()["detail"]
def test_api_signal_poll_rejects_state_conflicts() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def conflicted_signal_poll(interface: str) -> dict[str, object]:
raise dbus_client.InterfaceConflictError(
"interface wlan0 cannot be signal-polled in its current state: Interface is not connected to any network"
)
supervisor.signal_poll = conflicted_signal_poll # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.get("/interfaces/wlan0/signal_poll")
assert response.status_code == 409
assert "cannot be signal-polled" in response.json()["detail"]
def test_api_subscribe_probe_req_rejects_runtime_errors() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def failing_subscribe_probe_req(interface: str) -> None:
raise RuntimeError("failed to subscribe to probe requests for wlan0: boom")
supervisor.subscribe_probe_req = failing_subscribe_probe_req # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/subscribe_probe_req")
assert response.status_code == 503
assert "failed to subscribe to probe requests" in response.json()["detail"]
def test_api_unsubscribe_probe_req_rejects_runtime_errors() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def failing_unsubscribe_probe_req(interface: str) -> None:
raise RuntimeError("failed to unsubscribe from probe requests for wlan0: boom")
supervisor.unsubscribe_probe_req = failing_unsubscribe_probe_req # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/unsubscribe_probe_req")
assert response.status_code == 503
assert "failed to unsubscribe from probe requests" in response.json()["detail"]
def test_api_reassociate_rejects_state_conflicts() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def conflicted_reassociate(interface: str) -> None:
raise dbus_client.InterfaceConflictError(
"interface wlan0 cannot be reassociated in its current state: Interface is disabled"
)
supervisor.reassociate = conflicted_reassociate # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/reassociate")
assert response.status_code == 409
assert "cannot be reassociated" in response.json()["detail"]
def test_api_reconnect_rejects_state_conflicts() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def conflicted_reconnect(interface: str) -> None:
raise dbus_client.InterfaceConflictError(
"interface wlan0 cannot be reconnected in its current state: Interface is not connected to any network"
)
supervisor.reconnect = conflicted_reconnect # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/reconnect")
assert response.status_code == 409
assert "cannot be reconnected" in response.json()["detail"]
def test_api_eap_logoff_rejects_state_conflicts() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def conflicted_eap_logoff(interface: str) -> None:
raise dbus_client.InterfaceConflictError(
"interface wlan0 cannot be logged off in its current state: Interface is not connected to any network"
)
supervisor.eap_logoff = conflicted_eap_logoff # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/eap_logoff")
assert response.status_code == 409
assert "cannot be logged off" in response.json()["detail"]
def test_api_eap_logon_rejects_state_conflicts() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def conflicted_eap_logon(interface: str) -> None:
raise dbus_client.InterfaceConflictError(
"interface wlan0 cannot be logged on in its current state: Interface is not connected to any network"
)
supervisor.eap_logon = conflicted_eap_logon # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/eap_logon")
assert response.status_code == 409
assert "cannot be logged on" in response.json()["detail"]
def test_api_add_network_rejects_policy_denied_dbus_calls() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def denied_add_network(interface: str, payload: dict[str, object]) -> str:
raise PermissionError("D-Bus policy denied add network request for wlan0")
supervisor.add_network = denied_add_network # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/add_network", json={"ssid": "example"})
assert response.status_code == 403
assert "policy denied" in response.json()["detail"]
def test_api_reattach_rejects_policy_denied_dbus_calls() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def denied_reattach(interface: str) -> None:
raise PermissionError("D-Bus policy denied reattach request for wlan0")
supervisor.reattach = denied_reattach # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/reattach")
assert response.status_code == 403
assert "policy denied" in response.json()["detail"]
def test_api_reassociate_rejects_policy_denied_dbus_calls() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def denied_reassociate(interface: str) -> None:
raise PermissionError("D-Bus policy denied reassociate request for wlan0")
supervisor.reassociate = denied_reassociate # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/reassociate")
assert response.status_code == 403
assert "policy denied" in response.json()["detail"]
def test_api_reconnect_rejects_policy_denied_dbus_calls() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def denied_reconnect(interface: str) -> None:
raise PermissionError("D-Bus policy denied reconnect request for wlan0")
supervisor.reconnect = denied_reconnect # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/reconnect")
assert response.status_code == 403
assert "policy denied" in response.json()["detail"]
def test_api_eap_logoff_rejects_policy_denied_dbus_calls() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def denied_eap_logoff(interface: str) -> None:
raise PermissionError("D-Bus policy denied EAP logoff request for wlan0")
supervisor.eap_logoff = denied_eap_logoff # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/eap_logoff")
assert response.status_code == 403
assert "policy denied" in response.json()["detail"]
def test_api_eap_logon_rejects_policy_denied_dbus_calls() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def denied_eap_logon(interface: str) -> None:
raise PermissionError("D-Bus policy denied EAP logon request for wlan0")
supervisor.eap_logon = denied_eap_logon # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/eap_logon")
assert response.status_code == 403
assert "policy denied" in response.json()["detail"]
def test_api_scan_propagates_dbus_errors() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def failing_scan(interface: str) -> None:
raise RuntimeError("failed to start scan for wlan0: boom")
supervisor.scan = failing_scan # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/scan")
assert response.status_code == 503
assert "failed to start scan" in response.json()["detail"]
def test_api_disconnect_propagates_dbus_errors() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def failing_disconnect(interface: str) -> None:
raise RuntimeError("failed to disconnect wlan0: boom")
supervisor.disconnect_interface = failing_disconnect # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/disconnect")
assert response.status_code == 503
assert "failed to disconnect" in response.json()["detail"]
def test_api_signal_poll_propagates_dbus_errors() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def failing_signal_poll(interface: str) -> dict[str, object]:
raise RuntimeError("failed to signal poll wlan0: boom")
supervisor.signal_poll = failing_signal_poll # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.get("/interfaces/wlan0/signal_poll")
assert response.status_code == 503
assert "failed to signal poll" in response.json()["detail"]
def test_api_reattach_propagates_dbus_errors() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def failing_reattach(interface: str) -> None:
raise RuntimeError("failed to reattach wlan0: boom")
supervisor.reattach = failing_reattach # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/reattach")
assert response.status_code == 503
assert "failed to reattach" in response.json()["detail"]
def test_api_reassociate_propagates_dbus_errors() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def failing_reassociate(interface: str) -> None:
raise RuntimeError("failed to reassociate wlan0: boom")
supervisor.reassociate = failing_reassociate # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/reassociate")
assert response.status_code == 503
assert "failed to reassociate" in response.json()["detail"]
def test_api_reconnect_propagates_dbus_errors() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def failing_reconnect(interface: str) -> None:
raise RuntimeError("failed to reconnect wlan0: boom")
supervisor.reconnect = failing_reconnect # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/reconnect")
assert response.status_code == 503
assert "failed to reconnect" in response.json()["detail"]
def test_api_eap_logoff_propagates_dbus_errors() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def failing_eap_logoff(interface: str) -> None:
raise RuntimeError("failed to log off wlan0: boom")
supervisor.eap_logoff = failing_eap_logoff # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/eap_logoff")
assert response.status_code == 503
assert "failed to log off" in response.json()["detail"]
def test_api_eap_logon_propagates_dbus_errors() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def failing_eap_logon(interface: str) -> None:
raise RuntimeError("failed to log on wlan0: boom")
supervisor.eap_logon = failing_eap_logon # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/eap_logon")
assert response.status_code == 503
assert "failed to log on" in response.json()["detail"]
def test_api_add_network_rejects_invalid_args() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def invalid_add_network(interface: str, payload: dict[str, object]) -> str:
raise ValueError("invalid network configuration for wlan0: null values are not supported in D-Bus arguments")
supervisor.add_network = invalid_add_network # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/add_network", json={"ssid": None})
assert response.status_code == 400
assert "invalid network configuration" in response.json()["detail"]
def test_api_add_network_propagates_dbus_errors() -> None:
store = FakeStore()
supervisor = FakeSupervisor()
async def failing_add_network(interface: str, payload: dict[str, object]) -> str:
raise RuntimeError("failed to add network for wlan0: boom")
supervisor.add_network = failing_add_network # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/add_network", json={"ssid": "example"})
assert response.status_code == 503
assert "failed to add network" in response.json()["detail"]

View File

@ -0,0 +1,334 @@
from __future__ import annotations
import argparse
import io
from dataclasses import dataclass
import httpx
from dbus_agent.cli import ApiClient, CliSettings, _run_command, run
@dataclass
class FakeClient:
responses: dict[str, httpx.Response]
close_called: bool = False
def health(self) -> httpx.Response:
return self.responses["health"]
def state(self, ifname: str) -> httpx.Response:
return self.responses[f"state:{ifname}"]
def events(self, ifname: str, limit: int) -> httpx.Response:
return self.responses[f"events:{ifname}:{limit}"]
def scan_results(self, ifname: str) -> httpx.Response:
return self.responses[f"scan_results:{ifname}"]
def command(self, payload: dict[str, object]) -> httpx.Response:
self.responses["command_payload"] = httpx.Response(200, json=payload)
return self.responses["command"]
def close(self) -> None:
self.close_called = True
def test_api_client_uses_mock_transport_and_api_key_for_commands() -> None:
seen: dict[str, object] = {}
def handler(request: httpx.Request) -> httpx.Response:
seen["path"] = request.url.path
seen["auth"] = request.headers.get("X-API-Key")
seen["params"] = dict(request.url.params)
return httpx.Response(200, json={"ok": True})
transport = httpx.MockTransport(handler)
client = httpx.Client(base_url="http://test", transport=transport, timeout=1)
api = ApiClient(
CliSettings(
base_url="http://test",
api_key="secret",
timeout_seconds=1,
output="text",
api_key_header="X-API-Key",
),
client,
)
result = _run_command(argparse.Namespace(command="command", payload='{"action":"scan"}'), api)
assert result.status_code == 200
assert seen["path"] == "/commands"
assert seen["auth"] == "secret"
assert seen["params"] == {}
api.close()
def test_cli_health_text_output() -> None:
stdout = io.StringIO()
stderr = io.StringIO()
exit_code = run(
["--base-url", "http://test", "health"],
client_factory=lambda settings: FakeClient(
{
"health": httpx.Response(
200,
json={
"process_up": True,
"dbus_up": False,
"ingested_records": 7,
"expired_records": 2,
"message": "down",
},
),
"state:wlan0": httpx.Response(404, json={"detail": "not used"}),
"events:wlan0:100": httpx.Response(404, json={"detail": "not used"}),
"scan_results:wlan0": httpx.Response(404, json={"detail": "not used"}),
"command": httpx.Response(501, json={"detail": {"message": "stub"}}),
}
),
stdout=stdout,
stderr=stderr,
)
assert exit_code == 0
assert "process_up: yes" in stdout.getvalue()
assert "dbus_up: no" in stdout.getvalue()
assert "ingested_records: 7" in stdout.getvalue()
assert "expired_records: 2" in stdout.getvalue()
assert stderr.getvalue() == ""
def test_cli_state_json_output() -> None:
stdout = io.StringIO()
stderr = io.StringIO()
exit_code = run(
["--output", "json", "state", "wlan0"],
client_factory=lambda settings: FakeClient(
{
"health": httpx.Response(200, json={"ok": True}),
"state:wlan0": httpx.Response(
200,
json={"interface": "wlan0", "status": "healthy", "details": {"ssid": "example"}},
),
"events:wlan0:100": httpx.Response(404, json={"detail": "not used"}),
"scan_results:wlan0": httpx.Response(404, json={"detail": "not used"}),
"command": httpx.Response(501, json={"detail": {"message": "stub"}}),
}
),
stdout=stdout,
stderr=stderr,
)
assert exit_code == 0
assert '"interface": "wlan0"' in stdout.getvalue()
assert '"status": "healthy"' in stdout.getvalue()
assert stderr.getvalue() == ""
def test_cli_events_text_output_and_empty_response() -> None:
stdout = io.StringIO()
stderr = io.StringIO()
exit_code = run(
["events", "wlan0", "--limit", "5"],
client_factory=lambda settings: FakeClient(
{
"health": httpx.Response(200, json={"ok": True}),
"state:wlan0": httpx.Response(404, json={"detail": "not used"}),
"events:wlan0:5": httpx.Response(
200,
json=[
{
"interface": "wlan0",
"event_type": "PropertiesChanged",
"created_at": "2026-03-31T08:00:00+00:00",
"ttl_remaining_seconds": 42,
"payload": {"ssid": "example"},
}
],
),
"scan_results:wlan0": httpx.Response(404, json={"detail": "not used"}),
"command": httpx.Response(204),
}
),
stdout=stdout,
stderr=stderr,
)
assert exit_code == 0
assert "Event 1:" in stdout.getvalue()
assert "PropertiesChanged" in stdout.getvalue()
assert "ttl_remaining_seconds: 42" in stdout.getvalue()
assert stderr.getvalue() == ""
stdout = io.StringIO()
stderr = io.StringIO()
empty_exit = run(
["command", "--payload", "{}"],
client_factory=lambda settings: FakeClient(
{
"health": httpx.Response(200, json={"ok": True}),
"state:wlan0": httpx.Response(404, json={"detail": "not used"}),
"events:wlan0:100": httpx.Response(404, json={"detail": "not used"}),
"scan_results:wlan0": httpx.Response(404, json={"detail": "not used"}),
"command": httpx.Response(204),
}
),
stdout=stdout,
stderr=stderr,
)
assert empty_exit == 0
assert stdout.getvalue() == "\n"
assert stderr.getvalue() == ""
def test_cli_events_json_output_preserves_ttl() -> None:
stdout = io.StringIO()
stderr = io.StringIO()
exit_code = run(
["--output", "json", "events", "wlan0", "--limit", "5"],
client_factory=lambda settings: FakeClient(
{
"health": httpx.Response(200, json={"ok": True}),
"state:wlan0": httpx.Response(404, json={"detail": "not used"}),
"events:wlan0:5": httpx.Response(
200,
json=[
{
"interface": "wlan0",
"event_type": "PropertiesChanged",
"created_at": "2026-03-31T08:00:00+00:00",
"ttl_remaining_seconds": 42,
"payload": {"ssid": "example"},
}
],
),
"scan_results:wlan0": httpx.Response(404, json={"detail": "not used"}),
"command": httpx.Response(204),
}
),
stdout=stdout,
stderr=stderr,
)
assert exit_code == 0
assert '"ttl_remaining_seconds": 42' in stdout.getvalue()
assert stderr.getvalue() == ""
def test_cli_scan_results_text_output() -> None:
stdout = io.StringIO()
stderr = io.StringIO()
exit_code = run(
["scan-results", "wlan0"],
client_factory=lambda settings: FakeClient(
{
"health": httpx.Response(200, json={"ok": True}),
"state:wlan0": httpx.Response(404, json={"detail": "not used"}),
"events:wlan0:100": httpx.Response(404, json={"detail": "not used"}),
"scan_results:wlan0": httpx.Response(
200,
json={
"interface": "wlan0",
"results": [
{
"path": "/fi/w1/wpa_supplicant1/Interfaces/0/BSSs/0",
"interface": "fi.w1.wpa_supplicant1.BSS",
"properties": {
"BSSID": "00:01:02:03:04:05",
"Signal": -42,
"SSID": "example",
},
}
],
},
),
"command": httpx.Response(204),
}
),
stdout=stdout,
stderr=stderr,
)
assert exit_code == 0
assert "Interface: wlan0" in stdout.getvalue()
assert "Result 1:" in stdout.getvalue()
assert "SSID: example" in stdout.getvalue()
assert stderr.getvalue() == ""
def test_cli_error_scenarios() -> None:
stdout = io.StringIO()
stderr = io.StringIO()
transport_exit = run(
["health"],
client_factory=lambda settings: _RaisingClient(httpx.ConnectError("down", request=httpx.Request("GET", "http://test/health"))),
stdout=stdout,
stderr=stderr,
)
assert transport_exit == 3
assert "Transport error" in stderr.getvalue()
stdout = io.StringIO()
stderr = io.StringIO()
auth_exit = run(
["state", "wlan0"],
client_factory=lambda settings: FakeClient(
{
"health": httpx.Response(200, json={"ok": True}),
"state:wlan0": httpx.Response(401, json={"detail": "invalid"}),
"events:wlan0:100": httpx.Response(404, json={"detail": "not used"}),
"scan_results:wlan0": httpx.Response(404, json={"detail": "not used"}),
"command": httpx.Response(501, json={"detail": {"message": "stub"}}),
}
),
stdout=stdout,
stderr=stderr,
)
assert auth_exit == 4
assert "HTTP 401" in stderr.getvalue()
stdout = io.StringIO()
stderr = io.StringIO()
missing_exit = run(
["state", "missing"],
client_factory=lambda settings: FakeClient(
{
"health": httpx.Response(200, json={"ok": True}),
"state:missing": httpx.Response(404, json={"detail": "not found"}),
"events:missing:100": httpx.Response(404, json={"detail": "not used"}),
"scan_results:missing": httpx.Response(404, json={"detail": "not used"}),
"command": httpx.Response(501, json={"detail": {"message": "stub"}}),
}
),
stdout=stdout,
stderr=stderr,
)
assert missing_exit == 6
assert "HTTP 404" in stderr.getvalue()
class _RaisingClient:
def __init__(self, exc: Exception) -> None:
self._exc = exc
def health(self) -> httpx.Response:
raise self._exc
def state(self, ifname: str) -> httpx.Response:
raise self._exc
def events(self, ifname: str, limit: int) -> httpx.Response:
raise self._exc
def scan_results(self, ifname: str) -> httpx.Response:
raise self._exc
def command(self, payload: dict[str, object]) -> httpx.Response:
raise self._exc
def close(self) -> None:
return None

View File

@ -0,0 +1,76 @@
from __future__ import annotations
from pathlib import Path
from dbus_agent.config import load_agent_config, load_env_file
def test_load_env_file_and_config_overrides(tmp_path: Path, monkeypatch) -> None:
config_path = tmp_path / "config.yaml"
config_path.write_text(
"""
interface: wlan0
dbus:
service: fi.w1.wpa_supplicant1
database:
path: /var/lib/dbus-agent/dbus-agent.sqlite3
api:
host: 127.0.0.1
port: 8080
event_filter:
allowed_event_types:
- InterfaceAdded
- InterfaceRemoved
""".strip()
+ "\n",
encoding="utf-8",
)
env_path = tmp_path / "dbus-agent.env"
env_path.write_text(
"""
export DBUS_AGENT_INTERFACE="wlp2s0"
DBUS_AGENT_API_KEY='secret-key'
DBUS_AGENT_API_HOST=0.0.0.0
DBUS_AGENT_API_PORT=9090
DBUS_AGENT_DATABASE_PATH=/tmp/dbus-agent.sqlite3
DBUS_AGENT_RECORD_TTL_SECONDS=7200
DBUS_AGENT_EVENT_FILTER_ALLOWED_EVENT_TYPES=ScanDone, PropertiesChanged
""".strip()
+ "\n",
encoding="utf-8",
)
monkeypatch.setenv("DBUS_AGENT_API_KEY_HEADER", "X-Token")
parsed_env = load_env_file(env_path)
assert parsed_env["DBUS_AGENT_INTERFACE"] == "wlp2s0"
assert parsed_env["DBUS_AGENT_API_KEY"] == "secret-key"
config = load_agent_config(config_path, env_path)
assert config.interface == "wlp2s0"
assert config.api.api_key == "secret-key"
assert config.api.host == "0.0.0.0"
assert config.api.port == 9090
assert config.api.api_key_header == "X-Token"
assert config.database.path.as_posix() == "/tmp/dbus-agent.sqlite3"
assert config.retention.record_ttl_seconds == 7200.0
assert config.event_filter.allowed_event_types == ("ScanDone", "PropertiesChanged")
def test_load_agent_config_defaults_event_filter_to_all_events(tmp_path: Path, monkeypatch) -> None:
config_path = tmp_path / "config.yaml"
config_path.write_text(
"""
interface: wlan0
database:
path: /var/lib/dbus-agent/dbus-agent.sqlite3
""".strip()
+ "\n",
encoding="utf-8",
)
monkeypatch.delenv("DBUS_AGENT_EVENT_FILTER_ALLOWED_EVENT_TYPES", raising=False)
config = load_agent_config(config_path)
assert config.event_filter.allowed_event_types == ()

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,32 @@
from __future__ import annotations
import runpy
import sys
from types import SimpleNamespace
class _FakeSupervisor:
pass
def test_main_module_invokes_entrypoint(monkeypatch) -> None:
import dbus_agent.api
import dbus_agent.runtime
import uvicorn
fake_config = SimpleNamespace(api=SimpleNamespace(host="127.0.0.1", port=8080))
monkeypatch.setattr(
dbus_agent.runtime,
"build_runtime",
lambda config_path, env_path: (fake_config, None, None, _FakeSupervisor()),
)
monkeypatch.setattr(dbus_agent.api, "create_app", lambda config, store, supervisor: object())
monkeypatch.setattr(uvicorn, "run", lambda app, host, port, log_level: None)
monkeypatch.setattr(sys, "argv", ["dbus-agent"])
try:
runpy.run_module("dbus_agent.main", run_name="__main__")
except SystemExit as exc:
assert exc.code == 0
else: # pragma: no cover - the guard should always exit
raise AssertionError("module entrypoint did not exit")

View File

@ -0,0 +1,138 @@
from __future__ import annotations
import asyncio
from datetime import datetime, timezone
from pathlib import Path
from dbus_agent import runtime
from dbus_agent.models import EventRecord, InterfaceState
class FakeStore:
def __init__(self, path: Path) -> None:
self.path = path
self.recorded: list[EventRecord] = []
self.touched: list[InterfaceState] = []
self.scan_results: list[dict[str, object]] | None = None
async def record_event(self, event: EventRecord) -> None:
self.recorded.append(event)
self.touched.append(
InterfaceState(
interface=event.interface,
status="active",
last_event_at=event.created_at,
last_heartbeat_at=None,
details_json=event.payload_json,
)
)
async def touch_interface(self, state: InterfaceState) -> None:
self.touched.append(state)
async def replace_scan_results(self, interface: str, results: list[dict[str, object]], refreshed_at=None) -> None: # type: ignore[no-untyped-def]
self.scan_results = results
class FakeClient:
def __init__(self, config) -> None: # type: ignore[no-untyped-def]
self.callbacks: list = []
self.scan_results_requested: list[str] = []
def add_callback(self, callback) -> None: # type: ignore[no-untyped-def]
self.callbacks.append(callback)
async def read_scan_results(self, interface: str) -> list[dict[str, object]]: # type: ignore[no-untyped-def]
self.scan_results_requested.append(interface)
return [{"path": "/fi/w1/wpa_supplicant1/Interfaces/0/BSSs/0", "properties": {"SSID": "example"}}]
def test_build_runtime_wires_ingest_callback(tmp_path: Path, monkeypatch) -> None:
config_path = tmp_path / "config.yaml"
config_path.write_text(
"""
interface: wlan0
database:
path: /tmp/dbus-agent.sqlite3
""".strip()
+ "\n",
encoding="utf-8",
)
env_path = tmp_path / ".env"
env_path.write_text("DBUS_AGENT_RECORD_TTL_SECONDS=7200\n", encoding="utf-8")
monkeypatch.setattr(runtime, "SqliteStore", FakeStore)
monkeypatch.setattr(runtime, "WpaSupplicantDbusClient", FakeClient)
config, store, client, supervisor = runtime.build_runtime(config_path, env_path)
assert len(client.callbacks) == 1
event = EventRecord(
interface="wlan0",
event_type="ScanDone",
payload_json='{"success": true}',
created_at=datetime(2026, 3, 31, 8, 0, tzinfo=timezone.utc),
)
asyncio.run(client.callbacks[0](event))
assert len(store.recorded) == 1
assert store.scan_results == [{"path": "/fi/w1/wpa_supplicant1/Interfaces/0/BSSs/0", "properties": {"SSID": "example"}}]
assert client.scan_results_requested == ["wlan0"]
assert supervisor.health.ingested_records == 1
assert config.retention.record_ttl_seconds == 7200.0
def test_build_runtime_filters_event_cache_but_keeps_scan_done_refresh(tmp_path: Path, monkeypatch) -> None:
config_path = tmp_path / "config.yaml"
config_path.write_text(
"""
interface: wlan0
database:
path: /tmp/dbus-agent.sqlite3
event_filter:
allowed_event_types:
- PropertiesChanged
""".strip()
+ "\n",
encoding="utf-8",
)
monkeypatch.setattr(runtime, "SqliteStore", FakeStore)
monkeypatch.setattr(runtime, "WpaSupplicantDbusClient", FakeClient)
config, store, client, supervisor = runtime.build_runtime(config_path)
assert len(client.callbacks) == 1
async def emit(event: EventRecord) -> None:
await client.callbacks[0](event)
asyncio.run(
emit(
EventRecord(
interface="wlan0",
event_type="PropertiesChanged",
payload_json='{"ssid":"example"}',
created_at=datetime(2026, 3, 31, 8, 0, tzinfo=timezone.utc),
)
)
)
asyncio.run(
emit(
EventRecord(
interface="wlan0",
event_type="ScanDone",
payload_json='{"success": true}',
created_at=datetime(2026, 3, 31, 8, 1, tzinfo=timezone.utc),
)
)
)
assert [event.event_type for event in store.recorded] == ["PropertiesChanged"]
assert client.scan_results_requested == ["wlan0"]
assert supervisor.health.ingested_records == 1
assert config.event_filter.allowed_event_types == ("PropertiesChanged",)
assert any(state.last_event_at == datetime(2026, 3, 31, 8, 1, tzinfo=timezone.utc) for state in store.touched)

View File

@ -0,0 +1,102 @@
from __future__ import annotations
import asyncio
from datetime import datetime, timezone
from pathlib import Path
from dbus_agent.models import EventRecord, InterfaceState
from dbus_agent.storage import SqliteStore
def test_sqlite_store_roundtrip(tmp_path: Path) -> None:
async def scenario() -> None:
store = SqliteStore(tmp_path / "db.sqlite3")
await store.open()
event = EventRecord(
interface="wlan0",
event_type="PropertiesChanged",
payload_json='{"state":"completed"}',
created_at=datetime(2026, 3, 31, 8, 0, tzinfo=timezone.utc),
)
await store.record_event(event)
await store.mark_heartbeat("wlan0", datetime(2026, 3, 31, 8, 1, tzinfo=timezone.utc))
state = await store.get_state("wlan0")
assert state is not None
assert state.interface == "wlan0"
assert state.status == "healthy"
assert state.last_event_at == datetime(2026, 3, 31, 8, 0, tzinfo=timezone.utc)
assert state.last_heartbeat_at == datetime(2026, 3, 31, 8, 1, tzinfo=timezone.utc)
events = await store.list_events("wlan0", limit=10)
assert len(events) == 1
assert events[0].event_type == "PropertiesChanged"
await store.replace_scan_results(
"wlan0",
[
{
"path": "/fi/w1/wpa_supplicant1/Interfaces/0/BSSs/0",
"properties": {"SSID": "example"},
}
],
datetime(2026, 3, 31, 8, 2, tzinfo=timezone.utc),
)
cached = await store.get_scan_results("wlan0")
assert cached is not None
assert cached["interface"] == "wlan0"
assert cached["refreshed_at"] == datetime(2026, 3, 31, 8, 2, tzinfo=timezone.utc)
assert cached["results"][0]["properties"]["SSID"] == "example"
await store.close()
asyncio.run(scenario())
def test_sqlite_store_purges_expired_events_without_touching_state(tmp_path: Path) -> None:
async def scenario() -> None:
store = SqliteStore(tmp_path / "db.sqlite3")
await store.open()
await store.touch_interface(
InterfaceState(
interface="wlan0",
status="healthy",
last_event_at=datetime(2026, 3, 31, 7, 0, tzinfo=timezone.utc),
last_heartbeat_at=datetime(2026, 3, 31, 7, 5, tzinfo=timezone.utc),
details_json='{"ssid":"example"}',
)
)
await store.record_event(
EventRecord(
interface="wlan0",
event_type="OldEvent",
payload_json='{"state":"old"}',
created_at=datetime(2026, 3, 31, 7, 10, tzinfo=timezone.utc),
)
)
await store.record_event(
EventRecord(
interface="wlan0",
event_type="FreshEvent",
payload_json='{"state":"new"}',
created_at=datetime(2026, 3, 31, 8, 10, tzinfo=timezone.utc),
)
)
expired = await store.purge_expired_events(datetime(2026, 3, 31, 7, 30, tzinfo=timezone.utc))
assert expired == 1
events = await store.list_events("wlan0", limit=10)
assert len(events) == 1
assert events[0].event_type == "FreshEvent"
state = await store.get_state("wlan0")
assert state is not None
assert state.status == "active"
assert state.last_heartbeat_at == datetime(2026, 3, 31, 7, 5, tzinfo=timezone.utc)
await store.close()
asyncio.run(scenario())

View File

@ -0,0 +1,94 @@
from __future__ import annotations
import asyncio
from datetime import datetime, timezone
from pathlib import Path
from dbus_agent.dbus_client import DbusConnectionSnapshot
from dbus_agent.models import AgentConfig, ApiSettings, DatabaseSettings, DbusSettings, HeartbeatSettings, RetentionSettings
from dbus_agent.supervisor import ConnectionSupervisor
class FakeClient:
def __init__(self) -> None:
self.snapshot = DbusConnectionSnapshot(connected=False, last_error="starting")
self.connect_calls = 0
self.ping_calls = 0
self.disconnect_calls = 0
self._failed_once = False
async def connect(self) -> None:
self.connect_calls += 1
self.snapshot = DbusConnectionSnapshot(connected=True, last_ping_at=datetime.now(timezone.utc))
async def ping(self) -> None:
self.ping_calls += 1
if not self._failed_once:
self._failed_once = True
self.snapshot = DbusConnectionSnapshot(connected=False, last_error="boom")
raise RuntimeError("boom")
self.snapshot = DbusConnectionSnapshot(connected=True, last_ping_at=datetime.now(timezone.utc))
async def disconnect(self) -> None:
self.disconnect_calls += 1
self.snapshot = DbusConnectionSnapshot(connected=False, last_error=self.snapshot.last_error)
class FakeStore:
def __init__(self) -> None:
self.calls = 0
async def purge_expired_events(self, expired_before: datetime) -> int:
self.calls += 1
return 2 if self.calls == 1 else 0
def test_supervisor_reconnects_after_failure() -> None:
async def scenario() -> None:
config = AgentConfig(
interface="wlan0",
dbus=DbusSettings(),
database=DatabaseSettings(path=Path("/tmp/dbus-agent.sqlite3")),
api=ApiSettings(),
heartbeat=HeartbeatSettings(
interval_seconds=0.01,
reconnect_initial_delay_seconds=0.01,
reconnect_max_delay_seconds=0.02,
),
retention=RetentionSettings(record_ttl_seconds=1.0),
)
client = FakeClient()
store = FakeStore()
supervisor = ConnectionSupervisor(config, client, store) # type: ignore[arg-type]
task = asyncio.create_task(supervisor.run())
await asyncio.sleep(0.15)
await supervisor.stop()
await asyncio.wait_for(task, timeout=1)
assert client.connect_calls >= 1
assert client.ping_calls >= 1
assert client.disconnect_calls >= 1
assert supervisor.health.process_up is True
assert supervisor.health.expired_records >= 2
assert store.calls >= 1
asyncio.run(scenario())
def test_supervisor_counters_are_retained_in_health_snapshot() -> None:
config = AgentConfig(
interface="wlan0",
dbus=DbusSettings(),
database=DatabaseSettings(path=Path("/tmp/dbus-agent.sqlite3")),
api=ApiSettings(),
heartbeat=HeartbeatSettings(),
retention=RetentionSettings(record_ttl_seconds=86400.0),
)
supervisor = ConnectionSupervisor(config, FakeClient(), FakeStore()) # type: ignore[arg-type]
supervisor.record_ingested(3)
supervisor.record_expired(2)
assert supervisor.health.ingested_records == 3
assert supervisor.health.expired_records == 2

View File

@ -0,0 +1,11 @@
from __future__ import annotations
from pathlib import Path
def test_systemd_unit_uses_absolute_python_entrypoint() -> None:
unit_path = Path("deploy/systemd/dbus-agent.service")
content = unit_path.read_text(encoding="utf-8")
assert "ExecStart=/opt/dbus-agent/.venv/bin/python -m dbus_agent.main" in content
assert "ExecStart=/usr/bin/env dbus-agent" not in content

View File

@ -0,0 +1,105 @@
# Journal Event Collector
## Summary
`journal-event-collector` is a Linux application that reads journal messages through configured ACL rules, turns matching messages into events, caches them with expiry, and exposes the shared core through a REST API and a CLI.
The project is built around one core layer with thin adapters for the daemon runtime, API, and CLI. Active events live in memory, while persisted snapshots are stored in SQLite so local and remote inspection can read the same state.
## Architecture
The application follows a `core + adapters` layout:
1. `ApplicationCore` manages lifecycle, cache, collector loop, cleanup, and persistence.
2. `JournalctlReader` reads JSON journal entries from `journalctl` and feeds them into the core.
3. `EventCache` stores active events in memory and removes expired entries.
4. `StateStore` persists snapshots in SQLite and migrates legacy JSON state to SQLite when needed.
5. REST API and CLI are thin adapters over the same core.
Data flow:
`journalctl -> journal reader -> event builder -> in-memory cache -> SQLite snapshot -> REST/CLI`
## Structure
```text
.
├── docs/
│ ├── deployment-guide.md
│ └── usage-guide.md
├── journal-event-collector/
│ └── example-config.toml
├── README.md
├── src/
│ └── journal_event_collector/
│ ├── api.py
│ ├── cache.py
│ ├── cli.py
│ ├── config.py
│ ├── journal.py
│ ├── models.py
│ ├── runtime.py
│ ├── service.py
│ └── state.py
├── systemd/
│ └── journal-event-collector.service
└── tests/
└── ...
```
## Components
### `config.py`
- Loads TOML configuration.
- Validates required fields.
- Validates ACL rules, cache timing, API settings, and SQLite state file path.
### `journal.py`
- Launches `journalctl`.
- Reads JSON journal records.
- Filters entries by configured message ACL rules.
- Builds domain events from journal entries.
### `models.py`
- Defines `JournalEvent` and `ServiceStatus`.
- Keeps the shared data shape used by API, CLI, and persistence.
### `cache.py`
- Stores active events in memory.
- Removes expired events by TTL.
- Produces snapshots for publication and persistence.
### `state.py`
- Writes persisted snapshots to SQLite.
- Reads persisted snapshots for CLI and REST.
- Migrates legacy JSON state files to SQLite.
### `service.py`
- Orchestrates collector, cleanup, and persistence.
- Exposes `status()`, `events()`, and `persisted_snapshot()`.
### `runtime.py`
- Starts the REST API with `uvicorn`.
- Binds daemon lifecycle to the core.
### `api.py`
- Exposes `/health`, `/status`, `/events`, and `/state`.
- Returns live status and persisted snapshot data.
### `cli.py`
- Provides `run`, `status`, `events`, and `state`.
- Can read local persisted state or query a remote REST API.
## Key Decisions
1. One core for all interfaces. This avoids logic drift between daemon, REST, and CLI.
2. In-memory cache for live data. This keeps event handling simple and fast.
3. SQLite for persisted snapshots. This lets API and CLI read the same state without an external service.
4. Legacy JSON migration to SQLite. Old files are converted in place on startup.
5. Explicit virtualenv execution for `systemd`. The unit points directly to `.venv/bin/journal-event-collector`.
6. `GET /state` returns persisted snapshot directly rather than a copy of live cache.
## References
- [Deployment Guide](./docs/deployment-guide.md)
- [Usage Guide](./docs/usage-guide.md)

View File

@ -0,0 +1,100 @@
# Deployment Guide
## Overview
This guide describes how to deploy `journal-event-collector` on Linux with Python virtualenv support and `systemd`.
The recommended layout is:
1. Application checkout: `/opt/journal-event-collector`
2. Virtual environment: `/opt/journal-event-collector/.venv`
3. Configuration file: `/etc/journal-event-collector/config.toml`
4. SQLite persisted state: `/var/lib/journal-event-collector/journal-event-collector.sqlite`
## Prerequisites
1. Linux host with `systemd`
2. Python 3.12 or newer
3. Access to `journalctl`
4. A user account with permission to read the journal and manage the service
## Install
1. Create the application directory and place the repository there.
2. Create a virtual environment in the repository root.
3. Install the project into the virtual environment.
```bash
cd /opt/journal-event-collector
python3.12 -m venv .venv
. .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -e .
```
## Configure
1. Create the service config directory.
2. Copy or adapt the example config from `journal-event-collector/example-config.toml`.
3. Set the message ACL, REST binding, journal command, and the SQLite state file.
Example:
```toml
message_acl = [
'cache process sshd regexp "^Accepted" send urgent mark scan123',
'drop process cron regexp ".*"',
]
[application]
event_ttl_seconds = 300
cleanup_interval_seconds = 30
log_level = "info"
[api]
host = "127.0.0.1"
port = 8000
[journal]
command = ["journalctl", "-f", "-o", "json"]
[storage]
state_file = "/var/lib/journal-event-collector/journal-event-collector.sqlite"
```
4. Ensure the state directory exists and is writable by the service account.
```bash
sudo mkdir -p /etc/journal-event-collector
sudo mkdir -p /var/lib/journal-event-collector
```
## Install systemd Unit
1. Copy the unit file into `/etc/systemd/system`.
2. Adjust `WorkingDirectory`, `VIRTUAL_ENV`, `PATH`, and `ExecStart` if your deployment path differs from `/opt/journal-event-collector`.
3. Reload `systemd` and enable the service.
```bash
sudo cp systemd/journal-event-collector.service /etc/systemd/system/journal-event-collector.service
sudo systemctl daemon-reload
sudo systemctl enable --now journal-event-collector
```
## Verify
1. Check service status.
2. Inspect logs if the service does not start.
3. Confirm the REST API is listening on the configured host and port.
```bash
systemctl status journal-event-collector
journalctl -u journal-event-collector -f
```
## Notes
1. The sample unit runs the application from `/opt/journal-event-collector/.venv/bin/journal-event-collector`.
2. `systemd` does not activate a Python virtualenv automatically, so the unit must point directly to the venv binary.
3. If a legacy JSON state file exists at the configured `state_file` path, the application migrates it in place to SQLite on startup.
4. If you run the service as a non-root user, make sure that user can read the journal and write the configured SQLite file.

View File

@ -0,0 +1,123 @@
# Usage Guide
## Overview
`journal-event-collector` runs as a daemon, exposes a REST API, and offers a CLI for local and remote inspection.
## CLI
The CLI is available through the installed entry point:
```bash
journal-event-collector --help
```
### Run the daemon
```bash
journal-event-collector run
```
This command starts the collector, cache cleaner, and REST API in one process.
By default it reads `/etc/journal-event-collector/config.toml`.
### Inspect live status
```bash
journal-event-collector status
```
### Inspect current cached events
```bash
journal-event-collector events
```
### Inspect persisted snapshot
```bash
journal-event-collector state
```
These commands read `/etc/journal-event-collector/config.toml` by default and derive the REST API base URL from the `[api]` section.
If `api.host = "0.0.0.0"`, the CLI uses `127.0.0.1` for local requests.
If the REST API is unavailable and `storage.state_file` is configured, the CLI falls back to the persisted SQLite snapshot or local core state.
### Query a remote API
```bash
journal-event-collector status --api-base-url http://127.0.0.1:8000
journal-event-collector events --api-base-url http://127.0.0.1:8000
journal-event-collector state --api-base-url http://127.0.0.1:8000
```
## REST API
The REST API is served by the daemon.
### Health
```bash
GET /health
```
Returns:
```json
{"status":"ok"}
```
or:
```json
{"status":"degraded"}
```
### Service status
```bash
GET /status
```
Returns the live daemon state, active message ACL, cache size, TTL, cleanup interval, and the last error if any.
### Cached events
```bash
GET /events
```
Returns the current in-memory cache contents that have not expired.
### Persisted snapshot
```bash
GET /state
```
Returns the persisted SQLite snapshot directly:
```json
{
"status": { "...": "..." },
"events": [ { "...": "..." } ],
"updated_at": "2026-01-01T00:00:00+00:00"
}
```
## Configuration Notes
1. `message_acl` controls which journal messages become events and how they are classified.
2. The config uses a single `message_acl` array of one-line ACL strings.
3. If `message_acl` is omitted or empty, the default policy is to drop all messages.
4. `cache = "drop"` suppresses event creation for matching messages.
5. `cache = "cache"` stores the event and records `send` and `mark` in the cached event metadata.
6. `event_ttl_seconds` controls how long events remain in cache and in the persisted snapshot.
7. `cleanup_interval_seconds` controls how often expired events are purged.
8. `storage.state_file` should point to the SQLite database used for persisted state.
## Common Issues
1. If `run` exits immediately, check the config file path and the `journalctl` command.
2. If `state` returns nothing locally, make sure `storage.state_file` is configured and writable.
3. If the service cannot start under `systemd`, confirm that the venv path in the unit file matches the deployment layout.

View File

@ -0,0 +1,19 @@
message_acl = [
'cache process sshd regexp "^Accepted" send urgent mark scan123',
'drop process cron regexp ".*"',
]
[application]
event_ttl_seconds = 300
cleanup_interval_seconds = 30
log_level = "info"
[api]
host = "127.0.0.1"
port = 8000
[journal]
command = ["journalctl", "-f", "-o", "json"]
[storage]
state_file = "./state/journal-event-collector.sqlite"

View File

@ -0,0 +1,87 @@
# Requirements Document
## Introduction
This feature defines a Linux daemon that evaluates configured ACL rules against journal messages, turns matching messages into application events, caches those events for a configurable retention period, and exposes the shared functionality through both a REST API and a CLI. The application is intended to run under `systemd` and uses a common application core for all interfaces.
## Requirements
### Requirement 1: Configure journal message ACLs
**User Story:** As an operator, I want to configure ACL rules for journal messages, so that the daemon collects only relevant journal messages.
#### Acceptance Criteria
1. WHEN the application starts with a valid configuration file or equivalent configuration source THEN the system SHALL load the configured ACL rules and journal settings before starting event collection.
2. IF the configuration is missing required values or contains invalid values THEN the system SHALL fail startup with a clear error that identifies the invalid setting.
3. WHEN the ACL rule list is updated and the application is restarted THEN the system SHALL use the updated configuration for subsequent journal collection.
4. WHERE configuration values affect both the REST API and CLI THEN the system SHALL resolve them through the same shared application core.
### Requirement 2: Run as a Linux daemon under systemd
**User Story:** As an operator, I want the application to run as a Linux daemon managed by `systemd`, so that it can start automatically and remain available continuously.
#### Acceptance Criteria
1. WHEN the service is started by `systemd` THEN the application SHALL run in a long-lived daemon mode suitable for process supervision.
2. WHEN the application exits normally or abnormally THEN the system SHALL provide a non-interactive exit status that `systemd` can use to determine service health.
3. WHEN the service is stopped THEN the application SHALL shut down gracefully and stop journal collection and cache activity in an orderly manner.
4. IF the runtime environment is not Linux or does not provide `systemd` integration support THEN the system SHALL report that the daemon deployment target is unsupported.
### Requirement 3: Collect matching journal messages as events
**User Story:** As a user, I want matching journal messages to be captured as application events, so that relevant process activity is available for later retrieval.
#### Acceptance Criteria
1. WHEN a journal message matches a configured ACL rule THEN the system SHALL create an event record from the message unless the rule is configured to drop it.
2. WHEN a journal message does not match any configured ACL rule THEN the system SHALL ignore the message for event creation.
3. WHEN an event is created THEN the system SHALL preserve at least the source process name, message payload, and capture timestamp.
4. WHILE journal collection is running THEN the system SHALL continue processing new messages without requiring manual restart after each event.
5. IF a journal entry cannot be parsed or read THEN the system SHALL log the failure and continue processing subsequent journal messages.
### Requirement 4: Cache collected events with configurable expiry
**User Story:** As a user, I want collected events to be cached and removed on a configurable schedule, so that stored data stays current and bounded.
#### Acceptance Criteria
1. WHEN an event is created THEN the system SHALL store it in the cache before making it available to API or CLI consumers.
2. WHEN an event reaches its configured expiration time THEN the system SHALL remove it from the cache.
3. IF the expiration schedule is configured THEN the system SHALL apply the configured retention and cleanup timing to cached events.
4. WHEN the cache cleanup process runs THEN the system SHALL not remove events that have not yet reached expiration.
5. IF cache storage is unavailable or fails THEN the system SHALL report an error and preserve the integrity of already cached events where possible.
### Requirement 5: Expose cached events through a REST API
**User Story:** As a consumer, I want to query cached events through a REST API, so that other systems can read collected journal data programmatically.
#### Acceptance Criteria
1. WHEN the REST API receives a request for cached events THEN the system SHALL return the currently retained events from the shared cache.
2. WHEN the REST API receives a request for application status THEN the system SHALL return the daemon and collection status from the shared application core.
3. WHEN the REST API receives a request with invalid parameters THEN the system SHALL respond with a client error that describes the validation problem.
4. WHEN cached events are expired or removed THEN the REST API SHALL no longer return those events in retrieval responses.
5. WHERE REST API behavior depends on event data or cache state THEN the system SHALL use the same core logic as the daemon and CLI interfaces.
### Requirement 6: Provide CLI access to shared application functions
**User Story:** As an operator, I want to use a CLI to access the same application functions, so that the system can be managed and inspected without the REST API.
#### Acceptance Criteria
1. WHEN the CLI invokes a supported command THEN the system SHALL perform the command by calling the shared application core.
2. WHEN the CLI receives invalid arguments or options THEN the system SHALL display a usage error and exit with a non-zero status.
3. WHEN the CLI requests event or status information THEN the system SHALL return the same underlying data that the REST API exposes.
4. WHERE the CLI and REST API share a function THEN the system SHALL implement the function once in the application core and reuse it from both interfaces.
### Requirement 7: Handle operational failures safely
**User Story:** As an operator, I want the application to handle runtime failures safely, so that transient issues do not corrupt event data or stop the daemon unnecessarily.
#### Acceptance Criteria
1. WHEN a transient journal access failure occurs THEN the system SHALL log the error and continue running if recovery is possible.
2. WHEN a fatal configuration or startup error occurs THEN the system SHALL stop startup and return a clear failure reason.
3. IF repeated collection or cache failures occur THEN the system SHALL surface the problem through logs and status responses.
4. WHEN the application encounters recoverable errors THEN the system SHALL continue serving unaffected API and CLI requests where possible.

View File

@ -0,0 +1,27 @@
[build-system]
requires = ["setuptools>=69", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "journal-event-collector"
version = "0.1.0"
description = "Linux journal event collector with REST API and CLI"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.115",
"typer>=0.12",
"uvicorn[standard]>=0.30",
]
[project.scripts]
journal-event-collector = "journal_event_collector.cli:app"
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]

View File

@ -0,0 +1,6 @@
"""Journal event collector application package."""
from .config import AppConfig, ConfigError
from .models import JournalEvent, MessageAclRule, ServiceStatus
__all__ = ["AppConfig", "ConfigError", "JournalEvent", "MessageAclRule", "ServiceStatus"]

View File

@ -0,0 +1,93 @@
from __future__ import annotations
from contextlib import asynccontextmanager
from datetime import datetime
from typing import Any, Iterable
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, ConfigDict, Field
from .models import JournalEvent
from .service import ApplicationCore
class EventResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: str
process_name: str
message: str
captured_at: datetime
payload: dict[str, Any]
acl: dict[str, Any] = Field(default_factory=dict)
class MessageAclRuleResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
process_name: str
message_regex: str
cache: str
send: str | None = None
mark: str | None = None
class StatusResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
running: bool
started_at: datetime | None
cached_events: int
event_ttl_seconds: int
cleanup_interval_seconds: int
last_error: str | None
message_acl: list[MessageAclRuleResponse]
class StateSnapshotResponse(BaseModel):
status: dict[str, Any]
events: list[EventResponse]
updated_at: str
def create_app(core: ApplicationCore, manage_lifecycle: bool = False) -> FastAPI:
@asynccontextmanager
async def lifespan(_: FastAPI):
if manage_lifecycle:
core.start()
try:
yield
finally:
if manage_lifecycle:
core.stop()
app = FastAPI(title="journal-event-collector", lifespan=lifespan if manage_lifecycle else None)
@app.get("/health")
def health() -> dict[str, str]:
return {"status": "ok" if core.last_error is None else "degraded"}
@app.get("/status", response_model=StatusResponse)
def status() -> StatusResponse:
return StatusResponse.model_validate(core.status().to_dict())
@app.get("/events", response_model=list[EventResponse])
def events() -> list[EventResponse]:
return [EventResponse.model_validate(event.to_dict()) for event in core.events()]
@app.get("/state", response_model=StateSnapshotResponse)
def state() -> StateSnapshotResponse:
snapshot = core.persisted_snapshot()
if snapshot is None:
raise HTTPException(status_code=404, detail="state snapshot is not available")
return StateSnapshotResponse(
status=snapshot.status,
events=[EventResponse.model_validate(event) for event in snapshot.events],
updated_at=snapshot.updated_at,
)
return app
def serialize_events(events: Iterable[JournalEvent]) -> list[dict[str, Any]]:
return [event.to_dict() for event in events]

View File

@ -0,0 +1,52 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from threading import RLock
from typing import Callable, Iterable
from .models import JournalEvent, utc_now
@dataclass(slots=True)
class CacheRecord:
event: JournalEvent
expires_at: datetime
class EventCache:
def __init__(self) -> None:
self._records: dict[str, CacheRecord] = {}
self._lock = RLock()
def put(
self,
event: JournalEvent,
ttl_seconds: int,
now: Callable[[], datetime] = utc_now,
) -> None:
expires_at = now() + timedelta(seconds=ttl_seconds)
with self._lock:
self._records[event.id] = CacheRecord(event=event, expires_at=expires_at)
def purge_expired(self, now: Callable[[], datetime] = utc_now) -> int:
current = now()
removed = 0
with self._lock:
expired_ids = [event_id for event_id, record in self._records.items() if record.expires_at <= current]
for event_id in expired_ids:
removed += 1
self._records.pop(event_id, None)
return removed
def list_events(self, now: Callable[[], datetime] = utc_now) -> list[JournalEvent]:
self.purge_expired(now=now)
with self._lock:
events = [record.event for record in self._records.values()]
return sorted(events, key=lambda event: event.captured_at, reverse=True)
def count(self, now: Callable[[], datetime] = utc_now) -> int:
return len(self.list_events(now=now))
def snapshot(self, now: Callable[[], datetime] = utc_now) -> list[dict]:
return [event.to_dict() for event in self.list_events(now=now)]

View File

@ -0,0 +1,185 @@
from __future__ import annotations
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import urlopen
import json
import typer
from .config import AppConfig, ConfigError
from .journal import NullJournalReader
from .runtime import ApplicationRuntime
from .service import ApplicationCore
from .state import StateStore
app = typer.Typer(help="Journal event collector")
DEFAULT_CONFIG_PATH = "/etc/journal-event-collector/config.toml"
def _load_config(config: Path) -> AppConfig:
try:
return AppConfig.from_file(config)
except (OSError, ConfigError) as exc:
raise typer.BadParameter(str(exc)) from exc
def _print_json(payload) -> None:
typer.echo(json.dumps(payload, ensure_ascii=False, indent=2, default=str))
def _fetch_json(url: str):
try:
with urlopen(url) as response:
return json.load(response)
except (HTTPError, URLError) as exc:
raise typer.Exit(code=2) from exc
def _fetch_command_payload(endpoint: str, api_base_url: str):
try:
return _fetch_json(f"{api_base_url.rstrip('/')}/{endpoint}")
except typer.Exit:
raise
def _print_local_state(settings: AppConfig, fallback: str) -> bool:
if settings.state_file is None:
return False
snapshot = StateStore(settings.state_file).read()
if snapshot is None:
return False
if fallback == "status":
_print_json(snapshot.status)
return True
if fallback == "events":
_print_json(snapshot.events)
return True
if fallback == "state":
_print_json(
{
"status": snapshot.status,
"events": snapshot.events,
"updated_at": snapshot.updated_at,
}
)
return True
return False
@app.command()
def run(
config: Path = typer.Option(
DEFAULT_CONFIG_PATH,
help="Path to the TOML config file",
show_default=DEFAULT_CONFIG_PATH,
)
) -> None:
"""Run the collector and REST API as a daemon."""
settings = _load_config(config)
runtime = ApplicationRuntime(settings)
raise typer.Exit(code=runtime.run())
@app.command()
def status(
config: Path = typer.Option(
DEFAULT_CONFIG_PATH,
help="Path to the TOML config file",
show_default=DEFAULT_CONFIG_PATH,
),
api_base_url: str | None = typer.Option(None, help="REST API base URL"),
) -> None:
"""Show the current service status."""
if api_base_url:
payload = _fetch_command_payload("status", api_base_url)
_print_json(payload)
return
settings = _load_config(config)
try:
payload = _fetch_command_payload("status", settings.api_base_url())
except typer.Exit:
payload = None
if payload is not None:
_print_json(payload)
return
if _print_local_state(settings, "status"):
return
core = ApplicationCore(settings, reader=NullJournalReader())
_print_json(core.status().to_dict())
@app.command()
def events(
config: Path = typer.Option(
DEFAULT_CONFIG_PATH,
help="Path to the TOML config file",
show_default=DEFAULT_CONFIG_PATH,
),
api_base_url: str | None = typer.Option(None, help="REST API base URL"),
) -> None:
"""Show collected events."""
if api_base_url:
payload = _fetch_command_payload("events", api_base_url)
_print_json(payload)
return
settings = _load_config(config)
try:
payload = _fetch_command_payload("events", settings.api_base_url())
except typer.Exit:
payload = None
if payload is not None:
_print_json(payload)
return
if _print_local_state(settings, "events"):
return
core = ApplicationCore(settings, reader=NullJournalReader())
_print_json(core.cache.snapshot())
@app.command()
def state(
config: Path = typer.Option(
DEFAULT_CONFIG_PATH,
help="Path to the TOML config file",
show_default=DEFAULT_CONFIG_PATH,
),
api_base_url: str | None = typer.Option(None, help="REST API base URL"),
) -> None:
"""Show the persisted snapshot."""
if api_base_url:
payload = _fetch_command_payload("state", api_base_url)
_print_json(payload)
return
settings = _load_config(config)
try:
payload = _fetch_command_payload("state", settings.api_base_url())
except typer.Exit:
payload = None
if payload is not None:
_print_json(payload)
return
if _print_local_state(settings, "state"):
return
core = ApplicationCore(settings, reader=NullJournalReader())
snapshot = core.persisted_snapshot()
if snapshot is None:
raise typer.Exit(code=1)
_print_json(
{
"status": snapshot.status,
"events": snapshot.events,
"updated_at": snapshot.updated_at,
}
)

View File

@ -0,0 +1,302 @@
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
import re
import shlex
from typing import Any, Mapping
import tomllib
from .models import MessageAclRule
class ConfigError(ValueError):
"""Raised when the application configuration is invalid."""
def _require_positive_int(value: Any, field_name: str) -> int:
try:
parsed = int(value)
except (TypeError, ValueError) as exc:
raise ConfigError(f"{field_name} must be a positive integer") from exc
if parsed <= 0:
raise ConfigError(f"{field_name} must be a positive integer")
return parsed
def _default_message_acl() -> list[MessageAclRule]:
return [MessageAclRule(process_name="*", message_regex=".*", cache_policy="drop")]
def _require_message_acl(value: Any) -> list[MessageAclRule]:
if value is None:
return _default_message_acl()
if isinstance(value, list):
rules_value = value
if not rules_value:
return _default_message_acl()
elif isinstance(value, Mapping):
rules_value = value.get("rules")
if rules_value is None:
return _default_message_acl()
if not isinstance(rules_value, list):
raise ConfigError("message_acl must be a list of ACL rule strings")
if not rules_value:
return _default_message_acl()
else:
raise ConfigError("message_acl must be a list of ACL rule strings")
rules: list[MessageAclRule] = []
for index, item in enumerate(rules_value):
rules.append(_parse_message_acl_rule(item, index))
return rules
def _parse_message_acl_rule(value: Any, index: int) -> MessageAclRule:
if not isinstance(value, str) or not value.strip():
raise ConfigError(f"message_acl[{index}] must be a non-empty string")
raw_rule = value.strip()
try:
tokens = shlex.split(raw_rule)
except ValueError as exc:
raise ConfigError(f"message_acl[{index}] is invalid: {exc}") from exc
if not tokens:
raise ConfigError(f"message_acl[{index}] must not be empty")
if "=" in tokens[0]:
return _parse_message_acl_key_value_rule(tokens, index)
return _parse_message_acl_positional_rule(tokens, index)
def _parse_message_acl_key_value_rule(tokens: list[str], index: int) -> MessageAclRule:
fields: dict[str, str] = {}
for token in tokens:
if "=" not in token:
raise ConfigError(
f"message_acl[{index}] must use either key=value syntax or the compact DSL"
)
key, value = token.split("=", 1)
key = key.strip().casefold()
value = value.strip()
if not key:
raise ConfigError(f"message_acl[{index}] contains an empty field name")
if not value:
raise ConfigError(f"message_acl[{index}].{key} must be a non-empty string")
if key in fields:
raise ConfigError(f"message_acl[{index}] contains duplicate field {key}")
fields[key] = value
process_name = fields.get("process_name") or fields.get("process")
message_regex = fields.get("message_regex") or fields.get("regexp")
cache_policy = fields.get("cache")
send_policy = fields.get("send")
mark = fields.get("mark")
return _build_message_acl_rule(process_name, message_regex, cache_policy, send_policy, mark, index)
def _parse_message_acl_positional_rule(tokens: list[str], index: int) -> MessageAclRule:
if len(tokens) < 4:
raise ConfigError(
f"message_acl[{index}] must look like: cache process <name> regexp <pattern> [send <urgent|queue> mark <mark>]"
)
cache_policy = tokens[0].strip().casefold()
if cache_policy not in {"cache", "drop"}:
raise ConfigError(f"message_acl[{index}] must start with 'cache' or 'drop'")
position = 1
process_name: str | None = None
message_regex: str | None = None
send_policy: str | None = None
mark: str | None = None
while position < len(tokens):
key = tokens[position].strip().casefold()
if key in {"process", "process_name"}:
position += 1
if position >= len(tokens):
raise ConfigError(f"message_acl[{index}].process is missing a value")
if process_name is not None:
raise ConfigError(f"message_acl[{index}] contains duplicate process field")
process_name = tokens[position]
elif key in {"regexp", "message_regex"}:
position += 1
if position >= len(tokens):
raise ConfigError(f"message_acl[{index}].regexp is missing a value")
if message_regex is not None:
raise ConfigError(f"message_acl[{index}] contains duplicate regexp field")
message_regex = tokens[position]
elif key == "send":
position += 1
if position >= len(tokens):
raise ConfigError(f"message_acl[{index}].send is missing a value")
if send_policy is not None:
raise ConfigError(f"message_acl[{index}] contains duplicate send field")
send_policy = tokens[position]
elif key == "mark":
position += 1
if position >= len(tokens):
raise ConfigError(f"message_acl[{index}].mark is missing a value")
if mark is not None:
raise ConfigError(f"message_acl[{index}] contains duplicate mark field")
mark = tokens[position]
else:
raise ConfigError(f"message_acl[{index}] contains unsupported token: {tokens[position]}")
position += 1
if cache_policy == "drop" and (send_policy is not None or mark is not None):
raise ConfigError(f"message_acl[{index}] must not define send or mark when cache='drop'")
return _build_message_acl_rule(process_name, message_regex, cache_policy, send_policy, mark, index)
def _build_message_acl_rule(
process_name: str | None,
message_regex: str | None,
cache_policy: str | None,
send_policy: str | None,
mark: str | None,
index: int,
) -> MessageAclRule:
if not isinstance(process_name, str) or not process_name.strip():
raise ConfigError(f"message_acl[{index}].process_name must be a non-empty string")
if not isinstance(message_regex, str) or not message_regex.strip():
raise ConfigError(f"message_acl[{index}].message_regex must be a non-empty string")
if not isinstance(cache_policy, str) or not cache_policy.strip():
raise ConfigError(f"message_acl[{index}].cache must be a non-empty string")
cache_value = cache_policy.strip().casefold()
if cache_value not in {"cache", "drop"}:
raise ConfigError(f"message_acl[{index}].cache must be either 'cache' or 'drop'")
try:
if cache_value == "drop":
if send_policy is not None:
raise ConfigError(f"message_acl[{index}].send is not allowed when cache='drop'")
if mark is not None:
raise ConfigError(f"message_acl[{index}].mark is not allowed when cache='drop'")
return MessageAclRule(
process_name=process_name.strip(),
message_regex=message_regex.strip(),
cache_policy=cache_value,
)
if not isinstance(send_policy, str) or not send_policy.strip():
raise ConfigError(
f"message_acl[{index}].send must be a non-empty string when cache='cache'"
)
if not isinstance(mark, str) or not mark.strip():
raise ConfigError(
f"message_acl[{index}].mark must be a non-empty string when cache='cache'"
)
return MessageAclRule(
process_name=process_name.strip(),
message_regex=message_regex.strip(),
cache_policy=cache_value,
send_policy=send_policy.strip(),
mark=mark.strip(),
)
except re.error as exc:
raise ConfigError(
f"message_acl[{index}].message_regex must be a valid regular expression"
) from exc
except ValueError as exc:
message = str(exc)
if "mark must contain only ASCII letters, digits, underscore, and hyphen" in message:
raise ConfigError(f"message_acl[{index}].mark must match ^[A-Za-z0-9_-]+$") from exc
if "send must be either 'urgent' or 'queue'" in message:
raise ConfigError(f"message_acl[{index}].send must be either 'urgent' or 'queue'") from exc
raise ConfigError(f"message_acl[{index}] is invalid: {exc}") from exc
@dataclass(slots=True)
class AppConfig:
message_acl: list[MessageAclRule] = field(default_factory=list)
event_ttl_seconds: int = 300
cleanup_interval_seconds: int = 60
api_host: str = "127.0.0.1"
api_port: int = 8000
journal_command: list[str] = field(default_factory=lambda: ["journalctl", "-f", "-o", "json"])
log_level: str = "info"
state_file: Path | None = None
def api_base_url(self) -> str:
host = "127.0.0.1" if self.api_host == "0.0.0.0" else self.api_host
if ":" in host and not host.startswith("["):
host = f"[{host}]"
return f"http://{host}:{self.api_port}"
@classmethod
def from_mapping(cls, raw: Mapping[str, Any], *, base_path: Path | None = None) -> "AppConfig":
app_section = raw.get("application", raw)
api_section = raw.get("api", {})
journal_section = raw.get("journal", {})
storage_section = raw.get("storage", {})
message_acl_raw = raw.get("message_acl")
if not isinstance(app_section, Mapping):
raise ConfigError("application section must be a mapping")
if not isinstance(api_section, Mapping):
raise ConfigError("api section must be a mapping")
if not isinstance(journal_section, Mapping):
raise ConfigError("journal section must be a mapping")
if storage_section and not isinstance(storage_section, Mapping):
raise ConfigError("storage section must be a mapping")
if "monitored_process_names" in app_section:
raise ConfigError("monitored_process_names is no longer supported; use message_acl")
event_ttl_seconds = _require_positive_int(
app_section.get("event_ttl_seconds", 300), "event_ttl_seconds"
)
cleanup_interval_seconds = _require_positive_int(
app_section.get("cleanup_interval_seconds", 60), "cleanup_interval_seconds"
)
api_host = str(api_section.get("host", "127.0.0.1")).strip() or "127.0.0.1"
api_port = _require_positive_int(api_section.get("port", 8000), "api.port")
if not 1 <= api_port <= 65535:
raise ConfigError("api.port must be between 1 and 65535")
journal_command_value = journal_section.get("command", ["journalctl", "-f", "-o", "json"])
if not isinstance(journal_command_value, list) or not journal_command_value:
raise ConfigError("journal.command must be a non-empty list")
journal_command: list[str] = []
for item in journal_command_value:
if not isinstance(item, str) or not item.strip():
raise ConfigError("journal.command must contain only non-empty strings")
journal_command.append(item.strip())
log_level = str(app_section.get("log_level", "info")).strip() or "info"
state_file_value = storage_section.get("state_file") if isinstance(storage_section, Mapping) else None
state_file: Path | None = None
if state_file_value is not None:
if not isinstance(state_file_value, str) or not state_file_value.strip():
raise ConfigError("storage.state_file must be a non-empty string")
state_file = Path(state_file_value.strip())
if not state_file.is_absolute() and base_path is not None:
state_file = (base_path / state_file).resolve()
message_acl = _require_message_acl(message_acl_raw)
return cls(
message_acl=message_acl,
event_ttl_seconds=event_ttl_seconds,
cleanup_interval_seconds=cleanup_interval_seconds,
api_host=api_host,
api_port=api_port,
journal_command=journal_command,
log_level=log_level,
state_file=state_file,
)
@classmethod
def from_file(cls, path: str | Path) -> "AppConfig":
config_path = Path(path)
with config_path.open("rb") as handle:
raw = tomllib.load(handle)
if not isinstance(raw, Mapping):
raise ConfigError("configuration file must contain a mapping")
return cls.from_mapping(raw, base_path=config_path.parent)

View File

@ -0,0 +1,150 @@
from __future__ import annotations
from collections.abc import Iterable, Iterator, Mapping
from dataclasses import dataclass
from datetime import datetime, timezone
import json
import logging
import selectors
import subprocess
import sys
import threading
from typing import Any, Protocol
from .models import JournalEvent, MessageAclRule
class JournalReader(Protocol):
def stream(self, stop_event: threading.Event) -> Iterator[Mapping[str, Any]]:
...
class NullJournalReader:
def stream(self, stop_event: threading.Event) -> Iterator[Mapping[str, Any]]:
while not stop_event.is_set():
stop_event.wait(0.5)
if stop_event.is_set():
break
yield from ()
@dataclass(slots=True)
class JournalctlReader:
command: list[str]
logger: logging.Logger | None = None
def stream(self, stop_event: threading.Event) -> Iterator[Mapping[str, Any]]:
if sys.platform != "linux":
raise RuntimeError("journal daemon mode is only supported on Linux")
log = self.logger or logging.getLogger(__name__)
try:
process = subprocess.Popen(
self.command,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
bufsize=1,
)
except FileNotFoundError as exc:
raise RuntimeError("journalctl command was not found") from exc
if process.stdout is None:
raise RuntimeError("journalctl did not provide stdout")
selector = selectors.DefaultSelector()
selector.register(process.stdout, selectors.EVENT_READ)
try:
while not stop_event.is_set():
ready = selector.select(timeout=0.5)
if not ready:
if process.poll() is not None:
break
continue
line = process.stdout.readline()
if line == "":
if process.poll() is not None:
break
continue
line = line.strip()
if not line:
continue
try:
entry = json.loads(line)
except json.JSONDecodeError as exc:
log.warning("Skipping unparsable journal entry: %s", exc)
continue
if isinstance(entry, Mapping):
yield entry
finally:
selector.close()
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
process.kill()
def extract_process_name(entry: Mapping[str, Any]) -> str | None:
for key in ("_COMM", "COMM", "SYSLOG_IDENTIFIER", "process_name", "process", "name"):
value = entry.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return None
def extract_message(entry: Mapping[str, Any]) -> str:
value = entry.get("MESSAGE")
if value is None:
value = entry.get("message")
if value is None:
return ""
if isinstance(value, str):
return value
return str(value)
def extract_timestamp(entry: Mapping[str, Any]) -> datetime:
raw_value = entry.get("__REALTIME_TIMESTAMP")
if raw_value is None:
raw_value = entry.get("timestamp")
if isinstance(raw_value, datetime):
return raw_value if raw_value.tzinfo else raw_value.replace(tzinfo=timezone.utc)
if isinstance(raw_value, (int, float)):
seconds = float(raw_value)
if seconds > 1_000_000_000_000:
seconds = seconds / 1_000_000
return datetime.fromtimestamp(seconds, tz=timezone.utc)
if isinstance(raw_value, str) and raw_value.strip():
text = raw_value.strip().replace("Z", "+00:00")
try:
parsed = datetime.fromisoformat(text)
except ValueError:
return datetime.now(timezone.utc)
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
return datetime.now(timezone.utc)
def build_event(
entry: Mapping[str, Any],
message_acl: Iterable[MessageAclRule],
) -> JournalEvent | None:
process_name = extract_process_name(entry)
if process_name is None:
return None
message = extract_message(entry)
for rule in message_acl:
if not rule.matches(process_name, message):
continue
if rule.cache_policy == "drop":
return None
return JournalEvent.create(
process_name=process_name,
message=message,
captured_at=extract_timestamp(entry),
payload=entry,
acl=rule.to_dict(),
)
return None

View File

@ -0,0 +1,120 @@
from __future__ import annotations
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from typing import Any, Mapping
import re
import uuid
def utc_now() -> datetime:
return datetime.now(timezone.utc)
_MARK_PATTERN = re.compile(r"^[A-Za-z0-9_-]+$")
@dataclass(slots=True)
class MessageAclRule:
process_name: str
message_regex: str
cache_policy: str
send_policy: str | None = None
mark: str | None = None
_pattern: re.Pattern[str] = field(init=False, repr=False, compare=False)
def __post_init__(self) -> None:
self.process_name = self.process_name.strip()
self.message_regex = self.message_regex.strip()
self.cache_policy = self.cache_policy.strip().casefold()
if self.send_policy is not None:
self.send_policy = self.send_policy.strip().casefold()
if self.mark is not None:
self.mark = self.mark.strip()
if not self.process_name:
raise ValueError("process_name must be a non-empty string")
if not self.message_regex:
raise ValueError("message_regex must be a non-empty string")
if self.cache_policy not in {"cache", "drop"}:
raise ValueError("cache must be either 'cache' or 'drop'")
if self.send_policy is not None and self.send_policy not in {"urgent", "queue"}:
raise ValueError("send must be either 'urgent' or 'queue'")
if self.mark is not None and not _MARK_PATTERN.fullmatch(self.mark):
raise ValueError("mark must contain only ASCII letters, digits, underscore, and hyphen")
if self.cache_policy == "drop":
if self.send_policy is not None or self.mark is not None:
raise ValueError("drop rules must not define send or mark")
else:
if self.send_policy is None or self.mark is None:
raise ValueError("cache rules must define send and mark")
self._pattern = re.compile(self.message_regex)
def matches(self, process_name: str, message: str) -> bool:
process_matches = self.process_name == "*" or self.process_name.casefold() == process_name.casefold()
return process_matches and self._pattern.search(message) is not None
def to_dict(self) -> dict[str, Any]:
return {
"process_name": self.process_name,
"message_regex": self.message_regex,
"cache": self.cache_policy,
"send": self.send_policy,
"mark": self.mark,
}
@dataclass(slots=True)
class JournalEvent:
id: str
process_name: str
message: str
captured_at: datetime
payload: dict[str, Any] = field(default_factory=dict)
acl: dict[str, Any] = field(default_factory=dict)
@classmethod
def create(
cls,
process_name: str,
message: str,
captured_at: datetime | None = None,
payload: Mapping[str, Any] | None = None,
acl: Mapping[str, Any] | None = None,
) -> "JournalEvent":
return cls(
id=str(uuid.uuid4()),
process_name=process_name,
message=message,
captured_at=captured_at or utc_now(),
payload=dict(payload or {}),
acl=dict(acl or {}),
)
def to_dict(self) -> dict[str, Any]:
data = asdict(self)
data["captured_at"] = self.captured_at.isoformat()
return data
@dataclass(slots=True)
class ServiceStatus:
running: bool
started_at: datetime | None
cached_events: int
event_ttl_seconds: int
cleanup_interval_seconds: int
last_error: str | None = None
message_acl: list[MessageAclRule] = field(default_factory=list)
def to_dict(self) -> dict[str, Any]:
return {
"running": self.running,
"started_at": self.started_at.isoformat() if self.started_at else None,
"cached_events": self.cached_events,
"event_ttl_seconds": self.event_ttl_seconds,
"cleanup_interval_seconds": self.cleanup_interval_seconds,
"last_error": self.last_error,
"message_acl": [rule.to_dict() for rule in self.message_acl],
}

View File

@ -0,0 +1,30 @@
from __future__ import annotations
import logging
import uvicorn
from .api import create_app
from .config import AppConfig
from .journal import JournalctlReader
from .service import ApplicationCore
class ApplicationRuntime:
def __init__(self, config: AppConfig, reader=None) -> None:
self.config = config
self.logger = logging.getLogger(__name__)
self.core = ApplicationCore(config, reader=reader or JournalctlReader(config.journal_command, logger=self.logger), logger=self.logger)
def run(self) -> int:
self.core.start()
try:
uvicorn.run(
create_app(self.core, manage_lifecycle=False),
host=self.config.api_host,
port=self.config.api_port,
log_level=self.config.log_level.lower(),
)
finally:
self.core.stop()
return 1 if self.core.last_error else 0

Some files were not shown because too many files have changed in this diff Show More