From a18b38b7a0e58e5e2d7a892ba7a3acd03873e984 Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 15:42:54 +0100 Subject: [PATCH 01/20] docs: design the remote settings and control API Describe the API contract, cross-process config ownership, restart orchestration, and key migration; record ADR 0002 and add glossary terms for Settings, Revision, Scope, API key, and Restart. --- GLOSSARY.md | 20 + .../0002-remote-settings-and-control-api.md | 71 ++ docs/remote-api.md | 663 ++++++++++++++++++ 3 files changed, 754 insertions(+) create mode 100644 docs/adr/0002-remote-settings-and-control-api.md create mode 100644 docs/remote-api.md diff --git a/GLOSSARY.md b/GLOSSARY.md index 593070c..5914c42 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -23,3 +23,23 @@ _Avoid_: retry, send, try **Outbox**: The persisted queue of Webhooks that are waiting to be delivered. _Avoid_: queue, buffer, backlog + +**Settings**: +The operator-chosen configuration that OpenSMS keeps across restarts: the API port, whether the server starts at launch, and the Webhook configuration. +_Avoid_: config, preferences, options + +**Revision**: +The identifier of one persisted version of Settings. A write that expects an older Revision than the stored one is refused. +_Avoid_: version, generation, counter + +**Scope**: +A permission attached to an API key that allows a class of operations, such as sending SMS or changing Settings. +_Avoid_: role, permission level, grant + +**API key**: +The secret credential an external client presents to call the OpenSMS API. +_Avoid_: token, password, secret + +**Restart**: +Replacing the running API server with a new one that uses the current Settings, notably the port. +_Avoid_: reload, reboot, bounce diff --git a/docs/adr/0002-remote-settings-and-control-api.md b/docs/adr/0002-remote-settings-and-control-api.md new file mode 100644 index 0000000..274aac9 --- /dev/null +++ b/docs/adr/0002-remote-settings-and-control-api.md @@ -0,0 +1,71 @@ +# Remote settings and control are served by the existing API server over a revisioned config file and a control file + +The SMS proxy needs to configure and operate OpenSMS entirely over the LAN, while +the KivyMD UI and the Android foreground service remain separate processes that +both write the same persisted settings. The API server already runs inside the +service, so the endpoints belong there; the hard part is ownership, not HTTP. +See `docs/remote-api.md` for the contract. + +**Status**: accepted + +## Considered options + +- **A second FastAPI app or process for remote control**: rejected. It would + duplicate auth, hold a second listener, and add a lifecycle to an already + sticky Android service with no benefit. +- **Writing settings directly from the service, bypassing `config.json`**: rejected. + The UI reads the same file, the webhook worker hot-reloads it per delivery, and + the port must have one owner. `config.json` stays the single source of truth; + `request.json` carries intents only. +- **PATCH / partial-merge semantics**: rejected. Partial merges make "clear the + secret", "leave it alone", and "the field was absent" indistinguishable against + a UI that also holds a stale object. The API replaces the writable subset in + full and uses an explicit empty-string sentinel to clear the secret. +- **Revision as a monotonic counter only**: rejected. A counter that no request + checks protects nothing. `PUT` accepts an optional `revision` and refuses a + stale one, so a client that cares gets optimistic concurrency without forcing + it on hand-written calls. +- **Auto-restart when the port changes**: rejected. Restarts must be observable and + debounced; `PUT` reports `restart_required`, and `POST /api/server/restart` + performs the restart through the control file so a handler never stops its own + uvicorn instance. +- **Keeping the single key and a single scope**: rejected. Named keys with scopes + let the proxy hold its own credential and let the phone rotate its own without + revoking remote access. +- **Enforcing scopes on v1 keys as stored**: rejected. v1 entries say + `["sms:write"]` but scopes were never read, so every existing install would be + locked out of the new API. Migration grants both scopes once; v2 keys honour + whatever they are created with. +- **Adding an OS file lock or a new dependency**: rejected. The residual + cross-process race window is small, documented, and cheaper to accept than to + make buildozer ship another native dependency. +- **Unauthenticated `/api/health`**: rejected. It would reveal the device to any + host on the LAN; the proxy already holds a key. +- **CORS or a web UI**: rejected. Server-to-server only. + +## Consequences + +- Two processes write `config.json`. Writes are atomic and revision-bumped, but + there is no cross-process lock; the UI must re-read on entry and merge on save, + and a tiny last-writer-wins window remains. +- `PUT /api/settings` is a replace of the writable subset, not a patch. Adding a + writable field later is a breaking change for clients that do not send it. +- The webhook secret is write-only over the API; a client must GET, edit, and + re-PUT without the secret field to preserve it. +- Port changes are two-step by design: save, then restart. A restart is a + separate observable action, and `restart_required` tells the client when one is + pending. +- The v1 → v2 key migration escalates every legacy key to `settings:write`. This + is deliberate and one-time; replacing it with "honour stored scopes" would strand + every existing install. +- Disabling the webhook still discards new Inbound SMS (the inbound spool is + acknowledged even when forwarding is skipped). The API cannot fix that without + an inbox-retention design, so status must warn instead of implying safety. +- Webhook retry policy becomes live configuration. The dispatcher already reloads + `enabled`/`url`/`secret` per attempt; it now reloads `timeout`/`max_attempts`/ + `backoff` and capacity too, with today's constants as defaults. +- Tests need a config-dir seam, because both `postApi` and `appSvc` freeze the + app-private path at import. `httpx` becomes a dev-only dependency. A CI job is + required to run the suite; no workflow runs it today. +- The API ships untrusted-network-unsafe by design: bearer tokens over HTTP, no + TLS, no CORS. Deployments must stay on the LAN or a VPN/tunnel. diff --git a/docs/remote-api.md b/docs/remote-api.md new file mode 100644 index 0000000..10bd125 --- /dev/null +++ b/docs/remote-api.md @@ -0,0 +1,663 @@ +# Remote Settings & Control API + +**Status:** agreed design, not implemented. +**Supersedes:** the handoff brief of 2026-11-26. +**Baseline:** `develop` at `f3c7ba1`, app version `1.1.0`. +**Target:** ship as `1.2.0`; PRs go to `develop` (see `CONTRIBUTE.md`). + +This document is the implementation description. It replaces the pasted handoff +brief, corrects three claims in it that do not match the code, and settles the +questions the brief left open. + +--- + +## 1. Mission + +An SMS proxy server on the LAN owns blocking and forwarding rules and needs to +operate the phone without anyone touching it. Today OpenSMS exposes +`POST /sms/` and forwards inbound SMS to a webhook, but every setting lives +behind the KivyMD Settings screen. + +Deliver a bearer-authenticated JSON API, served by the FastAPI app that already +runs inside the Android foreground service, that lets the proxy: + +- read and write the writable settings (port, launch behaviour, webhook target, + secret, retry policy); +- read health and status; +- test the webhook; +- restart the API server after a port change; +- manage named API keys with scopes. + +No web UI. No new runtime dependencies. No unauthenticated routes. + +--- + +## 2. What the code actually does + +Verified against this checkout. The brief's line references are accurate to +±2. Three of its claims are wrong and shape the design: + +1. **The inbound spool is not deleted unconditionally.** In + `app/services/appSvc.py:196-218`, a claimed message is acknowledged when + `enqueue()` returns `True` **or `False`** (webhook disabled or target + invalid), and deliberately kept as `.processing` when `enqueue()` raises. + Data loss therefore happens when forwarding is **disabled**, not when it + fails. The at-least-once guarantee from + `docs/adr/0001-inbound-sms-webhook.md` must be preserved. +2. **`keys.json` v1 entries already carry `scopes`** (`["sms:write"]`), but + nothing ever reads them (`app/services/postApi.py:220-243`). Adding + enforcement is a new capability. "Migrate to both scopes" is therefore a + one-time privilege escalation, not a repair. +3. **`config_dir` is computed at import time** in `postApi.py:50` and + `appSvc.py:76`. A test seam must redirect the module globals; adding a setter + that nothing consumes is not enough. + +Other facts that constrain the work: + +| Area | Reality | +|---|---| +| Processes | Kivy UI and the `opensmssvc` foreground service are separate. The API server runs in the service. | +| `config.json` | Whole-object writes from the UI (`main.py:353-366`), atomic, no revision, no lock. Webhook config is re-read per delivery attempt (`webhookSvc.py:50-57`). | +| `request.json` | UI→service command channel polled every 0.2 s (`appSvc.py:233-260`); written non-atomically (`main.py:368-370`). | +| Restart | No restart path exists. `api_server_control` handles only `start`/`stop` (`appSvc.py:156-170`), and `start` uses `req_data["port"]`. | +| Keys | One key. `generate_new_api_key()` overwrites `keys.json` (`postApi.py:92-109`). Raw format `osms_`. | +| Outbox | Capacity drop-oldest at enqueue; `max_attempts` then drop (`webhookSvc.py:318-339`, `386-415`). Retry knobs are constructor-fixed; only `enabled`/`url`/`secret` hot-reload per attempt. | +| Version | Single source `app/services/config.py:3`; buildozer and CI derive from it. | +| Tests | One `unittest` file (`test_webhook.py`, local `ThreadingHTTPServer`). `httpx` is absent everywhere. No workflow runs tests; CI is build-and-release on `main` only. | +| Desktop imports | `postApi` imports `serial`/`psutil` but opens no port; no Kivy import. Importing it in desktop tests is safe. | +| Port rule | UI label says 1025–65535, code only checks `>= 1025` (`main.py:636-640`). | + +--- + +## 3. Scope + +### In scope + +1. JSON endpoints for all persistent settings that make sense remotely. +2. Operational endpoints: health, status, webhook test, server restart. +3. Named API keys with scopes; v1 read compatibility; no hash or secret leakage. +4. Cross-process config safety: atomic writes, revision counter, UI merge-on-save. +5. Live-configurable webhook retry policy and outbox capacity. +6. Tests (`unittest`), CI job, README/docs, one ADR, glossary terms. + +### Out of scope + +- Any HTML/CSS/JS UI, cookies, sessions, CORS, TLS. +- Blocking/forwarding rules, message history, delivery receipts, SIM selection. +- Persisting inbound SMS beyond the existing spool/outbox. +- Remote Android permission grants or app relaunch. +- Desktop serial settings in the remote API. +- Changing the key hashing algorithm (stay SHA-256). +- `/api/logs` — specified in Appendix A, deferred to a later change. + +--- + +## 4. Decisions + +| # | Decision | Why | +|---|---|---| +| D1 | Reuse the existing module-level FastAPI app in `postApi.py`. No second server, no static assets, no `buildozer.spec` changes. | The service already runs it; a second listener adds a lifecycle problem with no benefit. | +| D2 | Keep `HTTPBearer`. Add `require_scope(...)`: `/sms/` needs `sms:write`, every `/api/*` route needs `settings:write`. | Scopes already exist in the data model; enforcing them is cheap and makes limited keys possible. | +| D3 | `PUT /api/settings` replaces the **writable subset** in full. Unknown fields are rejected. Internal fields (`app`, `permissions`) and unknown disk fields are preserved. | Full replace avoids ambiguous patch semantics; preserving internal fields keeps the UI's config intact. | +| D4 | Every write bumps `revision`. `PUT` accepts an **optional** top-level `revision`; if present and stale, return `409`. | Two remote writers otherwise last-writer-wins. Optional keeps hand-written clients simple. | +| D5 | Restart is explicit and goes through `request.json`. A handler never calls `stop()` on its own server. `409` if already stopping/stopped, or if a restart happened within 5 s. | Stopping uvicorn from inside a request risks answering into a dead socket. | +| D6 | `config.json` is the single source of truth for the port. `request.json` carries intents only. | The UI currently seeds the port twice; one owner removes a class of drift. | +| D7 | All JSON writes are atomic: temp file in the same directory, `os.replace`. | A 0.2 s poller can otherwise read a partial file. | +| D8 | The UI re-reads `config.json` on Settings entry and merges on save through `settingsSvc`, preserving `revision` and unknown fields. | Today the UI holds a stale whole-object cache and clobbers remote changes. | +| D9 | `keys.json` v2: array of `{id, name, hash, scopes, created_at}`. Refuse to delete the last key (`409`). UI rotation replaces only the key named `opensms`. | Named keys need stable ids; nuking proxy-owned keys from the phone would be hostile. | +| D10 | Status is best-effort: runtime providers first, files second, honest `null`/`"unknown"` when neither exists. Add `warnings[]`. | `resp.json` records transitions, not liveness. | +| D11 | Retry policy (`timeout`, `max_attempts`, `backoff`, `capacity`) is a setting, read live per attempt/enqueue. Defaults stay exactly today's constants. | This is the data-loss mitigation; it belongs in the first release, not a follow-up. | +| D12 | Tests use `unittest` + `TestClient` against a temporary config dir. `httpx` becomes a dev-only dependency. Add a test workflow. | No Android needed; today nothing runs the suite. | +| D13 | Bump `__version__` to `1.2.0`, add a CHANGELOG entry, one ADR (`0002`), glossary terms, README section. | The tag is derived from `config.py`; docs are the repo's existing habit. | +| D14 | Baseline is `develop` at `f3c7ba1`. `0756bdc` is the `v1.1.0` merge into `main` and is **not** an ancestor of this line. | The brief's "verify against 0756bdc" is unverifiable here. | + +--- + +## 5. Vocabulary + +See `GLOSSARY.md`: **Settings**, **Revision**, **Scope**, **API key**, +**Restart**. **Outbox** remains webhook-only. + +--- + +## 6. API contract + +### 6.1 Conventions + +- Base: `http://:`. +- Every route, including `/api/health`, requires + `Authorization: Bearer osms_…`. +- JSON in, JSON out, UTF-8. +- Error body: `{"detail": "..."}`. Settings validation is done by hand (not by + Pydantic models) so `detail` stays a human-readable string on `422`; + FastAPI's malformed-JSON error may still be a list. Clients must tolerate + both. +- Status codes: + - `400` business-rule violation + - `401` invalid key + - `403` missing `Authorization` header (HTTPBearer default) or missing scope + - `404` unknown resource + - `409` conflict (stale revision, last key, restart debounce/stopped) + - `422` schema/range/unknown-field violation + - `502` webhook test delivery failed +- Never return: webhook secret, key hashes, raw keys after creation, full + webhook URL with credentials. + +### 6.2 `GET /api/health` + +```json +{"status": "ok", "version": "1.2.0", "platform": "android", "uptime_s": 812} +``` + +`uptime_s` is seconds since the current `PosiApiServer` instance started; `0` +when unknown. `platform` comes from `get_os_platform()`. + +### 6.3 `GET /api/status` + +```json +{ + "version": "1.2.0", + "api": {"running": true, "port": 9292, "bound_port": 9292, "uptime_s": 812}, + "service": {"server": "started", "serial": "none", "provider": "none"}, + "config": {"port": 9292, "boot": true, "revision": 7}, + "network": { + "wifi": [{"interface": "wlan0", "ip": "192.168.1.50"}], + "ethernet": [] + }, + "webhook": { + "enabled": true, + "url_host": "proxy.example.lan", + "secret_set": true, + "outbox_pending": 0, + "outbox_capacity": 100, + "last_delivery": { + "ok": true, "event": "sms.received", "delivery_id": "...", + "http_status": 204, "attempts": 1, "error": null, + "at": "2026-11-26T12:34:56+01:00" + } + }, + "warnings": [] +} +``` + +Rules: + +- `api.running`: provider value; default `true` when no provider is registered + (the response itself proves reachability). +- `api.bound_port`: provider value, `null` if unknown. +- `config`: from `settingsSvc.load_settings`; `null` only if the file is + unreadable in a way loading cannot repair. +- `service`: `resp.json` values, `"unknown"` individually if absent/unreadable. +- `network`: `get_network_ips()`; any failure yields empty lists and adds + `{"code": "network_unavailable"}`. +- `webhook.url_host`: `urlparse(url).hostname`, `null` if empty. Never path, + query, or credentials. +- `last_delivery`: `null` when no status file. +- `outbox_pending`: provider value, `null` when unavailable. +- `warnings` is always an array. Codes: + - `webhook_disabled` — accepted but every new Inbound SMS is discarded, with + a message saying exactly that. + - `webhook_url_invalid` — enabled with a target that fails + `is_valid_target`. + - `outbox_near_capacity` — `pending >= 0.8 * capacity`. + +### 6.4 `GET /api/settings` + +```json +{ + "revision": 7, + "settings": { + "port": 9292, + "boot": true, + "webhook": { + "enabled": true, + "url": "https://proxy.example.lan/hooks/opensms", + "secret_set": true, + "timeout": 10, + "max_attempts": 3, + "backoff": [5, 30], + "capacity": 100 + } + } +} +``` + +Never include `permissions`, `app`, or the raw secret. + +### 6.5 `PUT /api/settings` + +```json +{ + "revision": 7, + "port": 9292, + "boot": true, + "webhook": { + "enabled": true, + "url": "https://proxy.example.lan/hooks/opensms", + "secret": "new-shared-secret", + "timeout": 10, + "max_attempts": 3, + "backoff": [5, 30], + "capacity": 100 + } +} +``` + +Required: `port`, `boot`, `webhook` and all webhook fields except `secret`. +Optional: `revision`, `webhook.secret`. + +Secret sentinel: + +- omitted → keep the stored secret +- `""` → clear it +- non-empty string → replace it (max 256 characters) + +Validation: + +| Field | Rule | Failure | +|---|---|---| +| `port` | integer, `1025 <= port <= 65535` | `422` | +| `boot` | JSON boolean | `422` | +| `webhook.enabled` | JSON boolean | `422` | +| `webhook.url` | string; required; valid `http(s)://host[:port]/path` when `enabled` is true; may be `""` when disabled | `422` if wrong type; `400` if enabled and invalid/empty | +| `webhook.secret` | string, ≤ 256 chars, sentinel semantics | `422` | +| `webhook.timeout` | integer 1–60 (seconds) | `422` | +| `webhook.max_attempts` | integer 1–50 | `422` | +| `webhook.backoff` | list of 1–8 positive integers, each ≤ 3600 | `422` | +| `webhook.capacity` | integer 10–5000 | `422` | +| unknown key, any level | rejected | `422` | +| `revision` | integer; if present and ≠ current → conflict | `409` | + +Order of checks: schema/range (`422`) → revision (`409`) → business rule +(`400`) → write. + +Write procedure: + +1. `load_settings` from disk (fresh read). +2. Apply the writable fields; preserve `app`, `permissions`, and unknown keys. +3. Re-validate the merged object. +4. `revision = current.revision + 1`; atomic write. +5. Log field names only: `Settings updated: port=9292 webhook.enabled=true secret=set`. + +`200`: + +```json +{ + "revision": 8, + "restart_required": false, + "settings": { "...": "same shape as GET" } +} +``` + +`restart_required` is `true` when the saved `port` differs from the live +`bound_port` (provider) while the server is running. It is a statement about +current state, not about this request: a previously pending port change also +reports `true`. + +Changing `boot` or the webhook never requires a restart. + +### 6.6 `POST /api/webhook/test` + +Optional body: + +```json +{"url": "https://proxy.example.lan/hooks/opensms", "secret": "..."} +``` + +- No body → saved webhook target and secret. +- `url` present → used for this test only, must be valid (`400` otherwise); it + is allowed while `enabled` is false. +- `secret` present → used for this test only; `""` means unsigned. +- Uses the saved `timeout`. + +`200`: `{"ok": true, "http_status": 204, "error": null}` +`502`: `{"ok": false, "http_status": 500, "error": "HTTP 500"}` + +3xx counts as failure. Uses `webhookSvc.send_test_webhook`. + +### 6.7 `POST /api/server/restart` + +`202`: + +```json +{"status": "restarting", "port": 9292} +``` + +Rules: + +- `409` if the API is not running (provider) or a restart was requested within + the last 5 seconds. +- The handler reads the effective port from `config.json`, schedules the + control-file write **after** the response (`RESTART_DELAY = 0.4 s`), and + returns. +- The intent is written atomically as + `{"port": , "server": "restart"}` merged into the existing + `request.json`, preserving `serial_port`, `baudrate`, and unknown keys. +- The handler never calls `PosiApiServer.stop()`. + +Service side (`appSvc`): + +1. Handle `"restart"`: `stop()`, sleep 0.5 s, start with + `load_settings(config.json)["port"]`, falling back to `request.json["port"]`. +2. Write `resp.json` with `"started"`. +3. Rewrite `request.json` with `"server": "start"` and the effective port, + preserving other keys. +4. The 0.2 s loop then sees `"start"` with the server already started and does + nothing. No restart loop. + +### 6.8 Keys + +`POST /api/keys` + +```json +{"name": "sms-proxy", "scopes": ["sms:write", "settings:write"]} +``` + +`scopes` is optional; default is both scopes. It must be a non-empty subset of +`{"sms:write", "settings:write"}`. + +`201`: + +```json +{ + "id": "k_9f2a1c4d", + "name": "sms-proxy", + "key": "osms_…", + "scopes": ["settings:write", "sms:write"], + "created_at": "2026-11-26T12:00:00+00:00" +} +``` + +The raw `key` appears only here. + +`GET /api/keys` + +```json +{"keys": [ + {"id": "k_9f2a1c4d", "name": "sms-proxy", + "scopes": ["settings:write", "sms:write"], + "created_at": "2026-11-26T12:00:00+00:00"} +]} +``` + +Never return hashes. + +`DELETE /api/keys/{id}` → `204`; `404` unknown/malformed id; `409` if it is the +last remaining key. Deleting the key used for the current request is allowed +when another remains and takes effect immediately. + +Rules: + +- Name: trimmed, 2–64 characters, no control characters, unique + case-insensitively; duplicate → `409`. +- Id: `k_` + 8 lowercase hex (`secrets.token_hex(4)`). +- Scopes stored canonical-sorted. +- Hash: SHA-256 hex, untruncated (unchanged). +- Lookup: scan every entry with `secrets.compare_digest` against the computed + hash; do not return early on the first mismatch. +- Writes are atomic. + +### 6.9 `POST /sms/` (unchanged) + +Requires `sms:write`. Boolean success means "handed to Android/SIM", not +delivered. Numbers must be E.164. Default SIM only. + +--- + +## 7. Persisted schemas + +`config.json` (v1 gains `revision` and webhook retry fields): + +```json +{ + "app": "opensms", + "port": 9292, + "boot": false, + "permissions": false, + "revision": 7, + "webhook": { + "enabled": false, + "url": "", + "secret": "", + "timeout": 10, + "max_attempts": 3, + "backoff": [5, 30], + "capacity": 100 + } +} +``` + +- Missing `revision` → `0` on load; first save writes `1`. +- Missing retry fields → current constants. Unknown fields are preserved. +- The secret stays plaintext at rest, as today. Masking is API-level only. + +`keys.json` v2: + +```json +{ + "version": 2, + "keys": [ + { + "id": "k_9f2a1c4d", + "name": "sms-proxy", + "hash": "", + "scopes": ["settings:write", "sms:write"], + "created_at": "2026-11-26T12:00:00+00:00" + } + ] +} +``` + +v1 migration (`{hash: {name, scopes}}`): + +- Converted in memory on first load; persisted as v2 on the first key write or + on the first authenticated request (whichever comes first), guarded by a + module lock. +- Ids are newly generated; `created_at` becomes "now" (original unknown); + missing names become `"opensms"`. +- Scopes: existing scopes **plus** `settings:write`. This is a one-time + escalation; it is deliberate because v1 scopes were never enforced and every + existing install would otherwise lock itself out of the new API. Documented + in the ADR. + +--- + +## 8. Cross-process behaviour + +Two processes write `config.json`. There is no OS-level lock (no new +dependency). Accepted model: + +- **Writers**: the API (one uvicorn thread pool) and the Kivy UI. +- **In-process serialisation**: a module lock around read-modify-write in + `settingsSvc`; `keys.json` has its own lock. +- **Cross-process**: last writer wins, but the window is shrunk to + read-fresh-then-write, and every writer bumps `revision` against the value it + actually read. The residual race is documented, not hidden. + +UI merge-on-save: + +1. On Settings entry: `reload_settings()` re-reads `config.json`, updates + `config_template`, `req_template["port"]`, the port field, the boot switch, + the webhook fields, and the last-delivery label. (Replaces + `reload_webhook_config`.) +2. On save: build a patch from the form (`port` if non-empty, `boot`, webhook + `enabled`/`url`/`secret`), call + `settingsSvc.save_settings(config_path, patch)`. +3. Invalid port (< 1025 or > 65535) or enabled-without-valid-URL rejects the + **whole** save with a toast. No partial write. +4. Adopt the returned object into `config_template` and refresh the views. + +`write_request()` becomes atomic and writes `port` from the last loaded +settings. + +--- + +## 9. File-by-file change plan + +| File | Change | +|---|---| +| `app/services/settingsSvc.py` | **New.** `DEFAULT_SETTINGS`, `load_settings`, `save_settings(..., expected_revision=None)`, `validate_settings`, `apply_writable_settings`, `writable_settings`, `atomic_write_json`. No Kivy/jnius/Android imports. Reuses `webhookSvc.is_valid_target`. | +| `app/services/postApi.py` | Routes from §6; `_runtime` providers + `set_runtime_providers` + `set_config_dir`; `require_scope`; keys v2 load/migrate/create/list/delete; `PosiApiServer.bound_port`/`started_at`; restart debounce; remove the `/control/` placeholder (its shape is superseded). | +| `app/services/appSvc.py` | Register providers after constructing server/dispatcher; call `set_config_dir`; `"restart"` handling; start from `config.json` port; normalise the control file; keep spool ack semantics unchanged. | +| `app/services/webhookSvc.py` | `normalize_webhook_config` carries retry knobs with defaults; `enqueue` uses live capacity; `_deliver` reads live timeout/max-attempts/backoff. Constructor args default to `None` (live config → constant) and stay explicit overrides so existing tests keep working. | +| `app/main.py` | Replace cache-only writes with `settingsSvc` read-merge-write; `reload_settings` on entry and after save; atomic `write_request`; key rotation replaces only `"opensms"`; update the API-key supporting text. | +| `app/screens/settings.py` | Supporting text only: rotation wording; port label already says 1025–65535 and now matches validation. No new fields. | +| `app/tests/test_settings_svc.py` | **New.** Pure module tests (defaults, revision, atomicity, secret sentinel, unknown fields, merge preserving internal fields). | +| `app/tests/test_remote_api.py` | **New.** Endpoint/auth/keys/restart/status tests via `TestClient`. | +| `app/requirements-dev.txt` | **New.** `httpx`. Dev only; Android and desktop runtime requirements unchanged. | +| `.github/workflows/tests.yml` | **New.** Ubuntu, Python 3.13, install `fastapi uvicorn httpx psutil pyserial`, run `python -m unittest discover -s tests -p "test_*.py" -v` from `app/`, path-filtered to `app/**`. | +| `app/services/config.py` | `__version__ = "1.2.0"`. | +| `CHANGELOG.md` | `### 1.2.0` entry (heading must match `__version__` exactly). | +| `README.md` | "Remote API" section with curl examples, scopes, LAN/VPN warning; feature bullet. | +| `docs/adr/0002-remote-settings-and-control-api.md` | **New.** This design's ADR. | +| `GLOSSARY.md` | New terms. | +| `app/buildozer.spec` | No change. Verify no static assets or dev requirements leak in (`tests` is already excluded). | + +--- + +## 10. Tests + +Framework: `unittest`, consistent with `app/tests/test_webhook.py`. +`TestClient` from `fastapi.testclient` (requires dev `httpx`). + +Isolation: + +- `tempfile.TemporaryDirectory()` per test. +- `postApi.set_config_dir(tmp)`; reset `_runtime`, `_last_restart_at`, + `postApi._started_at`. +- `postApi.set_api_logger(dummy)` where the dummy swallows writes. +- Never import `appSvc` in tests: it creates real directories and imports + service-only code at module scope. + +Required cases: + +1. `GET /api/settings` on a missing `config.json` returns defaults; no secret. +2. `PUT` valid payload: revision increments, file is valid JSON and atomic + (no `*.tmp` left), response masks the secret, `restart_required` false when + the port is unchanged. +3. `PUT` validation: port < 1025 / > 65535 → `422`; `enabled: true` with + missing/invalid URL → `400`; unknown top-level and nested field → `422`; + secret omitted keeps the old value; `""` clears it. +4. `PUT` stale `revision` → `409`; matching `revision` → `200`. +5. `PUT` port change with a fake `bound_port` provider → `restart_required: + true`; port equal → `false`. +6. Auth: valid key → `200`; bad key → `401`; missing header → HTTPBearer's + `403`; key without `settings:write` → `403`; `/sms/` still requires + `sms:write`. +7. `GET /api/status`: merges providers and `resp.json`; unreadable files → + `"unknown"`/`null`; network failure → empty lists + warning; URL masked to + host; `webhook_disabled` warning present when disabled. +8. `POST /api/server/restart`: `202`; `request.json` gets `server=restart` + while preserving `serial_port`/`baudrate`; second call within 5 s → `409`; + stopped provider → `409`; debounce resets. +9. `POST /api/webhook/test`: success against a local `ThreadingHTTPServer` + (reuse the `test_webhook.py` `MockTarget` pattern); failure → `502`; + URL override works without saving. +10. Keys: create returns a raw key once and it authenticates; `GET` has no + hashes; duplicate name (case-insensitive) → `409`; unknown delete → `404`; + last key → `409`; deleting the calling key with another present → `204` and + the old key stops working; v1 file migrates, authenticates, and is + persisted as v2. +11. UI merge: after an API write, a simulated UI save built from a stale + `config_template` preserves the API-changed webhook URL and the incrementing + revision. +12. Live retry config: dispatcher picks up `max_attempts`/`backoff`/`capacity` + from `config.json` when constructor args are absent; constructor args still + override (existing tests must pass unchanged). + +Run: + +```bash +cd app +python -m unittest discover -s tests -p "test_*.py" -v +``` + +Manual Android smoke (not CI): build, start the service, then from a laptop on +the same Wi-Fi: `GET /api/health`, `GET /api/settings`, `PUT /api/settings`, +`POST /api/server/restart`; confirm the proxy receives `sms.received` and that +`request.json` ends as `"start"`. + +--- + +## 11. Phases + +| Phase | Content | LOC (src) | +|---|---|---| +| 1 | `settingsSvc.py`, schema, atomic writes, revision, validation, secret sentinel | 150–200 | +| 2 | Provider hooks, config-dir seam, scopes, `GET/PUT /api/settings` | 100–140 | +| 3 | `/api/health`, `/api/status`, `/api/webhook/test` | 80–120 | +| 4 | Restart orchestration + UI merge-on-save + atomic `request.json` | 100–160 | +| 5 | Keys v2, migration, CRUD | 110–160 | +| 6 | Live webhook retry/capacity (dispatcher + schema already in Phase 1) | 60–100 | +| — | Tests, docs, ADR, CI | 250–350 | + +Core total ≈ 600–900 source lines, 3–4 focused days. + +--- + +## 12. Acceptance criteria + +1. With only `Authorization: Bearer osms_…`, the proxy can read and write every + writable setting, test the webhook, restart the server, and manage keys. +2. `GET /api/settings` never reveals the secret; `GET /api/keys` never reveals + hashes; raw keys appear only in the creation response. +3. Webhook URL/secret/enable and retry changes take effect on the next inbound + SMS without a restart. +4. A port change followed by `POST /api/server/restart` leaves the API listening + on the new port; `request.json` ends at `"start"`; no restart loop; a bind + failure is visible as `bound_port: null` and a log entry. +5. An API settings change survives a subsequent UI save (merge test). +6. Invalid payloads return `4xx` with a descriptive `detail` and never leave a + partial or corrupt `config.json`. +7. `unittest` passes on desktop without Android imports; the new CI job runs it. +8. `POST /sms/` and the phone UI behave as before for valid inputs. +9. `GET /api/status` warns when forwarding is disabled, naming the data loss. +10. README documents the API, scopes, curl examples, and LAN/VPN-only guidance. + +--- + +## 13. Risks + +1. **Restart loop** if `request.json` stays `"restart"`. Normalise to `"start"` + immediately after starting. +2. **Self-deadlock** if a handler stops its own server. Always go through the + control file. +3. **Response/stop race**: the 202 must reach the client before uvicorn shuts + down. The `RESTART_DELAY` timer is the mitigation; do not lower it below + ~0.3 s. +4. **UI clobbering** remains possible in the tiny window between the UI's fresh + read and its replace. Accepted; documented. +5. **Ack-on-disabled discards SMS.** A remote client that disables the webhook + destroys every SMS received while it is off. The status warning must say so. +6. **Outbox full drops the oldest** record. Capacity is now configurable, but + the drop policy is unchanged. +7. **`resp.json` is not a heartbeat.** Do not present it as liveness; the + response itself proves the API is up. +8. **Unpinned FastAPI/Pydantic** on desktop vs `pydantic==2.12.3` on Android. + Avoid version-specific API usage; request bodies as plain `dict` with manual + validation sidesteps Pydantic v1/v2 differences. +9. **Bind errors are swallowed** into a callback (`postApi.py:173-178`). The new + status fields make the failure visible; they do not fix it. +10. **Key deletion** can lock out the caller only if it is the last key; `409` + prevents that. Rotation from the phone only touches the `opensms` key. +11. **No TLS/CORS.** LAN or VPN only. `/docs` is public but requires a key to + execute. + +--- + +## Appendix A — deferred `/api/logs` + +`GET /api/logs?lines=200` (default 200, max 1000) → `{"lines": [...]}`. + +- Source: `LogService.get_api_logs()`, last N lines, trailing newlines stripped. +- Never expose file paths. +- Missing file → `{"lines": []}`. +- Requires `settings:write` like every other `/api/*` route. + +Not in the `1.2.0` change. + +## Appendix B — deferred, explicitly + +Inbound SMS persistence/history, delivery receipts, SIM selection, remote +permission grants, serial settings over the API, TLS termination, CORS, a web +UI. From 1c97cd6ec135b1ce79d61e6f50960cb2551b45cf Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 15:50:19 +0100 Subject: [PATCH 02/20] test: add off-device API harness and CI --- .github/workflows/tests.yml | 46 +++++++++++++++++++++++++++++ app/requirements-dev.txt | 2 ++ app/services/postApi.py | 57 ++++++++++++++++++++++++++++++++---- app/tests/api_test_case.py | 40 +++++++++++++++++++++++++ app/tests/test_remote_api.py | 35 ++++++++++++++++++++++ 5 files changed, 174 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/tests.yml create mode 100644 app/requirements-dev.txt create mode 100644 app/tests/api_test_case.py create mode 100644 app/tests/test_remote_api.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..e4a25e7 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,46 @@ +# Runs the off-device test suite on Linux without Android. + +name: 'Tests' + +on: + push: + branches: + - main + - develop + paths: + - 'app/**' + - '.github/workflows/tests.yml' + pull_request: + paths: + - 'app/**' + - '.github/workflows/tests.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + linux_tests: + name: 'Unit tests (Linux)' + runs-on: 'ubuntu-24.04' + + steps: + + - name: GIT Checkout + uses: actions/checkout@v4 + + - name: Setup Python + uses: actions/setup-python@v7 + with: + python-version: '3.13' + cache: 'pip' + + - name: Install Dependencies + working-directory: ./app + run: | + pip install fastapi uvicorn psutil pyserial -r requirements-dev.txt + + - name: Run unit tests + working-directory: ./app + run: | + python -m unittest discover -s tests -p "test_*.py" -v diff --git a/app/requirements-dev.txt b/app/requirements-dev.txt new file mode 100644 index 0000000..d8f1530 --- /dev/null +++ b/app/requirements-dev.txt @@ -0,0 +1,2 @@ +# Development and test-only dependencies. Never shipped by buildozer. +httpx diff --git a/app/services/postApi.py b/app/services/postApi.py index 19c56e8..10391d0 100644 --- a/app/services/postApi.py +++ b/app/services/postApi.py @@ -34,20 +34,63 @@ logger = None sms_api = SmsCrossPlatform() +# Test seam: tests point the API at a temporary config directory so they never +# read or write the real app data directory. +_config_dir: str | None = None +_runtime: dict = {} +_last_restart_at: float | None = None +_started_at: float | None = None + ## OS specific setups # for android if platform == "android": from android.storage import app_storage_path from jnius import autoclass - base_path = app_storage_path() #for other platforms like windows or linux else: from services.serialMgr import SerialConDesktop from services.pathMgr import get_user_data_dir - base_path = get_user_data_dir(app_name) serial_mgr = SerialConDesktop() -config_dir = join(base_path, 'config') +def _default_config_dir() -> str: + if platform == "android": + base_path = app_storage_path() + else: + base_path = get_user_data_dir(app_name) + return join(base_path, "config") + +def get_config_dir() -> str: + """Return the config directory, resolving the platform default lazily.""" + if _config_dir: + return _config_dir + return _default_config_dir() + +def set_config_dir(path: str | None): + """Point config reads and writes at `path`; None restores the default.""" + global _config_dir + _config_dir = str(path) if path else None + +def set_runtime_providers(providers: dict | None = None): + """Replace the live runtime value providers (callables keyed by name).""" + _runtime.clear() + if providers: + _runtime.update(providers) + +def get_runtime_provider(name: str, default=None): + provider = _runtime.get(name) + if provider is None: + return default + try: + return provider() + except Exception: + return default + +def reset_runtime_state(): + """Test seam: forget runtime providers and restart/uptime bookkeeping.""" + global _last_restart_at, _started_at + set_runtime_providers({}) + _last_restart_at = None + _started_at = None ## Functions @@ -89,6 +132,9 @@ def hash_api_key(raw_key: str) -> str: """Hash the raw key using SHA-256.""" return hashlib.sha256(raw_key.encode("utf-8")).hexdigest() +def _keys_path() -> str: + return join(get_config_dir(), "keys.json") + def generate_new_api_key() -> str: # Generate a high-entropy secret token new_raw_key = secrets.token_urlsafe(32) @@ -101,15 +147,14 @@ def generate_new_api_key() -> str: "scopes": ["sms:write"] } } - keys_path = join(config_dir, "keys.json") - with open(keys_path, "w") as kf: + with open(_keys_path(), "w") as kf: json.dump(app_api_keys, kf) print("Created/updated the API key") log_activities("Created/updated the API key") return new_raw_key def get_api_keys() -> dict: - keys_path = join(config_dir, "keys.json") + keys_path = _keys_path() api_keys = {} if exists(keys_path): with open(keys_path, "r") as kf: diff --git a/app/tests/api_test_case.py b/app/tests/api_test_case.py new file mode 100644 index 0000000..19ba98f --- /dev/null +++ b/app/tests/api_test_case.py @@ -0,0 +1,40 @@ +"""Shared setup for HTTP-seam API tests. + +Every test points the API at a temporary config directory and resets the +module-level runtime providers, restart debounce state and logger, so no test +reads or writes the real app data directory. +""" + +import os +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from fastapi.testclient import TestClient + +from services import postApi + + +class ApiTestCase(unittest.TestCase): + + def _reset_module_state(self): + postApi.reset_runtime_state() + postApi.set_api_logger(None) + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.config_dir = self.tmp.name + postApi.set_config_dir(self.config_dir) + self._reset_module_state() + # /sms/ reads the server off app state; tests never start a real one. + postApi.app.state.server = postApi.PosiApiServer() + self.client = TestClient(postApi.app) + + def tearDown(self): + self.client.close() + postApi.app.state.server = None + self._reset_module_state() + postApi.set_config_dir(None) + self.tmp.cleanup() diff --git a/app/tests/test_remote_api.py b/app/tests/test_remote_api.py new file mode 100644 index 0000000..0d29823 --- /dev/null +++ b/app/tests/test_remote_api.py @@ -0,0 +1,35 @@ +import os + +from api_test_case import ApiTestCase + +from services import postApi + + +class ApiHarnessTests(ApiTestCase): + + def test_request_without_a_key_is_refused(self): + response = self.client.post( + "/sms/", + json={"number": "+14155552671", "text": "hello"}, + ) + + # Starlette returns 401 on current versions and 403 on older ones; + # either way HTTPBearer refuses the request. + self.assertIn(response.status_code, (401, 403)) + self.assertNotIn("stat", response.json()) + + def test_api_reads_keys_from_the_temporary_config_directory(self): + raw_key = postApi.generate_new_api_key() + self.assertTrue( + os.path.exists(os.path.join(self.config_dir, "keys.json")) + ) + + response = self.client.post( + "/sms/", + json={"number": "+14155552671", "text": "hello"}, + headers={"Authorization": f"Bearer {raw_key}"}, + ) + + self.assertEqual(response.status_code, 200) + self.assertIn("stat", response.json()) + self.assertEqual(postApi.get_config_dir(), self.config_dir) From 6cfef137f9587d29b149c09ad6ec7ac2c845e346 Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 16:01:54 +0100 Subject: [PATCH 03/20] feat: expose authenticated health and settings reads --- app/main.py | 12 +-- app/services/postApi.py | 174 +++++++++++++++++++++++------- app/services/settingsSvc.py | 119 +++++++++++++++++++++ app/tests/api_test_case.py | 52 +++++++++ app/tests/test_remote_api.py | 202 ++++++++++++++++++++++++++++++++++- 5 files changed, 509 insertions(+), 50 deletions(-) create mode 100644 app/services/settingsSvc.py diff --git a/app/main.py b/app/main.py index da686a9..0528ecd 100644 --- a/app/main.py +++ b/app/main.py @@ -40,7 +40,7 @@ from screens.settings import SettingsBox, ApiKeyTxtbox # import services -from services.postApi import get_api_keys, generate_new_api_key +from services.postApi import has_api_keys, generate_new_api_key from services.netSvc import get_network_ips from services.config import __version__, app_name from services.webhookSvc import ( @@ -245,9 +245,7 @@ def on_start(self): self.write_app_conf() port_no_inp.text = str(self.config_template["port"]) self.refresh_webhook_view() - api_keys = get_api_keys() - if len(api_keys) >= 1: - self.key_exists = True + self.check_if_key_exists() self.stop_resp_loop() self.resp_thred = Thread(target=self.resp_check_loop, daemon=True) self.resp_thred.start() @@ -509,11 +507,7 @@ def open_android_settings(self, instance=None): activity.startActivity(intent) def check_if_key_exists(self): - api_keys = get_api_keys() - if len(api_keys) >= 1: - self.key_exists = True - else: - self.key_exists = False + self.key_exists = has_api_keys() return self.key_exists def new_api_key_pop(self): diff --git a/app/services/postApi.py b/app/services/postApi.py index 10391d0..7d38018 100644 --- a/app/services/postApi.py +++ b/app/services/postApi.py @@ -1,9 +1,10 @@ import hashlib import secrets import asyncio -from threading import Thread -import sys -from os.path import dirname, abspath, join, exists +import time +from datetime import datetime, timezone +from threading import Thread, Lock +from os.path import join import json #from functools import partial @@ -16,7 +17,8 @@ from services.pathMgr import get_os_platform from services.smsApi import SmsCrossPlatform, clean_and_validate_phone from services.logSvc import LogService -from services.config import app_name +from services.config import __version__, app_name +from services import settingsSvc # OS specific #try: @@ -34,12 +36,17 @@ logger = None sms_api = SmsCrossPlatform() +# API key scopes +SCOPE_SEND = "sms:write" +SCOPE_SETTINGS = "settings:write" + # Test seam: tests point the API at a temporary config directory so they never # read or write the real app data directory. _config_dir: str | None = None _runtime: dict = {} _last_restart_at: float | None = None _started_at: float | None = None +_key_lock = Lock() ## OS specific setups # for android @@ -135,31 +142,90 @@ def hash_api_key(raw_key: str) -> str: def _keys_path() -> str: return join(get_config_dir(), "keys.json") +def _settings_path() -> str: + return join(get_config_dir(), "config.json") + +def _now_iso() -> str: + return datetime.now(timezone.utc).isoformat(timespec="seconds") + +def _migrate_v1_keys(raw: dict) -> list: + """Convert a version-one {hash: {name, scopes}} store to version two. + + Version-one scopes were stored but never enforced, so migration grants both + scopes once; otherwise every existing install would lock itself out. + """ + keys = [] + for key_hash, info in raw.items(): + if not isinstance(info, dict): + continue + scopes = info.get("scopes") + if not isinstance(scopes, list): + scopes = [] + scopes = {str(scope) for scope in scopes if isinstance(scope, str)} + scopes.update({SCOPE_SEND, SCOPE_SETTINGS}) + keys.append({ + "id": f"k_{secrets.token_hex(4)}", + "name": str(info.get("name") or "opensms"), + "hash": str(key_hash), + "scopes": sorted(scopes), + "created_at": _now_iso(), + }) + return keys + +def load_key_store() -> tuple[dict, bool]: + """Return the key store, migrating a version-one file in memory. + + The second item is True when a migration is pending persistence. + """ + try: + with open(_keys_path(), "r", encoding="utf-8") as keys_file: + raw = json.load(keys_file) + except Exception: + return {"version": 2, "keys": []}, False + if not isinstance(raw, dict): + return {"version": 2, "keys": []}, False + if raw.get("version") == 2 and isinstance(raw.get("keys"), list): + keys = [entry for entry in raw["keys"] if isinstance(entry, dict)] + return {"version": 2, "keys": keys}, False + return {"version": 2, "keys": _migrate_v1_keys(raw)}, True + +def save_key_store(store: dict): + settingsSvc.atomic_write_json(_keys_path(), store) + +def authenticate_key(raw_key: str) -> dict | None: + hashed = hash_api_key(raw_key) + with _key_lock: + store, migrated = load_key_store() + match = None + for entry in store["keys"]: + if secrets.compare_digest(entry.get("hash") or "", hashed): + match = entry + if match is not None and migrated: + save_key_store(store) + return match + +def has_api_keys() -> bool: + store, _ = load_key_store() + return bool(store["keys"]) + def generate_new_api_key() -> str: # Generate a high-entropy secret token - new_raw_key = secrets.token_urlsafe(32) - new_raw_key = f"osms_{new_raw_key}" - # Hash and store in your DB - new_hashed_key = hash_api_key(new_raw_key) - app_api_keys = { - new_hashed_key: { + new_raw_key = f"osms_{secrets.token_urlsafe(32)}" + save_key_store({ + "version": 2, + "keys": [{ + "id": f"k_{secrets.token_hex(4)}", "name": "opensms", - "scopes": ["sms:write"] - } - } - with open(_keys_path(), "w") as kf: - json.dump(app_api_keys, kf) + "hash": hash_api_key(new_raw_key), + "scopes": sorted({SCOPE_SEND, SCOPE_SETTINGS}), + "created_at": _now_iso(), + }], + }) print("Created/updated the API key") log_activities("Created/updated the API key") return new_raw_key -def get_api_keys() -> dict: - keys_path = _keys_path() - api_keys = {} - if exists(keys_path): - with open(keys_path, "r") as kf: - api_keys = json.load(kf) - return api_keys + # data formatting for request class SmsData(BaseModel): @@ -175,7 +241,7 @@ class ControlData(BaseModel): # FastAPI app app = FastAPI() -security = HTTPBearer() +security = HTTPBearer(auto_error=False) # api server class with callback function class PosiApiServer: @@ -186,6 +252,7 @@ def __init__(self, host="0.0.0.0", port=9292): self.kivyCallback = None self.server: uvicorn.Server | None = None self.thread: Thread | None = None + self.started_at: float | None = None # ---------------------------- # Control callback @@ -211,9 +278,11 @@ def _run(self, port=None): log_level="info", loop="asyncio" ) + global _started_at try: self.server = uvicorn.Server(config) app.state.server = self # attach instance + _started_at = self.started_at = time.time() asyncio.run(self.server.serve()) except OSError as e: err_msg = f"Error while port binding {final_port}: {e}" @@ -264,21 +333,16 @@ def stop(self): async def verify_api_key( request: Request, - credentials: HTTPAuthorizationCredentials = Depends(security) + credentials: HTTPAuthorizationCredentials | None = Depends(security) ) -> dict: client_ip = request.client.host if request.client else "unknown" - raw_token = credentials.credentials - hashed_token = hash_api_key(raw_token) - - # 1. Lookup candidate in DB by hash - app_api_keys = get_api_keys() - client_info = app_api_keys.get(hashed_token) - - # 2. Timing-safe comparison against stored hash - if not client_info or not secrets.compare_digest( - hashed_token, - hash_api_key(raw_token) - ): + if credentials is None: + raise HTTPException( + status_code=403, + detail="Not authenticated", + ) + client_info = authenticate_key(credentials.credentials) + if not client_info: print(f"Authentication failed from IP: {client_ip}") log_activities(f"Authentication failed from IP: {client_ip}") raise HTTPException( @@ -287,11 +351,47 @@ async def verify_api_key( ) return client_info +def require_scope(scope: str): + async def scope_guard( + client: dict = Depends(verify_api_key) + ) -> dict: + if scope not in (client.get("scopes") or []): + raise HTTPException( + status_code=403, + detail=f"Missing required scope: {scope}", + ) + return client + return scope_guard + +@app.get("/api/health") +async def api_health( + client: dict = Depends(require_scope(SCOPE_SETTINGS)) +): + server = getattr(app.state, "server", None) + started_at = getattr(server, "started_at", None) or _started_at + uptime_s = max(0, int(time.time() - started_at)) if started_at else 0 + return { + "status": "ok", + "version": __version__, + "platform": platform, + "uptime_s": uptime_s, + } + +@app.get("/api/settings") +async def api_get_settings( + client: dict = Depends(require_scope(SCOPE_SETTINGS)) +): + settings = settingsSvc.load_settings(_settings_path()) + return { + "revision": settingsSvc.get_revision(settings), + "settings": settingsSvc.writable_settings(settings), + } + @app.post("/sms/") async def process_sms_req( item: SmsData, request: Request, - client: dict = Depends(verify_api_key) + client: dict = Depends(require_scope(SCOPE_SEND)) ): server: PosiApiServer = request.app.state.server diff --git a/app/services/settingsSvc.py b/app/services/settingsSvc.py new file mode 100644 index 0000000..0b2a714 --- /dev/null +++ b/app/services/settingsSvc.py @@ -0,0 +1,119 @@ +""" Persisted Settings for OpenSMS. + +This module is deliberately free of Kivy, jnius and Android imports so the +Settings contract can be tested on any platform. It takes an explicit path and +holds no module state. +""" + +import json +import os +import tempfile + +from services.config import app_name +from services.webhookSvc import ( + DEFAULT_BACKOFF, + DEFAULT_CAPACITY, + DEFAULT_MAX_ATTEMPTS, + DEFAULT_TIMEOUT, +) + +DEFAULT_PORT = 9292 +DEFAULT_BOOT = False + +## Defaults + +def default_webhook_settings() -> dict: + return { + "enabled": False, + "url": "", + "secret": "", + "timeout": DEFAULT_TIMEOUT, + "max_attempts": DEFAULT_MAX_ATTEMPTS, + "backoff": list(DEFAULT_BACKOFF), + "capacity": DEFAULT_CAPACITY, + } + +def default_settings() -> dict: + return { + "app": app_name, + "port": DEFAULT_PORT, + "boot": DEFAULT_BOOT, + "permissions": False, + "revision": 0, + "webhook": default_webhook_settings(), + } + +## Load + +def load_settings(config_path: str) -> dict: + """Load Settings, filling missing fields from the defaults. + + Unknown fields, at the top level and inside the Webhook object, are kept so + a later write can preserve them. + """ + settings = default_settings() + try: + with open(config_path, "r", encoding="utf-8") as config_file: + raw = json.load(config_file) + except Exception: + return settings + if not isinstance(raw, dict): + return settings + for key, value in raw.items(): + if key == "webhook": + continue + settings[key] = value + raw_webhook = raw.get("webhook") + if isinstance(raw_webhook, dict): + settings["webhook"].update(raw_webhook) + return settings + +def get_revision(settings: dict) -> int: + try: + return int(settings.get("revision") or 0) + except (TypeError, ValueError): + return 0 + +## API shape + +def writable_settings(settings: dict) -> dict: + """Return only the writable subset, with the secret masked.""" + webhook = settings.get("webhook") + if not isinstance(webhook, dict): + webhook = {} + backoff = webhook.get("backoff") + if not isinstance(backoff, list): + backoff = list(DEFAULT_BACKOFF) + return { + "port": settings.get("port", DEFAULT_PORT), + "boot": settings.get("boot", DEFAULT_BOOT), + "webhook": { + "enabled": webhook.get("enabled", False), + "url": webhook.get("url", ""), + "secret_set": bool(webhook.get("secret")), + "timeout": webhook.get("timeout", DEFAULT_TIMEOUT), + "max_attempts": webhook.get("max_attempts", DEFAULT_MAX_ATTEMPTS), + "backoff": list(backoff), + "capacity": webhook.get("capacity", DEFAULT_CAPACITY), + }, + } + +## Writes + +def atomic_write_json(path: str, data): + """Write JSON via a temporary file in the same directory, then replace.""" + directory = os.path.dirname(path) + if directory: + os.makedirs(directory, exist_ok=True) + file_descriptor, tmp_path = tempfile.mkstemp( + prefix="config.", + suffix=".tmp", + dir=directory or ".", + ) + try: + with os.fdopen(file_descriptor, "w", encoding="utf-8") as tmp_file: + json.dump(data, tmp_file) + os.replace(tmp_path, path) + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) diff --git a/app/tests/api_test_case.py b/app/tests/api_test_case.py index 19ba98f..721e4d4 100644 --- a/app/tests/api_test_case.py +++ b/app/tests/api_test_case.py @@ -5,7 +5,9 @@ reads or writes the real app data directory. """ +import json import os +import secrets import sys import tempfile import unittest @@ -38,3 +40,53 @@ def tearDown(self): self._reset_module_state() postApi.set_config_dir(None) self.tmp.cleanup() + + def auth(self, raw_key: str) -> dict: + return {"Authorization": f"Bearer {raw_key}"} + + def write_config(self, config: dict): + with open( + os.path.join(self.config_dir, "config.json"), "w", encoding="utf-8" + ) as config_file: + json.dump(config, config_file) + + def read_key_store(self) -> dict: + with open( + os.path.join(self.config_dir, "keys.json"), encoding="utf-8" + ) as keys_file: + return json.load(keys_file) + + def add_api_key(self, scopes=("sms:write", "settings:write"), + name: str = "test") -> str: + """Write a v2 key store entry and return the raw key.""" + raw_key = f"osms_{secrets.token_urlsafe(16)}" + keys_path = os.path.join(self.config_dir, "keys.json") + if os.path.exists(keys_path): + store = self.read_key_store() + else: + store = {"version": 2, "keys": []} + store["keys"].append({ + "id": f"k_{secrets.token_hex(4)}", + "name": name, + "hash": postApi.hash_api_key(raw_key), + "scopes": sorted(scopes), + "created_at": "2026-01-01T00:00:00+00:00", + }) + with open(keys_path, "w", encoding="utf-8") as keys_file: + json.dump(store, keys_file) + return raw_key + + def add_legacy_api_key(self, scopes=("sms:write",), + name: str = "opensms") -> str: + """Write a version-one key store entry and return the raw key.""" + raw_key = f"osms_{secrets.token_urlsafe(16)}" + with open( + os.path.join(self.config_dir, "keys.json"), "w", encoding="utf-8" + ) as keys_file: + json.dump({ + postApi.hash_api_key(raw_key): { + "name": name, + "scopes": list(scopes), + }, + }, keys_file) + return raw_key diff --git a/app/tests/test_remote_api.py b/app/tests/test_remote_api.py index 0d29823..e3b69a2 100644 --- a/app/tests/test_remote_api.py +++ b/app/tests/test_remote_api.py @@ -1,8 +1,11 @@ import os +import time from api_test_case import ApiTestCase from services import postApi +from services.config import __version__ +from services.pathMgr import get_os_platform class ApiHarnessTests(ApiTestCase): @@ -13,9 +16,7 @@ def test_request_without_a_key_is_refused(self): json={"number": "+14155552671", "text": "hello"}, ) - # Starlette returns 401 on current versions and 403 on older ones; - # either way HTTPBearer refuses the request. - self.assertIn(response.status_code, (401, 403)) + self.assertEqual(response.status_code, 403) self.assertNotIn("stat", response.json()) def test_api_reads_keys_from_the_temporary_config_directory(self): @@ -27,9 +28,202 @@ def test_api_reads_keys_from_the_temporary_config_directory(self): response = self.client.post( "/sms/", json={"number": "+14155552671", "text": "hello"}, - headers={"Authorization": f"Bearer {raw_key}"}, + headers=self.auth(raw_key), ) self.assertEqual(response.status_code, 200) self.assertIn("stat", response.json()) self.assertEqual(postApi.get_config_dir(), self.config_dir) + + +class HealthTests(ApiTestCase): + + def test_health_refuses_a_missing_key(self): + response = self.client.get("/api/health") + self.assertEqual(response.status_code, 403) + + def test_health_refuses_an_invalid_key(self): + self.add_api_key() + response = self.client.get( + "/api/health", headers=self.auth("osms_not_a_real_key") + ) + self.assertEqual(response.status_code, 401) + + def test_health_reports_status_version_platform_and_uptime(self): + raw_key = self.add_api_key() + postApi.app.state.server.started_at = time.time() - 10 + + response = self.client.get("/api/health", headers=self.auth(raw_key)) + + self.assertEqual(response.status_code, 200) + body = response.json() + self.assertEqual(body["status"], "ok") + self.assertEqual(body["version"], __version__) + self.assertEqual(body["platform"], get_os_platform()) + self.assertGreaterEqual(body["uptime_s"], 9) + + +class SettingsReadTests(ApiTestCase): + + def test_settings_defaults_when_no_config_exists(self): + raw_key = self.add_api_key() + + response = self.client.get( + "/api/settings", headers=self.auth(raw_key) + ) + + self.assertEqual(response.status_code, 200) + body = response.json() + self.assertEqual(body["revision"], 0) + self.assertEqual(body["settings"], { + "port": 9292, + "boot": False, + "webhook": { + "enabled": False, + "url": "", + "secret_set": False, + "timeout": 10, + "max_attempts": 3, + "backoff": [5, 30], + "capacity": 100, + }, + }) + + def test_settings_masks_the_secret_and_hides_internal_fields(self): + self.write_config({ + "app": "opensms", + "port": 9393, + "boot": True, + "permissions": True, + "revision": 7, + "unknown_top_level": "internal", + "webhook": { + "enabled": True, + "url": "https://proxy.example.lan/hooks/opensms", + "secret": "topsecret", + "timeout": 5, + "max_attempts": 2, + "backoff": [1, 2], + "capacity": 50, + "unknown_webhook": "internal", + }, + }) + raw_key = self.add_api_key() + + response = self.client.get( + "/api/settings", headers=self.auth(raw_key) + ) + + self.assertEqual(response.status_code, 200) + self.assertNotIn("topsecret", response.text) + body = response.json() + self.assertEqual(body["revision"], 7) + settings = body["settings"] + self.assertEqual(settings["port"], 9393) + self.assertTrue(settings["boot"]) + self.assertNotIn("app", settings) + self.assertNotIn("permissions", settings) + self.assertNotIn("unknown_top_level", settings) + self.assertTrue(settings["webhook"]["secret_set"]) + self.assertNotIn("secret", settings["webhook"]) + self.assertNotIn("unknown_webhook", settings["webhook"]) + + def test_settings_fill_defaults_for_a_legacy_config(self): + self.write_config({ + "app": "opensms", + "port": 9393, + "boot": True, + "webhook": { + "enabled": False, + "url": "", + "secret": "", + }, + }) + raw_key = self.add_api_key() + + response = self.client.get( + "/api/settings", headers=self.auth(raw_key) + ) + + self.assertEqual(response.status_code, 200) + body = response.json() + self.assertEqual(body["revision"], 0) + webhook = body["settings"]["webhook"] + self.assertEqual(webhook["timeout"], 10) + self.assertEqual(webhook["max_attempts"], 3) + self.assertEqual(webhook["backoff"], [5, 30]) + self.assertEqual(webhook["capacity"], 100) + + +class KeyMigrationTests(ApiTestCase): + + def test_legacy_key_authenticates_and_is_migrated_on_first_use(self): + raw_key = self.add_legacy_api_key() + + response = self.client.get( + "/api/settings", headers=self.auth(raw_key) + ) + + self.assertEqual(response.status_code, 200) + store = self.read_key_store() + self.assertEqual(store["version"], 2) + self.assertEqual(len(store["keys"]), 1) + entry = store["keys"][0] + self.assertEqual(entry["hash"], postApi.hash_api_key(raw_key)) + self.assertEqual(entry["scopes"], ["settings:write", "sms:write"]) + self.assertTrue(entry["id"].startswith("k_")) + self.assertTrue(entry["created_at"]) + + again = self.client.get( + "/api/settings", headers=self.auth(raw_key) + ) + self.assertEqual(again.status_code, 200) + + def test_legacy_key_without_scopes_is_granted_both(self): + raw_key = self.add_legacy_api_key(scopes=()) + + response = self.client.get( + "/api/settings", headers=self.auth(raw_key) + ) + self.assertEqual(response.status_code, 200) + entry = self.read_key_store()["keys"][0] + self.assertEqual(entry["scopes"], ["settings:write", "sms:write"]) + + send = self.client.post( + "/sms/", + json={"number": "+14155552671", "text": "hello"}, + headers=self.auth(raw_key), + ) + self.assertEqual(send.status_code, 200) + + +class ScopeTests(ApiTestCase): + + def test_send_only_key_cannot_read_settings(self): + raw_key = self.add_api_key(scopes=("sms:write",)) + + response = self.client.get( + "/api/settings", headers=self.auth(raw_key) + ) + + self.assertEqual(response.status_code, 403) + + def test_send_only_key_cannot_read_health(self): + raw_key = self.add_api_key(scopes=("sms:write",)) + + response = self.client.get( + "/api/health", headers=self.auth(raw_key) + ) + + self.assertEqual(response.status_code, 403) + + def test_settings_only_key_cannot_send_sms(self): + raw_key = self.add_api_key(scopes=("settings:write",)) + + response = self.client.post( + "/sms/", + json={"number": "+14155552671", "text": "hello"}, + headers=self.auth(raw_key), + ) + + self.assertEqual(response.status_code, 403) From a4aaf95284d0023ed376589de8fdf1527124dfa7 Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 17:12:05 +0100 Subject: [PATCH 04/20] feat: allow settings to be changed over the network --- app/services/appSvc.py | 5 + app/services/postApi.py | 51 +++++ app/services/settingsSvc.py | 274 +++++++++++++++++++++- app/tests/api_test_case.py | 6 + app/tests/test_remote_api.py | 432 +++++++++++++++++++++++++++++++++++ 5 files changed, 767 insertions(+), 1 deletion(-) diff --git a/app/services/appSvc.py b/app/services/appSvc.py index 38a47bd..ae3440c 100644 --- a/app/services/appSvc.py +++ b/app/services/appSvc.py @@ -23,6 +23,7 @@ PosiApiServer, set_api_logger, set_serial_port, + set_runtime_providers, log_activities, ) from services.logSvc import LogService @@ -93,6 +94,10 @@ def request_stop(signum=None, frame=None): status_path=webhook_status_file, log=log_activities, ) +# Let the API compare a saved port with the one the live server is bound to. +set_runtime_providers({ + "bound_port": lambda: app_api_server.bound_port, +}) ## functions def write_resp(): diff --git a/app/services/postApi.py b/app/services/postApi.py index 7d38018..05a2a04 100644 --- a/app/services/postApi.py +++ b/app/services/postApi.py @@ -249,6 +249,7 @@ class PosiApiServer: def __init__(self, host="0.0.0.0", port=9292): self.host = host self.port = port + self.bound_port: int | None = None self.kivyCallback = None self.server: uvicorn.Server | None = None self.thread: Thread | None = None @@ -271,6 +272,8 @@ def set_kivy_caller(self, callback=None): # ---------------------------- def _run(self, port=None): final_port = port if port else self.port + self.port = final_port + self.bound_port = final_port config = uvicorn.Config( app, host=self.host, @@ -297,6 +300,7 @@ def _run(self, port=None): if self.controlCallback: self.controlCallback("error", str(e)) finally: + self.bound_port = None self.server = None # ---------------------------- @@ -382,11 +386,58 @@ async def api_get_settings( client: dict = Depends(require_scope(SCOPE_SETTINGS)) ): settings = settingsSvc.load_settings(_settings_path()) + return _settings_body(settings) + +def _settings_body(settings: dict) -> dict: return { "revision": settingsSvc.get_revision(settings), "settings": settingsSvc.writable_settings(settings), } +def _settings_log_message(payload: dict) -> str: + """Field names only: values and request bodies must never reach the log.""" + fields = ["port", "boot"] + webhook = payload.get("webhook") + if isinstance(webhook, dict): + fields.extend(f"webhook.{field}" for field in webhook) + return "Settings updated: " + ", ".join(fields) + +def _restart_required(settings: dict) -> bool: + """True only when the saved port differs from a known live bound port.""" + bound_port = get_runtime_provider("bound_port") + if bound_port is None: + return False + try: + return int(settings.get("port")) != int(bound_port) + except (TypeError, ValueError): + return False + +@app.put("/api/settings") +async def api_put_settings( + request: Request, + client: dict = Depends(require_scope(SCOPE_SETTINGS)) +): + try: + payload = await request.json() + except Exception: + raise HTTPException( + status_code=422, + detail="Request body must be valid JSON", + ) + try: + saved = settingsSvc.save_settings(_settings_path(), payload) + except settingsSvc.SettingsRevisionConflict as exc: + raise HTTPException(status_code=409, detail=exc.detail) + except settingsSvc.SettingsRuleError as exc: + raise HTTPException(status_code=400, detail=str(exc)) + except settingsSvc.SettingsValidationError as exc: + raise HTTPException(status_code=422, detail=str(exc)) + log_activities(_settings_log_message(payload)) + return { + **_settings_body(saved), + "restart_required": _restart_required(saved), + } + @app.post("/sms/") async def process_sms_req( item: SmsData, diff --git a/app/services/settingsSvc.py b/app/services/settingsSvc.py index 0b2a714..aeb2424 100644 --- a/app/services/settingsSvc.py +++ b/app/services/settingsSvc.py @@ -2,12 +2,13 @@ This module is deliberately free of Kivy, jnius and Android imports so the Settings contract can be tested on any platform. It takes an explicit path and -holds no module state. +holds only a process-local write lock, never Settings themselves. """ import json import os import tempfile +import threading from services.config import app_name from services.webhookSvc import ( @@ -15,11 +16,58 @@ DEFAULT_CAPACITY, DEFAULT_MAX_ATTEMPTS, DEFAULT_TIMEOUT, + is_valid_target, ) DEFAULT_PORT = 9292 DEFAULT_BOOT = False +# Ranges from the API contract in docs/remote-api.md. +PORT_MIN = 1025 +PORT_MAX = 65535 +TIMEOUT_MIN = 1 +TIMEOUT_MAX = 60 +MAX_ATTEMPTS_MIN = 1 +MAX_ATTEMPTS_MAX = 50 +BACKOFF_MIN_COUNT = 1 +BACKOFF_MAX_COUNT = 8 +BACKOFF_MAX_SECONDS = 3600 +CAPACITY_MIN = 10 +CAPACITY_MAX = 5000 +SECRET_MAX_LENGTH = 256 + +TOP_LEVEL_FIELDS = {"port", "boot", "webhook", "revision"} +REQUIRED_TOP_LEVEL_FIELDS = ("port", "boot", "webhook") +WRITABLE_WEBHOOK_FIELDS = ( + "enabled", + "url", + "timeout", + "max_attempts", + "backoff", + "capacity", +) +WEBHOOK_FIELDS = set(WRITABLE_WEBHOOK_FIELDS) | {"secret"} + + +class SettingsValidationError(ValueError): + """A malformed or out-of-range write (HTTP 422).""" + + +class SettingsRuleError(SettingsValidationError): + """A schema-valid write that breaks a business rule (HTTP 400).""" + + +class SettingsRevisionConflict(Exception): + """The write expected a Revision the stored Settings no longer have.""" + + def __init__(self, expected: int, current: int): + self.expected = expected + self.current = current + self.detail = ( + f"Revision conflict: expected {expected}, current revision is {current}" + ) + super().__init__(self.detail) + ## Defaults def default_webhook_settings() -> dict: @@ -74,6 +122,176 @@ def get_revision(settings: dict) -> int: except (TypeError, ValueError): return 0 +## Validation + +def _is_int(value) -> bool: + """JSON integers only: `true` is not a port, and `1.0` is not an integer.""" + return isinstance(value, int) and not isinstance(value, bool) + + +def _unknown_field_error(prefix: str, unknown) -> SettingsValidationError: + names = ", ".join(sorted(unknown)) + return SettingsValidationError(f"Unknown field(s) in {prefix}: {names}") + + +def validate_settings_payload(payload) -> dict: + """Validate a PUT body and return the normalized writable subset. + + Only schema and range checks happen here, so a malformed field is reported + before a stale Revision. Business rules live in `validate_business_rules`. + """ + if not isinstance(payload, dict): + raise SettingsValidationError("Request body must be a JSON object") + + unknown = set(payload) - TOP_LEVEL_FIELDS + if unknown: + raise _unknown_field_error("request", unknown) + + for field in REQUIRED_TOP_LEVEL_FIELDS: + if field not in payload: + raise SettingsValidationError(f"Missing required field: {field}") + + revision = payload.get("revision") + if "revision" in payload and not _is_int(revision): + raise SettingsValidationError("revision must be an integer") + + port = payload["port"] + if not _is_int(port) or not PORT_MIN <= port <= PORT_MAX: + raise SettingsValidationError( + f"port must be an integer between {PORT_MIN} and {PORT_MAX}" + ) + + boot = payload["boot"] + if not isinstance(boot, bool): + raise SettingsValidationError("boot must be a boolean") + + webhook = payload["webhook"] + if not isinstance(webhook, dict): + raise SettingsValidationError("webhook must be an object") + + unknown = set(webhook) - WEBHOOK_FIELDS + if unknown: + raise _unknown_field_error("webhook", unknown) + + for field in WRITABLE_WEBHOOK_FIELDS: + if field not in webhook: + raise SettingsValidationError( + f"Missing required webhook field: {field}" + ) + + enabled = webhook["enabled"] + if not isinstance(enabled, bool): + raise SettingsValidationError("webhook.enabled must be a boolean") + + url = webhook["url"] + if not isinstance(url, str): + raise SettingsValidationError("webhook.url must be a string") + + normalized_webhook = { + "enabled": enabled, + "url": url, + "timeout": _validate_int_range( + webhook["timeout"], + "webhook.timeout", + TIMEOUT_MIN, + TIMEOUT_MAX, + ), + "max_attempts": _validate_int_range( + webhook["max_attempts"], + "webhook.max_attempts", + MAX_ATTEMPTS_MIN, + MAX_ATTEMPTS_MAX, + ), + "backoff": _validate_backoff(webhook["backoff"]), + "capacity": _validate_int_range( + webhook["capacity"], + "webhook.capacity", + CAPACITY_MIN, + CAPACITY_MAX, + ), + } + + if "secret" in webhook: + secret = webhook["secret"] + if not isinstance(secret, str): + raise SettingsValidationError("webhook.secret must be a string") + if len(secret) > SECRET_MAX_LENGTH: + raise SettingsValidationError( + f"webhook.secret must be at most {SECRET_MAX_LENGTH} characters" + ) + normalized_webhook["secret"] = secret + + normalized = { + "port": port, + "boot": boot, + "webhook": normalized_webhook, + } + if "revision" in payload: + normalized["revision"] = revision + return normalized + + +def _validate_int_range(value, name: str, low: int, high: int) -> int: + if not _is_int(value) or not low <= value <= high: + raise SettingsValidationError( + f"{name} must be an integer between {low} and {high}" + ) + return value + + +def _validate_backoff(value) -> list: + if not isinstance(value, list) or not ( + BACKOFF_MIN_COUNT <= len(value) <= BACKOFF_MAX_COUNT + ): + raise SettingsValidationError( + "webhook.backoff must be a list of " + f"{BACKOFF_MIN_COUNT}-{BACKOFF_MAX_COUNT} integers" + ) + normalized = [] + for index, wait_for in enumerate(value): + if ( + not _is_int(wait_for) + or wait_for < 1 + or wait_for > BACKOFF_MAX_SECONDS + ): + raise SettingsValidationError( + f"webhook.backoff[{index}] must be an integer between 1 and " + f"{BACKOFF_MAX_SECONDS}" + ) + normalized.append(wait_for) + return normalized + + +def validate_business_rules(writable: dict): + """Business rules that are not schema errors (HTTP 400).""" + webhook = writable["webhook"] + if webhook["enabled"] and not is_valid_target(webhook["url"]): + raise SettingsRuleError( + "webhook.url must be a valid http(s) URL when webhook.enabled is true" + ) + + +def validate_merged_settings(settings: dict): + """Re-validate a merged Settings object before persisting it. + + The stored secret is type-checked but not length-checked: the 256-character + cap belongs to a secret being written, so an old over-long value must not + block a write that leaves the secret alone. + """ + webhook = settings.get("webhook") + if not isinstance(webhook, dict): + raise SettingsValidationError("webhook must be an object") + if not isinstance(webhook.get("secret", ""), str): + raise SettingsValidationError("webhook.secret must be a string") + validate_settings_payload({ + "port": settings.get("port"), + "boot": settings.get("boot"), + "webhook": { + field: webhook.get(field) + for field in WRITABLE_WEBHOOK_FIELDS + }, + }) + ## API shape def writable_settings(settings: dict) -> dict: @@ -100,6 +318,60 @@ def writable_settings(settings: dict) -> dict: ## Writes +# Serialises read-modify-write inside this process (the API and the UI are +# separate processes; that cross-process window is accepted and documented). +_write_lock = threading.Lock() + + +def apply_writable_settings(settings: dict, writable: dict) -> dict: + """Replace the writable subset, preserving internal and unknown fields. + + The secret follows sentinel semantics: absent from `writable` keeps the + stored value, so this function only writes it when the payload carried it. + """ + updated = dict(settings) + updated["port"] = writable["port"] + updated["boot"] = writable["boot"] + existing_webhook = updated.get("webhook") + webhook = dict(existing_webhook) if isinstance(existing_webhook, dict) else {} + incoming = writable["webhook"] + for field in WRITABLE_WEBHOOK_FIELDS: + webhook[field] = incoming[field] + webhook["backoff"] = list(incoming["backoff"]) + if "secret" in incoming: + webhook["secret"] = incoming["secret"] + updated["webhook"] = webhook + return updated + + +def save_settings(config_path: str, payload, expected_revision: int | None = None) -> dict: + """Validated read-merge-write of the writable Settings subset. + + `expected_revision` falls back to the payload's `revision` when omitted. + Order: schema/range (422) -> Revision (409) -> business rule (400) -> write. + On any error the persisted object is untouched and no temporary file is + left behind. + """ + writable = validate_settings_payload(payload) + with _write_lock: + current = load_settings(config_path) + if expected_revision is None: + expected_revision = writable.get("revision") + if ( + expected_revision is not None + and expected_revision != get_revision(current) + ): + raise SettingsRevisionConflict( + expected_revision, get_revision(current) + ) + validate_business_rules(writable) + merged = apply_writable_settings(current, writable) + validate_merged_settings(merged) + merged["revision"] = get_revision(current) + 1 + atomic_write_json(config_path, merged) + return merged + + def atomic_write_json(path: str, data): """Write JSON via a temporary file in the same directory, then replace.""" directory = os.path.dirname(path) diff --git a/app/tests/api_test_case.py b/app/tests/api_test_case.py index 721e4d4..7147e93 100644 --- a/app/tests/api_test_case.py +++ b/app/tests/api_test_case.py @@ -50,6 +50,12 @@ def write_config(self, config: dict): ) as config_file: json.dump(config, config_file) + def read_config(self) -> dict: + with open( + os.path.join(self.config_dir, "config.json"), encoding="utf-8" + ) as config_file: + return json.load(config_file) + def read_key_store(self) -> dict: with open( os.path.join(self.config_dir, "keys.json"), encoding="utf-8" diff --git a/app/tests/test_remote_api.py b/app/tests/test_remote_api.py index e3b69a2..a700504 100644 --- a/app/tests/test_remote_api.py +++ b/app/tests/test_remote_api.py @@ -1,4 +1,6 @@ +import glob import os +import threading import time from api_test_case import ApiTestCase @@ -227,3 +229,433 @@ def test_settings_only_key_cannot_send_sms(self): ) self.assertEqual(response.status_code, 403) + + +class RecordingLogger: + + def __init__(self): + self.messages = [] + self.written = threading.Event() + self._lock = threading.Lock() + + def write_log(self, message: str): + with self._lock: + self.messages.append(message) + self.written.set() + + def text(self) -> str: + with self._lock: + return "\n".join(self.messages) + + +class SettingsWriteTestCase(ApiTestCase): + + def valid_payload(self, **overrides) -> dict: + payload = { + "port": 9292, + "boot": False, + "webhook": { + "enabled": False, + "url": "", + "timeout": 10, + "max_attempts": 3, + "backoff": [5, 30], + "capacity": 100, + }, + } + webhook_overrides = overrides.pop("webhook", None) + if webhook_overrides: + payload["webhook"].update(webhook_overrides) + payload.update(overrides) + return payload + + def stored_config(self) -> dict: + return { + "app": "opensms", + "port": 9292, + "boot": False, + "permissions": True, + "revision": 3, + "unknown_top_level": "internal", + "webhook": { + "enabled": False, + "url": "", + "secret": "old-secret", + "timeout": 10, + "max_attempts": 3, + "backoff": [5, 30], + "capacity": 100, + "unknown_webhook": "internal", + }, + } + + def put(self, payload: dict, raw_key: str): + return self.client.put( + "/api/settings", json=payload, headers=self.auth(raw_key) + ) + + def tmp_files(self) -> list: + return glob.glob(os.path.join(self.config_dir, "*.tmp")) + + +class SettingsWriteTests(SettingsWriteTestCase): + + def test_put_replaces_the_writable_subset_and_bumps_the_revision(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + + response = self.put(self.valid_payload( + port=9393, + boot=True, + webhook={ + "enabled": True, + "url": "https://proxy.example.lan/hooks/opensms", + "timeout": 7, + "max_attempts": 4, + "backoff": [1, 2, 3], + "capacity": 250, + }, + ), raw_key) + + self.assertEqual(response.status_code, 200) + body = response.json() + self.assertEqual(body["revision"], 4) + self.assertEqual(body["settings"]["port"], 9393) + self.assertTrue(body["settings"]["boot"]) + self.assertEqual(body["settings"]["webhook"], { + "enabled": True, + "url": "https://proxy.example.lan/hooks/opensms", + "secret_set": True, + "timeout": 7, + "max_attempts": 4, + "backoff": [1, 2, 3], + "capacity": 250, + }) + self.assertNotIn("old-secret", response.text) + + on_disk = self.read_config() + self.assertEqual(on_disk["revision"], 4) + self.assertEqual(on_disk["port"], 9393) + self.assertTrue(on_disk["boot"]) + self.assertEqual(on_disk["app"], "opensms") + self.assertTrue(on_disk["permissions"]) + self.assertEqual(on_disk["unknown_top_level"], "internal") + self.assertEqual(on_disk["webhook"]["unknown_webhook"], "internal") + self.assertEqual(on_disk["webhook"]["secret"], "old-secret") + self.assertEqual(self.tmp_files(), []) + + def test_omitting_the_secret_keeps_the_stored_secret(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + + response = self.put(self.valid_payload(), raw_key) + + self.assertEqual(response.status_code, 200) + self.assertTrue(response.json()["settings"]["webhook"]["secret_set"]) + self.assertEqual(self.read_config()["webhook"]["secret"], "old-secret") + + def test_an_empty_secret_clears_the_stored_secret(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + + response = self.put( + self.valid_payload(webhook={"secret": ""}), raw_key + ) + + self.assertEqual(response.status_code, 200) + self.assertFalse(response.json()["settings"]["webhook"]["secret_set"]) + self.assertEqual(self.read_config()["webhook"]["secret"], "") + + def test_a_non_empty_secret_replaces_the_stored_secret(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + + response = self.put( + self.valid_payload(webhook={"secret": "new-shared-secret"}), raw_key + ) + + self.assertEqual(response.status_code, 200) + self.assertTrue(response.json()["settings"]["webhook"]["secret_set"]) + self.assertEqual( + self.read_config()["webhook"]["secret"], "new-shared-secret" + ) + self.assertNotIn("new-shared-secret", response.text) + + def test_put_rejects_a_secret_longer_than_256_characters(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + + response = self.put( + self.valid_payload(webhook={"secret": "x" * 257}), raw_key + ) + + self.assertEqual(response.status_code, 422) + self.assertIsInstance(response.json()["detail"], str) + self.assertEqual(self.read_config()["webhook"]["secret"], "old-secret") + + +class SettingsValidationTests(SettingsWriteTestCase): + + def test_put_rejects_invalid_values_and_leaves_settings_unchanged(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + before = self.read_config() + + cases = { + "port below range": {"port": 1024}, + "port above range": {"port": 65536}, + "port not an integer": {"port": "9292"}, + "port is a boolean": {"port": True}, + "boot is not a boolean": {"boot": "yes"}, + "enabled is not a boolean": {"webhook": {"enabled": "yes"}}, + "url is not a string": {"webhook": {"url": 42}}, + "timeout below range": {"webhook": {"timeout": 0}}, + "timeout above range": {"webhook": {"timeout": 61}}, + "max attempts below range": {"webhook": {"max_attempts": 0}}, + "max attempts above range": {"webhook": {"max_attempts": 51}}, + "backoff empty": {"webhook": {"backoff": []}}, + "backoff has a zero": {"webhook": {"backoff": [0]}}, + "backoff has a negative value": {"webhook": {"backoff": [-1]}}, + "backoff above range": {"webhook": {"backoff": [3601]}}, + "backoff too long": {"webhook": {"backoff": [1] * 9}}, + "backoff is not a list": {"webhook": {"backoff": "5"}}, + "capacity below range": {"webhook": {"capacity": 9}}, + "capacity above range": {"webhook": {"capacity": 5001}}, + "unknown top-level field": {"unknown_top_level": 1}, + "unknown webhook field": {"webhook": {"unknown_webhook": 1}}, + } + + for name, overrides in cases.items(): + with self.subTest(name): + response = self.put(self.valid_payload(**overrides), raw_key) + + self.assertEqual(response.status_code, 422, response.text) + self.assertIsInstance(response.json()["detail"], str) + self.assertTrue(response.json()["detail"]) + self.assertEqual(self.read_config(), before) + self.assertEqual(self.tmp_files(), []) + + def test_put_rejects_missing_required_fields(self): + raw_key = self.add_api_key() + cases = { + "port": "port", + "boot": "boot", + "webhook": "webhook", + "webhook.enabled": ("webhook", "enabled"), + "webhook.url": ("webhook", "url"), + "webhook.timeout": ("webhook", "timeout"), + "webhook.max_attempts": ("webhook", "max_attempts"), + "webhook.backoff": ("webhook", "backoff"), + "webhook.capacity": ("webhook", "capacity"), + } + + for name, path in cases.items(): + with self.subTest(name): + payload = self.valid_payload() + if isinstance(path, tuple): + del payload[path[0]][path[1]] + else: + del payload[path] + + response = self.put(payload, raw_key) + + self.assertEqual(response.status_code, 422, response.text) + self.assertIn(name.split(".")[-1], response.json()["detail"]) + + def test_put_rejects_enabling_forwarding_without_a_valid_target(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + before = self.read_config() + + for name, url in { + "empty target": "", + "not a url": "not-a-url", + "not http": "ftp://proxy.example.lan/hooks", + "no host": "http:///hooks", + }.items(): + with self.subTest(name): + response = self.put( + self.valid_payload(webhook={"enabled": True, "url": url}), + raw_key, + ) + + self.assertEqual(response.status_code, 400, response.text) + self.assertIsInstance(response.json()["detail"], str) + self.assertEqual(self.read_config(), before) + self.assertEqual(self.tmp_files(), []) + + def test_put_rejects_a_non_object_body(self): + raw_key = self.add_api_key() + + response = self.client.put( + "/api/settings", json=["not", "an", "object"], + headers=self.auth(raw_key), + ) + + self.assertEqual(response.status_code, 422) + self.assertIsInstance(response.json()["detail"], str) + + def test_put_rejects_malformed_json(self): + raw_key = self.add_api_key() + + response = self.client.put( + "/api/settings", + content=b'{"port": ', + headers={**self.auth(raw_key), "Content-Type": "application/json"}, + ) + + self.assertEqual(response.status_code, 422) + self.assertIsInstance(response.json()["detail"], str) + + +class SettingsRevisionTests(SettingsWriteTestCase): + + def test_a_stale_revision_is_a_conflict(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + before = self.read_config() + + response = self.put(self.valid_payload(revision=2), raw_key) + + self.assertEqual(response.status_code, 409) + self.assertIsInstance(response.json()["detail"], str) + self.assertEqual(self.read_config(), before) + self.assertEqual(self.tmp_files(), []) + + def test_a_matching_revision_succeeds(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + + response = self.put(self.valid_payload(revision=3), raw_key) + + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["revision"], 4) + + def test_an_absent_revision_is_last_writer_wins(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + + response = self.put(self.valid_payload(), raw_key) + + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["revision"], 4) + + def test_a_non_integer_revision_is_rejected(self): + raw_key = self.add_api_key() + + response = self.put(self.valid_payload(revision="3"), raw_key) + + self.assertEqual(response.status_code, 422) + + def test_schema_errors_are_reported_before_a_stale_revision(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + + response = self.put( + self.valid_payload(revision=1, port=80), raw_key + ) + + self.assertEqual(response.status_code, 422) + + def test_a_stale_revision_is_reported_before_a_business_rule(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + + response = self.put( + self.valid_payload( + revision=1, webhook={"enabled": True, "url": ""} + ), + raw_key, + ) + + self.assertEqual(response.status_code, 409) + + +class SettingsRestartRequiredTests(SettingsWriteTestCase): + + def test_restart_is_not_required_when_the_saved_port_is_bound(self): + postApi.set_runtime_providers({"bound_port": lambda: 9292}) + raw_key = self.add_api_key() + + response = self.put(self.valid_payload(port=9292), raw_key) + + self.assertEqual(response.status_code, 200) + self.assertFalse(response.json()["restart_required"]) + + def test_restart_is_required_when_the_saved_port_differs(self): + postApi.set_runtime_providers({"bound_port": lambda: 9292}) + raw_key = self.add_api_key() + + response = self.put(self.valid_payload(port=9393), raw_key) + + self.assertEqual(response.status_code, 200) + self.assertTrue(response.json()["restart_required"]) + + def test_a_pending_port_change_keeps_reporting_restart_required(self): + config = self.stored_config() + config["port"] = 9393 + self.write_config(config) + postApi.set_runtime_providers({"bound_port": lambda: 9292}) + raw_key = self.add_api_key() + + response = self.put(self.valid_payload(port=9393), raw_key) + + self.assertEqual(response.status_code, 200) + self.assertTrue(response.json()["restart_required"]) + + def test_restart_is_not_required_when_the_bound_port_is_unknown(self): + raw_key = self.add_api_key() + + response = self.put(self.valid_payload(port=9393), raw_key) + + self.assertEqual(response.status_code, 200) + self.assertFalse(response.json()["restart_required"]) + + +class SettingsWriteAuthTests(SettingsWriteTestCase): + + def test_put_refuses_a_missing_key(self): + response = self.client.put("/api/settings", json=self.valid_payload()) + + self.assertEqual(response.status_code, 403) + + def test_put_refuses_an_invalid_key(self): + self.add_api_key() + + response = self.put(self.valid_payload(), "osms_not_a_real_key") + + self.assertEqual(response.status_code, 401) + + def test_put_requires_the_settings_scope(self): + raw_key = self.add_api_key(scopes=("sms:write",)) + + response = self.put(self.valid_payload(), raw_key) + + self.assertEqual(response.status_code, 403) + + +class SettingsWriteLoggingTests(SettingsWriteTestCase): + + def test_logs_name_fields_without_the_secret_or_the_body(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + logger = RecordingLogger() + postApi.set_api_logger(logger) + + response = self.put(self.valid_payload( + webhook={ + "enabled": True, + "url": "https://proxy.example.lan/hooks/SENSITIVE-PATH", + "secret": "super-duper-secret", + }, + ), raw_key) + + self.assertEqual(response.status_code, 200) + self.assertTrue(logger.written.wait(timeout=2)) + logged = logger.text() + self.assertIn("Settings updated", logged) + self.assertIn("port", logged) + self.assertIn("webhook", logged) + self.assertNotIn("super-duper-secret", logged) + self.assertNotIn("SENSITIVE-PATH", logged) + self.assertNotIn("old-secret", logged) From 30c967385c2333b4bed32aea2f27d184aab5bb6a Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 17:26:54 +0100 Subject: [PATCH 05/20] fix: merge local settings saves over a fresh read --- app/main.py | 181 +++++++++++++------- app/services/settingsSvc.py | 99 +++++++++-- app/tests/test_settings_local_save.py | 231 ++++++++++++++++++++++++++ 3 files changed, 440 insertions(+), 71 deletions(-) create mode 100644 app/tests/test_settings_local_save.py diff --git a/app/main.py b/app/main.py index 0528ecd..2336ca7 100644 --- a/app/main.py +++ b/app/main.py @@ -40,13 +40,13 @@ from screens.settings import SettingsBox, ApiKeyTxtbox # import services +from services import settingsSvc from services.postApi import has_api_keys, generate_new_api_key from services.netSvc import get_network_ips from services.config import __version__, app_name from services.webhookSvc import ( default_webhook_config, format_webhook_status, - get_webhook_config, is_valid_target, normalize_webhook_config, read_webhook_status, @@ -121,6 +121,11 @@ def __init__(self, **kwargs): self.serial_dropdown_menu = None self.webhook_status_path = None self.webhook_switch_guard = False + self.port_loaded = None + self.boot_loaded = False + self.webhook_enabled_loaded = False + self.webhook_url_loaded = "" + self.webhook_secret_loaded = "" self.config_template = { "app": app_name, "port": 9292, @@ -215,17 +220,17 @@ def on_start(self): self.config_dir, "webhook_status.json" ) auto_start_sw = self.root.ids.settings_scr.ids.auto_start_sw - port_no_inp = self.root.ids.settings_scr.ids.port_no_inp if os.path.exists(self.app_config): - with open(self.app_config, "r", encoding="utf-8") as cf: - saved_config = json.load(cf) - self.config_template["port"] = int(saved_config["port"]) - self.config_template["boot"] = saved_config["boot"] - self.config_template["permissions"] = saved_config.get("permissions", False) - self.config_template["webhook"] = normalize_webhook_config( - saved_config.get("webhook") + saved_config = settingsSvc.load_settings(self.app_config) + self.config_template = saved_config + self.config_template["port"] = int( + saved_config.get("port") or settingsSvc.DEFAULT_PORT + ) + self.config_template["boot"] = bool(saved_config.get("boot")) + self.config_template["permissions"] = bool( + saved_config.get("permissions", False) ) - webhook_cfg = self.config_template["webhook"] + webhook_cfg = normalize_webhook_config(saved_config.get("webhook")) print( "start config check: " f"port={self.config_template['port']}, " @@ -243,8 +248,7 @@ def on_start(self): auto_start_sw.active = False else: self.write_app_conf() - port_no_inp.text = str(self.config_template["port"]) - self.refresh_webhook_view() + self.refresh_settings_view() self.check_if_key_exists() self.stop_resp_loop() self.resp_thred = Thread(target=self.resp_check_loop, daemon=True) @@ -624,23 +628,49 @@ def start_serial_connection(self, instance=None): ## Settings sections def save_settings(self, instance=None, control_txt="none"): - port_no_inp = self.root.ids.settings_scr.ids.port_no_inp + boot = None if control_txt == "switch": - self.config_template["boot"] = not self.config_template["boot"] - if port_no_inp.text != "": - port_no = int(port_no_inp.text) - if port_no >= 1025: - self.config_template["port"] = port_no - self.req_template["port"] = port_no - webhook_enabled, webhook_url, webhook_secret = self.read_webhook_inputs() - if not self.validate_webhook(webhook_enabled, webhook_url): + boot = not self.config_template["boot"] + form = self.read_settings_form(boot=boot) + if form is None: return - self.save_webhook_config( - webhook_enabled, webhook_url, webhook_secret + if not self.persist_settings_form(form): + return + print( + f"Service on start: {self.config_template['boot']}, " + f"port: {self.config_template['port']}" ) - print(f"Service on start: {self.config_template["boot"]}, port: {self.config_template["port"]}") Clock.schedule_once(lambda dt: self.show_toast_msg("Settings has been saved.")) + def read_settings_form(self, boot=None): + """Return the form-owned writable subset, or None when it is invalid. + + Only fields the operator actually edited are carried; everything else + is filled from a fresh read when the form is persisted, so a remote + change to a field left alone on this screen survives the save. + """ + settings = self.root.ids.settings_scr.ids + form = {} + port_text = (settings.port_no_inp.text or "").strip() + if port_text != self.port_loaded: + try: + form["port"] = int(port_text) + except ValueError: + self.show_toast_msg( + "Port must be an integer between " + f"{settingsSvc.PORT_MIN} and {settingsSvc.PORT_MAX}", + is_error=True, + ) + return None + boot_value = self.config_template["boot"] if boot is None else boot + if boot_value != self.boot_loaded: + form["boot"] = boot_value + webhook = self.read_webhook_form() + if webhook is None: + return None + form["webhook"] = webhook + return form + def read_webhook_inputs(self): settings = self.root.ids.settings_scr.ids return ( @@ -649,13 +679,41 @@ def read_webhook_inputs(self): settings.webhook_secret_inp.text.strip(), ) - def save_webhook_config(self, enabled: bool, url: str, secret: str): - self.config_template["webhook"] = { - "enabled": enabled, - "url": url, - "secret": secret, - } - Thread(target=self.write_app_conf, daemon=True).start() + def read_webhook_form(self): + """Return the Webhook fields the operator edited, or None when invalid. + + The secret and target follow the same rule as the port: an untouched + field is omitted, so a change made over the network is preserved. + """ + enabled, url, secret = self.read_webhook_inputs() + if not self.validate_webhook(enabled, url): + return None + webhook = {} + if enabled != self.webhook_enabled_loaded: + webhook["enabled"] = enabled + if url != self.webhook_url_loaded: + webhook["url"] = url + if secret != self.webhook_secret_loaded: + webhook["secret"] = secret + return webhook + + def persist_settings_form(self, form): + """Merge the form over fresh Settings and persist it atomically.""" + try: + saved = settingsSvc.save_local_settings(self.app_config, form) + except settingsSvc.SettingsValidationError as exc: + self.show_toast_msg(str(exc), is_error=True) + return False + self.apply_persisted_settings(saved) + return True + + def apply_persisted_settings(self, settings: dict): + """Adopt freshly persisted Settings and show them.""" + self.config_template = dict(settings) + self.req_template["port"] = int( + self.config_template.get("port") or settingsSvc.DEFAULT_PORT + ) + self.refresh_settings_view() def webhook_switch_active(self, instance, value): """Apply the toggle immediately, instead of waiting for Save. @@ -665,20 +723,17 @@ def webhook_switch_active(self, instance, value): """ if self.webhook_switch_guard: return - enabled = bool(value) - _, url, secret = self.read_webhook_inputs() - if enabled and not is_valid_target(url): + webhook = self.read_webhook_form() + if webhook is None: self.webhook_switch_guard = True instance.active = False self.webhook_switch_guard = False - self.show_toast_msg( - "Add a valid http:// or https:// webhook URL first", - is_error=True, - ) return - self.save_webhook_config(enabled, url, secret) + if not self.persist_settings_form({"webhook": webhook}): + self.refresh_webhook_view() + return self.show_toast_msg( - "Webhook enabled" if enabled else "Webhook disabled" + "Webhook enabled" if bool(value) else "Webhook disabled" ) def validate_webhook(self, enabled: bool, url: str) -> bool: @@ -705,14 +760,18 @@ def refresh_webhook_view(self): self.webhook_switch_guard = False settings.webhook_url_inp.text = webhook["url"] settings.webhook_secret_inp.text = webhook["secret"] + self.webhook_enabled_loaded = webhook["enabled"] + self.webhook_url_loaded = webhook["url"].strip() + self.webhook_secret_loaded = webhook["secret"].strip() self.refresh_webhook_status() - def reload_webhook_config(self): - """Pick up the persisted config (e.g. after an external change).""" - self.config_template["webhook"] = get_webhook_config( - self.app_config + def reload_settings_config(self): + """Re-read persisted Settings (e.g. after an external change).""" + if not self.app_config or not os.path.exists(self.app_config): + return + self.apply_persisted_settings( + settingsSvc.load_settings(self.app_config) ) - self.refresh_webhook_view() def refresh_webhook_status(self): if not self.webhook_status_path: @@ -754,21 +813,31 @@ def show_webhook_test_result(self, ok: bool, status, error): def refresh_settings_view(self): auto_start_sw = self.root.ids.settings_scr.ids.auto_start_sw port_no_inp = self.root.ids.settings_scr.ids.port_no_inp - if self.config_template["boot"]: - auto_start_sw.active = True - else: - auto_start_sw.active = False + self.boot_loaded = bool(self.config_template["boot"]) + auto_start_sw.active = self.boot_loaded port_no_inp.text = str(self.config_template["port"]) + self.port_loaded = port_no_inp.text.strip() self.refresh_webhook_view() def reset_settings(self, instance=None): - self.config_template["port"] = 9292 - self.config_template["boot"] = False - self.config_template["webhook"] = default_webhook_config() - self.req_template["port"] = 9292 + defaults = settingsSvc.default_settings() + default_webhook = defaults["webhook"] + form = { + "port": defaults["port"], + "boot": defaults["boot"], + "webhook": { + "enabled": default_webhook["enabled"], + "url": default_webhook["url"], + "secret": default_webhook["secret"], + "timeout": default_webhook["timeout"], + "max_attempts": default_webhook["max_attempts"], + "backoff": list(default_webhook["backoff"]), + "capacity": default_webhook["capacity"], + }, + } + if not self.persist_settings_form(form): + return print("Settings reset has been done!") - self.refresh_settings_view() - Thread(target=self.write_app_conf, daemon=True).start() Clock.schedule_once(lambda dt: self.show_toast_msg("Settings reset has been done!")) ## App or UI related things @@ -850,7 +919,7 @@ def on_main_screen_entry(self, instance=None): def on_settings_entry(self, instance=None): self.root.ids.top_back_btn.opacity = 1 self.root.ids.top_back_btn.disabled = False - self.reload_webhook_config() + self.reload_settings_config() def back_button_action(self, instance=None): if self.root.ids.screen_manager.current in ["Settings", "Logs"]: diff --git a/app/services/settingsSvc.py b/app/services/settingsSvc.py index aeb2424..500d692 100644 --- a/app/services/settingsSvc.py +++ b/app/services/settingsSvc.py @@ -344,6 +344,72 @@ def apply_writable_settings(settings: dict, writable: dict) -> dict: return updated +def merge_local_settings(current: dict, form: dict) -> dict: + """Overlay the fields the on-device form owns on freshly read Settings. + + Fields the form does not own keep the value that was just read: the + Webhook retry settings, the secret when the form left it untouched, and + every internal or unknown on-disk field. This is what lets a change made + over the network survive a later local save. + """ + if not isinstance(form, dict): + raise SettingsValidationError("Request body must be a JSON object") + + unknown = set(form) - TOP_LEVEL_FIELDS + if unknown: + raise _unknown_field_error("request", unknown) + + fresh = writable_settings(current) + merged = { + "port": fresh["port"], + "boot": fresh["boot"], + "webhook": { + field: fresh["webhook"][field] + for field in WRITABLE_WEBHOOK_FIELDS + }, + } + for field in ("port", "boot"): + if field in form: + merged[field] = form[field] + if "revision" in form: + merged["revision"] = form["revision"] + if "webhook" in form: + form_webhook = form["webhook"] + if not isinstance(form_webhook, dict): + raise SettingsValidationError("webhook must be an object") + unknown = set(form_webhook) - WEBHOOK_FIELDS + if unknown: + raise _unknown_field_error("webhook", unknown) + merged["webhook"].update(form_webhook) + return merged + + +def _store_writable( + config_path: str, writable: dict, expected_revision: int | None +) -> dict: + """Validate and persist a normalized writable subset. + + The caller must hold `_write_lock`, so the read-merge-write stays in one + process-local critical section. + """ + current = load_settings(config_path) + if expected_revision is None: + expected_revision = writable.get("revision") + if ( + expected_revision is not None + and expected_revision != get_revision(current) + ): + raise SettingsRevisionConflict( + expected_revision, get_revision(current) + ) + validate_business_rules(writable) + merged = apply_writable_settings(current, writable) + validate_merged_settings(merged) + merged["revision"] = get_revision(current) + 1 + atomic_write_json(config_path, merged) + return merged + + def save_settings(config_path: str, payload, expected_revision: int | None = None) -> dict: """Validated read-merge-write of the writable Settings subset. @@ -353,23 +419,26 @@ def save_settings(config_path: str, payload, expected_revision: int | None = Non left behind. """ writable = validate_settings_payload(payload) + with _write_lock: + return _store_writable(config_path, writable, expected_revision) + + +def save_local_settings( + config_path: str, form: dict, expected_revision: int | None = None +) -> dict: + """Save the on-device form's fields over a fresh read of Settings. + + `form` carries only the fields the screen owns (port, boot, and some + Webhook fields). Everything else keeps its freshly read value, so a remote + change is not undone and the Revision is bumped rather than reset. + Validation is the same one the API uses. + """ with _write_lock: current = load_settings(config_path) - if expected_revision is None: - expected_revision = writable.get("revision") - if ( - expected_revision is not None - and expected_revision != get_revision(current) - ): - raise SettingsRevisionConflict( - expected_revision, get_revision(current) - ) - validate_business_rules(writable) - merged = apply_writable_settings(current, writable) - validate_merged_settings(merged) - merged["revision"] = get_revision(current) + 1 - atomic_write_json(config_path, merged) - return merged + writable = validate_settings_payload( + merge_local_settings(current, form) + ) + return _store_writable(config_path, writable, expected_revision) def atomic_write_json(path: str, data): diff --git a/app/tests/test_settings_local_save.py b/app/tests/test_settings_local_save.py new file mode 100644 index 0000000..2327d3a --- /dev/null +++ b/app/tests/test_settings_local_save.py @@ -0,0 +1,231 @@ +"""Shared-seam tests for a local (on-device) Settings save. + +The Kivy screen has no automated seam, so the merge that keeps a remote change +alive is exercised through `settingsSvc.save_local_settings`: the caller passes +only the fields the form owns, exactly as the screen does, and the module fills +the rest from a fresh read. +""" + +import glob +import json +import os +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from services import settingsSvc + + +class LocalSaveTestCase(unittest.TestCase): + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.config_path = os.path.join(self.tmp.name, "config.json") + self.write_config(self.stored_config()) + + def tearDown(self): + self.tmp.cleanup() + + def stored_config(self) -> dict: + return { + "app": "opensms", + "port": 9292, + "boot": False, + "permissions": True, + "revision": 3, + "unknown_top_level": "internal", + "webhook": { + "enabled": True, + "url": "https://remote.example.lan/hooks/opensms", + "secret": "remote-secret", + "timeout": 7, + "max_attempts": 4, + "backoff": [1, 2, 3], + "capacity": 250, + "unknown_webhook": "internal", + }, + } + + def write_config(self, config: dict): + with open(self.config_path, "w", encoding="utf-8") as config_file: + json.dump(config, config_file) + + def read_config(self) -> dict: + with open(self.config_path, encoding="utf-8") as config_file: + return json.load(config_file) + + def tmp_files(self) -> list: + return glob.glob(os.path.join(self.tmp.name, "*.tmp")) + + def screen_form(self, current: dict, **overrides) -> dict: + """Mimic the screen showing freshly read Settings, then editing them. + + Only the fields the screen owns are carried; the secret is omitted + unless the operator typed a new one. + """ + writable = settingsSvc.writable_settings(current) + form = { + "port": writable["port"], + "boot": writable["boot"], + "webhook": { + "enabled": writable["webhook"]["enabled"], + "url": writable["webhook"]["url"], + }, + } + webhook_overrides = overrides.pop("webhook", None) + if webhook_overrides: + form["webhook"].update(webhook_overrides) + form.update(overrides) + return form + + +class LocalSaveMergeTests(LocalSaveTestCase): + + def test_entering_then_saving_keeps_a_remote_webhook_target(self): + # The screen re-reads on entry, so it shows the remote target. + current = settingsSvc.load_settings(self.config_path) + form = self.screen_form(current, port=9393) + + saved = settingsSvc.save_local_settings(self.config_path, form) + + self.assertEqual(saved["revision"], 4) + self.assertEqual(saved["port"], 9393) + webhook = saved["webhook"] + self.assertEqual( + webhook["url"], "https://remote.example.lan/hooks/opensms" + ) + self.assertEqual(webhook["secret"], "remote-secret") + on_disk = self.read_config() + self.assertEqual(on_disk["revision"], 4) + self.assertEqual(on_disk["webhook"]["url"], webhook["url"]) + self.assertEqual(on_disk["webhook"]["secret"], "remote-secret") + + def test_fields_the_form_does_not_own_keep_their_freshly_read_values(self): + # A port-only local save must not touch the Webhook at all. + form = {"port": 9393} + + saved = settingsSvc.save_local_settings(self.config_path, form) + + webhook = saved["webhook"] + self.assertEqual( + webhook["url"], "https://remote.example.lan/hooks/opensms" + ) + self.assertEqual(webhook["secret"], "remote-secret") + self.assertEqual(webhook["timeout"], 7) + self.assertEqual(webhook["max_attempts"], 4) + self.assertEqual(webhook["backoff"], [1, 2, 3]) + self.assertEqual(webhook["capacity"], 250) + self.assertEqual(saved["unknown_top_level"], "internal") + self.assertEqual(webhook["unknown_webhook"], "internal") + self.assertEqual(saved["permissions"], True) + self.assertEqual(self.read_config(), saved) + + def test_an_untouched_secret_keeps_the_stored_value(self): + form = { + "webhook": { + "enabled": True, + "url": "https://new.example.lan/hooks/opensms", + } + } + + saved = settingsSvc.save_local_settings(self.config_path, form) + + self.assertEqual( + saved["webhook"]["url"], + "https://new.example.lan/hooks/opensms", + ) + self.assertEqual(saved["webhook"]["secret"], "remote-secret") + + def test_an_edited_secret_replaces_the_stored_value(self): + form = {"webhook": {"secret": "local-secret"}} + + saved = settingsSvc.save_local_settings(self.config_path, form) + + self.assertEqual(saved["webhook"]["secret"], "local-secret") + self.assertEqual(self.read_config()["webhook"]["secret"], "local-secret") + + def test_clearing_the_secret_field_clears_the_stored_secret(self): + form = {"webhook": {"secret": ""}} + + saved = settingsSvc.save_local_settings(self.config_path, form) + + self.assertEqual(saved["webhook"]["secret"], "") + self.assertEqual(self.read_config()["webhook"]["secret"], "") + + def test_a_legacy_config_gains_defaults_and_keeps_a_saved_port(self): + self.write_config({ + "app": "opensms", + "port": 9292, + "boot": False, + "webhook": { + "enabled": False, + "url": "", + "secret": "", + }, + }) + + saved = settingsSvc.save_local_settings(self.config_path, {"port": 9393}) + + self.assertEqual(saved["revision"], 1) + self.assertEqual(saved["port"], 9393) + self.assertEqual(saved["webhook"]["timeout"], 10) + self.assertEqual(saved["webhook"]["max_attempts"], 3) + self.assertEqual(saved["webhook"]["backoff"], [5, 30]) + self.assertEqual(saved["webhook"]["capacity"], 100) + + +class LocalSaveValidationTests(LocalSaveTestCase): + + def assert_rejected(self, form: dict, error_class): + before = self.read_config() + + with self.assertRaises(error_class): + settingsSvc.save_local_settings(self.config_path, form) + + self.assertEqual(self.read_config(), before) + self.assertEqual(self.tmp_files(), []) + + def test_an_out_of_range_port_rejects_the_whole_save(self): + for port in ( + settingsSvc.PORT_MIN - 1, + settingsSvc.PORT_MAX + 1, + ): + with self.subTest(port=port): + self.assert_rejected( + {"port": port}, settingsSvc.SettingsValidationError + ) + + def test_a_non_integer_port_rejects_the_whole_save(self): + self.assert_rejected( + {"port": "9393"}, settingsSvc.SettingsValidationError + ) + + def test_a_boolean_port_rejects_the_whole_save(self): + self.assert_rejected({"port": True}, settingsSvc.SettingsValidationError) + + def test_enabling_forwarding_without_a_valid_target_rejects_the_save(self): + for url in ("", "not-a-url", "ftp://proxy.example.lan/hooks", "http:///x"): + with self.subTest(url=url): + self.assert_rejected( + { + "webhook": { + "enabled": True, + "url": url, + } + }, + settingsSvc.SettingsRuleError, + ) + + def test_both_port_bounds_are_accepted(self): + for port in (settingsSvc.PORT_MIN, settingsSvc.PORT_MAX): + with self.subTest(port=port): + saved = settingsSvc.save_local_settings( + self.config_path, {"port": port} + ) + self.assertEqual(saved["port"], port) + + +if __name__ == "__main__": + unittest.main() From 5d33ef95644bb3561000bed1b1e2542b5bd2792a Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 17:34:05 +0100 Subject: [PATCH 06/20] feat: report forwarding health through the API --- app/services/appSvc.py | 5 +- app/services/postApi.py | 183 ++++++++++++++++++++++- app/tests/test_remote_api.py | 275 +++++++++++++++++++++++++++++++++++ 3 files changed, 461 insertions(+), 2 deletions(-) diff --git a/app/services/appSvc.py b/app/services/appSvc.py index ae3440c..17304a0 100644 --- a/app/services/appSvc.py +++ b/app/services/appSvc.py @@ -94,9 +94,12 @@ def request_stop(signum=None, frame=None): status_path=webhook_status_file, log=log_activities, ) -# Let the API compare a saved port with the one the live server is bound to. +# Let the API report live facts: the port the server is bound to, whether it is +# running, and how many Webhooks are waiting in the Outbox. set_runtime_providers({ + "running": lambda: app_api_server.bound_port is not None, "bound_port": lambda: app_api_server.bound_port, + "outbox_pending": lambda: webhook_dispatcher.pending_count(), }) ## functions diff --git a/app/services/postApi.py b/app/services/postApi.py index 05a2a04..0036946 100644 --- a/app/services/postApi.py +++ b/app/services/postApi.py @@ -5,6 +5,7 @@ from datetime import datetime, timezone from threading import Thread, Lock from os.path import join +from urllib.parse import urlparse import json #from functools import partial @@ -18,7 +19,7 @@ from services.smsApi import SmsCrossPlatform, clean_and_validate_phone from services.logSvc import LogService from services.config import __version__, app_name -from services import settingsSvc +from services import netSvc, settingsSvc, webhookSvc # OS specific #try: @@ -381,6 +382,186 @@ async def api_health( "uptime_s": uptime_s, } +def _status_runtime(name: str, fallback=None): + """A runtime provider value, or `fallback` when none is registered.""" + if name not in _runtime: + return fallback + return get_runtime_provider(name, fallback) + + +def _live_server(): + return getattr(app.state, "server", None) + + +def _live_attr(name: str): + return getattr(_live_server(), name, None) + + +def _status_uptime_s() -> int: + started_at = _live_attr("started_at") or _started_at + if not started_at: + return 0 + return max(0, int(time.time() - started_at)) + + +def _service_status() -> dict: + """Read the service transition log, reporting unknown fields honestly.""" + try: + with open( + join(get_config_dir(), "resp.json"), "r", encoding="utf-8" + ) as response_file: + resp = json.load(response_file) + except Exception: + resp = None + if not isinstance(resp, dict): + resp = {} + return { + field: ( + resp.get(field) + if isinstance(resp.get(field), str) and resp.get(field) + else "unknown" + ) + for field in ("server", "serial", "provider") + } + + +def _network_status(warnings: list) -> dict: + """Return the network interface lists, or empty lists on any failure.""" + try: + provider = _runtime.get("network_ips") + network = provider() if provider is not None else netSvc.get_network_ips() + except Exception: + network = None + if not isinstance(network, dict): + warnings.append({ + "code": "network_unavailable", + "message": "Network interfaces could not be discovered.", + }) + return {"wifi": [], "ethernet": []} + + def entries(name: str) -> list: + values = network.get(name) + if not isinstance(values, list): + return [] + return [ + entry for entry in values + if isinstance(entry, dict) + and isinstance(entry.get("interface"), str) + and isinstance(entry.get("ip"), str) + ] + + return {"wifi": entries("wifi"), "ethernet": entries("ethernet")} + + +def _last_delivery(config_dir: str) -> dict | None: + status = webhookSvc.read_webhook_status( + join(config_dir, "webhook_status.json") + ) + if not status: + return None + return { + field: status.get(field) + for field in ( + "ok", + "event", + "delivery_id", + "http_status", + "attempts", + "error", + "at", + ) + } + + +def _webhook_status(settings: dict, config_dir: str, warnings: list) -> dict: + webhook = settingsSvc.writable_settings(settings)["webhook"] + url = webhook["url"] + url_host = None + if url: + try: + url_host = urlparse(url).hostname + except ValueError: + url_host = None + + pending = _status_runtime("outbox_pending") + capacity = webhook["capacity"] + if not isinstance(capacity, int) or isinstance(capacity, bool): + capacity = None + + if not webhook["enabled"]: + warnings.append({ + "code": "webhook_disabled", + "message": ( + "Webhook forwarding is disabled: new Inbound SMS are " + "discarded." + ), + }) + elif not webhookSvc.is_valid_target(url): + warnings.append({ + "code": "webhook_url_invalid", + "message": ( + "Webhook forwarding is enabled with an invalid Webhook target." + ), + }) + + if ( + isinstance(pending, int) + and not isinstance(pending, bool) + and isinstance(capacity, int) + and not isinstance(capacity, bool) + and capacity > 0 + and pending >= 0.8 * capacity + ): + warnings.append({ + "code": "outbox_near_capacity", + "message": ( + f"The Outbox holds {pending} of {capacity} Webhooks; the " + "oldest will be dropped when it is full." + ), + }) + + return { + "enabled": bool(webhook["enabled"]), + "url_host": url_host, + "secret_set": bool(webhook["secret_set"]), + "outbox_pending": pending, + "outbox_capacity": capacity, + "last_delivery": _last_delivery(config_dir), + } + + +@app.get("/api/status") +async def api_status( + client: dict = Depends(require_scope(SCOPE_SETTINGS)) +): + config_dir = get_config_dir() + settings = settingsSvc.load_settings(_settings_path()) + warnings: list = [] + + network = _network_status(warnings) + webhook = _webhook_status(settings, config_dir, warnings) + + return { + "version": __version__, + "api": { + "running": bool(_status_runtime("running", True)), + "port": _status_runtime("port", _live_attr("port")), + "bound_port": _status_runtime( + "bound_port", _live_attr("bound_port") + ), + "uptime_s": _status_uptime_s(), + }, + "service": _service_status(), + "config": { + "port": settings.get("port"), + "boot": settings.get("boot"), + "revision": settingsSvc.get_revision(settings), + }, + "network": network, + "webhook": webhook, + "warnings": warnings, + } + @app.get("/api/settings") async def api_get_settings( client: dict = Depends(require_scope(SCOPE_SETTINGS)) diff --git a/app/tests/test_remote_api.py b/app/tests/test_remote_api.py index a700504..efd49de 100644 --- a/app/tests/test_remote_api.py +++ b/app/tests/test_remote_api.py @@ -1,4 +1,5 @@ import glob +import json import os import threading import time @@ -65,6 +66,280 @@ def test_health_reports_status_version_platform_and_uptime(self): self.assertGreaterEqual(body["uptime_s"], 9) +class StatusTests(ApiTestCase): + + def config(self, **overrides) -> dict: + config = { + "app": "opensms", + "port": 9393, + "boot": True, + "permissions": True, + "revision": 5, + "webhook": { + "enabled": False, + "url": "", + "secret": "", + "timeout": 10, + "max_attempts": 3, + "backoff": [5, 30], + "capacity": 100, + }, + } + webhook_overrides = overrides.pop("webhook", None) + if webhook_overrides: + config["webhook"].update(webhook_overrides) + config.update(overrides) + return config + + def write_json(self, name: str, value): + with open( + os.path.join(self.config_dir, name), "w", encoding="utf-8" + ) as json_file: + json.dump(value, json_file) + + def status(self, raw_key: str): + return self.client.get("/api/status", headers=self.auth(raw_key)) + + def warning_codes(self, body: dict) -> list: + return [warning["code"] for warning in body["warnings"]] + + def test_status_refuses_a_missing_or_invalid_key(self): + response = self.client.get("/api/status") + self.assertEqual(response.status_code, 403) + + self.add_api_key() + response = self.client.get( + "/api/status", headers=self.auth("osms_not_a_real_key") + ) + self.assertEqual(response.status_code, 401) + + def test_status_requires_the_settings_scope(self): + raw_key = self.add_api_key(scopes=("sms:write",)) + + response = self.status(raw_key) + + self.assertEqual(response.status_code, 403) + + def test_status_separates_the_configured_and_bound_ports(self): + self.write_config(self.config(port=9393)) + postApi.set_runtime_providers({ + "running": lambda: True, + "port": lambda: 9292, + "bound_port": lambda: 9292, + }) + raw_key = self.add_api_key() + + response = self.status(raw_key) + + self.assertEqual(response.status_code, 200) + body = response.json() + self.assertEqual(body["version"], __version__) + self.assertEqual(body["config"], { + "port": 9393, + "boot": True, + "revision": 5, + }) + self.assertTrue(body["api"]["running"]) + self.assertEqual(body["api"]["port"], 9292) + self.assertEqual(body["api"]["bound_port"], 9292) + + def test_missing_runtime_values_are_null_not_invented(self): + postApi.set_runtime_providers({}) + raw_key = self.add_api_key() + + body = self.status(raw_key).json() + + self.assertIsNone(body["api"]["bound_port"]) + self.assertIsNone(body["webhook"]["outbox_pending"]) + self.assertIsNone(body["webhook"]["last_delivery"]) + + def test_status_reports_service_transitions_and_unknowns(self): + self.write_json("resp.json", { + "server": "started", + "serial": "none", + "provider": "test-network", + }) + raw_key = self.add_api_key() + + body = self.status(raw_key).json() + self.assertEqual(body["service"], { + "server": "started", + "serial": "none", + "provider": "test-network", + }) + + with open( + os.path.join(self.config_dir, "resp.json"), "w", encoding="utf-8" + ) as resp_file: + resp_file.write("not json") + + body = self.status(raw_key).json() + self.assertEqual(body["service"], { + "server": "unknown", + "serial": "unknown", + "provider": "unknown", + }) + + def test_status_reports_network_interfaces(self): + postApi.set_runtime_providers({ + "network_ips": lambda: { + "wifi": [ + {"interface": "wlan0", "ip": "192.168.1.50"}, + ], + "ethernet": [ + {"interface": "eth0", "ip": "10.0.0.2"}, + ], + }, + }) + raw_key = self.add_api_key() + + body = self.status(raw_key).json() + + self.assertEqual(body["network"], { + "wifi": [{"interface": "wlan0", "ip": "192.168.1.50"}], + "ethernet": [{"interface": "eth0", "ip": "10.0.0.2"}], + }) + self.assertNotIn("network_unavailable", self.warning_codes(body)) + + def test_network_failure_is_an_empty_list_and_a_warning(self): + def fail(): + raise RuntimeError("no network facts") + + postApi.set_runtime_providers({"network_ips": fail}) + raw_key = self.add_api_key() + + response = self.status(raw_key) + + self.assertEqual(response.status_code, 200) + body = response.json() + self.assertEqual(body["network"], {"wifi": [], "ethernet": []}) + self.assertIn("network_unavailable", self.warning_codes(body)) + + def test_status_reports_the_last_delivery_attempt_and_outbox_depth(self): + self.write_config(self.config( + webhook={ + "enabled": True, + "url": "https://proxy.example.lan/hooks/opensms", + "capacity": 100, + }, + )) + self.write_json("webhook_status.json", { + "ok": False, + "event": "sms.received", + "delivery_id": "d-1", + "http_status": 500, + "attempts": 3, + "error": "HTTP 500", + "at": "2026-11-26T12:34:56+00:00", + }) + postApi.set_runtime_providers({"outbox_pending": lambda: 3}) + raw_key = self.add_api_key() + + body = self.status(raw_key).json() + + self.assertEqual(body["webhook"]["outbox_pending"], 3) + self.assertEqual(body["webhook"]["outbox_capacity"], 100) + self.assertEqual(body["webhook"]["last_delivery"], { + "ok": False, + "event": "sms.received", + "delivery_id": "d-1", + "http_status": 500, + "attempts": 3, + "error": "HTTP 500", + "at": "2026-11-26T12:34:56+00:00", + }) + + def test_an_unreadable_delivery_status_is_null(self): + with open( + os.path.join(self.config_dir, "webhook_status.json"), + "w", + encoding="utf-8", + ) as status_file: + status_file.write("not json") + raw_key = self.add_api_key() + + body = self.status(raw_key).json() + + self.assertIsNone(body["webhook"]["last_delivery"]) + + def test_status_reports_only_the_webhook_host_and_secret_presence(self): + self.write_config(self.config( + webhook={ + "enabled": True, + "url": ( + "http://proxy-user:proxy-pass@proxy.example.lan:8080/" + "hooks/SENSITIVE-PATH?token=SENSITIVE-TOKEN" + ), + "secret": "SENSITIVE-SECRET", + }, + )) + raw_key = self.add_api_key() + + response = self.status(raw_key) + + self.assertEqual(response.status_code, 200) + body = response.json() + self.assertEqual(body["webhook"]["url_host"], "proxy.example.lan") + self.assertTrue(body["webhook"]["secret_set"]) + for sensitive in ( + "SENSITIVE-PATH", + "SENSITIVE-TOKEN", + "SENSITIVE-SECRET", + "proxy-user", + "proxy-pass", + "/hooks", + "/hook", + ): + with self.subTest(sensitive=sensitive): + self.assertNotIn(sensitive, response.text) + + def test_forwarding_disabled_warns_that_new_inbound_sms_are_discarded(self): + raw_key = self.add_api_key() + + body = self.status(raw_key).json() + + self.assertFalse(body["webhook"]["enabled"]) + self.assertIn("webhook_disabled", self.warning_codes(body)) + warning = next( + warning for warning in body["warnings"] + if warning["code"] == "webhook_disabled" + ) + self.assertIn("new Inbound SMS", warning["message"]) + self.assertIn("discarded", warning["message"]) + self.assertNotIn("webhook_url_invalid", self.warning_codes(body)) + + def test_an_enabled_but_invalid_target_is_a_warning(self): + self.write_config(self.config( + webhook={"enabled": True, "url": "not-a-url"}, + )) + raw_key = self.add_api_key() + + body = self.status(raw_key).json() + + self.assertIn("webhook_url_invalid", self.warning_codes(body)) + self.assertNotIn("webhook_disabled", self.warning_codes(body)) + + def test_an_outbox_near_capacity_is_a_warning(self): + self.write_config(self.config( + webhook={ + "enabled": True, + "url": "https://proxy.example.lan/hooks/opensms", + "capacity": 10, + }, + )) + raw_key = self.add_api_key() + + postApi.set_runtime_providers({"outbox_pending": lambda: 7}) + body = self.status(raw_key).json() + self.assertNotIn("outbox_near_capacity", self.warning_codes(body)) + + postApi.set_runtime_providers({"outbox_pending": lambda: 8}) + body = self.status(raw_key).json() + self.assertIn("outbox_near_capacity", self.warning_codes(body)) + self.assertEqual(body["webhook"]["outbox_pending"], 8) + self.assertEqual(body["webhook"]["outbox_capacity"], 10) + + class SettingsReadTests(ApiTestCase): def test_settings_defaults_when_no_config_exists(self): From 80630b6623a9ef63178592f43050488f0ce386b4 Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 17:44:15 +0100 Subject: [PATCH 07/20] feat: validate a Webhook target before saving Add POST /api/webhook/test, which sends a test Webhook to a candidate target and secret without changing live Settings. The call is offloaded from the event loop, never follows redirects, and scrubs URL parts from errors. Covered against a local HTTP receiver. --- app/services/postApi.py | 134 +++++++++++++++++++ app/tests/test_remote_api.py | 250 +++++++++++++++++++++++++++++++++++ 2 files changed, 384 insertions(+) diff --git a/app/services/postApi.py b/app/services/postApi.py index 0036946..ddbc4ce 100644 --- a/app/services/postApi.py +++ b/app/services/postApi.py @@ -10,6 +10,8 @@ #from functools import partial from fastapi import FastAPI, Request, HTTPException, Depends +from fastapi.concurrency import run_in_threadpool +from fastapi.responses import JSONResponse from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from pydantic import BaseModel import uvicorn @@ -619,6 +621,138 @@ async def api_put_settings( "restart_required": _restart_required(saved), } +WEBHOOK_TEST_FIELDS = {"url", "secret"} + + +def _webhook_test_overrides(payload) -> dict: + """Validate a Webhook test body; an absent body means "use saved Settings".""" + if not isinstance(payload, dict): + raise HTTPException( + status_code=422, + detail="Request body must be a JSON object", + ) + unknown = set(payload) - WEBHOOK_TEST_FIELDS + if unknown: + raise HTTPException( + status_code=422, + detail=f"Unknown field(s) in request: {', '.join(sorted(unknown))}", + ) + overrides = {} + if "url" in payload: + if not isinstance(payload["url"], str): + raise HTTPException( + status_code=422, detail="url must be a string" + ) + overrides["url"] = payload["url"] + if "secret" in payload: + secret = payload["secret"] + if not isinstance(secret, str): + raise HTTPException( + status_code=422, detail="secret must be a string" + ) + if len(secret) > settingsSvc.SECRET_MAX_LENGTH: + raise HTTPException( + status_code=422, + detail=( + "secret must be at most " + f"{settingsSvc.SECRET_MAX_LENGTH} characters" + ), + ) + overrides["secret"] = secret + return overrides + + +def _resolve_webhook_test_config(settings: dict, overrides: dict) -> tuple: + """Resolve the target, secret and timeout for one test delivery. + + Overrides apply to this test only; every absent field comes from the saved + Settings. An empty secret means unsigned delivery, whether saved or passed. + """ + webhook = settings.get("webhook") + if not isinstance(webhook, dict): + webhook = {} + url = overrides.get("url", webhook.get("url", "")) + if not webhookSvc.is_valid_target(url): + raise HTTPException( + status_code=400, + detail=( + "A valid http(s) Webhook target is required to send a test" + ), + ) + secret = webhook.get("secret") + if not isinstance(secret, str): + secret = "" + secret = overrides.get("secret", secret) + try: + timeout = float(webhook.get("timeout", webhookSvc.DEFAULT_TIMEOUT)) + except (TypeError, ValueError): + timeout = webhookSvc.DEFAULT_TIMEOUT + return url, secret, timeout + + +def _scrub_webhook_target(url: str, error: str) -> str: + """Remove URL parts from an error so credentials never reach the caller.""" + if not error: + return error + candidates = {url, url.strip()} + try: + parsed = urlparse(url) + except ValueError: + parsed = None + if parsed is not None: + candidates.update({ + parsed.username, + parsed.password, + parsed.path if parsed.path not in ("", "/") else None, + parsed.query or None, + parsed.fragment or None, + }) + for sensitive in candidates: + if sensitive: + error = error.replace(sensitive, "") + return error + + +@app.post("/api/webhook/test") +async def api_webhook_test( + request: Request, + client: dict = Depends(require_scope(SCOPE_SETTINGS)) +): + raw_body = await request.body() + payload = {} + if raw_body: + try: + payload = json.loads(raw_body) + except Exception: + raise HTTPException( + status_code=422, + detail="Request body must be valid JSON", + ) + overrides = _webhook_test_overrides(payload) + settings = settingsSvc.load_settings(_settings_path()) + url, secret, timeout = _resolve_webhook_test_config(settings, overrides) + + # The delivery is blocking; keep the event loop free while it runs. + ok, status, error = await run_in_threadpool( + webhookSvc.send_test_webhook, + {"url": url, "secret": secret}, + timeout=timeout, + ) + if ok: + log_activities(f"Webhook test delivered (HTTP {status})") + return {"ok": True, "http_status": status, "error": None} + if error: + error = _scrub_webhook_target(url, error) + if status is None: + log_activities("Webhook test failed") + else: + log_activities(f"Webhook test failed (HTTP {status})") + return JSONResponse( + status_code=502, + content={"ok": False, "http_status": status, "error": error}, + ) + + @app.post("/sms/") async def process_sms_req( item: SmsData, diff --git a/app/tests/test_remote_api.py b/app/tests/test_remote_api.py index efd49de..36c5fc1 100644 --- a/app/tests/test_remote_api.py +++ b/app/tests/test_remote_api.py @@ -1,10 +1,14 @@ import glob +import hashlib +import hmac import json import os import threading import time +from unittest import mock from api_test_case import ApiTestCase +from test_webhook import MockTarget from services import postApi from services.config import __version__ @@ -934,3 +938,249 @@ def test_logs_name_fields_without_the_secret_or_the_body(self): self.assertNotIn("super-duper-secret", logged) self.assertNotIn("SENSITIVE-PATH", logged) self.assertNotIn("old-secret", logged) + + +class WebhookTestTests(ApiTestCase): + + def setUp(self): + super().setUp() + self.target = MockTarget() + self.target.redirect_to(self.target.url + "-redirected") + + def tearDown(self): + self.target.close() + super().tearDown() + + def post_test(self, raw_key: str, payload=None): + kwargs = {"headers": self.auth(raw_key)} + if payload is not None: + kwargs["json"] = payload + return self.client.post("/api/webhook/test", **kwargs) + + def save_webhook(self, **overrides) -> dict: + webhook = { + "enabled": False, + "url": self.target.url, + "secret": "saved-secret", + "timeout": 5, + "max_attempts": 3, + "backoff": [5, 30], + "capacity": 100, + } + webhook.update(overrides) + self.write_config({"webhook": webhook}) + return webhook + + def signature_for(self, secret: str, body: bytes) -> str: + digest = hmac.new( + secret.encode("utf-8"), body, hashlib.sha256 + ).hexdigest() + return f"sha256={digest}" + + def test_success_reports_the_status_and_a_null_error(self): + raw_key = self.add_api_key() + + response = self.post_test( + raw_key, {"url": self.target.url, "secret": "override-secret"} + ) + + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json(), { + "ok": True, + "http_status": 200, + "error": None, + }) + request = self.target.next_request() + self.assertEqual(json.loads(request["body"])["event"], "webhook.test") + self.assertEqual( + request["headers"]["x-opensms-signature"], + self.signature_for("override-secret", request["body"]), + ) + + def test_a_failed_delivery_reports_the_http_status_and_error(self): + self.target.queue_statuses(500) + raw_key = self.add_api_key() + + response = self.post_test(raw_key, {"url": self.target.url}) + + self.assertEqual(response.status_code, 502) + self.assertEqual(response.json(), { + "ok": False, + "http_status": 500, + "error": "HTTP 500", + }) + + def test_a_redirect_counts_as_a_failure(self): + self.target.queue_statuses(302) + raw_key = self.add_api_key() + + response = self.post_test(raw_key, {"url": self.target.url}) + + self.assertEqual(response.status_code, 502) + body = response.json() + self.assertFalse(body["ok"]) + self.assertEqual(body["http_status"], 302) + self.assertTrue(body["error"]) + # The redirect must not be followed, so only the original POST arrived. + self.assertEqual(self.target.count, 1) + + def test_an_unreachable_target_reports_no_http_status(self): + raw_key = self.add_api_key() + + response = self.post_test( + raw_key, {"url": "http://127.0.0.1:1/unreachable"} + ) + + self.assertEqual(response.status_code, 502) + body = response.json() + self.assertFalse(body["ok"]) + self.assertIsNone(body["http_status"]) + self.assertTrue(body["error"]) + + def test_no_body_uses_the_saved_target_and_secret(self): + self.save_webhook(enabled=False, secret="saved-secret") + before = self.read_config() + raw_key = self.add_api_key() + + response = self.post_test(raw_key) + + self.assertEqual(response.status_code, 200) + request = self.target.next_request() + self.assertEqual( + request["headers"]["x-opensms-signature"], + self.signature_for("saved-secret", request["body"]), + ) + self.assertEqual(self.read_config(), before) + + def test_an_override_is_used_for_the_test_only(self): + self.save_webhook( + url="http://127.0.0.1:1/unreachable", secret="saved-secret" + ) + before = self.read_config() + raw_key = self.add_api_key() + + response = self.post_test( + raw_key, {"url": self.target.url, "secret": "override-secret"} + ) + + self.assertEqual(response.status_code, 200) + request = self.target.next_request() + self.assertEqual( + request["headers"]["x-opensms-signature"], + self.signature_for("override-secret", request["body"]), + ) + self.assertEqual(self.read_config(), before) + + # The next test without a body uses the saved target again. + response = self.post_test(raw_key, {"url": self.target.url}) + self.assertEqual(response.status_code, 200) + request = self.target.next_request() + self.assertEqual( + request["headers"]["x-opensms-signature"], + self.signature_for("saved-secret", request["body"]), + ) + + def test_an_empty_secret_tests_unsigned_delivery(self): + self.save_webhook(secret="saved-secret") + raw_key = self.add_api_key() + + response = self.post_test( + raw_key, {"url": self.target.url, "secret": ""} + ) + + self.assertEqual(response.status_code, 200) + request = self.target.next_request() + self.assertNotIn("x-opensms-signature", request["headers"]) + self.assertEqual( + self.read_config()["webhook"]["secret"], "saved-secret" + ) + + def test_an_error_never_echoes_the_target_with_credentials(self): + raw_key = self.add_api_key() + + response = self.post_test(raw_key, { + "url": ( + "http://proxy-user:proxy-pass@127.0.0.1:1/" + "pa th?token=SENSITIVE-TOKEN" + ), + }) + + self.assertEqual(response.status_code, 502) + body = response.json() + self.assertFalse(body["ok"]) + self.assertIsNone(body["http_status"]) + self.assertTrue(body["error"]) + for sensitive in ( + "proxy-user", + "proxy-pass", + "SENSITIVE-TOKEN", + "/pa th", + ): + with self.subTest(sensitive=sensitive): + self.assertNotIn(sensitive, response.text) + + def test_a_test_needs_a_valid_target(self): + raw_key = self.add_api_key() + + cases = { + "no saved target": None, + "empty override": {"url": ""}, + "not a url": {"url": "not-a-url"}, + "not http": {"url": "ftp://proxy.example.lan/hooks"}, + "no host": {"url": "http:///hooks"}, + } + for name, payload in cases.items(): + with self.subTest(name): + response = self.post_test(raw_key, payload) + + self.assertEqual(response.status_code, 400, response.text) + self.assertIsInstance(response.json()["detail"], str) + + self.assertEqual(self.target.count, 0) + + def test_the_saved_timeout_is_used(self): + self.save_webhook(timeout=7) + raw_key = self.add_api_key() + calls = [] + + def record(config, timeout): + calls.append((config, timeout)) + return True, 204, None + + with mock.patch.object( + postApi.webhookSvc, "send_test_webhook", side_effect=record + ): + response = self.post_test(raw_key, {"url": self.target.url}) + + self.assertEqual(response.status_code, 200) + self.assertEqual(calls[0][1], 7) + + def test_unknown_fields_and_wrong_types_are_rejected(self): + raw_key = self.add_api_key() + + cases = { + "unknown field": {"url": self.target.url, "unknown": 1}, + "url not a string": {"url": 42}, + "secret not a string": {"secret": 42}, + "secret too long": {"secret": "x" * 257}, + } + for name, payload in cases.items(): + with self.subTest(name): + response = self.post_test(raw_key, payload) + + self.assertEqual(response.status_code, 422, response.text) + self.assertIsInstance(response.json()["detail"], str) + + self.assertEqual(self.target.count, 0) + + def test_a_webhook_test_requires_authentication_and_the_settings_scope(self): + response = self.client.post( + "/api/webhook/test", json={"url": self.target.url} + ) + self.assertEqual(response.status_code, 403) + + raw_key = self.add_api_key(scopes=("sms:write",)) + response = self.post_test(raw_key, {"url": self.target.url}) + self.assertEqual(response.status_code, 403) + + self.assertEqual(self.target.count, 0) From 84a98201f97d1832ffd008baa60f181f113d0f37 Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 17:54:05 +0100 Subject: [PATCH 08/20] feat: restart the server onto a new port --- app/main.py | 7 +- app/services/appSvc.py | 80 ++++++++++++---- app/services/controlSvc.py | 99 +++++++++++++++++++ app/services/postApi.py | 105 +++++++++++++++++---- app/services/settingsSvc.py | 7 +- app/tests/test_control_svc.py | 170 +++++++++++++++++++++++++++++++++ app/tests/test_remote_api.py | 173 ++++++++++++++++++++++++++++++++++ 7 files changed, 596 insertions(+), 45 deletions(-) create mode 100644 app/services/controlSvc.py create mode 100644 app/tests/test_control_svc.py diff --git a/app/main.py b/app/main.py index 2336ca7..49003f7 100644 --- a/app/main.py +++ b/app/main.py @@ -40,7 +40,7 @@ from screens.settings import SettingsBox, ApiKeyTxtbox # import services -from services import settingsSvc +from services import settingsSvc, controlSvc from services.postApi import has_api_keys, generate_new_api_key from services.netSvc import get_network_ips from services.config import __version__, app_name @@ -175,7 +175,6 @@ def on_start(self): self.internal_storage = app_storage_path() self.config_dir = os.path.join(self.internal_storage, 'config') os.makedirs(self.config_dir, exist_ok=True) - self.request_path = os.path.join(self.config_dir, "request.json") self.resp_path = os.path.join(self.config_dir, "resp.json") svc_running = False # start the listner service on Android @@ -195,7 +194,6 @@ def on_start(self): self.internal_storage = get_user_data_dir(self.config_template["app"]) self.config_dir = os.path.join(self.internal_storage, 'config') os.makedirs(self.config_dir, exist_ok=True) - self.request_path = os.path.join(self.config_dir, "request.json") self.resp_path = os.path.join(self.config_dir, "resp.json") self.write_request() # Serial setup @@ -368,8 +366,7 @@ def write_app_conf(self): os.remove(tmp_path) def write_request(self): - with open(self.request_path, "w") as rf: - json.dump(self.req_template, rf) + controlSvc.write_control(self.config_dir, self.req_template) def clear_api_details(self): endpoint_box = self.root.ids.home_scr.ids.endpoint_box diff --git a/app/services/appSvc.py b/app/services/appSvc.py index 17304a0..a48db40 100644 --- a/app/services/appSvc.py +++ b/app/services/appSvc.py @@ -28,6 +28,7 @@ ) from services.logSvc import LogService from services.config import app_name +from services import controlSvc from services.webhookSvc import ( WebhookDispatcher, ack_inbox_message, @@ -44,6 +45,9 @@ req_data = {} api_started = False serial_started = False +# True when a handled Restart could not be normalised on disk; the loop then +# suppresses the stale intent instead of restarting again. +restart_intent_handled = False serial_mgr = None sms_receiver = None sms_receiver_context = None @@ -110,14 +114,18 @@ def write_resp(): json.dump(resp_template, rf) def read_req_file(): - """ Read the command file from file (Instrunctions from main app). """ - global req_data - if exists(req_file): - try: - with open(req_file, "r") as rf: - req_data = json.load(rf) - except Exception as e: - print(f"Error while reading config from svc: {e}") + """ Read the control file (intents from the API or the main app). """ + global req_data, restart_intent_handled + if not exists(req_file): + return + req_data = controlSvc.read_control(config_dir) + intent = req_data.get(controlSvc.INTENT_KEY) + if restart_intent_handled and intent == controlSvc.INTENT_RESTART: + # A handled Restart could not be persisted as "start"; do not let the + # stale file restart the server again. + req_data[controlSvc.INTENT_KEY] = controlSvc.INTENT_START + elif intent != controlSvc.INTENT_RESTART: + restart_intent_handled = False def register_sms_receiver(): """Register the Android SMS_RECEIVED receiver in this service process. @@ -161,22 +169,54 @@ def unregister_sms_receiver(): sms_receiver = None sms_receiver_context = None -def api_server_control(api_stat: str): - """ Turns API server on/off """ +def stop_api_server() -> bool: + """ Stop the API server, reporting whether it exited in time. """ global api_started - global resp_template - global req_data + stopped = app_api_server.stop() + api_started = False + return stopped + +def api_server_control(api_stat: str, port: int | None = None): + """ Turns API server on/off """ + global api_started, resp_template print(req_data) if api_stat == "stop": - app_api_server.stop() - api_started = False - resp_template["server"] = "stopped" + if stop_api_server(): + resp_template["server"] = "stopped" elif api_stat == "start": - app_api_server.start(req_data["port"]) + # Settings own the port; the control file is only a fallback. + start_port = ( + port if port is not None else controlSvc.effective_port(config_dir) + ) + app_api_server.start(start_port) api_started = True resp_template["server"] = "started" Thread(target=write_resp, daemon=True).start() +def restart_api_server(): + """ Stop once, then start again on the effective port. + + The control intent is normalised back to "start" after the new server has + been asked to start, so the 0.2 s poll cannot trigger the Restart again. + """ + global req_data, restart_intent_handled + port = controlSvc.effective_port(config_dir) + req_data["port"] = port + if not stop_api_server(): + # Never add a second listener while the previous one is still up; the + # intent stays "restart" so the next poll retries the stop. + print("Restart deferred: the previous server has not stopped yet") + return + time.sleep(0.5) + api_server_control("start", port) + try: + controlSvc.normalise_restart(config_dir, port) + restart_intent_handled = False + except Exception as e: + restart_intent_handled = True + print(f"Could not normalise the Restart intent: {e}") + log_activities(f"Could not normalise the Restart intent: {e}") + def serial_conn_control(cmd:str): global serial_started global serial_mgr @@ -247,10 +287,12 @@ def app_service_thread(): register_sms_receiver() # handle api server - server_stat = req_data.get("server", "") - if not api_started and server_stat == "start": + server_stat = req_data.get(controlSvc.INTENT_KEY, "") + if server_stat == controlSvc.INTENT_RESTART: + restart_api_server() + elif not api_started and server_stat == controlSvc.INTENT_START: api_server_control("start") - elif api_started and server_stat == "stop": + elif api_started and server_stat == controlSvc.INTENT_STOP: api_server_control("stop") # handle serial request diff --git a/app/services/controlSvc.py b/app/services/controlSvc.py new file mode 100644 index 0000000..879acc6 --- /dev/null +++ b/app/services/controlSvc.py @@ -0,0 +1,99 @@ +""" The control file: intents from the API and UI to the service loop. + +The persisted Settings remain the single source of truth for the port. This +module only carries intents (start, stop, restart) and is deliberately free of +Kivy, jnius and Android imports, so Restart handling can be tested anywhere. +""" + +import json +import os + +from services import settingsSvc + +CONTROL_FILE = "request.json" +SETTINGS_FILE = "config.json" +INTENT_KEY = "server" +INTENT_START = "start" +INTENT_STOP = "stop" +INTENT_RESTART = "restart" + +## Read and write + +def _control_path(config_dir: str) -> str: + return os.path.join(config_dir, CONTROL_FILE) + +def read_control(config_dir: str) -> dict: + """Read the control file, treating a missing or malformed file as empty.""" + try: + with open(_control_path(config_dir), "r", encoding="utf-8") as control_file: + control = json.load(control_file) + except Exception: + return {} + return control if isinstance(control, dict) else {} + +def write_control(config_dir: str, control: dict): + """Write the control file atomically; the service polls every 0.2 s.""" + settingsSvc.atomic_write_json(_control_path(config_dir), control) + +## Intents + +def intent(config_dir: str) -> str: + """Return the requested server intent, or "" when none is usable.""" + value = read_control(config_dir).get(INTENT_KEY) + return value if isinstance(value, str) else "" + +## Effective port + +def _settings_port(config_dir: str) -> int | None: + """Read the port from Settings, or None when the file is unusable. + + Settings are read raw rather than through `load_settings` so an unreadable + file is distinguishable from defaults; otherwise the control-file fallback + could never apply. + """ + try: + with open( + os.path.join(config_dir, SETTINGS_FILE), "r", encoding="utf-8" + ) as settings_file: + raw = json.load(settings_file) + except Exception: + return None + if not isinstance(raw, dict): + return None + port = raw.get("port") + return port if settingsSvc.is_valid_port(port) else None + +def effective_port(config_dir: str) -> int: + """Resolve the port to start on: Settings first, the control file second.""" + port = _settings_port(config_dir) + if port is not None: + return port + port = read_control(config_dir).get("port") + if settingsSvc.is_valid_port(port): + return port + return settingsSvc.DEFAULT_PORT + +def request_restart(config_dir: str, port: int) -> dict: + """Record a Restart without disturbing serial or unknown control keys.""" + control = read_control(config_dir) + control["port"] = port + control[INTENT_KEY] = INTENT_RESTART + write_control(config_dir, control) + return control + +def restart_pending(config_dir: str) -> bool: + return intent(config_dir) == INTENT_RESTART + +def normalise_restart(config_dir: str, port: int | None = None) -> bool: + """Turn a handled Restart back into a plain start, preserving other keys. + + Returns True only when a Restart was normalised, so a polling loop can + handle each request exactly once. + """ + control = read_control(config_dir) + if control.get(INTENT_KEY) != INTENT_RESTART: + return False + control[INTENT_KEY] = INTENT_START + control["port"] = effective_port(config_dir) if port is None else port + write_control(config_dir, control) + return True diff --git a/app/services/postApi.py b/app/services/postApi.py index ddbc4ce..a98afb3 100644 --- a/app/services/postApi.py +++ b/app/services/postApi.py @@ -3,7 +3,7 @@ import asyncio import time from datetime import datetime, timezone -from threading import Thread, Lock +from threading import Thread, Lock, Timer from os.path import join from urllib.parse import urlparse import json @@ -21,7 +21,7 @@ from services.smsApi import SmsCrossPlatform, clean_and_validate_phone from services.logSvc import LogService from services.config import __version__, app_name -from services import netSvc, settingsSvc, webhookSvc +from services import netSvc, settingsSvc, controlSvc, webhookSvc # OS specific #try: @@ -48,9 +48,15 @@ _config_dir: str | None = None _runtime: dict = {} _last_restart_at: float | None = None +_restart_lock = Lock() _started_at: float | None = None _key_lock = Lock() +# Restart orchestration. The handler acknowledges before anything stops, and +# the control intent is written only after the response has had time to leave. +RESTART_DELAY_SECONDS = 0.4 +RESTART_DEBOUNCE_SECONDS = 5.0 + ## OS specific setups # for android if platform == "android": @@ -236,12 +242,6 @@ class SmsData(BaseModel): text: str #sub_text: str | None = None -class ControlData(BaseModel): - """ - This is not yet implemented. Placeholder only. - """ - api: str - # FastAPI app app = FastAPI() security = HTTPBearer(auto_error=False) @@ -326,15 +326,26 @@ def start(self, port=None): # ---------------------------- # Public stop # ---------------------------- - def stop(self): + def stop(self) -> bool: + """Stop the server; False when its thread outlived the join timeout. + + Leaving `thread` in place on a timeout keeps `start()` from adding a + second listener while the first is still shutting down. + """ if self.server: print("Stopping FastAPI...") self.server.should_exit = True + stopped = True if self.thread: self.thread.join(timeout=5) + stopped = not self.thread.is_alive() self.server = None - self.thread = None - print("FastAPI stopped") + if stopped: + self.thread = None + print("FastAPI stopped") + else: + print("FastAPI did not stop within 5 seconds") + return stopped # handle post requests @@ -595,6 +606,30 @@ def _restart_required(settings: dict) -> bool: except (TypeError, ValueError): return False +def _write_restart_intent(config_dir: str, port: int): + global _last_restart_at + try: + controlSvc.request_restart(config_dir, port) + except Exception as exc: + # The 202 has already promised nothing is written yet; let a retry + # through instead of debouncing a Restart that never happened. + with _restart_lock: + _last_restart_at = None + print(f"Could not write the Restart intent: {exc}") + log_activities(f"Could not write the Restart intent: {exc}") + + +def _schedule_restart(config_dir: str, port: int): + """Write the control intent after the 202 has had time to reach the client.""" + timer = Timer( + RESTART_DELAY_SECONDS, + _write_restart_intent, + args=(config_dir, port), + ) + timer.daemon = True + timer.start() + + @app.put("/api/settings") async def api_put_settings( request: Request, @@ -753,6 +788,45 @@ async def api_webhook_test( ) +@app.post("/api/server/restart", status_code=202) +async def api_server_restart( + client: dict = Depends(require_scope(SCOPE_SETTINGS)) +): + """Acknowledge a Restart, then hand the intent to the service loop. + + The handler never stops its own server: stopping uvicorn from inside a + request risks answering into a dead socket. + """ + global _last_restart_at + + if not _status_runtime("running", True): + raise HTTPException( + status_code=409, + detail="The API server is not running", + ) + + now = time.monotonic() + with _restart_lock: + if ( + _last_restart_at is not None + and now - _last_restart_at < RESTART_DEBOUNCE_SECONDS + ): + raise HTTPException( + status_code=409, + detail=( + "A Restart was requested less than " + f"{RESTART_DEBOUNCE_SECONDS:g} seconds ago" + ), + ) + _last_restart_at = now + + config_dir = get_config_dir() + port = controlSvc.effective_port(config_dir) + _schedule_restart(config_dir, port) + log_activities(f"Restart requested on port {port}") + return {"status": "restarting", "port": port} + + @app.post("/sms/") async def process_sms_req( item: SmsData, @@ -791,15 +865,6 @@ async def process_sms_req( return {"stat": stat} -@app.post("/control/") -async def internal_control( - item: ControlData, - request: Request, - client: dict = Depends(verify_api_key) -): - server: PosiApiServer = request.app.state.server - return item - # test locally if __name__ == "__main__": apiServ = PosiApiServer() diff --git a/app/services/settingsSvc.py b/app/services/settingsSvc.py index 500d692..cdc7714 100644 --- a/app/services/settingsSvc.py +++ b/app/services/settingsSvc.py @@ -129,6 +129,11 @@ def _is_int(value) -> bool: return isinstance(value, int) and not isinstance(value, bool) +def is_valid_port(value) -> bool: + """Whether `value` is a JSON integer inside the API port range.""" + return _is_int(value) and PORT_MIN <= value <= PORT_MAX + + def _unknown_field_error(prefix: str, unknown) -> SettingsValidationError: names = ", ".join(sorted(unknown)) return SettingsValidationError(f"Unknown field(s) in {prefix}: {names}") @@ -156,7 +161,7 @@ def validate_settings_payload(payload) -> dict: raise SettingsValidationError("revision must be an integer") port = payload["port"] - if not _is_int(port) or not PORT_MIN <= port <= PORT_MAX: + if not is_valid_port(port): raise SettingsValidationError( f"port must be an integer between {PORT_MIN} and {PORT_MAX}" ) diff --git a/app/tests/test_control_svc.py b/app/tests/test_control_svc.py new file mode 100644 index 0000000..46d24f9 --- /dev/null +++ b/app/tests/test_control_svc.py @@ -0,0 +1,170 @@ +"""Direct tests for the control file, the API-to-service intent channel. + +The control module is the seam where Restart normalisation, effective-port +resolution and the no-loop guarantee are proven without Android, Kivy or a +running server. +""" + +import glob +import json +import os +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from services import controlSvc + + +class ControlTestCase(unittest.TestCase): + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.config_dir = self.tmp.name + + def tearDown(self): + self.tmp.cleanup() + + def control_path(self) -> str: + return os.path.join(self.config_dir, controlSvc.CONTROL_FILE) + + def settings_path(self) -> str: + return os.path.join(self.config_dir, controlSvc.SETTINGS_FILE) + + def write_control(self, control): + with open(self.control_path(), "w", encoding="utf-8") as control_file: + json.dump(control, control_file) + + def read_control(self) -> dict: + with open(self.control_path(), encoding="utf-8") as control_file: + return json.load(control_file) + + def write_settings(self, port): + with open(self.settings_path(), "w", encoding="utf-8") as settings_file: + json.dump({"app": "opensms", "port": port}, settings_file) + + def tmp_files(self) -> list: + return glob.glob(os.path.join(self.config_dir, "*.tmp")) + + +class ControlFileTests(ControlTestCase): + + def test_a_missing_control_file_reads_as_empty(self): + self.assertEqual(controlSvc.read_control(self.config_dir), {}) + + def test_an_unreadable_control_file_reads_as_empty(self): + with open(self.control_path(), "w", encoding="utf-8") as control_file: + control_file.write("not json") + + self.assertEqual(controlSvc.read_control(self.config_dir), {}) + + def test_writing_the_control_file_is_atomic_json(self): + controlSvc.write_control(self.config_dir, {"server": "start", "port": 9292}) + + self.assertEqual( + self.read_control(), {"server": "start", "port": 9292} + ) + self.assertEqual(self.tmp_files(), []) + + +class EffectivePortTests(ControlTestCase): + + def test_the_settings_port_wins(self): + self.write_settings(9393) + self.write_control({"port": 9292, "server": "start"}) + + self.assertEqual(controlSvc.effective_port(self.config_dir), 9393) + + def test_the_control_port_is_the_fallback_without_settings(self): + self.write_control({"port": 9393, "server": "start"}) + + self.assertEqual(controlSvc.effective_port(self.config_dir), 9393) + + def test_an_unreadable_settings_file_falls_back_to_the_control_port(self): + with open(self.settings_path(), "w", encoding="utf-8") as settings_file: + settings_file.write("not json") + self.write_control({"port": 9393, "server": "start"}) + + self.assertEqual(controlSvc.effective_port(self.config_dir), 9393) + + def test_an_invalid_settings_port_falls_back_to_the_control_port(self): + self.write_settings(80) + self.write_control({"port": 9393, "server": "start"}) + + self.assertEqual(controlSvc.effective_port(self.config_dir), 9393) + + def test_the_default_port_is_the_last_resort(self): + self.assertEqual( + controlSvc.effective_port(self.config_dir), + controlSvc.settingsSvc.DEFAULT_PORT, + ) + + +class ControlPreservationTests(ControlTestCase): + + def test_requesting_a_restart_preserves_unrelated_keys(self): + self.write_control({ + "port": 9292, + "server": "start", + "serial_port": "/dev/ttyUSB0", + "baudrate": 9600, + "unknown_key": "keep me", + }) + + controlSvc.request_restart(self.config_dir, 9393) + + self.assertEqual(self.read_control(), { + "port": 9393, + "server": "restart", + "serial_port": "/dev/ttyUSB0", + "baudrate": 9600, + "unknown_key": "keep me", + }) + self.assertEqual(self.tmp_files(), []) + + def test_normalising_a_restart_returns_start_and_keeps_other_keys(self): + self.write_control({ + "port": 9393, + "server": "restart", + "serial_port": "/dev/ttyUSB0", + "baudrate": 9600, + "unknown_key": "keep me", + }) + + changed = controlSvc.normalise_restart(self.config_dir, 9393) + + self.assertTrue(changed) + self.assertEqual(self.read_control(), { + "port": 9393, + "server": "start", + "serial_port": "/dev/ttyUSB0", + "baudrate": 9600, + "unknown_key": "keep me", + }) + self.assertEqual(self.tmp_files(), []) + + def test_normalising_without_a_port_uses_the_effective_port(self): + self.write_settings(9393) + self.write_control({"port": 9292, "server": "restart"}) + + controlSvc.normalise_restart(self.config_dir) + + self.assertEqual(self.read_control()["port"], 9393) + + def test_normalising_a_non_restart_intent_does_nothing(self): + self.write_control({"port": 9292, "server": "start"}) + + self.assertFalse(controlSvc.normalise_restart(self.config_dir, 9393)) + self.assertEqual(self.read_control(), {"port": 9292, "server": "start"}) + + def test_repeated_polling_does_not_restart_again(self): + self.write_control({"port": 9292, "server": "start"}) + controlSvc.request_restart(self.config_dir, 9393) + + self.assertTrue(controlSvc.restart_pending(self.config_dir)) + self.assertTrue(controlSvc.normalise_restart(self.config_dir, 9393)) + + self.assertFalse(controlSvc.restart_pending(self.config_dir)) + self.assertFalse(controlSvc.normalise_restart(self.config_dir, 9393)) + self.assertEqual(self.read_control()["server"], "start") diff --git a/app/tests/test_remote_api.py b/app/tests/test_remote_api.py index 36c5fc1..605b09b 100644 --- a/app/tests/test_remote_api.py +++ b/app/tests/test_remote_api.py @@ -1184,3 +1184,176 @@ def test_a_webhook_test_requires_authentication_and_the_settings_scope(self): self.assertEqual(response.status_code, 403) self.assertEqual(self.target.count, 0) + + +class FakeTimer: + """A threading.Timer that records its callback instead of firing.""" + + instances = [] + + def __init__(self, interval, target=None, args=(), kwargs=None): + self.interval = interval + self.target = target + self.args = args + self.kwargs = kwargs or {} + self.started = False + self.daemon = False + FakeTimer.instances.append(self) + + def start(self): + self.started = True + + def fire(self): + self.target(*self.args, **self.kwargs) + + +class RestartTestCase(ApiTestCase): + + def setUp(self): + super().setUp() + FakeTimer.instances = [] + postApi.set_runtime_providers({"running": lambda: True}) + self.timer_patch = mock.patch.object(postApi, "Timer", FakeTimer) + self.timer_patch.start() + + def tearDown(self): + self.timer_patch.stop() + super().tearDown() + + def request_path(self) -> str: + return os.path.join(self.config_dir, postApi.controlSvc.CONTROL_FILE) + + def read_request(self): + with open(self.request_path(), encoding="utf-8") as request_file: + return json.load(request_file) + + def write_request(self, value: dict): + with open(self.request_path(), "w", encoding="utf-8") as request_file: + json.dump(value, request_file) + + def restart(self, raw_key: str): + return self.client.post( + "/api/server/restart", headers=self.auth(raw_key) + ) + + +class RestartTests(RestartTestCase): + + def test_restart_is_acknowledged_before_the_intent_is_written(self): + self.write_config({"port": 9393, "boot": False, "webhook": {}}) + self.write_request({ + "port": 9292, + "server": "start", + "serial_port": "/dev/ttyUSB0", + "baudrate": 9600, + "unknown_key": "keep me", + }) + raw_key = self.add_api_key() + + with mock.patch.object(postApi.PosiApiServer, "stop") as stop_server: + response = self.restart(raw_key) + + self.assertEqual(response.status_code, 202) + self.assertEqual(response.json(), { + "status": "restarting", + "port": 9393, + }) + stop_server.assert_not_called() + # The response is already back while the control file still says start. + self.assertEqual(self.read_request()["server"], "start") + self.assertEqual(len(FakeTimer.instances), 1) + timer = FakeTimer.instances[0] + self.assertTrue(timer.started) + self.assertTrue(timer.daemon) + self.assertEqual(timer.interval, postApi.RESTART_DELAY_SECONDS) + + timer.fire() + + self.assertEqual(self.read_request(), { + "port": 9393, + "server": "restart", + "serial_port": "/dev/ttyUSB0", + "baudrate": 9600, + "unknown_key": "keep me", + }) + + def test_the_restart_uses_the_effective_port_over_the_control_port(self): + self.write_config({"port": 9393, "boot": False, "webhook": {}}) + self.write_request({"port": 9292, "server": "start"}) + raw_key = self.add_api_key() + + response = self.restart(raw_key) + + self.assertEqual(response.status_code, 202) + self.assertEqual(response.json()["port"], 9393) + + def test_a_second_restart_within_five_seconds_is_refused(self): + raw_key = self.add_api_key() + + first = self.restart(raw_key) + second = self.restart(raw_key) + + self.assertEqual(first.status_code, 202) + self.assertEqual(second.status_code, 409) + self.assertIsInstance(second.json()["detail"], str) + self.assertEqual(len(FakeTimer.instances), 1) + + def test_the_debounce_lifts_after_five_seconds(self): + raw_key = self.add_api_key() + self.restart(raw_key) + + postApi._last_restart_at = ( + time.monotonic() - postApi.RESTART_DEBOUNCE_SECONDS - 1 + ) + second = self.restart(raw_key) + + self.assertEqual(second.status_code, 202) + self.assertEqual(len(FakeTimer.instances), 2) + + def test_a_failed_intent_write_releases_the_debounce(self): + raw_key = self.add_api_key() + self.assertEqual(self.restart(raw_key).status_code, 202) + + with mock.patch.object( + postApi.controlSvc, + "request_restart", + side_effect=OSError("disk full"), + ): + FakeTimer.instances[-1].fire() + + self.assertFalse(os.path.exists(self.request_path())) + retry = self.restart(raw_key) + self.assertEqual(retry.status_code, 202) + + def test_a_restart_is_refused_while_the_server_is_not_running(self): + postApi.set_runtime_providers({"running": lambda: False}) + raw_key = self.add_api_key() + + response = self.restart(raw_key) + + self.assertEqual(response.status_code, 409) + self.assertIsInstance(response.json()["detail"], str) + self.assertFalse(os.path.exists(self.request_path())) + self.assertEqual(FakeTimer.instances, []) + + def test_restart_requires_authentication_and_the_settings_scope(self): + response = self.client.post("/api/server/restart") + self.assertEqual(response.status_code, 403) + + raw_key = self.add_api_key(scopes=("sms:write",)) + response = self.restart(raw_key) + self.assertEqual(response.status_code, 403) + + self.assertEqual(FakeTimer.instances, []) + + +class ControlRouteTests(ApiTestCase): + + def test_the_superseded_control_route_is_gone(self): + raw_key = self.add_api_key() + + response = self.client.post( + "/control/", json={"api": "start"}, headers=self.auth(raw_key) + ) + + self.assertEqual(response.status_code, 404) From 2fe6a0c35253aceeb6ede48894357cbabfe10376 Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 18:11:19 +0100 Subject: [PATCH 09/20] feat: give each integration its own API key --- README.md | 2 +- app/main.py | 6 +- app/openSmsCli.py | 4 +- app/screens/settings.py | 4 +- app/services/postApi.py | 226 +++++++++++++++++++++++-- app/tests/test_remote_api.py | 313 +++++++++++++++++++++++++++++++++++ 6 files changed, 531 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 19dc06f..3e8a246 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ You may need to run this first to generate the first API Key. ```bash python openSmsCli.py interactive --serial /dev/ttyUSB0 # change your serial port, on windows: COM1 (example) -# generate a new API key +# replace this phone's API key (other keys keep working) newkey # get other interactive commands diff --git a/app/main.py b/app/main.py index 49003f7..82e1ca6 100644 --- a/app/main.py +++ b/app/main.py @@ -523,7 +523,7 @@ def new_api_key_pop(self): ), MDButton( MDButtonText( - text="Generate", + text="Replace", theme_text_color= "Custom", text_color= "green" ), @@ -533,8 +533,8 @@ def new_api_key_pop(self): spacing="8dp", ) self.show_text_dialog( - "Generate API Key", - "Do you want to generate the a new API key? This will make old keys invalid.", + "Replace API Key", + "Do you want to replace this phone's API key? The old key for this phone stops working; other API keys keep working.", None, buttons ) diff --git a/app/openSmsCli.py b/app/openSmsCli.py index 7cf3d9e..9094cb5 100644 --- a/app/openSmsCli.py +++ b/app/openSmsCli.py @@ -101,7 +101,7 @@ def command_loop(self): print("Available commands: newkey, status, help, quit\n") help_cmd = """ Available commands: - newkey - Generate New API Key + newkey - Replace this phone's API key status - Show service status help - Show available commands quit - Stop OpenSMS @@ -116,7 +116,7 @@ def command_loop(self): break elif cmd == "newkey": - confirmation = input("Old key will be invalid, are you sure (y/n) > ").strip().lower() + confirmation = input("This phone's key will be replaced; other keys keep working. Are you sure (y/n) > ").strip().lower() if confirmation == "y": self.new_api_key() diff --git a/app/screens/settings.py b/app/screens/settings.py index 0529eb2..aa57b45 100644 --- a/app/screens/settings.py +++ b/app/screens/settings.py @@ -99,9 +99,9 @@ MDListItemHeadlineText: text: "API Key" MDListItemSupportingText: - text: "Generate New API Key" + text: "Replace this phone's API key" MDListItemTertiaryText: - text: "Old key will not work" + text: "Other API keys keep working" MDFabButton: icon: "autorenew" style: "small" diff --git a/app/services/postApi.py b/app/services/postApi.py index a98afb3..52bd7fc 100644 --- a/app/services/postApi.py +++ b/app/services/postApi.py @@ -1,4 +1,5 @@ import hashlib +import re import secrets import asyncio import time @@ -43,6 +44,25 @@ SCOPE_SEND = "sms:write" SCOPE_SETTINGS = "settings:write" +VALID_SCOPES = frozenset({SCOPE_SEND, SCOPE_SETTINGS}) +PHONE_KEY_NAME = "opensms" +KEY_NAME_MIN = 2 +KEY_NAME_MAX = 64 +_KEY_ID_PATTERN = re.compile(r"^k_[0-9a-f]{8}$") +_SCOPE_ERROR = ( + "scopes must be a non-empty subset of: " + + ", ".join(sorted(VALID_SCOPES)) +) +_DEFAULT_SCOPES = object() + + +class KeyValidationError(ValueError): + """A malformed key request (HTTP 422).""" + + +class KeyConflict(Exception): + """A key request that conflicts with the stored keys (HTTP 409).""" + # Test seam: tests point the API at a temporary config directory so they never # read or write the real app data directory. _config_dir: str | None = None @@ -174,7 +194,7 @@ def _migrate_v1_keys(raw: dict) -> list: scopes.update({SCOPE_SEND, SCOPE_SETTINGS}) keys.append({ "id": f"k_{secrets.token_hex(4)}", - "name": str(info.get("name") or "opensms"), + "name": str(info.get("name") or PHONE_KEY_NAME), "hash": str(key_hash), "scopes": sorted(scopes), "created_at": _now_iso(), @@ -217,22 +237,130 @@ def has_api_keys() -> bool: store, _ = load_key_store() return bool(store["keys"]) +def _normalize_key_name(value) -> str: + if not isinstance(value, str): + raise KeyValidationError("name must be a string") + name = value.strip() + if not KEY_NAME_MIN <= len(name) <= KEY_NAME_MAX: + raise KeyValidationError( + f"name must be {KEY_NAME_MIN}-{KEY_NAME_MAX} characters" + ) + if not name.isprintable(): + raise KeyValidationError("name must not contain control characters") + return name + +def _normalize_key_scopes(value) -> list: + if not isinstance(value, list): + raise KeyValidationError("scopes must be a list") + scopes = set() + for scope in value: + if not isinstance(scope, str) or scope not in VALID_SCOPES: + raise KeyValidationError(_SCOPE_ERROR) + scopes.add(scope) + if not scopes: + raise KeyValidationError(_SCOPE_ERROR) + return sorted(scopes) + +def _new_key_entry(name: str, scopes, raw_key: str) -> dict: + return { + "id": f"k_{secrets.token_hex(4)}", + "name": name, + "hash": hash_api_key(raw_key), + "scopes": sorted(scopes), + "created_at": _now_iso(), + } + +def _new_raw_key() -> str: + return f"osms_{secrets.token_urlsafe(32)}" + +def public_key(entry: dict) -> dict: + """The listable shape of a key: never the hash or the raw key.""" + scopes = entry.get("scopes") + if not isinstance(scopes, list): + scopes = [] + return { + "id": entry.get("id"), + "name": entry.get("name"), + "scopes": list(scopes), + "created_at": entry.get("created_at"), + } + +def create_api_key(name, scopes=_DEFAULT_SCOPES) -> dict: + """Create a named key; the raw key is returned only in this result.""" + name = _normalize_key_name(name) + normalized_scopes = ( + sorted(VALID_SCOPES) + if scopes is _DEFAULT_SCOPES + else _normalize_key_scopes(scopes) + ) + raw_key = _new_raw_key() + with _key_lock: + store, _ = load_key_store() + for entry in store["keys"]: + existing_name = entry.get("name") + if ( + isinstance(existing_name, str) + and existing_name.casefold() == name.casefold() + ): + raise KeyConflict(f"An API key named {name} already exists") + entry = _new_key_entry(name, normalized_scopes, raw_key) + store["keys"].append(entry) + save_key_store(store) + log_activities(f"API key created: {name}") + return {**public_key(entry), "key": raw_key} + +def list_api_keys() -> list: + """Every key without its hash or raw value.""" + store, _ = load_key_store() + return [public_key(entry) for entry in store["keys"]] + +def delete_api_key(key_id: str) -> bool: + """Delete a key by id, returning False when it does not exist. + + Raises KeyConflict when deleting it would leave no key at all. + """ + if not isinstance(key_id, str) or not _KEY_ID_PATTERN.fullmatch(key_id): + return False + with _key_lock: + store, _ = load_key_store() + keys = store["keys"] + index = next( + ( + position + for position, entry in enumerate(keys) + if entry.get("id") == key_id + ), + None, + ) + if index is None: + return False + if len(keys) <= 1: + raise KeyConflict("The last remaining API key cannot be deleted") + removed = keys.pop(index) + save_key_store(store) + log_activities(f"API key deleted: {removed.get('name')}") + return True + +def rotate_phone_key() -> str: + """Replace only the phone-owned key, leaving proxy-owned keys intact.""" + raw_key = _new_raw_key() + with _key_lock: + store, _ = load_key_store() + store["keys"] = [ + entry for entry in store["keys"] + if str(entry.get("name") or "").casefold() != PHONE_KEY_NAME + ] + store["keys"].append( + _new_key_entry(PHONE_KEY_NAME, VALID_SCOPES, raw_key) + ) + save_key_store(store) + print("Replaced the phone API key") + log_activities("Replaced the phone API key") + return raw_key + def generate_new_api_key() -> str: - # Generate a high-entropy secret token - new_raw_key = f"osms_{secrets.token_urlsafe(32)}" - save_key_store({ - "version": 2, - "keys": [{ - "id": f"k_{secrets.token_hex(4)}", - "name": "opensms", - "hash": hash_api_key(new_raw_key), - "scopes": sorted({SCOPE_SEND, SCOPE_SETTINGS}), - "created_at": _now_iso(), - }], - }) - print("Created/updated the API key") - log_activities("Created/updated the API key") - return new_raw_key + """Backwards-compatible entry point for rotating the phone key.""" + return rotate_phone_key() @@ -656,6 +784,72 @@ async def api_put_settings( "restart_required": _restart_required(saved), } +KEY_REQUEST_FIELDS = {"name", "scopes"} + + +async def _key_request_body(request: Request) -> dict: + """Validate the shape of a key-creation body, before touching the store.""" + try: + payload = await request.json() + except Exception: + raise HTTPException( + status_code=422, + detail="Request body must be valid JSON", + ) + if not isinstance(payload, dict): + raise HTTPException( + status_code=422, + detail="Request body must be a JSON object", + ) + unknown = set(payload) - KEY_REQUEST_FIELDS + if unknown: + raise HTTPException( + status_code=422, + detail=f"Unknown field(s) in request: {', '.join(sorted(unknown))}", + ) + if "name" not in payload: + raise HTTPException( + status_code=422, + detail="Missing required field: name", + ) + return payload + + +@app.post("/api/keys", status_code=201) +async def api_create_key( + request: Request, + client: dict = Depends(require_scope(SCOPE_SETTINGS)) +): + payload = await _key_request_body(request) + try: + return create_api_key( + payload["name"], payload.get("scopes", _DEFAULT_SCOPES) + ) + except KeyConflict as exc: + raise HTTPException(status_code=409, detail=str(exc)) + except KeyValidationError as exc: + raise HTTPException(status_code=422, detail=str(exc)) + + +@app.get("/api/keys") +async def api_list_keys( + client: dict = Depends(require_scope(SCOPE_SETTINGS)) +): + return {"keys": list_api_keys()} + + +@app.delete("/api/keys/{key_id}", status_code=204) +async def api_delete_key( + key_id: str, + client: dict = Depends(require_scope(SCOPE_SETTINGS)) +): + try: + deleted = delete_api_key(key_id) + except KeyConflict as exc: + raise HTTPException(status_code=409, detail=str(exc)) + if not deleted: + raise HTTPException(status_code=404, detail="API key not found") + WEBHOOK_TEST_FIELDS = {"url", "secret"} diff --git a/app/tests/test_remote_api.py b/app/tests/test_remote_api.py index 605b09b..422ee90 100644 --- a/app/tests/test_remote_api.py +++ b/app/tests/test_remote_api.py @@ -1357,3 +1357,316 @@ def test_the_superseded_control_route_is_gone(self): ) self.assertEqual(response.status_code, 404) + + +class KeyCreateTests(ApiTestCase): + + def create_key(self, raw_key: str, payload: dict): + return self.client.post( + "/api/keys", json=payload, headers=self.auth(raw_key) + ) + + def test_create_returns_the_key_once_and_it_authenticates_immediately(self): + admin = self.add_api_key(name="admin") + + response = self.create_key(admin, {"name": " sms-proxy "}) + + self.assertEqual(response.status_code, 201) + body = response.json() + self.assertEqual(body["name"], "sms-proxy") + self.assertRegex(body["id"], r"^k_[0-9a-f]{8}$") + self.assertEqual(body["scopes"], ["settings:write", "sms:write"]) + self.assertTrue(body["created_at"]) + self.assertTrue(body["key"].startswith("osms_")) + self.assertNotIn("hash", body) + + health = self.client.get("/api/health", headers=self.auth(body["key"])) + self.assertEqual(health.status_code, 200) + + def test_scopes_are_an_optional_subset(self): + admin = self.add_api_key(name="admin") + + response = self.create_key( + admin, {"name": "sender", "scopes": ["sms:write"]} + ) + + self.assertEqual(response.status_code, 201) + self.assertEqual(response.json()["scopes"], ["sms:write"]) + key = response.json()["key"] + self.assertEqual( + self.client.post( + "/sms/", + json={"number": "+14155552671", "text": "hello"}, + headers=self.auth(key), + ).status_code, + 200, + ) + self.assertEqual( + self.client.get( + "/api/settings", headers=self.auth(key) + ).status_code, + 403, + ) + + def test_an_empty_or_unknown_scope_set_is_rejected(self): + admin = self.add_api_key(name="admin") + + cases = { + "empty list": [], + "null": None, + "unknown scope": ["sms:read"], + "mixed unknown": ["sms:write", "admin"], + "not a list": "sms:write", + } + for name, scopes in cases.items(): + with self.subTest(name): + response = self.create_key( + admin, {"name": "bad-scopes", "scopes": scopes} + ) + + self.assertEqual(response.status_code, 422, response.text) + self.assertIsInstance(response.json()["detail"], str) + + def test_a_duplicate_name_differing_only_by_case_is_refused(self): + admin = self.add_api_key(name="admin") + first = self.create_key(admin, {"name": "sms-proxy"}) + self.assertEqual(first.status_code, 201) + + response = self.create_key(admin, {"name": "SMS-Proxy"}) + + self.assertEqual(response.status_code, 409) + self.assertIsInstance(response.json()["detail"], str) + + def test_names_are_trimmed_and_length_checked(self): + admin = self.add_api_key(name="admin") + + cases = { + "too short": "a", + "blank": " ", + "too long": "x" * 65, + "control character": "bad\nname", + "C1 control character": "bad\u0085name", + "line separator": "bad\u2028name", + "not a string": 42, + } + for name, value in cases.items(): + with self.subTest(name): + response = self.create_key(admin, {"name": value}) + + self.assertEqual(response.status_code, 422, response.text) + self.assertIsInstance(response.json()["detail"], str) + + def test_create_rejects_unknown_fields_and_a_non_object_body(self): + admin = self.add_api_key(name="admin") + + response = self.create_key( + admin, {"name": "proxy", "unexpected": True} + ) + self.assertEqual(response.status_code, 422) + + response = self.client.post( + "/api/keys", json=["not", "an", "object"], + headers=self.auth(admin), + ) + self.assertEqual(response.status_code, 422) + + def test_create_requires_authentication_and_the_settings_scope(self): + response = self.client.post( + "/api/keys", json={"name": "proxy"} + ) + self.assertEqual(response.status_code, 403) + + sender = self.add_api_key(name="sender", scopes=("sms:write",)) + response = self.create_key(sender, {"name": "proxy"}) + self.assertEqual(response.status_code, 403) + + def test_the_stored_key_is_hashed_and_never_returned_again(self): + admin = self.add_api_key(name="admin") + created = self.create_key(admin, {"name": "proxy"}).json() + + store = self.read_key_store() + entry = next( + key for key in store["keys"] if key["id"] == created["id"] + ) + self.assertEqual(entry["hash"], postApi.hash_api_key(created["key"])) + self.assertEqual(entry["scopes"], ["settings:write", "sms:write"]) + self.assertNotIn(created["key"], json.dumps(store)) + + +class KeyListTests(ApiTestCase): + + def test_list_never_returns_hashes(self): + admin = self.add_api_key(name="admin") + created = self.client.post( + "/api/keys", json={"name": "proxy"}, headers=self.auth(admin) + ).json() + + response = self.client.get("/api/keys", headers=self.auth(admin)) + + self.assertEqual(response.status_code, 200) + body = response.json() + self.assertEqual(len(body["keys"]), 2) + entry = next( + key for key in body["keys"] if key["id"] == created["id"] + ) + self.assertEqual(entry, { + "id": created["id"], + "name": "proxy", + "scopes": ["settings:write", "sms:write"], + "created_at": created["created_at"], + }) + self.assertNotIn("hash", response.text) + self.assertNotIn(created["key"], response.text) + + def test_list_requires_authentication_and_the_settings_scope(self): + response = self.client.get("/api/keys") + self.assertEqual(response.status_code, 403) + + sender = self.add_api_key(name="sender", scopes=("sms:write",)) + response = self.client.get("/api/keys", headers=self.auth(sender)) + self.assertEqual(response.status_code, 403) + + +class KeyDeleteTests(ApiTestCase): + + def delete(self, raw_key: str, key_id: str): + return self.client.delete( + f"/api/keys/{key_id}", headers=self.auth(raw_key) + ) + + def test_delete_takes_effect_immediately(self): + admin = self.add_api_key(name="admin") + created = self.client.post( + "/api/keys", json={"name": "proxy"}, headers=self.auth(admin) + ).json() + key = created["key"] + + response = self.delete(admin, created["id"]) + + self.assertEqual(response.status_code, 204) + self.assertEqual( + self.client.get("/api/health", headers=self.auth(key)).status_code, + 401, + ) + + def test_an_unknown_or_malformed_id_is_not_found(self): + admin = self.add_api_key(name="admin") + self.add_api_key(name="other") + + for key_id in ("k_deadbeef", "not-an-id", "k_xyz"): + with self.subTest(key_id): + response = self.delete(admin, key_id) + + self.assertEqual(response.status_code, 404) + + def test_deleting_the_last_remaining_key_is_refused(self): + only_key = self.add_api_key(name="only") + key_id = self.read_key_store()["keys"][0]["id"] + + response = self.delete(only_key, key_id) + + self.assertEqual(response.status_code, 409) + self.assertIsInstance(response.json()["detail"], str) + self.assertEqual( + self.client.get( + "/api/health", headers=self.auth(only_key) + ).status_code, + 200, + ) + + def test_the_caller_can_delete_its_own_key_while_another_remains(self): + first = self.add_api_key(name="first") + second = self.add_api_key(name="second") + first_id = next( + key["id"] for key in self.read_key_store()["keys"] + if key["name"] == "first" + ) + + response = self.delete(first, first_id) + + self.assertEqual(response.status_code, 204) + self.assertEqual( + self.client.get( + "/api/health", headers=self.auth(first) + ).status_code, + 401, + ) + self.assertEqual( + self.client.get( + "/api/health", headers=self.auth(second) + ).status_code, + 200, + ) + + def test_delete_requires_authentication_and_the_settings_scope(self): + admin = self.add_api_key(name="admin") + other = self.add_api_key(name="other") + other_id = next( + key["id"] for key in self.read_key_store()["keys"] + if key["name"] == "other" + ) + + self.assertEqual( + self.client.delete(f"/api/keys/{other_id}").status_code, 403 + ) + + sender = self.add_api_key(name="sender", scopes=("sms:write",)) + self.assertEqual( + self.delete(sender, other_id).status_code, 403 + ) + self.assertEqual( + self.client.get( + "/api/health", headers=self.auth(other) + ).status_code, + 200, + ) + + +class PhoneKeyRotationTests(ApiTestCase): + + def test_rotation_replaces_only_the_phone_key(self): + old_phone = self.add_api_key(name="opensms") + proxy = self.add_api_key(name="sms-proxy") + + new_phone = postApi.generate_new_api_key() + + self.assertEqual( + self.client.get( + "/api/health", headers=self.auth(old_phone) + ).status_code, + 401, + ) + self.assertEqual( + self.client.get( + "/api/health", headers=self.auth(new_phone) + ).status_code, + 200, + ) + self.assertEqual( + self.client.get( + "/api/health", headers=self.auth(proxy) + ).status_code, + 200, + ) + names = [key["name"] for key in self.read_key_store()["keys"]] + self.assertEqual(names.count("opensms"), 1) + self.assertIn("sms-proxy", names) + + def test_rotation_adds_a_phone_key_without_touching_proxy_keys(self): + proxy = self.add_api_key(name="sms-proxy") + + new_phone = postApi.generate_new_api_key() + + self.assertEqual( + self.client.get( + "/api/health", headers=self.auth(new_phone) + ).status_code, + 200, + ) + self.assertEqual( + self.client.get( + "/api/health", headers=self.auth(proxy) + ).status_code, + 200, + ) + self.assertEqual(len(self.read_key_store()["keys"]), 2) From 102a8e1566e059652db5cbae71bdc1871f868a3c Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 18:24:29 +0100 Subject: [PATCH 10/20] feat: keep Inbound SMS through a longer proxy outage Read Webhook timeout, maximum attempts, backoff, and Outbox capacity from the live Settings on each Delivery attempt and at enqueue. Missing or invalid values fall back to today's constants, a malformed Settings file cannot crash the dispatcher, and explicit constructor overrides still win. --- app/services/settingsSvc.py | 40 +++--- app/services/webhookSvc.py | 137 +++++++++++++++++--- app/tests/test_settings_local_save.py | 28 +++- app/tests/test_webhook.py | 179 +++++++++++++++++++++++++- docs/adr/0001-inbound-sms-webhook.md | 4 +- 5 files changed, 342 insertions(+), 46 deletions(-) diff --git a/app/services/settingsSvc.py b/app/services/settingsSvc.py index cdc7714..6ba2baf 100644 --- a/app/services/settingsSvc.py +++ b/app/services/settingsSvc.py @@ -12,28 +12,30 @@ from services.config import app_name from services.webhookSvc import ( + BACKOFF_MAX_COUNT, + BACKOFF_MAX_SECONDS, + BACKOFF_MIN_COUNT, + CAPACITY_MAX, + CAPACITY_MIN, DEFAULT_BACKOFF, DEFAULT_CAPACITY, DEFAULT_MAX_ATTEMPTS, DEFAULT_TIMEOUT, + MAX_ATTEMPTS_MAX, + MAX_ATTEMPTS_MIN, + TIMEOUT_MAX, + TIMEOUT_MIN, is_valid_target, + normalize_webhook_config, ) DEFAULT_PORT = 9292 DEFAULT_BOOT = False -# Ranges from the API contract in docs/remote-api.md. +# Port range from the API contract in docs/remote-api.md. The Webhook retry +# ranges live with the delivery defaults in webhookSvc. PORT_MIN = 1025 PORT_MAX = 65535 -TIMEOUT_MIN = 1 -TIMEOUT_MAX = 60 -MAX_ATTEMPTS_MIN = 1 -MAX_ATTEMPTS_MAX = 50 -BACKOFF_MIN_COUNT = 1 -BACKOFF_MAX_COUNT = 8 -BACKOFF_MAX_SECONDS = 3600 -CAPACITY_MIN = 10 -CAPACITY_MAX = 5000 SECRET_MAX_LENGTH = 256 TOP_LEVEL_FIELDS = {"port", "boot", "webhook", "revision"} @@ -300,13 +302,15 @@ def validate_merged_settings(settings: dict): ## API shape def writable_settings(settings: dict) -> dict: - """Return only the writable subset, with the secret masked.""" + """Return only the writable subset, with the secret masked. + + Retry values are normalized the same way the dispatcher reads them, so an + invalid value stored by hand is reported as the constant actually in use. + """ webhook = settings.get("webhook") if not isinstance(webhook, dict): webhook = {} - backoff = webhook.get("backoff") - if not isinstance(backoff, list): - backoff = list(DEFAULT_BACKOFF) + retry = normalize_webhook_config(webhook) return { "port": settings.get("port", DEFAULT_PORT), "boot": settings.get("boot", DEFAULT_BOOT), @@ -314,10 +318,10 @@ def writable_settings(settings: dict) -> dict: "enabled": webhook.get("enabled", False), "url": webhook.get("url", ""), "secret_set": bool(webhook.get("secret")), - "timeout": webhook.get("timeout", DEFAULT_TIMEOUT), - "max_attempts": webhook.get("max_attempts", DEFAULT_MAX_ATTEMPTS), - "backoff": list(backoff), - "capacity": webhook.get("capacity", DEFAULT_CAPACITY), + "timeout": retry["timeout"], + "max_attempts": retry["max_attempts"], + "backoff": list(retry["backoff"]), + "capacity": retry["capacity"], }, } diff --git a/app/services/webhookSvc.py b/app/services/webhookSvc.py index cd20be0..f3f60ab 100644 --- a/app/services/webhookSvc.py +++ b/app/services/webhookSvc.py @@ -30,6 +30,17 @@ DEFAULT_MAX_ATTEMPTS = 3 DEFAULT_CAPACITY = 100 +# Live Settings ranges, shared with the API validator in settingsSvc. +TIMEOUT_MIN = 1 +TIMEOUT_MAX = 60 +MAX_ATTEMPTS_MIN = 1 +MAX_ATTEMPTS_MAX = 50 +BACKOFF_MIN_COUNT = 1 +BACKOFF_MAX_COUNT = 8 +BACKOFF_MAX_SECONDS = 3600 +CAPACITY_MIN = 10 +CAPACITY_MAX = 5000 + ## Config def default_webhook_config() -> dict: @@ -37,14 +48,63 @@ def default_webhook_config() -> dict: "enabled": False, "url": "", "secret": "", + "timeout": DEFAULT_TIMEOUT, + "max_attempts": DEFAULT_MAX_ATTEMPTS, + "backoff": list(DEFAULT_BACKOFF), + "capacity": DEFAULT_CAPACITY, } +def _int_setting(value, default: int, low: int, high: int) -> int: + """Return `value` when it is an in-range JSON integer, else `default`.""" + if ( + isinstance(value, int) + and not isinstance(value, bool) + and low <= value <= high + ): + return value + return default + +def _backoff_setting(value) -> list: + if not isinstance(value, list) or not ( + BACKOFF_MIN_COUNT <= len(value) <= BACKOFF_MAX_COUNT + ): + return list(DEFAULT_BACKOFF) + normalized = [] + for wait_for in value: + if ( + not isinstance(wait_for, int) + or isinstance(wait_for, bool) + or wait_for < 1 + or wait_for > BACKOFF_MAX_SECONDS + ): + return list(DEFAULT_BACKOFF) + normalized.append(wait_for) + return normalized + def normalize_webhook_config(raw: dict | None) -> dict: + """Normalize the Webhook object, falling back to today's constants. + + A missing or invalid retry value must never crash the dispatcher; the + value simply behaves as the constant it replaced. + """ config = default_webhook_config() if isinstance(raw, dict): config["enabled"] = bool(raw.get("enabled", False)) config["url"] = str(raw.get("url") or "").strip() config["secret"] = str(raw.get("secret") or "") + config["timeout"] = _int_setting( + raw.get("timeout"), DEFAULT_TIMEOUT, TIMEOUT_MIN, TIMEOUT_MAX + ) + config["max_attempts"] = _int_setting( + raw.get("max_attempts"), + DEFAULT_MAX_ATTEMPTS, + MAX_ATTEMPTS_MIN, + MAX_ATTEMPTS_MAX, + ) + config["backoff"] = _backoff_setting(raw.get("backoff")) + config["capacity"] = _int_setting( + raw.get("capacity"), DEFAULT_CAPACITY, CAPACITY_MIN, CAPACITY_MAX + ) return config def get_webhook_config(config_path: str) -> dict: @@ -261,18 +321,26 @@ def __init__( outbox_path: str, status_path: str, log=None, - timeout: float = DEFAULT_TIMEOUT, - backoff: tuple = DEFAULT_BACKOFF, - max_attempts: int = DEFAULT_MAX_ATTEMPTS, - capacity: int = DEFAULT_CAPACITY, + timeout: float | None = None, + backoff: tuple | None = None, + max_attempts: int | None = None, + capacity: int | None = None, ): + # `None` means "read the live Settings value on each use"; an explicit + # value is a test override and always wins, as it did before. self.config_path = config_path self.outbox_path = outbox_path self.status_path = status_path - self.timeout = timeout - self.backoff = tuple(backoff) - self.max_attempts = max(1, int(max_attempts)) - self.capacity = max(1, int(capacity)) + self._timeout_override = timeout + self._backoff_override = ( + tuple(backoff) if backoff is not None else None + ) + self._max_attempts_override = ( + max(1, int(max_attempts)) if max_attempts is not None else None + ) + self._capacity_override = ( + max(1, int(capacity)) if capacity is not None else None + ) self.log = log or (lambda message: None) self._queue = queue.Queue() self._lock = threading.Lock() @@ -286,6 +354,31 @@ def __init__( ) self._thread.start() + ## Live Settings + + @staticmethod + def _resolved(override, live_value): + """An explicit constructor override always wins over live Settings.""" + return live_value if override is None else override + + def _timeout_for(self, config: dict) -> float: + return self._resolved(self._timeout_override, config["timeout"]) + + def _backoff_for(self, config: dict) -> tuple: + return self._resolved( + self._backoff_override, tuple(config["backoff"]) + ) + + def _max_attempts_for(self, config: dict) -> int: + return self._resolved( + self._max_attempts_override, config["max_attempts"] + ) + + def _capacity_for(self, config: dict) -> int: + return self._resolved( + self._capacity_override, config["capacity"] + ) + ## Outbox def _load_outbox(self): @@ -327,7 +420,8 @@ def enqueue(self, payload: dict) -> bool: "attempts": 0, } with self._lock: - while len(self._outbox) >= self.capacity: + capacity = self._capacity_for(config) + while len(self._outbox) >= capacity: dropped_id, dropped = self._outbox.popitem(last=False) self.log( f"Webhook outbox full, dropped {dropped.get('event')} " @@ -387,32 +481,37 @@ def _deliver(self, record: dict) -> tuple: """Attempt delivery. Returns (ok, status, error, interrupted).""" status = None error = None - attempts_done = int(record.get("attempts") or 0) - if attempts_done >= self.max_attempts: - return False, None, "retry limit reached", False - for attempt in range(attempts_done + 1, self.max_attempts + 1): + attempt = int(record.get("attempts") or 0) + 1 + while True: if self._stop.is_set(): return False, status, "dispatcher stopped", True config = get_webhook_config(self.config_path) if not config["enabled"]: return False, status, "webhook disabled", False + max_attempts = self._max_attempts_for(config) + if attempt > max_attempts: + return False, status, "retry limit reached", False record["attempts"] = attempt with self._lock: self._persist_outbox() body = encode_payload(record["payload"]) headers = build_headers(record["payload"], body, config["secret"]) ok, status, error = post_json( - record["url"], body, headers, self.timeout + record["url"], body, headers, self._timeout_for(config) ) if ok: return True, status, None, False if self._stop.is_set(): return False, status, "dispatcher stopped", True - if attempt < self.max_attempts: - wait_for = self.backoff[min(attempt - 1, len(self.backoff) - 1)] - if self._stop.wait(wait_for): - return False, status, "dispatcher stopped", True - return False, status, error, False + if attempt >= max_attempts: + return False, status, error, False + backoff = self._backoff_for(config) + wait_for = ( + backoff[min(attempt - 1, len(backoff) - 1)] if backoff else 0 + ) + if self._stop.wait(wait_for): + return False, status, "dispatcher stopped", True + attempt += 1 def _write_status(self, record: dict, ok: bool, status, error): payload = { diff --git a/app/tests/test_settings_local_save.py b/app/tests/test_settings_local_save.py index 2327d3a..552a876 100644 --- a/app/tests/test_settings_local_save.py +++ b/app/tests/test_settings_local_save.py @@ -81,8 +81,34 @@ def screen_form(self, current: dict, **overrides) -> dict: return form -class LocalSaveMergeTests(LocalSaveTestCase): +class WritableSettingsTests(LocalSaveTestCase): + + def test_invalid_stored_retry_values_report_the_effective_defaults(self): + config = self.stored_config() + config["webhook"].update({ + "timeout": 0, + "max_attempts": "many", + "backoff": [], + "capacity": 99999, + }) + self.write_config(config) + + writable = settingsSvc.writable_settings( + settingsSvc.load_settings(self.config_path) + ) + webhook = writable["webhook"] + self.assertEqual(webhook["timeout"], settingsSvc.DEFAULT_TIMEOUT) + self.assertEqual( + webhook["max_attempts"], settingsSvc.DEFAULT_MAX_ATTEMPTS + ) + self.assertEqual( + webhook["backoff"], list(settingsSvc.DEFAULT_BACKOFF) + ) + self.assertEqual(webhook["capacity"], settingsSvc.DEFAULT_CAPACITY) + + +class LocalSaveMergeTests(LocalSaveTestCase): def test_entering_then_saving_keeps_a_remote_webhook_target(self): # The screen re-reads on entry, so it shows the remote target. current = settingsSvc.load_settings(self.config_path) diff --git a/app/tests/test_webhook.py b/app/tests/test_webhook.py index e420ae3..35039c0 100644 --- a/app/tests/test_webhook.py +++ b/app/tests/test_webhook.py @@ -10,6 +10,7 @@ import unittest from datetime import datetime from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest import mock sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) @@ -28,6 +29,8 @@ def do_POST(self): "headers": {k.lower(): v for k, v in self.headers.items()}, "body": body, }) + if self.server.delay: + time.sleep(self.server.delay) status = self.server.statuses.get_nowait() \ if not self.server.statuses.empty() else 200 if status in (301, 302, 303, 307, 308): @@ -48,6 +51,7 @@ def __init__(self): self.server.requests = queue.Queue() self.server.statuses = queue.Queue() self.server.count = 0 + self.server.delay = 0 self.server.redirect_location = None self.thread = threading.Thread( target=self.server.serve_forever, daemon=True @@ -69,6 +73,9 @@ def queue_statuses(self, *codes): def redirect_to(self, url): self.server.redirect_location = url + def set_delay(self, seconds): + self.server.delay = seconds + def next_request(self, timeout=5): return self.server.requests.get(timeout=timeout) @@ -106,18 +113,33 @@ def tearDown(self): self.target.close() self.tmp.cleanup() - def write_config(self, enabled=True, url=None, secret=""): + def write_config(self, enabled=True, url=None, secret="", **retry): + webhook = { + "enabled": enabled, + "url": url if url is not None else self.target.url, + "secret": secret, + } + webhook.update(retry) with open(self.config_path, "w", encoding="utf-8") as cf: json.dump({ "port": 9292, "boot": False, - "webhook": { - "enabled": enabled, - "url": url if url is not None else self.target.url, - "secret": secret, - }, + "webhook": webhook, }, cf) + def write_live_webhook(self, **overrides): + webhook = { + "enabled": True, + "url": self.target.url, + "secret": "", + "timeout": webhookSvc.DEFAULT_TIMEOUT, + "max_attempts": webhookSvc.DEFAULT_MAX_ATTEMPTS, + "backoff": list(webhookSvc.DEFAULT_BACKOFF), + "capacity": webhookSvc.DEFAULT_CAPACITY, + } + webhook.update(overrides) + self.write_config(**webhook) + def make_dispatcher(self, **kwargs): kwargs.setdefault("backoff", (0.01, 0.01)) kwargs.setdefault("timeout", 1) @@ -365,6 +387,151 @@ def _deliver(self, record): self.assertEqual(blocking.pending_count(), 2) blocking.release.set() + ## Live Settings + + def test_missing_retry_settings_use_constants(self): + self.write_config(enabled=True) + config = webhookSvc.get_webhook_config(self.config_path) + self.assertEqual(config["timeout"], webhookSvc.DEFAULT_TIMEOUT) + self.assertEqual( + config["max_attempts"], webhookSvc.DEFAULT_MAX_ATTEMPTS + ) + self.assertEqual(config["backoff"], list(webhookSvc.DEFAULT_BACKOFF)) + self.assertEqual(config["capacity"], webhookSvc.DEFAULT_CAPACITY) + + def test_invalid_retry_settings_fall_back_to_constants(self): + config = webhookSvc.normalize_webhook_config({ + "enabled": True, + "url": self.target.url, + "timeout": 0, + "max_attempts": "many", + "backoff": [0, -1], + "capacity": 99999, + }) + self.assertEqual(config["timeout"], webhookSvc.DEFAULT_TIMEOUT) + self.assertEqual( + config["max_attempts"], webhookSvc.DEFAULT_MAX_ATTEMPTS + ) + self.assertEqual(config["backoff"], list(webhookSvc.DEFAULT_BACKOFF)) + self.assertEqual(config["capacity"], webhookSvc.DEFAULT_CAPACITY) + + def test_malformed_settings_never_crash_the_dispatcher(self): + with open(self.config_path, "w", encoding="utf-8") as cf: + cf.write("{not json") + dispatcher = self.make_dispatcher() + self.assertFalse(dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": "y", + }))) + self.assertEqual(dispatcher.pending_count(), 0) + + def test_malformed_settings_do_not_crash_a_queued_delivery(self): + payload = webhookSvc.build_inbound_payload({"from": "x", "text": "y"}) + with open(self.outbox_path, "w", encoding="utf-8") as of: + json.dump([{ + "delivery_id": payload["delivery_id"], + "event": payload["event"], + "url": self.target.url, + "payload": payload, + "attempts": 0, + }], of) + with open(self.config_path, "w", encoding="utf-8") as cf: + cf.write("{not json") + dispatcher = self.make_dispatcher() + self.assertTrue(wait_for(lambda: dispatcher.pending_count() == 0)) + status = self.wait_for_status() + self.assertFalse(status["ok"]) + self.assertEqual(status["error"], "webhook disabled") + + def test_live_timeout_is_read_per_attempt(self): + dispatcher = self.make_dispatcher(timeout=None) + self.write_live_webhook(timeout=1, max_attempts=1) + self.target.set_delay(2) + started = time.time() + dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": "y", + })) + status = self.wait_for_status(timeout=5) + elapsed = time.time() - started + self.assertFalse(status["ok"]) + self.assertEqual(status["attempts"], 1) + self.assertLess(elapsed, 1.8) + + def test_live_max_attempts_changes_without_restart(self): + dispatcher = self.make_dispatcher() + self.write_live_webhook(max_attempts=1) + self.target.queue_statuses(500) + dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": "y", + })) + status = self.wait_for_status() + self.assertFalse(status["ok"]) + self.assertEqual(status["attempts"], 1) + self.assertEqual(self.target.count, 1) + + def test_live_backoff_is_read_per_attempt(self): + dispatcher = self.make_dispatcher(backoff=None) + self.write_live_webhook(max_attempts=2, backoff=[7]) + self.target.queue_statuses(500) + waits = [] + + def fake_wait(event, timeout=None): + waits.append(timeout) + return False + + with mock.patch.object(threading.Event, "wait", fake_wait): + dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": "y", + })) + status = self.wait_for_status() + + self.assertTrue(status["ok"]) + self.assertEqual(status["attempts"], 2) + self.assertEqual([wait for wait in waits if wait is not None], [7]) + + def test_live_capacity_drops_oldest(self): + class BlockingDispatcher(webhookSvc.WebhookDispatcher): + def __init__(self, *args, **kwargs): + self.release = threading.Event() + super().__init__(*args, **kwargs) + + def _deliver(self, record): + self.release.wait(5) + return True, 200, None, False + + dispatcher = BlockingDispatcher( + config_path=self.config_path, + outbox_path=self.outbox_path, + status_path=self.status_path, + log=lambda message: None, + ) + self.dispatchers.append(dispatcher) + self.write_live_webhook(capacity=10) + first = webhookSvc.build_inbound_payload({"from": "a", "text": "1"}) + dispatcher.enqueue(first) + self.assertTrue(wait_for(lambda: dispatcher.pending_count() == 1)) + for index in range(2, 12): + dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": str(index), + })) + self.assertEqual(dispatcher.pending_count(), 10) + with open(self.outbox_path, encoding="utf-8") as of: + records = json.load(of) + delivery_ids = [record["delivery_id"] for record in records] + self.assertEqual(len(delivery_ids), 10) + self.assertNotIn(first["delivery_id"], delivery_ids) + dispatcher.release.set() + + def test_explicit_max_attempts_wins_over_live_settings(self): + dispatcher = self.make_dispatcher(max_attempts=1) + self.write_live_webhook(max_attempts=5) + self.target.queue_statuses(500) + dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": "y", + })) + status = self.wait_for_status() + self.assertEqual(status["attempts"], 1) + self.assertEqual(self.target.count, 1) + ## Inbox spool def test_claim_and_ack_spool(self): diff --git a/docs/adr/0001-inbound-sms-webhook.md b/docs/adr/0001-inbound-sms-webhook.md index 1fc91c4..2896f0a 100644 --- a/docs/adr/0001-inbound-sms-webhook.md +++ b/docs/adr/0001-inbound-sms-webhook.md @@ -19,8 +19,8 @@ OpenSMS was outbound-only: a sticky foreground service on Android runs the FastA - A claimed spool file is acknowledged only after the Outbox has persisted the delivery. A crash between those steps can deliver the same SMS twice (at-least-once); a crash before the acknowledge loses nothing. - The webhook payload is a public contract. Multipart SMS is assembled into one Inbound SMS, and the sender is the raw originating address (it may be alphanumeric, not E.164). - `received_at` comes from the receiver, not from when the service drains the spool, so a late or recovered delivery reports the real receipt time. -- Delivery is at-least-once with bounded retry, and the attempt count is persisted so a restart cannot exceed the documented limit. +- Delivery is at-least-once with bounded retry, and the attempt count is persisted so a restart cannot exceed the attempt limit; the limit and backoff are live Settings since ADR 0002. - Redirects are treated as failures; a redirected POST is never counted as delivered. -- The Outbox is capped at 100 pending Webhooks; the oldest is dropped (and logged) when full. +- The Outbox is capped by the live Settings capacity (100 by default); the oldest is dropped (and logged) when full. - LAN targets require the phone and the receiver to share a network; the README states this. - The Settings "Send test" action runs in the UI process and posts directly, so it does not depend on the service being alive. From 1c8be823aaa0ec62ccdda44be5c942a63f7abb44 Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 19:36:16 +0100 Subject: [PATCH 11/20] fix: reject credentialed webhook targets --- README.md | 2 +- app/main.py | 3 +- app/services/postApi.py | 24 ++-- app/services/settingsSvc.py | 3 + app/services/webhookSvc.py | 92 +++++++++++++- app/tests/test_remote_api.py | 168 ++++++++++++++++++++++---- app/tests/test_settings_local_save.py | 27 +++++ app/tests/test_webhook.py | 57 +++++++++ docs/remote-api.md | 22 ++-- 9 files changed, 349 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index 3e8a246..1117c91 100644 --- a/README.md +++ b/README.md @@ -139,7 +139,7 @@ OpenSMS can forward every SMS received by the phone to your own HTTP endpoint as ### Configure it 1. Open `Settings` and find the **Webhook (Inbound SMS)** section. -2. Enter the **Webhook URL** (`http://` or `https://`). +2. Enter the **Webhook target** (`http://` or `https://`) without `username:password@` userinfo. 3. Optionally set a **Signing Secret** to sign every request. 4. Enable the switch and tap **Save**. 5. Tap **Send Test Webhook** to check the endpoint. This sends `event: "webhook.test"`. diff --git a/app/main.py b/app/main.py index 82e1ca6..4dfe6d3 100644 --- a/app/main.py +++ b/app/main.py @@ -51,6 +51,7 @@ normalize_webhook_config, read_webhook_status, send_test_webhook, + target_host, ) # IMPORTANT: Set this property for keyboard behaviour @@ -234,7 +235,7 @@ def on_start(self): f"port={self.config_template['port']}, " f"boot={self.config_template['boot']}, " f"webhook enabled={webhook_cfg['enabled']}, " - f"target={webhook_cfg['url']}" + f"target={target_host(webhook_cfg['url']) or 'unknown'}" ) self.req_template["port"] = int(self.config_template["port"]) start_on_launch = self.config_template["boot"] diff --git a/app/services/postApi.py b/app/services/postApi.py index 52bd7fc..b775050 100644 --- a/app/services/postApi.py +++ b/app/services/postApi.py @@ -617,12 +617,7 @@ def _last_delivery(config_dir: str) -> dict | None: def _webhook_status(settings: dict, config_dir: str, warnings: list) -> dict: webhook = settingsSvc.writable_settings(settings)["webhook"] url = webhook["url"] - url_host = None - if url: - try: - url_host = urlparse(url).hostname - except ValueError: - url_host = None + url_host = webhookSvc.target_host(url) pending = _status_runtime("outbox_pending") capacity = webhook["capacity"] @@ -661,13 +656,19 @@ def _webhook_status(settings: dict, config_dir: str, warnings: list) -> dict: ), }) + last_delivery = _last_delivery(config_dir) + if last_delivery and isinstance(last_delivery.get("error"), str): + last_delivery["error"] = _scrub_webhook_target( + url, last_delivery["error"] + ) + return { "enabled": bool(webhook["enabled"]), "url_host": url_host, "secret_set": bool(webhook["secret_set"]), "outbox_pending": pending, "outbox_capacity": capacity, - "last_delivery": _last_delivery(config_dir), + "last_delivery": last_delivery, } @@ -711,9 +712,13 @@ async def api_get_settings( return _settings_body(settings) def _settings_body(settings: dict) -> dict: + writable = settingsSvc.writable_settings(settings) + writable["webhook"]["url"] = webhookSvc.redact_target_credentials( + writable["webhook"]["url"] + ) return { "revision": settingsSvc.get_revision(settings), - "settings": settingsSvc.writable_settings(settings), + "settings": writable, } def _settings_log_message(payload: dict) -> str: @@ -923,7 +928,8 @@ def _scrub_webhook_target(url: str, error: str) -> str: """Remove URL parts from an error so credentials never reach the caller.""" if not error: return error - candidates = {url, url.strip()} + error = webhookSvc.scrub_webhook_error(error) + candidates: set[str | None] = {url, url.strip()} try: parsed = urlparse(url) except ValueError: diff --git a/app/services/settingsSvc.py b/app/services/settingsSvc.py index 6ba2baf..03e2256 100644 --- a/app/services/settingsSvc.py +++ b/app/services/settingsSvc.py @@ -25,6 +25,7 @@ MAX_ATTEMPTS_MIN, TIMEOUT_MAX, TIMEOUT_MIN, + has_target_credentials, is_valid_target, normalize_webhook_config, ) @@ -272,6 +273,8 @@ def _validate_backoff(value) -> list: def validate_business_rules(writable: dict): """Business rules that are not schema errors (HTTP 400).""" webhook = writable["webhook"] + if has_target_credentials(webhook["url"]): + raise SettingsRuleError("webhook.url must not contain credentials") if webhook["enabled"] and not is_valid_target(webhook["url"]): raise SettingsRuleError( "webhook.url must be a valid http(s) URL when webhook.enabled is true" diff --git a/app/services/webhookSvc.py b/app/services/webhookSvc.py index f3f60ab..9d77fe9 100644 --- a/app/services/webhookSvc.py +++ b/app/services/webhookSvc.py @@ -9,6 +9,7 @@ import json import os import queue +import re import threading import time import uuid @@ -16,7 +17,7 @@ from datetime import datetime, timezone from urllib import error as urlerror from urllib import request as urlrequest -from urllib.parse import urlparse +from urllib.parse import ParseResult, urlparse, urlunparse from services.config import __version__ @@ -24,6 +25,12 @@ EVENT_INBOUND = "sms.received" EVENT_TEST = "webhook.test" +_WEBHOOK_URL_IN_ERROR = re.compile(r"https?://[^\s]+", re.IGNORECASE) +_INVALID_TARGET_ERROR = ( + "Webhook target must be a valid http(s) URL without credentials" +) +VALID_TARGET_SCHEMES = ("http", "https") + # Delivery semantics (see docs/adr/0001-inbound-sms-webhook.md) DEFAULT_TIMEOUT = 10 DEFAULT_BACKOFF = (5, 30) @@ -116,14 +123,71 @@ def get_webhook_config(config_path: str) -> dict: return default_webhook_config() return normalize_webhook_config(app_config.get("webhook")) -def is_valid_target(url: str) -> bool: +def _parse_target(url: str) -> ParseResult | None: if not isinstance(url, str): - return False + return None try: - parsed = urlparse(url.strip()) + return urlparse(url.strip()) except ValueError: + return None + + +def _parsed_has_credentials(parsed: ParseResult) -> bool: + return parsed.username is not None or parsed.password is not None + + +def _malformed_authority_has_credentials(url: str) -> bool: + """Detect userinfo even when urlparse rejects the authority.""" + scheme, separator, remainder = url.strip().partition("://") + if not separator or scheme.lower() not in VALID_TARGET_SCHEMES: return False - return parsed.scheme in ("http", "https") and bool(parsed.netloc) + for delimiter in ("/", "?", "#"): + remainder = remainder.split(delimiter, 1)[0] + return "@" in remainder + + +def has_target_credentials(url: str) -> bool: + """Whether an HTTP(S) target carries URL userinfo, even an empty value.""" + parsed = _parse_target(url) + if parsed is not None: + return _parsed_has_credentials(parsed) + return isinstance(url, str) and _malformed_authority_has_credentials(url) + + +def redact_target_credentials(url: str) -> str: + """Return a display-safe target without echoing URL userinfo. + + The persisted value is not changed. A malformed value is omitted rather + than risking the echo of credentials that cannot be parsed reliably. + """ + parsed = _parse_target(url) + if parsed is None: + return "" + if not _parsed_has_credentials(parsed): + return url + netloc = parsed.netloc.rsplit("@", 1)[-1] + return urlunparse(parsed._replace(netloc=netloc)) + + +def target_host(url: str) -> str | None: + """Return only the parsed host, never userinfo, path, query, or fragment.""" + parsed = _parse_target(url) + if parsed is None: + return None + try: + return parsed.hostname + except ValueError: + return None + + +def is_valid_target(url: str) -> bool: + parsed = _parse_target(url) + return ( + parsed is not None + and parsed.scheme in VALID_TARGET_SCHEMES + and bool(parsed.netloc) + and not _parsed_has_credentials(parsed) + ) ## Payload @@ -218,6 +282,8 @@ def redirect_request(self, req, fp, code, msg, headers, newurl): def post_json(url: str, body: bytes, headers: dict, timeout: float) -> tuple: """POST once. Returns (ok, http_status, error_message).""" + if not is_valid_target(url): + return False, None, _INVALID_TARGET_ERROR try: req = urlrequest.Request(url, data=body, headers=headers, method="POST") except Exception as exc: @@ -255,6 +321,17 @@ def read_webhook_status(status_path: str) -> dict | None: except Exception: return None +def scrub_webhook_error(error: str) -> str: + """Remove credentialed target URLs from human-readable delivery errors.""" + def replace(match: re.Match[str]) -> str: + target = match.group(0) + if has_target_credentials(target): + return "" + return target + + return _WEBHOOK_URL_IN_ERROR.sub(replace, error) + + def format_webhook_status(status: dict | None) -> str: if not status: return "No deliveries yet" @@ -262,6 +339,8 @@ def format_webhook_status(status: dict | None) -> str: if status.get("ok"): return f"Last delivery: delivered (HTTP {status.get('http_status')}) at {when}" error = status.get("error") or "failed" + if isinstance(error, str): + error = scrub_webhook_error(error) if error == "webhook disabled": return f"Last delivery: not sent (webhook disabled) at {when}" attempts = status.get("attempts", 0) @@ -488,6 +567,9 @@ def _deliver(self, record: dict) -> tuple: config = get_webhook_config(self.config_path) if not config["enabled"]: return False, status, "webhook disabled", False + target = record.get("url") + if not isinstance(target, str) or not is_valid_target(target): + return False, status, _INVALID_TARGET_ERROR, False max_attempts = self._max_attempts_for(config) if attempt > max_attempts: return False, status, "retry limit reached", False diff --git a/app/tests/test_remote_api.py b/app/tests/test_remote_api.py index 422ee90..232fe28 100644 --- a/app/tests/test_remote_api.py +++ b/app/tests/test_remote_api.py @@ -267,16 +267,22 @@ def test_an_unreadable_delivery_status_is_null(self): self.assertIsNone(body["webhook"]["last_delivery"]) def test_status_reports_only_the_webhook_host_and_secret_presence(self): + credentialed_url = ( + "http://proxy-user:proxy-pass@proxy.example.lan:8080/" + "hooks/SENSITIVE-PATH?token=SENSITIVE-TOKEN" + ) self.write_config(self.config( webhook={ "enabled": True, - "url": ( - "http://proxy-user:proxy-pass@proxy.example.lan:8080/" - "hooks/SENSITIVE-PATH?token=SENSITIVE-TOKEN" - ), + "url": credentialed_url, "secret": "SENSITIVE-SECRET", }, )) + self.write_json("webhook_status.json", { + "ok": False, + "error": f"Could not deliver to {credentialed_url}", + "at": "2026-11-26T12:34:56+00:00", + }) raw_key = self.add_api_key() response = self.status(raw_key) @@ -285,6 +291,7 @@ def test_status_reports_only_the_webhook_host_and_secret_presence(self): body = response.json() self.assertEqual(body["webhook"]["url_host"], "proxy.example.lan") self.assertTrue(body["webhook"]["secret_set"]) + self.assertIn("webhook_url_invalid", self.warning_codes(body)) for sensitive in ( "SENSITIVE-PATH", "SENSITIVE-TOKEN", @@ -297,6 +304,27 @@ def test_status_reports_only_the_webhook_host_and_secret_presence(self): with self.subTest(sensitive=sensitive): self.assertNotIn(sensitive, response.text) + def test_status_scrubs_credentials_from_a_previous_target_error(self): + self.write_config(self.config(webhook={ + "enabled": True, + "url": "https://current.example.lan/hook", + })) + self.write_json("webhook_status.json", { + "ok": False, + "error": ( + "Could not deliver to " + "http://old-user:old-password@old.example.lan/hook" + ), + }) + raw_key = self.add_api_key() + + response = self.status(raw_key) + + self.assertEqual(response.status_code, 200) + self.assertNotIn("old-user", response.text) + self.assertNotIn("old-password", response.text) + self.assertNotIn("http://", response.text) + def test_forwarding_disabled_warns_that_new_inbound_sms_are_discarded(self): raw_key = self.add_api_key() @@ -409,6 +437,41 @@ def test_settings_masks_the_secret_and_hides_internal_fields(self): self.assertNotIn("secret", settings["webhook"]) self.assertNotIn("unknown_webhook", settings["webhook"]) + def test_settings_redacts_userinfo_from_a_legacy_target(self): + credentialed_url = ( + "http://proxy-user:proxy-pass@proxy.example.lan:8080/" + "hooks/opensms?token=SENSITIVE-TOKEN" + ) + config = { + "port": 9292, + "boot": False, + "revision": 4, + "webhook": { + "enabled": True, + "url": credentialed_url, + "secret": "topsecret", + }, + } + self.write_config(config) + raw_key = self.add_api_key() + + response = self.client.get( + "/api/settings", headers=self.auth(raw_key) + ) + + self.assertEqual(response.status_code, 200) + self.assertEqual( + response.json()["settings"]["webhook"]["url"], + ( + "http://proxy.example.lan:8080/hooks/opensms" + "?token=SENSITIVE-TOKEN" + ), + ) + for sensitive in ("proxy-user", "proxy-pass", "topsecret"): + with self.subTest(sensitive=sensitive): + self.assertNotIn(sensitive, response.text) + self.assertEqual(self.read_config(), config) + def test_settings_fill_defaults_for_a_legacy_config(self): self.write_config({ "app": "opensms", @@ -623,6 +686,32 @@ def test_put_replaces_the_writable_subset_and_bumps_the_revision(self): self.assertEqual(on_disk["webhook"]["secret"], "old-secret") self.assertEqual(self.tmp_files(), []) + def test_put_replacing_a_legacy_credentialed_target_never_echoes_it(self): + config = self.stored_config() + config["webhook"]["enabled"] = True + config["webhook"]["url"] = ( + "http://legacy-user:legacy-password@proxy.example.lan/hooks/old" + ) + self.write_config(config) + raw_key = self.add_api_key() + + response = self.put(self.valid_payload(webhook={ + "enabled": True, + "url": "https://proxy.example.lan/hooks/new", + }), raw_key) + + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual( + response.json()["settings"]["webhook"]["url"], + "https://proxy.example.lan/hooks/new", + ) + self.assertNotIn("legacy-user", response.text) + self.assertNotIn("legacy-password", response.text) + self.assertEqual( + self.read_config()["webhook"]["url"], + "https://proxy.example.lan/hooks/new", + ) + def test_omitting_the_secret_keeps_the_stored_secret(self): self.write_config(self.stored_config()) raw_key = self.add_api_key() @@ -763,6 +852,32 @@ def test_put_rejects_enabling_forwarding_without_a_valid_target(self): self.assertEqual(self.read_config(), before) self.assertEqual(self.tmp_files(), []) + def test_put_rejects_a_credentialed_target_even_when_disabled(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + before = self.read_config() + + targets = { + "valid authority": ( + "http://proxy-user:proxy-pass@proxy.example.lan/hooks/opensms" + ), + "malformed authority": "http://proxy-user:proxy-pass@[invalid", + } + for name, url in targets.items(): + for enabled in (True, False): + with self.subTest(name=name, enabled=enabled): + response = self.put(self.valid_payload(webhook={ + "enabled": enabled, + "url": url, + }), raw_key) + + self.assertEqual(response.status_code, 400, response.text) + self.assertIsInstance(response.json()["detail"], str) + self.assertNotIn("proxy-user", response.text) + self.assertNotIn("proxy-pass", response.text) + self.assertEqual(self.read_config(), before) + self.assertEqual(self.tmp_files(), []) + def test_put_rejects_a_non_object_body(self): raw_key = self.add_api_key() @@ -1095,29 +1210,34 @@ def test_an_empty_secret_tests_unsigned_delivery(self): self.read_config()["webhook"]["secret"], "saved-secret" ) - def test_an_error_never_echoes_the_target_with_credentials(self): + def test_credentialed_targets_are_rejected_without_posting(self): raw_key = self.add_api_key() + port = self.target.server.server_address[1] + targets = { + "password": f"http://proxy-user:proxy-pass@127.0.0.1:{port}/hook", + "username only": f"http://proxy-user@127.0.0.1:{port}/hook", + "empty password": f"http://proxy-user:@127.0.0.1:{port}/hook", + "empty userinfo": f"http://:@127.0.0.1:{port}/hook", + "https": "https://proxy-user:proxy-pass@proxy.example.lan/hook", + } - response = self.post_test(raw_key, { - "url": ( - "http://proxy-user:proxy-pass@127.0.0.1:1/" - "pa th?token=SENSITIVE-TOKEN" - ), - }) + for name, url in targets.items(): + with self.subTest(name): + response = self.post_test(raw_key, {"url": url}) - self.assertEqual(response.status_code, 502) - body = response.json() - self.assertFalse(body["ok"]) - self.assertIsNone(body["http_status"]) - self.assertTrue(body["error"]) - for sensitive in ( - "proxy-user", - "proxy-pass", - "SENSITIVE-TOKEN", - "/pa th", - ): - with self.subTest(sensitive=sensitive): - self.assertNotIn(sensitive, response.text) + self.assertEqual(response.status_code, 400, response.text) + self.assertIsInstance(response.json()["detail"], str) + for sensitive in ("proxy-user", "proxy-pass", ":@", "@127"): + with self.subTest(sensitive=sensitive): + self.assertNotIn(sensitive, response.text) + + legacy_url = targets["password"] + self.save_webhook(url=legacy_url) + response = self.post_test(raw_key) + self.assertEqual(response.status_code, 400, response.text) + self.assertNotIn("proxy-user", response.text) + self.assertNotIn("proxy-pass", response.text) + self.assertEqual(self.target.count, 0) def test_a_test_needs_a_valid_target(self): raw_key = self.add_api_key() diff --git a/app/tests/test_settings_local_save.py b/app/tests/test_settings_local_save.py index 552a876..178444b 100644 --- a/app/tests/test_settings_local_save.py +++ b/app/tests/test_settings_local_save.py @@ -244,6 +244,33 @@ def test_enabling_forwarding_without_a_valid_target_rejects_the_save(self): settingsSvc.SettingsRuleError, ) + def test_a_credentialed_target_rejects_the_whole_local_save(self): + credentialed_url = ( + "http://local-user:local-password@remote.example.lan/hooks/opensms" + ) + for enabled in (True, False): + with self.subTest(enabled=enabled): + config = self.stored_config() + config["webhook"]["enabled"] = enabled + self.write_config(config) + + self.assert_rejected( + {"webhook": {"url": credentialed_url}}, + settingsSvc.SettingsRuleError, + ) + + def test_an_unrelated_save_cannot_preserve_a_legacy_credentialed_target(self): + config = self.stored_config() + config["webhook"]["url"] = ( + "http://legacy-user:legacy-password@remote.example.lan/" + "hooks/opensms" + ) + self.write_config(config) + + self.assert_rejected( + {"port": 9393}, settingsSvc.SettingsRuleError + ) + def test_both_port_bounds_are_accepted(self): for port in (settingsSvc.PORT_MIN, settingsSvc.PORT_MAX): with self.subTest(port=port): diff --git a/app/tests/test_webhook.py b/app/tests/test_webhook.py index 35039c0..b7bd7af 100644 --- a/app/tests/test_webhook.py +++ b/app/tests/test_webhook.py @@ -236,6 +236,18 @@ def test_test_without_url_fails_cleanly(self): self.assertIsNone(status) self.assertTrue(error) + def test_credentialed_target_is_not_posted_by_test_delivery(self): + url = self.target.url.replace("http://", "http://user:password@") + + ok, status, error = webhookSvc.send_test_webhook( + {"url": url, "secret": ""} + ) + + self.assertFalse(ok) + self.assertIsNone(status) + self.assertIn("credentials", error) + self.assertEqual(self.target.count, 0) + ## Delivery def test_delivers_signed_payload(self): @@ -339,6 +351,31 @@ def test_resume_honours_persisted_attempts(self): self.assertFalse(status["ok"]) self.assertEqual(status["attempts"], 3) + def test_legacy_credentialed_outbox_target_is_not_posted(self): + payload = webhookSvc.build_inbound_payload({ + "from": "+14155552671", "text": "legacy", + }) + credentialed_url = self.target.url.replace( + "http://", "http://legacy-user:legacy-password@" + ) + with open(self.outbox_path, "w", encoding="utf-8") as of: + json.dump([{ + "delivery_id": payload["delivery_id"], + "event": payload["event"], + "url": credentialed_url, + "payload": payload, + "attempts": 0, + }], of) + + dispatcher = self.make_dispatcher(max_attempts=1) + + self.assertTrue(wait_for(lambda: dispatcher.pending_count() == 0)) + status = self.wait_for_status() + self.assertFalse(status["ok"]) + self.assertEqual(status["attempts"], 0) + self.assertIn("credentials", status["error"]) + self.assertEqual(self.target.count, 0) + def test_outbox_is_delivered_after_restart(self): payload = webhookSvc.build_inbound_payload({ "from": "x", "text": "y", "parts": 1, @@ -583,6 +620,26 @@ def test_format_status(self): "error": "timed out", "at": "now", }) self.assertIn("failed after 3 attempt(s)", failed) + credentialed = webhookSvc.format_webhook_status({ + "ok": False, + "attempts": 1, + "error": ( + "Could not deliver to " + "http://status-user:status-password@old.example.lan/hook" + ), + "at": "now", + }) + self.assertNotIn("status-user", credentialed) + self.assertNotIn("status-password", credentialed) + self.assertNotIn("http://", credentialed) + ordinary_url = "http://ordinary.example.lan/hook" + ordinary = webhookSvc.format_webhook_status({ + "ok": False, + "attempts": 1, + "error": f"Could not deliver to {ordinary_url}", + "at": "now", + }) + self.assertIn(ordinary_url, ordinary) if __name__ == "__main__": diff --git a/docs/remote-api.md b/docs/remote-api.md index 10bd125..25d15b1 100644 --- a/docs/remote-api.md +++ b/docs/remote-api.md @@ -140,8 +140,9 @@ See `GLOSSARY.md`: **Settings**, **Revision**, **Scope**, **API key**, - `409` conflict (stale revision, last key, restart debounce/stopped) - `422` schema/range/unknown-field violation - `502` webhook test delivery failed -- Never return: webhook secret, key hashes, raw keys after creation, full - webhook URL with credentials. +- Never return: webhook secret, key hashes, raw keys after creation, a full + Webhook target with credentials. A legacy target's userinfo is removed from + Settings responses without changing the stored value. ### 6.2 `GET /api/health` @@ -192,7 +193,8 @@ Rules: `{"code": "network_unavailable"}`. - `webhook.url_host`: `urlparse(url).hostname`, `null` if empty. Never path, query, or credentials. -- `last_delivery`: `null` when no status file. +- `last_delivery`: `null` when no status file. Credentialed target URLs and + details of the current target are scrubbed from its error text. - `outbox_pending`: provider value, `null` when unavailable. - `warnings` is always an array. Codes: - `webhook_disabled` — accepted but every new Inbound SMS is discarded, with @@ -222,7 +224,9 @@ Rules: } ``` -Never include `permissions`, `app`, or the raw secret. +Never include `permissions`, `app`, or the raw secret. If a stored legacy +target contains URL userinfo, `webhook.url` is returned with that userinfo +removed; the persisted value remains unchanged and invalid for forwarding. ### 6.5 `PUT /api/settings` @@ -259,7 +263,7 @@ Validation: | `port` | integer, `1025 <= port <= 65535` | `422` | | `boot` | JSON boolean | `422` | | `webhook.enabled` | JSON boolean | `422` | -| `webhook.url` | string; required; valid `http(s)://host[:port]/path` when `enabled` is true; may be `""` when disabled | `422` if wrong type; `400` if enabled and invalid/empty | +| `webhook.url` | string; required; credential-free valid `http(s)://host[:port]/path` when `enabled` is true; may be `""` when disabled; URL userinfo is always rejected | `422` if wrong type; `400` if enabled and invalid/empty or if userinfo is present | | `webhook.secret` | string, ≤ 256 chars, sentinel semantics | `422` | | `webhook.timeout` | integer 1–60 (seconds) | `422` | | `webhook.max_attempts` | integer 1–50 | `422` | @@ -305,8 +309,8 @@ Optional body: ``` - No body → saved webhook target and secret. -- `url` present → used for this test only, must be valid (`400` otherwise); it - is allowed while `enabled` is false. +- `url` present → used for this test only, must be valid and credential-free + (`400` otherwise); it is allowed while `enabled` is false. - `secret` present → used for this test only; `""` means unsigned. - Uses the saved `timeout`. @@ -559,7 +563,7 @@ Required cases: the old key stops working; v1 file migrates, authenticates, and is persisted as v2. 11. UI merge: after an API write, a simulated UI save built from a stale - `config_template` preserves the API-changed webhook URL and the incrementing + `config_template` preserves the API-changed Webhook target and the incrementing revision. 12. Live retry config: dispatcher picks up `max_attempts`/`backoff`/`capacity` from `config.json` when constructor args are absent; constructor args still @@ -601,7 +605,7 @@ Core total ≈ 600–900 source lines, 3–4 focused days. writable setting, test the webhook, restart the server, and manage keys. 2. `GET /api/settings` never reveals the secret; `GET /api/keys` never reveals hashes; raw keys appear only in the creation response. -3. Webhook URL/secret/enable and retry changes take effect on the next inbound +3. Webhook target/secret/enable and retry changes take effect on the next inbound SMS without a restart. 4. A port change followed by `POST /api/server/restart` leaves the API listening on the new port; `request.json` ends at `"start"`; no restart loop; a bind From 869023d35852c819a1f9e8a1611a21383f532cb2 Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 19:43:25 +0100 Subject: [PATCH 12/20] fix: preserve remote Settings on permission confirmation --- app/main.py | 28 +++++++++++++---- app/services/settingsSvc.py | 31 ++++++++++++++---- app/tests/test_settings_local_save.py | 45 +++++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 12 deletions(-) diff --git a/app/main.py b/app/main.py index 4dfe6d3..7cfd0e2 100644 --- a/app/main.py +++ b/app/main.py @@ -490,8 +490,16 @@ def show_settings_popup(self): ) def confirm_android_permissions(self, instnce=None): - self.config_template["permissions"] = True - Thread(target=self.write_app_conf, daemon=True).start() + Thread(target=self.persist_android_permissions, daemon=True).start() + + def persist_android_permissions(self): + """Persist only the permission flag over freshly read Settings.""" + saved = self.persist_local_settings({"permissions": True}) + if saved is None: + return + Clock.schedule_once( + lambda dt, settings=saved: self.apply_persisted_settings(settings) + ) def open_android_settings(self, instance=None): self.txt_dialog_closer() @@ -697,14 +705,22 @@ def read_webhook_form(self): def persist_settings_form(self, form): """Merge the form over fresh Settings and persist it atomically.""" - try: - saved = settingsSvc.save_local_settings(self.app_config, form) - except settingsSvc.SettingsValidationError as exc: - self.show_toast_msg(str(exc), is_error=True) + saved = self.persist_local_settings(form) + if saved is None: return False self.apply_persisted_settings(saved) return True + def persist_local_settings(self, form): + """Save local fields, reporting validation errors on Kivy's thread.""" + try: + return settingsSvc.save_local_settings(self.app_config, form) + except settingsSvc.SettingsValidationError as exc: + Clock.schedule_once( + lambda dt: self.show_toast_msg(str(exc), is_error=True) + ) + return None + def apply_persisted_settings(self, settings: dict): """Adopt freshly persisted Settings and show them.""" self.config_template = dict(settings) diff --git a/app/services/settingsSvc.py b/app/services/settingsSvc.py index 03e2256..ea0afdb 100644 --- a/app/services/settingsSvc.py +++ b/app/services/settingsSvc.py @@ -291,6 +291,8 @@ def validate_merged_settings(settings: dict): webhook = settings.get("webhook") if not isinstance(webhook, dict): raise SettingsValidationError("webhook must be an object") + if not isinstance(settings.get("permissions", False), bool): + raise SettingsValidationError("permissions must be a boolean") if not isinstance(webhook.get("secret", ""), str): raise SettingsValidationError("webhook.secret must be a string") validate_settings_payload({ @@ -397,7 +399,10 @@ def merge_local_settings(current: dict, form: dict) -> dict: def _store_writable( - config_path: str, writable: dict, expected_revision: int | None + config_path: str, + writable: dict, + expected_revision: int | None, + permissions: bool | None = None, ) -> dict: """Validate and persist a normalized writable subset. @@ -416,6 +421,8 @@ def _store_writable( ) validate_business_rules(writable) merged = apply_writable_settings(current, writable) + if permissions is not None: + merged["permissions"] = permissions validate_merged_settings(merged) merged["revision"] = get_revision(current) + 1 atomic_write_json(config_path, merged) @@ -438,19 +445,31 @@ def save_settings(config_path: str, payload, expected_revision: int | None = Non def save_local_settings( config_path: str, form: dict, expected_revision: int | None = None ) -> dict: - """Save the on-device form's fields over a fresh read of Settings. + """Save on-device fields over a fresh read of Settings. `form` carries only the fields the screen owns (port, boot, and some - Webhook fields). Everything else keeps its freshly read value, so a remote - change is not undone and the Revision is bumped rather than reset. - Validation is the same one the API uses. + Webhook fields), plus internal fields owned by the permission flow. + Everything else keeps its freshly read value, so a remote change is not + undone and the Revision is bumped rather than reset. Validation is the + same one the API uses. """ + permissions = None + if isinstance(form, dict) and "permissions" in form: + permissions = form["permissions"] + if not isinstance(permissions, bool): + raise SettingsValidationError("permissions must be a boolean") + form = { + field: value for field, value in form.items() + if field != "permissions" + } with _write_lock: current = load_settings(config_path) writable = validate_settings_payload( merge_local_settings(current, form) ) - return _store_writable(config_path, writable, expected_revision) + return _store_writable( + config_path, writable, expected_revision, permissions + ) def atomic_write_json(path: str, data): diff --git a/app/tests/test_settings_local_save.py b/app/tests/test_settings_local_save.py index 178444b..d01358b 100644 --- a/app/tests/test_settings_local_save.py +++ b/app/tests/test_settings_local_save.py @@ -202,6 +202,46 @@ def test_a_legacy_config_gains_defaults_and_keeps_a_saved_port(self): self.assertEqual(saved["webhook"]["capacity"], 100) +class PermissionConfirmationSaveTests(LocalSaveTestCase): + def test_permission_confirmation_preserves_a_remote_write_after_a_stale_read(self): + stored_settings = self.stored_config() + stored_settings["permissions"] = False + self.write_config(stored_settings) + stale = settingsSvc.load_settings(self.config_path) + remote = settingsSvc.writable_settings(stale) + remote["revision"] = stale["revision"] + remote["webhook"].pop("secret_set") + remote["webhook"].update({ + "url": "https://remote-after-open.example.lan/hooks/opensms", + "secret": "remote-after-open-secret", + "timeout": 11, + "max_attempts": 6, + "backoff": [2, 4, 8], + "capacity": 300, + }) + settingsSvc.save_settings(self.config_path, remote) + + saved = settingsSvc.save_local_settings( + self.config_path, {"permissions": True} + ) + + self.assertEqual(saved["revision"], 5) + self.assertEqual(saved["permissions"], True) + webhook = saved["webhook"] + self.assertEqual( + webhook["url"], "https://remote-after-open.example.lan/hooks/opensms" + ) + self.assertEqual(webhook["secret"], "remote-after-open-secret") + self.assertEqual(webhook["timeout"], 11) + self.assertEqual(webhook["max_attempts"], 6) + self.assertEqual(webhook["backoff"], [2, 4, 8]) + self.assertEqual(webhook["capacity"], 300) + self.assertEqual(saved["unknown_top_level"], "internal") + self.assertEqual(webhook["unknown_webhook"], "internal") + self.assertEqual(self.read_config(), saved) + self.assertEqual(self.tmp_files(), []) + + class LocalSaveValidationTests(LocalSaveTestCase): def assert_rejected(self, form: dict, error_class): @@ -213,6 +253,11 @@ def assert_rejected(self, form: dict, error_class): self.assertEqual(self.read_config(), before) self.assertEqual(self.tmp_files(), []) + def test_a_non_boolean_permission_rejects_the_whole_save(self): + self.assert_rejected( + {"permissions": "true"}, settingsSvc.SettingsValidationError + ) + def test_an_out_of_range_port_rejects_the_whole_save(self): for port in ( settingsSvc.PORT_MIN - 1, From 3e32c2517e7518cc26e9c438bf36783d018ca84a Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 20:03:16 +0100 Subject: [PATCH 13/20] fix: keep status truthful under malformed state --- app/services/netSvc.py | 16 ++- app/services/postApi.py | 74 +++++++---- app/services/settingsSvc.py | 43 +++++- app/tests/test_remote_api.py | 245 +++++++++++++++++++++++++++++++++++ 4 files changed, 349 insertions(+), 29 deletions(-) diff --git a/app/services/netSvc.py b/app/services/netSvc.py index 9ddb8b9..bf0a1c1 100644 --- a/app/services/netSvc.py +++ b/app/services/netSvc.py @@ -30,8 +30,18 @@ def get_internet_iface_ips(): return ip_addresses -def get_network_ips(): - lan_ips = {"wifi": [], "ethernet": []} +def get_network_ips( + *, strict: bool = False +) -> dict[str, list[dict[str, str]]]: + """Discover LAN interfaces, optionally raising when discovery fails. + + The UI keeps the historical empty-list fallback. Status uses strict mode so + a failed discovery is not mistaken for a successful discovery of no addresses. + """ + lan_ips: dict[str, list[dict[str, str]]] = { + "wifi": [], + "ethernet": [], + } try: if platform == "android": from jnius import autoclass @@ -65,6 +75,8 @@ def get_network_ips(): except Exception as e: print(f"Error in fetching IPs: {e}") + if strict: + raise return lan_ips diff --git a/app/services/postApi.py b/app/services/postApi.py index b775050..b12fcc3 100644 --- a/app/services/postApi.py +++ b/app/services/postApi.py @@ -570,7 +570,11 @@ def _network_status(warnings: list) -> dict: """Return the network interface lists, or empty lists on any failure.""" try: provider = _runtime.get("network_ips") - network = provider() if provider is not None else netSvc.get_network_ips() + network = ( + provider() + if provider is not None + else netSvc.get_network_ips(strict=True) + ) except Exception: network = None if not isinstance(network, dict): @@ -614,17 +618,31 @@ def _last_delivery(config_dir: str) -> dict | None: } -def _webhook_status(settings: dict, config_dir: str, warnings: list) -> dict: - webhook = settingsSvc.writable_settings(settings)["webhook"] - url = webhook["url"] - url_host = webhookSvc.target_host(url) - +def _webhook_status( + settings: dict | None, config_dir: str, warnings: list +) -> dict: pending = _status_runtime("outbox_pending") - capacity = webhook["capacity"] - if not isinstance(capacity, int) or isinstance(capacity, bool): - capacity = None - - if not webhook["enabled"]: + stored_webhook = settings.get("webhook") if settings is not None else None + effective_webhook = webhookSvc.normalize_webhook_config( + stored_webhook if isinstance(stored_webhook, dict) else None + ) + if settings is None or not isinstance(stored_webhook, dict): + enabled = url = secret_set = capacity = None + url_host = None + else: + webhook = settingsSvc.writable_settings(settings)["webhook"] + stored_enabled = webhook["enabled"] + enabled = stored_enabled if isinstance(stored_enabled, bool) else None + url = webhook["url"] + url_host = webhookSvc.target_host(url) + secret_set = webhook["secret_set"] + capacity = webhook["capacity"] + if not isinstance(capacity, int) or isinstance(capacity, bool): + capacity = None + + # Warnings describe what the dispatcher will do with malformed Settings, + # even when the persisted value itself is unknown. + if not effective_webhook["enabled"]: warnings.append({ "code": "webhook_disabled", "message": ( @@ -632,7 +650,7 @@ def _webhook_status(settings: dict, config_dir: str, warnings: list) -> dict: "discarded." ), }) - elif not webhookSvc.is_valid_target(url): + elif not webhookSvc.is_valid_target(effective_webhook["url"]): warnings.append({ "code": "webhook_url_invalid", "message": ( @@ -663,9 +681,9 @@ def _webhook_status(settings: dict, config_dir: str, warnings: list) -> dict: ) return { - "enabled": bool(webhook["enabled"]), + "enabled": enabled, "url_host": url_host, - "secret_set": bool(webhook["secret_set"]), + "secret_set": secret_set, "outbox_pending": pending, "outbox_capacity": capacity, "last_delivery": last_delivery, @@ -677,7 +695,10 @@ async def api_status( client: dict = Depends(require_scope(SCOPE_SETTINGS)) ): config_dir = get_config_dir() - settings = settingsSvc.load_settings(_settings_path()) + try: + settings = settingsSvc.load_settings(_settings_path(), strict=True) + except settingsSvc.SettingsLoadError: + settings = None warnings: list = [] network = _network_status(warnings) @@ -694,11 +715,15 @@ async def api_status( "uptime_s": _status_uptime_s(), }, "service": _service_status(), - "config": { - "port": settings.get("port"), - "boot": settings.get("boot"), - "revision": settingsSvc.get_revision(settings), - }, + "config": ( + { + "port": settings.get("port"), + "boot": settings.get("boot"), + "revision": settingsSvc.get_revision(settings), + } + if settings is not None + else None + ), "network": network, "webhook": webhook, "warnings": warnings, @@ -732,10 +757,11 @@ def _settings_log_message(payload: dict) -> str: def _restart_required(settings: dict) -> bool: """True only when the saved port differs from a known live bound port.""" bound_port = get_runtime_provider("bound_port") - if bound_port is None: + port = settings.get("port") + if bound_port is None or port is None: return False try: - return int(settings.get("port")) != int(bound_port) + return int(port) != int(bound_port) except (TypeError, ValueError): return False @@ -924,10 +950,12 @@ def _resolve_webhook_test_config(settings: dict, overrides: dict) -> tuple: return url, secret, timeout -def _scrub_webhook_target(url: str, error: str) -> str: +def _scrub_webhook_target(url: object, error: str) -> str: """Remove URL parts from an error so credentials never reach the caller.""" if not error: return error + if not isinstance(url, str): + return "Webhook delivery failed." error = webhookSvc.scrub_webhook_error(error) candidates: set[str | None] = {url, url.strip()} try: diff --git a/app/services/settingsSvc.py b/app/services/settingsSvc.py index ea0afdb..e5246f0 100644 --- a/app/services/settingsSvc.py +++ b/app/services/settingsSvc.py @@ -6,6 +6,7 @@ """ import json +import math import os import tempfile import threading @@ -71,6 +72,10 @@ def __init__(self, expected: int, current: int): ) super().__init__(self.detail) + +class SettingsLoadError(ValueError): + """Existing Settings could not be read as a JSON object.""" + ## Defaults def default_webhook_settings() -> dict: @@ -96,19 +101,47 @@ def default_settings() -> dict: ## Load -def load_settings(config_path: str) -> dict: +def _reject_non_finite_json_number(value: str) -> None: + raise ValueError(f"Non-finite JSON number: {value}") + + +def _finite_json_float(value: str) -> float: + number = float(value) + if not math.isfinite(number): + raise ValueError(f"Non-finite JSON number: {value}") + return number + + +def load_settings(config_path: str, *, strict: bool = False) -> dict: """Load Settings, filling missing fields from the defaults. Unknown fields, at the top level and inside the Webhook object, are kept so - a later write can preserve them. + a later write can preserve them. A missing file always means defaults. With + ``strict=True``, an existing file that cannot be read as a JSON object raises + ``SettingsLoadError`` so callers can report unknown instead of live defaults. + A malformed stored Webhook container is preserved in strict mode so callers + can distinguish it from a legacy object whose missing fields use defaults. """ settings = default_settings() try: with open(config_path, "r", encoding="utf-8") as config_file: - raw = json.load(config_file) - except Exception: + if strict: + raw = json.load( + config_file, + parse_float=_finite_json_float, + parse_constant=_reject_non_finite_json_number, + ) + else: + raw = json.load(config_file) + except FileNotFoundError: + return settings + except Exception as exc: + if strict: + raise SettingsLoadError("Existing Settings could not be read") from exc return settings if not isinstance(raw, dict): + if strict: + raise SettingsLoadError("Existing Settings must be a JSON object") return settings for key, value in raw.items(): if key == "webhook": @@ -117,6 +150,8 @@ def load_settings(config_path: str) -> dict: raw_webhook = raw.get("webhook") if isinstance(raw_webhook, dict): settings["webhook"].update(raw_webhook) + elif strict and "webhook" in raw: + settings["webhook"] = raw_webhook return settings def get_revision(settings: dict) -> int: diff --git a/app/tests/test_remote_api.py b/app/tests/test_remote_api.py index 232fe28..099d19f 100644 --- a/app/tests/test_remote_api.py +++ b/app/tests/test_remote_api.py @@ -147,6 +147,105 @@ def test_status_separates_the_configured_and_bound_ports(self): self.assertEqual(body["api"]["port"], 9292) self.assertEqual(body["api"]["bound_port"], 9292) + def test_missing_settings_file_reports_the_documented_defaults(self): + raw_key = self.add_api_key() + + response = self.status(raw_key) + + self.assertEqual(response.status_code, 200, response.text) + body = response.json() + self.assertEqual(body["config"], { + "port": 9292, + "boot": False, + "revision": 0, + }) + self.assertFalse(body["webhook"]["enabled"]) + self.assertEqual(body["webhook"]["outbox_capacity"], 100) + self.assertIn("webhook_disabled", self.warning_codes(body)) + + def test_an_unreadable_existing_settings_file_is_unknown(self): + os.mkdir(os.path.join(self.config_dir, "config.json")) + raw_key = self.add_api_key() + + response = self.status(raw_key) + + self.assertEqual(response.status_code, 200, response.text) + self.assertIsNone(response.json()["config"]) + self.assertIn( + "webhook_disabled", self.warning_codes(response.json()) + ) + + def test_non_finite_settings_numbers_are_unknown(self): + cases = { + "overflowing port": '{"port": 1e999, "boot": false}', + "infinite revision": '{"revision": Infinity, "boot": false}', + "not-a-number capacity": ( + '{"boot": false, "webhook": {"capacity": NaN}}' + ), + } + raw_key = self.add_api_key() + for name, content in cases.items(): + with self.subTest(name=name): + with open( + os.path.join(self.config_dir, "config.json"), + "w", + encoding="utf-8", + ) as config_file: + config_file.write(content) + + response = self.status(raw_key) + + self.assertEqual(response.status_code, 200, response.text) + self.assertIsNone(response.json()["config"]) + + def test_corrupt_settings_are_unknown_but_other_status_is_preserved(self): + with open( + os.path.join(self.config_dir, "config.json"), "w", encoding="utf-8" + ) as config_file: + config_file.write("not json") + self.write_json("resp.json", {"server": "started"}) + self.write_json("webhook_status.json", { + "ok": True, + "http_status": 204, + "at": "2026-11-26T12:34:56+00:00", + }) + postApi.set_runtime_providers({ + "network_ips": lambda: { + "wifi": [{"interface": "wlan0", "ip": "192.168.1.50"}], + "ethernet": [], + }, + "outbox_pending": lambda: 2, + }) + raw_key = self.add_api_key() + + response = self.status(raw_key) + + self.assertEqual(response.status_code, 200, response.text) + body = response.json() + self.assertIsNone(body["config"]) + self.assertEqual(body["service"]["server"], "started") + self.assertEqual(body["network"]["wifi"], [ + {"interface": "wlan0", "ip": "192.168.1.50"}, + ]) + self.assertEqual(body["webhook"], { + "enabled": None, + "url_host": None, + "secret_set": None, + "outbox_pending": 2, + "outbox_capacity": None, + "last_delivery": { + "ok": True, + "event": None, + "delivery_id": None, + "http_status": 204, + "attempts": None, + "error": None, + "at": "2026-11-26T12:34:56+00:00", + }, + }) + self.assertIn("webhook_disabled", self.warning_codes(body)) + self.assertNotIn("webhook_url_invalid", self.warning_codes(body)) + def test_missing_runtime_values_are_null_not_invented(self): postApi.set_runtime_providers({}) raw_key = self.add_api_key() @@ -219,6 +318,28 @@ def fail(): self.assertEqual(body["network"], {"wifi": [], "ethernet": []}) self.assertIn("network_unavailable", self.warning_codes(body)) + def test_default_network_discovery_failure_is_distinguishable(self): + raw_key = self.add_api_key() + + with mock.patch.object( + postApi.netSvc, + "get_desktop_lan_ips", + side_effect=OSError("network discovery failed"), + ): + response = self.status(raw_key) + + self.assertEqual(response.status_code, 200, response.text) + body = response.json() + self.assertEqual(body["network"], {"wifi": [], "ethernet": []}) + self.assertIn("network_unavailable", self.warning_codes(body)) + + postApi.set_runtime_providers({ + "network_ips": lambda: {"wifi": [], "ethernet": []}, + }) + body = self.status(raw_key).json() + self.assertEqual(body["network"], {"wifi": [], "ethernet": []}) + self.assertNotIn("network_unavailable", self.warning_codes(body)) + def test_status_reports_the_last_delivery_attempt_and_outbox_depth(self): self.write_config(self.config( webhook={ @@ -351,6 +472,130 @@ def test_an_enabled_but_invalid_target_is_a_warning(self): self.assertIn("webhook_url_invalid", self.warning_codes(body)) self.assertNotIn("webhook_disabled", self.warning_codes(body)) + def test_a_malformed_webhook_object_is_unknown_but_warns_if_disabled(self): + raw_key = self.add_api_key() + for webhook in ([], "broken", None, 42): + with self.subTest(webhook=webhook): + config = self.config() + config["webhook"] = webhook + self.write_config(config) + postApi.set_runtime_providers({"outbox_pending": lambda: 2}) + + response = self.status(raw_key) + + self.assertEqual(response.status_code, 200, response.text) + body = response.json() + self.assertEqual(body["config"], { + "port": 9393, + "boot": True, + "revision": 5, + }) + self.assertEqual(body["webhook"], { + "enabled": None, + "url_host": None, + "secret_set": None, + "outbox_pending": 2, + "outbox_capacity": None, + "last_delivery": None, + }) + self.assertIn( + "webhook_disabled", self.warning_codes(body) + ) + self.assertNotIn( + "webhook_url_invalid", self.warning_codes(body) + ) + + def test_a_malformed_enabled_state_is_unknown_but_warns_effectively(self): + valid_url = "https://proxy.example.lan/hooks/opensms" + cases = ( + ("true", valid_url, None), + (1, valid_url, None), + ([], valid_url, "webhook_disabled"), + ({}, valid_url, "webhook_disabled"), + ("true", "not-a-url", "webhook_url_invalid"), + (1, 42, "webhook_url_invalid"), + ) + raw_key = self.add_api_key() + for enabled, url, expected_warning in cases: + with self.subTest(enabled=enabled, url=url): + self.write_config(self.config(webhook={ + "enabled": enabled, + "url": url, + })) + + response = self.status(raw_key) + + self.assertEqual(response.status_code, 200, response.text) + body = response.json() + self.assertIsNone(body["webhook"]["enabled"]) + self.assertEqual( + body["webhook"]["url_host"], + "proxy.example.lan" if url == valid_url else None, + ) + if expected_warning is None: + self.assertNotIn( + "webhook_disabled", self.warning_codes(body) + ) + self.assertNotIn( + "webhook_url_invalid", self.warning_codes(body) + ) + else: + self.assertIn( + expected_warning, self.warning_codes(body) + ) + other_warning = ( + "webhook_url_invalid" + if expected_warning == "webhook_disabled" + else "webhook_disabled" + ) + self.assertNotIn( + other_warning, self.warning_codes(body) + ) + + def test_a_malformed_stored_target_type_is_safe_and_warns(self): + cases = { + "number": 42, + "list": ["https://MALFORMED-TARGET.example.lan/hook"], + "object": {"target": "MALFORMED-TARGET"}, + "null": None, + "malformed authority": "http://proxy-user:proxy-pass@[invalid", + } + raw_key = self.add_api_key() + for name, url in cases.items(): + with self.subTest(name=name): + self.write_config(self.config( + webhook={"enabled": True, "url": url}, + )) + self.write_json("webhook_status.json", { + "ok": False, + "error": f"Could not deliver to {url}", + }) + + response = self.status(raw_key) + + self.assertEqual(response.status_code, 200, response.text) + body = response.json() + self.assertIsNone(body["webhook"]["url_host"]) + if not isinstance(url, str): + self.assertEqual( + body["webhook"]["last_delivery"]["error"], + "Webhook delivery failed.", + ) + self.assertIn( + "webhook_url_invalid", self.warning_codes(body) + ) + self.assertNotIn( + "webhook_disabled", self.warning_codes(body) + ) + for sensitive in ( + "MALFORMED-TARGET", + "old-user", + "old-password", + "proxy-user", + "proxy-pass", + ): + self.assertNotIn(sensitive, response.text) + def test_an_outbox_near_capacity_is_a_warning(self): self.write_config(self.config( webhook={ From 8b9fd80b12b36212838af99d64a5febef836e5a3 Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 20:08:06 +0100 Subject: [PATCH 14/20] test: cover stale Settings form saves Add regression coverage for remote Webhook and retry changes surviving a stale local save, and for invalid stale forms leaving Settings unchanged. --- app/tests/test_settings_local_save.py | 84 +++++++++++++++++++++++---- 1 file changed, 72 insertions(+), 12 deletions(-) diff --git a/app/tests/test_settings_local_save.py b/app/tests/test_settings_local_save.py index d01358b..91ee05e 100644 --- a/app/tests/test_settings_local_save.py +++ b/app/tests/test_settings_local_save.py @@ -56,6 +56,14 @@ def read_config(self) -> dict: with open(self.config_path, encoding="utf-8") as config_file: return json.load(config_file) + def write_remote_settings(self, **webhook_overrides) -> dict: + current = settingsSvc.load_settings(self.config_path) + remote_settings = settingsSvc.writable_settings(current) + remote_settings["revision"] = current["revision"] + remote_settings["webhook"].pop("secret_set") + remote_settings["webhook"].update(webhook_overrides) + return settingsSvc.save_settings(self.config_path, remote_settings) + def tmp_files(self) -> list: return glob.glob(os.path.join(self.tmp.name, "*.tmp")) @@ -202,24 +210,76 @@ def test_a_legacy_config_gains_defaults_and_keeps_a_saved_port(self): self.assertEqual(saved["webhook"]["capacity"], 100) +class StaleSettingsFormRegressionTests(LocalSaveTestCase): + + def test_saving_a_stale_form_preserves_remote_target_and_retry_policy(self): + # The screen snapshots only edited fields before the remote write. It + # is not reloaded before this stale form is saved. + stale_form = {"port": 9393} + self.write_remote_settings( + url="https://remote-after-open.example.lan/hooks/opensms", + timeout=11, + max_attempts=6, + backoff=[2, 4, 8], + capacity=300, + ) + + saved = settingsSvc.save_local_settings(self.config_path, stale_form) + + self.assertEqual(saved["revision"], 5) + self.assertEqual(saved["port"], 9393) + webhook = saved["webhook"] + self.assertEqual( + webhook["url"], "https://remote-after-open.example.lan/hooks/opensms" + ) + self.assertEqual(webhook["timeout"], 11) + self.assertEqual(webhook["max_attempts"], 6) + self.assertEqual(webhook["backoff"], [2, 4, 8]) + self.assertEqual(webhook["capacity"], 300) + self.assertEqual(webhook["secret"], "remote-secret") + self.assertEqual(saved["unknown_top_level"], "internal") + self.assertEqual(webhook["unknown_webhook"], "internal") + self.assertEqual(self.read_config(), saved) + self.assertEqual(self.tmp_files(), []) + + def test_an_invalid_stale_form_rejects_the_whole_save(self): + stale_form = {"port": settingsSvc.PORT_MIN - 1} + self.write_remote_settings( + url="https://remote-after-open.example.lan/hooks/opensms", + timeout=11, + ) + before = self.read_config() + + with self.assertRaises(settingsSvc.SettingsValidationError): + settingsSvc.save_local_settings(self.config_path, stale_form) + + self.assertEqual(self.read_config(), before) + self.assertEqual(before["revision"], 4) + self.assertEqual( + before["webhook"]["url"], + "https://remote-after-open.example.lan/hooks/opensms", + ) + self.assertEqual(before["webhook"]["timeout"], 11) + self.assertEqual(before["unknown_top_level"], "internal") + self.assertEqual(before["webhook"]["unknown_webhook"], "internal") + self.assertEqual(self.tmp_files(), []) + + class PermissionConfirmationSaveTests(LocalSaveTestCase): def test_permission_confirmation_preserves_a_remote_write_after_a_stale_read(self): stored_settings = self.stored_config() stored_settings["permissions"] = False self.write_config(stored_settings) stale = settingsSvc.load_settings(self.config_path) - remote = settingsSvc.writable_settings(stale) - remote["revision"] = stale["revision"] - remote["webhook"].pop("secret_set") - remote["webhook"].update({ - "url": "https://remote-after-open.example.lan/hooks/opensms", - "secret": "remote-after-open-secret", - "timeout": 11, - "max_attempts": 6, - "backoff": [2, 4, 8], - "capacity": 300, - }) - settingsSvc.save_settings(self.config_path, remote) + self.assertEqual(stale["revision"], 3) + self.write_remote_settings( + url="https://remote-after-open.example.lan/hooks/opensms", + secret="remote-after-open-secret", + timeout=11, + max_attempts=6, + backoff=[2, 4, 8], + capacity=300, + ) saved = settingsSvc.save_local_settings( self.config_path, {"permissions": True} From eaabe73ef4808bdb29bef8fab7e42d7af12ac91b Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 22:04:01 +0100 Subject: [PATCH 15/20] Add Pydantic request models for remote API Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- app/main.py | 26 +- app/services/keySvc.py | 445 ++++++++++++++ app/services/postApi.py | 558 ++++++++++-------- app/services/settingsSvc.py | 16 +- app/services/webhookSvc.py | 17 +- app/tests/api_test_case.py | 10 +- app/tests/test_key_svc.py | 384 ++++++++++++ app/tests/test_remote_api.py | 277 ++++++++- app/tests/test_settings_local_save.py | 27 +- app/tests/test_webhook.py | 49 +- .../0002-remote-settings-and-control-api.md | 7 +- docs/remote-api.md | 41 +- 12 files changed, 1547 insertions(+), 310 deletions(-) create mode 100644 app/services/keySvc.py create mode 100644 app/tests/test_key_svc.py diff --git a/app/main.py b/app/main.py index 7cfd0e2..ad67296 100644 --- a/app/main.py +++ b/app/main.py @@ -47,6 +47,7 @@ from services.webhookSvc import ( default_webhook_config, format_webhook_status, + get_webhook_config, is_valid_target, normalize_webhook_config, read_webhook_status, @@ -795,6 +796,20 @@ def refresh_webhook_status(self): format_webhook_status(status) ) + def get_webhook_test_timeout(self) -> int: + """Return the normalized timeout from fresh or loaded Settings.""" + config_template = getattr(self, "config_template", None) + fallback = ( + config_template.get("webhook") + if isinstance(config_template, dict) + else None + ) + webhook = get_webhook_config( + getattr(self, "app_config", None), + fallback=fallback, + ) + return webhook["timeout"] + def send_webhook_test(self, instance=None): webhook_enabled, webhook_url, webhook_secret = self.read_webhook_inputs() # A test always needs a URL, even while the toggle is off. @@ -804,14 +819,19 @@ def send_webhook_test(self, instance=None): "Sending test webhook..." ) config = {"url": webhook_url, "secret": webhook_secret} + timeout = self.get_webhook_test_timeout() Thread( target=self.run_webhook_test, - kwargs={"config": config}, + kwargs={"config": config, "timeout": timeout}, daemon=True, ).start() - def run_webhook_test(self, config: dict): - ok, status, error = send_test_webhook(config) + def run_webhook_test(self, config: dict, timeout=None): + if timeout is None: + timeout = self.get_webhook_test_timeout() + else: + timeout = normalize_webhook_config({"timeout": timeout})["timeout"] + ok, status, error = send_test_webhook(config, timeout=timeout) Clock.schedule_once( lambda dt: self.show_webhook_test_result(ok, status, error) ) diff --git a/app/services/keySvc.py b/app/services/keySvc.py new file mode 100644 index 0000000..72041d5 --- /dev/null +++ b/app/services/keySvc.py @@ -0,0 +1,445 @@ +"""Named API key persistence. + +This module owns the versioned ``keys.json`` store, hashing, migration, scopes, +and key lifecycle. Every operation takes an explicit config directory so the +HTTP server, phone UI, and CLI share one implementation without a hidden path +or import-time filesystem dependency. +""" + +import hashlib +import json +import os +import re +import secrets +import threading +import time +from contextlib import contextmanager +from datetime import datetime, timezone + +from services.settingsSvc import atomic_write_json + +try: + import fcntl +except ImportError: + fcntl = None + +try: + import msvcrt +except ImportError: + msvcrt = None + + +SCOPE_SEND = "sms:write" +SCOPE_SETTINGS = "settings:write" + +VALID_SCOPES = frozenset({SCOPE_SEND, SCOPE_SETTINGS}) +PHONE_KEY_NAME = "opensms" +PHONE_KEY_OWNER = "phone" +PROXY_KEY_OWNER = "proxy" +KEY_OWNER_FIELD = "owner" +KEY_NAME_MIN = 2 +KEY_NAME_MAX = 64 +KEYS_FILE = "keys.json" +KEY_LOCK_FILE = "keys.json.lock" +_KEY_ID_PATTERN = re.compile(r"^k_[0-9a-f]{8}$") +_SHA256_HEX_PATTERN = re.compile(r"[0-9a-f]{64}") +_SCOPE_ERROR = ( + "scopes must be a non-empty subset of: " + + ", ".join(sorted(VALID_SCOPES)) +) +DEFAULT_SCOPES = object() +_key_lock = threading.RLock() + + +class KeyValidationError(ValueError): + """A malformed key request (HTTP 422).""" + + +class KeyConflict(Exception): + """A key request that conflicts with the stored keys (HTTP 409).""" + + +def hash_api_key(raw_key: str) -> str: + """Hash the raw key using SHA-256.""" + return hashlib.sha256(raw_key.encode("utf-8")).hexdigest() + + +def _is_canonical_sha256_hash(value) -> bool: + return ( + isinstance(value, str) + and _SHA256_HEX_PATTERN.fullmatch(value) is not None + ) + + +def _keys_path(config_dir: str) -> str: + return os.path.join(config_dir, KEYS_FILE) + + +def _key_lock_path(config_dir: str) -> str: + return os.path.join(config_dir, KEY_LOCK_FILE) + + +@contextmanager +def _key_store_lock(config_dir: str): + """Serialize key-store reads and writes across threads and processes.""" + os.makedirs(config_dir, exist_ok=True) + with _key_lock: + with open(_key_lock_path(config_dir), "a+b") as lock_file: + locked = False + try: + if fcntl is not None: + fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX) + locked = True + elif msvcrt is not None: + lock_file.seek(0, os.SEEK_END) + if lock_file.tell() == 0: + lock_file.write(b"\0") + lock_file.flush() + lock_file.seek(0) + while True: + try: + msvcrt.locking( + lock_file.fileno(), + msvcrt.LK_NBLCK, + 1, + ) + locked = True + break + except OSError: + time.sleep(0.01) + yield + finally: + if locked: + if fcntl is not None: + fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN) + else: + lock_file.seek(0) + msvcrt.locking( + lock_file.fileno(), + msvcrt.LK_UNLCK, + 1, + ) + + +def _now_iso() -> str: + return datetime.now(timezone.utc).isoformat(timespec="seconds") + + +def _normalize_owner_value(value) -> str | None: + if not isinstance(value, str): + return None + normalized = value.strip().casefold().replace("-", "_") + if normalized in { + "phone", + "phone_key", + "phoneowned", + "phone_owned", + }: + return PHONE_KEY_OWNER + if normalized in { + "proxy", + "proxy_key", + "integration", + }: + return PROXY_KEY_OWNER + return None + + +def _entry_owner(entry: dict) -> str | None: + """Read an explicit persisted ownership marker, without inferring by name.""" + explicit_marker = False + for field in (KEY_OWNER_FIELD, "owned_by", "key_owner", "ownership"): + if field not in entry: + continue + explicit_marker = True + owner = _normalize_owner_value(entry.get(field)) + if owner is not None: + return owner + + for field in ("phone_owned", "is_phone_key"): + if field not in entry: + continue + explicit_marker = True + value = entry.get(field) + if isinstance(value, bool): + return PHONE_KEY_OWNER if value else PROXY_KEY_OWNER + + if explicit_marker: + return PROXY_KEY_OWNER + return None + + +def _is_phone_owned(entry: dict) -> bool: + """Whether this entry carries an explicit phone ownership marker.""" + return _entry_owner(entry) == PHONE_KEY_OWNER + + +def _normalize_v2_keys(entries: list) -> tuple[list, bool]: + """Add explicit ownership to unmarked v2 entries and report pending writes.""" + normalized = [] + changed = False + for entry in entries: + if not isinstance(entry, dict): + changed = True + continue + current = dict(entry) + owner = _entry_owner(current) + if owner is None: + name = current.get("name") + owner = ( + PHONE_KEY_OWNER + if isinstance(name, str) + and name.strip().casefold() == PHONE_KEY_NAME + else PROXY_KEY_OWNER + ) + if current.get(KEY_OWNER_FIELD) != owner: + current[KEY_OWNER_FIELD] = owner + changed = True + normalized.append(current) + return normalized, changed + + +def _migrate_v1_keys(raw: dict) -> list: + """Convert a version-one {hash: {name, scopes}} store to version two. + + Version-one scopes were stored but never enforced, so migration grants both + scopes once; otherwise every existing install would lock itself out. + """ + keys = [] + for key_hash, info in raw.items(): + if not isinstance(info, dict): + continue + scopes = info.get("scopes") + if not isinstance(scopes, list): + scopes = [] + scopes = {str(scope) for scope in scopes if isinstance(scope, str)} + scopes.update({SCOPE_SEND, SCOPE_SETTINGS}) + name = str(info.get("name") or PHONE_KEY_NAME).strip() + keys.append({ + "id": f"k_{secrets.token_hex(4)}", + "name": name, + "hash": str(key_hash), + "scopes": sorted(scopes), + "created_at": _now_iso(), + "owner": ( + PHONE_KEY_OWNER + if name.casefold() == PHONE_KEY_NAME + else PROXY_KEY_OWNER + ), + }) + return keys + + +def load_key_store(config_dir: str) -> tuple[dict, bool]: + """Return the key store, migrating a version-one file in memory. + + The second item is True when a migration is pending persistence. + """ + try: + with open(_keys_path(config_dir), "r", encoding="utf-8") as keys_file: + raw = json.load(keys_file) + except Exception: + return {"version": 2, "keys": []}, False + if not isinstance(raw, dict): + return {"version": 2, "keys": []}, False + if raw.get("version") == 2 and isinstance(raw.get("keys"), list): + keys, normalized = _normalize_v2_keys(raw["keys"]) + return {"version": 2, "keys": keys}, normalized + return {"version": 2, "keys": _migrate_v1_keys(raw)}, True + + +def save_key_store(config_dir: str, store: dict): + """Persist a version-two key store atomically.""" + with _key_store_lock(config_dir): + _save_key_store(config_dir, store) + + +def _save_key_store(config_dir: str, store: dict): + """Persist a key store while the caller holds the key-store lock.""" + atomic_write_json(_keys_path(config_dir), store) + + +def authenticate_key(config_dir: str, raw_key: str) -> dict | None: + """Return the matching stored entry, persisting a pending migration.""" + hashed = hash_api_key(raw_key) + with _key_store_lock(config_dir): + store, migrated = load_key_store(config_dir) + match = None + for entry in store["keys"]: + if not isinstance(entry, dict): + continue + stored_hash = entry.get("hash") + if not _is_canonical_sha256_hash(stored_hash): + continue + if secrets.compare_digest(stored_hash, hashed): + match = entry + if match is not None and migrated: + _save_key_store(config_dir, store) + return match + + +def has_api_keys(config_dir: str) -> bool: + with _key_store_lock(config_dir): + store, migrated = load_key_store(config_dir) + if migrated: + _save_key_store(config_dir, store) + return bool(store["keys"]) + + +def _normalize_key_name(value) -> str: + if not isinstance(value, str): + raise KeyValidationError("name must be a string") + name = value.strip() + if not KEY_NAME_MIN <= len(name) <= KEY_NAME_MAX: + raise KeyValidationError( + f"name must be {KEY_NAME_MIN}-{KEY_NAME_MAX} characters" + ) + if not name.isprintable(): + raise KeyValidationError("name must not contain control characters") + if name.casefold() == PHONE_KEY_NAME: + raise KeyValidationError( + f"name {PHONE_KEY_NAME} is reserved for the phone key" + ) + return name + + +def _normalize_key_scopes(value) -> list: + if not isinstance(value, list): + raise KeyValidationError("scopes must be a list") + scopes = set() + for scope in value: + if not isinstance(scope, str) or scope not in VALID_SCOPES: + raise KeyValidationError(_SCOPE_ERROR) + scopes.add(scope) + if not scopes: + raise KeyValidationError(_SCOPE_ERROR) + return sorted(scopes) + + +def _new_key_entry( + name: str, + scopes, + raw_key: str, + *, + owner: str = PROXY_KEY_OWNER, +) -> dict: + return { + "id": f"k_{secrets.token_hex(4)}", + "name": name, + "hash": hash_api_key(raw_key), + "scopes": sorted(scopes), + "created_at": _now_iso(), + "owner": owner, + } + + +def _new_raw_key() -> str: + return f"osms_{secrets.token_urlsafe(32)}" + + +def public_key(entry: dict) -> dict: + """The listable shape of a key: never the hash or the raw key.""" + scopes = entry.get("scopes") + if not isinstance(scopes, list): + scopes = [] + return { + "id": entry.get("id"), + "name": entry.get("name"), + "scopes": list(scopes), + "created_at": entry.get("created_at"), + } + + +def create_api_key( + config_dir: str, + name, + scopes=DEFAULT_SCOPES, + *, + log=None, +) -> dict: + """Create a named key; the raw key is returned only in this result.""" + name = _normalize_key_name(name) + normalized_scopes = ( + sorted(VALID_SCOPES) + if scopes is DEFAULT_SCOPES + else _normalize_key_scopes(scopes) + ) + raw_key = _new_raw_key() + with _key_store_lock(config_dir): + store, _ = load_key_store(config_dir) + for entry in store["keys"]: + existing_name = entry.get("name") + if ( + isinstance(existing_name, str) + and existing_name.casefold() == name.casefold() + ): + raise KeyConflict(f"An API key named {name} already exists") + entry = _new_key_entry(name, normalized_scopes, raw_key) + store["keys"].append(entry) + _save_key_store(config_dir, store) + if log is not None: + log(f"API key created: {name}") + return {**public_key(entry), "key": raw_key} + + +def list_api_keys(config_dir: str) -> list: + """Every key without its hash or raw value.""" + with _key_store_lock(config_dir): + store, migrated = load_key_store(config_dir) + if migrated: + _save_key_store(config_dir, store) + return [public_key(entry) for entry in store["keys"]] + + +def delete_api_key(config_dir: str, key_id: str, *, log=None) -> bool: + """Delete a key by id, returning False when it does not exist. + + Raises KeyConflict when deleting it would leave no key at all. + """ + if not isinstance(key_id, str) or not _KEY_ID_PATTERN.fullmatch(key_id): + return False + removed = None + with _key_store_lock(config_dir): + store, _ = load_key_store(config_dir) + keys = store["keys"] + index = next( + ( + position + for position, entry in enumerate(keys) + if entry.get("id") == key_id + ), + None, + ) + if index is None: + return False + if len(keys) <= 1: + raise KeyConflict("The last remaining API key cannot be deleted") + removed = keys.pop(index) + _save_key_store(config_dir, store) + if log is not None: + log(f"API key deleted: {removed.get('name')}") + return True + + +def rotate_phone_key(config_dir: str, *, log=None) -> str: + """Replace only the phone-owned key, leaving proxy-owned keys intact.""" + raw_key = _new_raw_key() + with _key_store_lock(config_dir): + store, _ = load_key_store(config_dir) + store["keys"] = [ + entry for entry in store["keys"] + if not _is_phone_owned(entry) + ] + store["keys"].append( + _new_key_entry( + PHONE_KEY_NAME, + VALID_SCOPES, + raw_key, + owner=PHONE_KEY_OWNER, + ) + ) + _save_key_store(config_dir, store) + print("Replaced the phone API key") + if log is not None: + log("Replaced the phone API key") + return raw_key diff --git a/app/services/postApi.py b/app/services/postApi.py index b12fcc3..744e03c 100644 --- a/app/services/postApi.py +++ b/app/services/postApi.py @@ -1,20 +1,18 @@ -import hashlib -import re -import secrets import asyncio import time -from datetime import datetime, timezone from threading import Thread, Lock, Timer from os.path import join from urllib.parse import urlparse import json #from functools import partial +from typing import Annotated from fastapi import FastAPI, Request, HTTPException, Depends from fastapi.concurrency import run_in_threadpool +from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials -from pydantic import BaseModel +from pydantic import BaseModel, Field, StrictBool, StrictInt, StrictStr import uvicorn # local imports @@ -22,7 +20,8 @@ from services.smsApi import SmsCrossPlatform, clean_and_validate_phone from services.logSvc import LogService from services.config import __version__, app_name -from services import netSvc, settingsSvc, controlSvc, webhookSvc +from services import netSvc, settingsSvc, controlSvc, webhookSvc, keySvc +from services.keySvc import KeyConflict, KeyValidationError # OS specific #try: @@ -40,28 +39,11 @@ logger = None sms_api = SmsCrossPlatform() -# API key scopes -SCOPE_SEND = "sms:write" -SCOPE_SETTINGS = "settings:write" - -VALID_SCOPES = frozenset({SCOPE_SEND, SCOPE_SETTINGS}) -PHONE_KEY_NAME = "opensms" -KEY_NAME_MIN = 2 -KEY_NAME_MAX = 64 -_KEY_ID_PATTERN = re.compile(r"^k_[0-9a-f]{8}$") -_SCOPE_ERROR = ( - "scopes must be a non-empty subset of: " - + ", ".join(sorted(VALID_SCOPES)) -) -_DEFAULT_SCOPES = object() - - -class KeyValidationError(ValueError): - """A malformed key request (HTTP 422).""" - - -class KeyConflict(Exception): - """A key request that conflicts with the stored keys (HTTP 409).""" +# API key scopes and request sentinel come from the persistence owner. +SCOPE_SEND = keySvc.SCOPE_SEND +SCOPE_SETTINGS = keySvc.SCOPE_SETTINGS +VALID_SCOPES = keySvc.VALID_SCOPES +_DEFAULT_SCOPES = keySvc.DEFAULT_SCOPES # Test seam: tests point the API at a temporary config directory so they never # read or write the real app data directory. @@ -70,7 +52,6 @@ class KeyConflict(Exception): _last_restart_at: float | None = None _restart_lock = Lock() _started_at: float | None = None -_key_lock = Lock() # Restart orchestration. The handler acknowledges before anything stops, and # the control intent is written only after the response has had time to leave. @@ -164,216 +145,291 @@ def log_activities(message:str): daemon=True ).start() -def hash_api_key(raw_key: str) -> str: - """Hash the raw key using SHA-256.""" - return hashlib.sha256(raw_key.encode("utf-8")).hexdigest() - -def _keys_path() -> str: - return join(get_config_dir(), "keys.json") - def _settings_path() -> str: return join(get_config_dir(), "config.json") -def _now_iso() -> str: - return datetime.now(timezone.utc).isoformat(timespec="seconds") -def _migrate_v1_keys(raw: dict) -> list: - """Convert a version-one {hash: {name, scopes}} store to version two. +# Key persistence lives in keySvc. These adapters keep existing server, UI, and +# CLI call sites working while binding them to this module's config-directory +# seam and activity logger. +def hash_api_key(raw_key: str) -> str: + return keySvc.hash_api_key(raw_key) - Version-one scopes were stored but never enforced, so migration grants both - scopes once; otherwise every existing install would lock itself out. - """ - keys = [] - for key_hash, info in raw.items(): - if not isinstance(info, dict): - continue - scopes = info.get("scopes") - if not isinstance(scopes, list): - scopes = [] - scopes = {str(scope) for scope in scopes if isinstance(scope, str)} - scopes.update({SCOPE_SEND, SCOPE_SETTINGS}) - keys.append({ - "id": f"k_{secrets.token_hex(4)}", - "name": str(info.get("name") or PHONE_KEY_NAME), - "hash": str(key_hash), - "scopes": sorted(scopes), - "created_at": _now_iso(), - }) - return keys def load_key_store() -> tuple[dict, bool]: - """Return the key store, migrating a version-one file in memory. + return keySvc.load_key_store(get_config_dir()) - The second item is True when a migration is pending persistence. - """ - try: - with open(_keys_path(), "r", encoding="utf-8") as keys_file: - raw = json.load(keys_file) - except Exception: - return {"version": 2, "keys": []}, False - if not isinstance(raw, dict): - return {"version": 2, "keys": []}, False - if raw.get("version") == 2 and isinstance(raw.get("keys"), list): - keys = [entry for entry in raw["keys"] if isinstance(entry, dict)] - return {"version": 2, "keys": keys}, False - return {"version": 2, "keys": _migrate_v1_keys(raw)}, True def save_key_store(store: dict): - settingsSvc.atomic_write_json(_keys_path(), store) + keySvc.save_key_store(get_config_dir(), store) + def authenticate_key(raw_key: str) -> dict | None: - hashed = hash_api_key(raw_key) - with _key_lock: - store, migrated = load_key_store() - match = None - for entry in store["keys"]: - if secrets.compare_digest(entry.get("hash") or "", hashed): - match = entry - if match is not None and migrated: - save_key_store(store) - return match + return keySvc.authenticate_key(get_config_dir(), raw_key) + def has_api_keys() -> bool: - store, _ = load_key_store() - return bool(store["keys"]) - -def _normalize_key_name(value) -> str: - if not isinstance(value, str): - raise KeyValidationError("name must be a string") - name = value.strip() - if not KEY_NAME_MIN <= len(name) <= KEY_NAME_MAX: - raise KeyValidationError( - f"name must be {KEY_NAME_MIN}-{KEY_NAME_MAX} characters" - ) - if not name.isprintable(): - raise KeyValidationError("name must not contain control characters") - return name - -def _normalize_key_scopes(value) -> list: - if not isinstance(value, list): - raise KeyValidationError("scopes must be a list") - scopes = set() - for scope in value: - if not isinstance(scope, str) or scope not in VALID_SCOPES: - raise KeyValidationError(_SCOPE_ERROR) - scopes.add(scope) - if not scopes: - raise KeyValidationError(_SCOPE_ERROR) - return sorted(scopes) - -def _new_key_entry(name: str, scopes, raw_key: str) -> dict: - return { - "id": f"k_{secrets.token_hex(4)}", - "name": name, - "hash": hash_api_key(raw_key), - "scopes": sorted(scopes), - "created_at": _now_iso(), - } + return keySvc.has_api_keys(get_config_dir()) -def _new_raw_key() -> str: - return f"osms_{secrets.token_urlsafe(32)}" def public_key(entry: dict) -> dict: - """The listable shape of a key: never the hash or the raw key.""" - scopes = entry.get("scopes") - if not isinstance(scopes, list): - scopes = [] - return { - "id": entry.get("id"), - "name": entry.get("name"), - "scopes": list(scopes), - "created_at": entry.get("created_at"), - } + return keySvc.public_key(entry) + def create_api_key(name, scopes=_DEFAULT_SCOPES) -> dict: - """Create a named key; the raw key is returned only in this result.""" - name = _normalize_key_name(name) - normalized_scopes = ( - sorted(VALID_SCOPES) - if scopes is _DEFAULT_SCOPES - else _normalize_key_scopes(scopes) + return keySvc.create_api_key( + get_config_dir(), name, scopes, log=log_activities ) - raw_key = _new_raw_key() - with _key_lock: - store, _ = load_key_store() - for entry in store["keys"]: - existing_name = entry.get("name") - if ( - isinstance(existing_name, str) - and existing_name.casefold() == name.casefold() - ): - raise KeyConflict(f"An API key named {name} already exists") - entry = _new_key_entry(name, normalized_scopes, raw_key) - store["keys"].append(entry) - save_key_store(store) - log_activities(f"API key created: {name}") - return {**public_key(entry), "key": raw_key} + def list_api_keys() -> list: - """Every key without its hash or raw value.""" - store, _ = load_key_store() - return [public_key(entry) for entry in store["keys"]] + return keySvc.list_api_keys(get_config_dir()) + def delete_api_key(key_id: str) -> bool: - """Delete a key by id, returning False when it does not exist. + return keySvc.delete_api_key( + get_config_dir(), key_id, log=log_activities + ) - Raises KeyConflict when deleting it would leave no key at all. - """ - if not isinstance(key_id, str) or not _KEY_ID_PATTERN.fullmatch(key_id): - return False - with _key_lock: - store, _ = load_key_store() - keys = store["keys"] - index = next( - ( - position - for position, entry in enumerate(keys) - if entry.get("id") == key_id - ), - None, - ) - if index is None: - return False - if len(keys) <= 1: - raise KeyConflict("The last remaining API key cannot be deleted") - removed = keys.pop(index) - save_key_store(store) - log_activities(f"API key deleted: {removed.get('name')}") - return True def rotate_phone_key() -> str: - """Replace only the phone-owned key, leaving proxy-owned keys intact.""" - raw_key = _new_raw_key() - with _key_lock: - store, _ = load_key_store() - store["keys"] = [ - entry for entry in store["keys"] - if str(entry.get("name") or "").casefold() != PHONE_KEY_NAME - ] - store["keys"].append( - _new_key_entry(PHONE_KEY_NAME, VALID_SCOPES, raw_key) - ) - save_key_store(store) - print("Replaced the phone API key") - log_activities("Replaced the phone API key") - return raw_key + return keySvc.rotate_phone_key(get_config_dir(), log=log_activities) + def generate_new_api_key() -> str: """Backwards-compatible entry point for rotating the phone key.""" return rotate_phone_key() - # data formatting for request class SmsData(BaseModel): number: str text: str #sub_text: str | None = None + +BackoffWait = Annotated[ + StrictInt, + Field(ge=1, le=settingsSvc.BACKOFF_MAX_SECONDS), +] + + +class WebhookSettingsRequest(BaseModel): + enabled: StrictBool + url: StrictStr + timeout: StrictInt = Field( + ge=settingsSvc.TIMEOUT_MIN, + le=settingsSvc.TIMEOUT_MAX, + ) + max_attempts: StrictInt = Field( + ge=settingsSvc.MAX_ATTEMPTS_MIN, + le=settingsSvc.MAX_ATTEMPTS_MAX, + ) + backoff: list[BackoffWait] = Field( + min_length=settingsSvc.BACKOFF_MIN_COUNT, + max_length=settingsSvc.BACKOFF_MAX_COUNT, + min_items=settingsSvc.BACKOFF_MIN_COUNT, + max_items=settingsSvc.BACKOFF_MAX_COUNT, + ) + capacity: StrictInt = Field( + ge=settingsSvc.CAPACITY_MIN, + le=settingsSvc.CAPACITY_MAX, + ) + secret: StrictStr = Field( + default=None, + max_length=settingsSvc.SECRET_MAX_LENGTH, + ) + + class Config: + extra = "forbid" + + +class SettingsRequest(BaseModel): + revision: StrictInt = None + port: StrictInt = Field( + ge=settingsSvc.PORT_MIN, + le=settingsSvc.PORT_MAX, + ) + boot: StrictBool + webhook: WebhookSettingsRequest + + def __init__(self, **data): + if "revision" in data and data["revision"] is None: + raise ValueError("revision must be an integer") + webhook = data.get("webhook") + if ( + isinstance(webhook, dict) + and "secret" in webhook + and webhook["secret"] is None + ): + raise ValueError("webhook.secret must be a string") + super().__init__(**data) + + class Config: + extra = "forbid" + + +class KeyCreateRequest(BaseModel): + name: StrictStr + scopes: list[StrictStr] = None + + def __init__(self, **data): + if "scopes" in data and data["scopes"] is None: + raise ValueError("scopes must be a list") + super().__init__(**data) + + class Config: + extra = "forbid" + + # FastAPI app app = FastAPI() security = HTTPBearer(auto_error=False) + +def _model_dump(model): + if hasattr(model, "model_dump"): + return model.model_dump(exclude_unset=True) + return model.dict(exclude_unset=True) + + +def _request_validation_detail(exc: RequestValidationError) -> str: + errors = exc.errors() + if not errors: + return "Request body must be valid JSON" + + error = errors[0] + error_type = str(error.get("type", "")) + loc = tuple(error.get("loc", ())) + field_parts = [ + str(part) + for part in loc + if str(part) not in ("body", "__root__") + ] + field = ".".join(field_parts) + message = str(error.get("msg", "")) + + if error_type in {"json_invalid", "value_error.jsondecode"}: + return "Request body must be valid JSON" + + if "webhook.secret must be a string" in message: + return "webhook.secret must be a string" + if "scopes must be a list" in message: + return "scopes must be a list" + if "revision must be an integer" in message: + return "revision must be an integer" + + if error_type in {"extra_forbidden", "value_error.extra"}: + extra_errors = [ + item + for item in errors + if str(item.get("type", "")) in { + "extra_forbidden", + "value_error.extra", + } + ] + names = sorted({ + str(item["loc"][-1]) + for item in extra_errors + if item.get("loc") + }) + prefix = "webhook" if "webhook" in field_parts else "request" + return f"Unknown field(s) in {prefix}: {', '.join(names)}" + + if error_type in {"missing", "value_error.missing"}: + if not field_parts: + return "Request body must be valid JSON" + if "webhook" in field_parts: + return f"Missing required webhook field: {field_parts[-1]}" + return f"Missing required field: {field_parts[-1]}" + + if not field_parts and error_type in { + "model_attributes_type", + "model_type", + "dict_type", + "list_type", + "type_error.dict", + "type_error.list", + }: + return "Request body must be a JSON object" + + if field == "revision": + return "revision must be an integer" + if field == "port": + return ( + f"port must be an integer between " + f"{settingsSvc.PORT_MIN} and {settingsSvc.PORT_MAX}" + ) + if field == "boot": + return "boot must be a boolean" + if field == "webhook": + return "webhook must be an object" + if field == "webhook.enabled": + return "webhook.enabled must be a boolean" + if field == "webhook.url": + return "webhook.url must be a string" + if field == "webhook.timeout": + return ( + f"webhook.timeout must be an integer between " + f"{settingsSvc.TIMEOUT_MIN} and {settingsSvc.TIMEOUT_MAX}" + ) + if field == "webhook.max_attempts": + return ( + f"webhook.max_attempts must be an integer between " + f"{settingsSvc.MAX_ATTEMPTS_MIN} and " + f"{settingsSvc.MAX_ATTEMPTS_MAX}" + ) + if field == "webhook.backoff": + return ( + f"webhook.backoff must be a list of " + f"{settingsSvc.BACKOFF_MIN_COUNT}-" + f"{settingsSvc.BACKOFF_MAX_COUNT} integers" + ) + if field.startswith("webhook.backoff."): + index = field.rsplit(".", 1)[-1] + return ( + f"webhook.backoff[{index}] must be an integer between 1 and " + f"{settingsSvc.BACKOFF_MAX_SECONDS}" + ) + if field == "webhook.capacity": + return ( + f"webhook.capacity must be an integer between " + f"{settingsSvc.CAPACITY_MIN} and {settingsSvc.CAPACITY_MAX}" + ) + if field == "webhook.secret": + if error_type in { + "string_too_long", + "value_error.any_str.max_length", + }: + return ( + f"webhook.secret must be at most " + f"{settingsSvc.SECRET_MAX_LENGTH} characters" + ) + return "webhook.secret must be a string" + if field == "name": + return "name must be a string" + if field == "scopes": + return "scopes must be a list" + if field.startswith("scopes."): + return ( + "scopes must be a non-empty subset of: " + + ", ".join(sorted(keySvc.VALID_SCOPES)) + ) + + return message.removeprefix("Value error, ").replace("Value error, ", "") + + +@app.exception_handler(RequestValidationError) +async def request_validation_exception_handler( + request: Request, + exc: RequestValidationError, +): + return JSONResponse( + status_code=422, + content={"detail": _request_validation_detail(exc)}, + ) + + # api server class with callback function class PosiApiServer: @@ -789,72 +845,75 @@ def _schedule_restart(config_dir: str, port: int): timer.start() -@app.put("/api/settings") -async def api_put_settings( - request: Request, - client: dict = Depends(require_scope(SCOPE_SETTINGS)) -): +async def _request_json(request: Request, *, allow_empty: bool = False): + """Parse a JSON body, optionally treating no body as an empty object.""" + raw_body = await request.body() + if allow_empty and not raw_body: + return {} try: - payload = await request.json() + return json.loads(raw_body) except Exception: raise HTTPException( status_code=422, detail="Request body must be valid JSON", ) - try: - saved = settingsSvc.save_settings(_settings_path(), payload) - except settingsSvc.SettingsRevisionConflict as exc: - raise HTTPException(status_code=409, detail=exc.detail) - except settingsSvc.SettingsRuleError as exc: - raise HTTPException(status_code=400, detail=str(exc)) - except settingsSvc.SettingsValidationError as exc: - raise HTTPException(status_code=422, detail=str(exc)) - log_activities(_settings_log_message(payload)) - return { - **_settings_body(saved), - "restart_required": _restart_required(saved), - } - -KEY_REQUEST_FIELDS = {"name", "scopes"} -async def _key_request_body(request: Request) -> dict: - """Validate the shape of a key-creation body, before touching the store.""" - try: - payload = await request.json() - except Exception: - raise HTTPException( - status_code=422, - detail="Request body must be valid JSON", - ) +def _require_json_object(payload): if not isinstance(payload, dict): raise HTTPException( status_code=422, detail="Request body must be a JSON object", ) - unknown = set(payload) - KEY_REQUEST_FIELDS + return payload + + +async def _request_json_object( + request: Request, *, allow_empty: bool = False +) -> dict: + payload = await _request_json(request, allow_empty=allow_empty) + return _require_json_object(payload) + + +def _reject_unknown_fields(payload: dict, allowed_fields): + unknown = set(payload) - allowed_fields if unknown: raise HTTPException( status_code=422, detail=f"Unknown field(s) in request: {', '.join(sorted(unknown))}", ) - if "name" not in payload: - raise HTTPException( - status_code=422, - detail="Missing required field: name", - ) - return payload +@app.put("/api/settings") +async def api_put_settings( + payload: SettingsRequest, + client: dict = Depends(require_scope(SCOPE_SETTINGS)) +): + payload_dict = _model_dump(payload) + try: + saved = settingsSvc.save_settings(_settings_path(), payload_dict) + except settingsSvc.SettingsRevisionConflict as exc: + raise HTTPException(status_code=409, detail=exc.detail) + except settingsSvc.SettingsRuleError as exc: + raise HTTPException(status_code=400, detail=str(exc)) + except settingsSvc.SettingsValidationError as exc: + raise HTTPException(status_code=422, detail=str(exc)) + log_activities(_settings_log_message(payload_dict)) + return { + **_settings_body(saved), + "restart_required": _restart_required(saved), + } + @app.post("/api/keys", status_code=201) async def api_create_key( - request: Request, + payload: KeyCreateRequest, client: dict = Depends(require_scope(SCOPE_SETTINGS)) ): - payload = await _key_request_body(request) + payload_dict = _model_dump(payload) try: return create_api_key( - payload["name"], payload.get("scopes", _DEFAULT_SCOPES) + payload_dict["name"], + payload_dict.get("scopes", _DEFAULT_SCOPES), ) except KeyConflict as exc: raise HTTPException(status_code=409, detail=str(exc)) @@ -884,19 +943,9 @@ async def api_delete_key( WEBHOOK_TEST_FIELDS = {"url", "secret"} -def _webhook_test_overrides(payload) -> dict: - """Validate a Webhook test body; an absent body means "use saved Settings".""" - if not isinstance(payload, dict): - raise HTTPException( - status_code=422, - detail="Request body must be a JSON object", - ) - unknown = set(payload) - WEBHOOK_TEST_FIELDS - if unknown: - raise HTTPException( - status_code=422, - detail=f"Unknown field(s) in request: {', '.join(sorted(unknown))}", - ) +def _webhook_test_overrides(payload: dict) -> dict: + """Validate Webhook test overrides; an absent body means saved Settings.""" + _reject_unknown_fields(payload, WEBHOOK_TEST_FIELDS) overrides = {} if "url" in payload: if not isinstance(payload["url"], str): @@ -981,16 +1030,7 @@ async def api_webhook_test( request: Request, client: dict = Depends(require_scope(SCOPE_SETTINGS)) ): - raw_body = await request.body() - payload = {} - if raw_body: - try: - payload = json.loads(raw_body) - except Exception: - raise HTTPException( - status_code=422, - detail="Request body must be valid JSON", - ) + payload = await _request_json_object(request, allow_empty=True) overrides = _webhook_test_overrides(payload) settings = settingsSvc.load_settings(_settings_path()) url, secret, timeout = _resolve_webhook_test_config(settings, overrides) diff --git a/app/services/settingsSvc.py b/app/services/settingsSvc.py index e5246f0..a320f77 100644 --- a/app/services/settingsSvc.py +++ b/app/services/settingsSvc.py @@ -18,14 +18,11 @@ BACKOFF_MIN_COUNT, CAPACITY_MAX, CAPACITY_MIN, - DEFAULT_BACKOFF, - DEFAULT_CAPACITY, - DEFAULT_MAX_ATTEMPTS, - DEFAULT_TIMEOUT, MAX_ATTEMPTS_MAX, MAX_ATTEMPTS_MIN, TIMEOUT_MAX, TIMEOUT_MIN, + default_webhook_config, has_target_credentials, is_valid_target, normalize_webhook_config, @@ -79,15 +76,8 @@ class SettingsLoadError(ValueError): ## Defaults def default_webhook_settings() -> dict: - return { - "enabled": False, - "url": "", - "secret": "", - "timeout": DEFAULT_TIMEOUT, - "max_attempts": DEFAULT_MAX_ATTEMPTS, - "backoff": list(DEFAULT_BACKOFF), - "capacity": DEFAULT_CAPACITY, - } + """Return the dispatcher-owned defaults in the persisted Settings shape.""" + return default_webhook_config() def default_settings() -> dict: return { diff --git a/app/services/webhookSvc.py b/app/services/webhookSvc.py index 9d77fe9..be665d3 100644 --- a/app/services/webhookSvc.py +++ b/app/services/webhookSvc.py @@ -114,13 +114,26 @@ def normalize_webhook_config(raw: dict | None) -> dict: ) return config -def get_webhook_config(config_path: str) -> dict: - """Read the current webhook config from the app config file (hot reload).""" +def get_webhook_config( + config_path: str, fallback: dict | None = None +) -> dict: + """Read the current webhook config from the app config file (hot reload). + + ``fallback`` is used only when the config file is absent, such as before + the on-device Settings screen has written it for the first time. An + unreadable or malformed file keeps the dispatcher-owned defaults. + """ + if not config_path: + return normalize_webhook_config(fallback) try: with open(config_path, "r", encoding="utf-8") as cf: app_config = json.load(cf) + except FileNotFoundError: + return normalize_webhook_config(fallback) except Exception: return default_webhook_config() + if not isinstance(app_config, dict): + return default_webhook_config() return normalize_webhook_config(app_config.get("webhook")) def _parse_target(url: str) -> ParseResult | None: diff --git a/app/tests/api_test_case.py b/app/tests/api_test_case.py index 7147e93..02516df 100644 --- a/app/tests/api_test_case.py +++ b/app/tests/api_test_case.py @@ -16,7 +16,7 @@ from fastapi.testclient import TestClient -from services import postApi +from services import keySvc, postApi class ApiTestCase(unittest.TestCase): @@ -63,7 +63,8 @@ def read_key_store(self) -> dict: return json.load(keys_file) def add_api_key(self, scopes=("sms:write", "settings:write"), - name: str = "test") -> str: + name: str = "test", + owner: str = "proxy") -> str: """Write a v2 key store entry and return the raw key.""" raw_key = f"osms_{secrets.token_urlsafe(16)}" keys_path = os.path.join(self.config_dir, "keys.json") @@ -74,9 +75,10 @@ def add_api_key(self, scopes=("sms:write", "settings:write"), store["keys"].append({ "id": f"k_{secrets.token_hex(4)}", "name": name, - "hash": postApi.hash_api_key(raw_key), + "hash": keySvc.hash_api_key(raw_key), "scopes": sorted(scopes), "created_at": "2026-01-01T00:00:00+00:00", + "owner": owner, }) with open(keys_path, "w", encoding="utf-8") as keys_file: json.dump(store, keys_file) @@ -90,7 +92,7 @@ def add_legacy_api_key(self, scopes=("sms:write",), os.path.join(self.config_dir, "keys.json"), "w", encoding="utf-8" ) as keys_file: json.dump({ - postApi.hash_api_key(raw_key): { + keySvc.hash_api_key(raw_key): { "name": name, "scopes": list(scopes), }, diff --git a/app/tests/test_key_svc.py b/app/tests/test_key_svc.py new file mode 100644 index 0000000..28c2d07 --- /dev/null +++ b/app/tests/test_key_svc.py @@ -0,0 +1,384 @@ +import json +import multiprocessing +import os +import queue +import sys +import tempfile +import unittest +from unittest import mock + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from services import keySvc + + +def create_key_worker(config_dir, name, result_queue): + try: + created = keySvc.create_api_key(config_dir, name) + result_queue.put(("ok", created["name"])) + except BaseException as exc: + result_queue.put(("error", f"{type(exc).__name__}: {exc}")) + + +def authenticate_key_worker(config_dir, raw_key, result_queue): + try: + entry = keySvc.authenticate_key(config_dir, raw_key) + result_queue.put(("ok", entry is not None)) + except BaseException as exc: + result_queue.put(("error", f"{type(exc).__name__}: {exc}")) + + +def delete_key_worker(config_dir, key_id, result_queue): + try: + deleted = keySvc.delete_api_key(config_dir, key_id) + result_queue.put(("ok", deleted)) + except BaseException as exc: + result_queue.put(("error", f"{type(exc).__name__}: {exc}")) + + +def rotate_phone_key_worker(config_dir, result_queue): + try: + raw_key = keySvc.rotate_phone_key(config_dir) + result_queue.put(("ok", raw_key)) + except BaseException as exc: + result_queue.put(("error", f"{type(exc).__name__}: {exc}")) + + +def read_key_store_worker(config_dir, iterations, result_queue): + try: + for _ in range(iterations): + with open( + os.path.join(config_dir, "keys.json"), + "r", + encoding="utf-8", + ) as keys_file: + store = json.load(keys_file) + if not isinstance(store, dict) or not isinstance( + store.get("keys"), list + ): + raise AssertionError("Malformed readable key store") + result_queue.put(("ok", None)) + except BaseException as exc: + result_queue.put(("error", f"{type(exc).__name__}: {exc}")) + + +class KeyStoreTests(unittest.TestCase): + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.first_dir = os.path.join(self.tmp.name, "first") + self.second_dir = os.path.join(self.tmp.name, "second") + + def tearDown(self): + self.tmp.cleanup() + + def test_persistence_is_scoped_to_the_explicit_config_directory(self): + created = keySvc.create_api_key(self.first_dir, "proxy") + + self.assertTrue(os.path.isfile(os.path.join(self.first_dir, "keys.json"))) + self.assertFalse(os.path.exists(os.path.join(self.second_dir, "keys.json"))) + self.assertFalse(keySvc.has_api_keys(self.second_dir)) + self.assertIsNotNone( + keySvc.authenticate_key(self.first_dir, created["key"]) + ) + self.assertIsNone( + keySvc.authenticate_key(self.second_dir, created["key"]) + ) + + with open( + os.path.join(self.first_dir, "keys.json"), encoding="utf-8" + ) as keys_file: + stored = json.load(keys_file) + self.assertNotIn(created["key"], json.dumps(stored)) + self.assertEqual( + keySvc.list_api_keys(self.first_dir), + [{field: created[field] for field in ( + "id", "name", "scopes", "created_at" + )}], + ) + + def test_malformed_v2_hashes_are_authentication_failures(self): + malformed_hashes = ( + 123, + None, + {"digest": "a" * 64}, + ["a" * 64], + "a" * 63, + "g" * 64, + ) + os.makedirs(self.first_dir, exist_ok=True) + + for index, malformed_hash in enumerate(malformed_hashes): + with self.subTest(malformed_hash=malformed_hash): + store = { + "version": 2, + "keys": [{ + "id": f"k_{index:08x}", + "name": f"malformed-{index}", + "hash": malformed_hash, + "scopes": ["sms:write", "settings:write"], + "created_at": "2026-01-01T00:00:00+00:00", + "owner": "proxy", + }], + } + with open( + os.path.join(self.first_dir, "keys.json"), + "w", + encoding="utf-8", + ) as keys_file: + json.dump(store, keys_file) + + with mock.patch.object( + keySvc.secrets, + "compare_digest", + wraps=keySvc.secrets.compare_digest, + ) as compare_digest: + match = keySvc.authenticate_key( + self.first_dir, + "osms_attempt", + ) + + self.assertIsNone(match) + compare_digest.assert_not_called() + + def test_malformed_v2_hashes_do_not_hide_a_later_valid_hash(self): + raw_key = "osms_valid_after_malformed" + valid_hash = keySvc.hash_api_key(raw_key) + os.makedirs(self.first_dir, exist_ok=True) + store = { + "version": 2, + "keys": [ + { + "id": "k_00000001", + "name": "malformed", + "hash": ["not", "a", "hash"], + "scopes": ["sms:write", "settings:write"], + "created_at": "2026-01-01T00:00:00+00:00", + "owner": "proxy", + }, + { + "id": "k_00000002", + "name": "valid", + "hash": valid_hash, + "scopes": ["sms:write", "settings:write"], + "created_at": "2026-01-01T00:00:00+00:00", + "owner": "proxy", + }, + ], + } + with open( + os.path.join(self.first_dir, "keys.json"), + "w", + encoding="utf-8", + ) as keys_file: + json.dump(store, keys_file) + + match = keySvc.authenticate_key(self.first_dir, raw_key) + + self.assertIsNotNone(match) + self.assertEqual(match["name"], "valid") + + def test_concurrent_processes_can_create_keys_without_lost_updates(self): + keySvc.create_api_key(self.first_dir, "seed") + context = multiprocessing.get_context("spawn") + result_queue = context.Queue() + + creators = [ + context.Process( + target=create_key_worker, + args=(self.first_dir, f"proxy-{index}", result_queue), + ) + for index in range(8) + ] + readers = [ + context.Process( + target=read_key_store_worker, + args=(self.first_dir, 100, result_queue), + ) + for _ in range(2) + ] + + for process in creators + readers: + process.start() + for process in creators + readers: + process.join(20) + + for process in creators + readers: + if process.is_alive(): + process.terminate() + process.join() + self.assertEqual(process.exitcode, 0) + + outcomes = [] + for _ in range(len(creators) + len(readers)): + try: + outcomes.append(result_queue.get(timeout=5)) + except queue.Empty: + self.fail("A cross-process key-store worker did not report") + + failures = [ + outcome for outcome in outcomes + if outcome[0] != "ok" + ] + self.assertEqual(failures, []) + + store = keySvc.load_key_store(self.first_dir)[0] + names = [entry["name"] for entry in store["keys"]] + self.assertEqual(len(names), 9) + self.assertEqual( + set(names), + {"seed", *(f"proxy-{index}" for index in range(8))}, + ) + self.assertEqual(len(set(names)), len(names)) + + def test_concurrent_authentication_migrates_a_legacy_store_once(self): + raw_keys = ("legacy-one", "legacy-two") + legacy_store = { + keySvc.hash_api_key(raw_keys[0]): { + "name": "first", + "scopes": ["sms:write"], + }, + keySvc.hash_api_key(raw_keys[1]): { + "name": "second", + "scopes": [], + }, + } + os.makedirs(self.first_dir, exist_ok=True) + with open( + os.path.join(self.first_dir, "keys.json"), + "w", + encoding="utf-8", + ) as keys_file: + json.dump(legacy_store, keys_file) + + context = multiprocessing.get_context("spawn") + result_queue = context.Queue() + authenticators = [ + context.Process( + target=authenticate_key_worker, + args=(self.first_dir, raw_key, result_queue), + ) + for raw_key in raw_keys + ] + for process in authenticators: + process.start() + for process in authenticators: + process.join(20) + + for process in authenticators: + if process.is_alive(): + process.terminate() + process.join() + self.assertEqual(process.exitcode, 0) + + outcomes = [] + for _ in authenticators: + try: + outcomes.append(result_queue.get(timeout=5)) + except queue.Empty: + self.fail("An authentication worker did not report") + self.assertEqual(outcomes, [("ok", True), ("ok", True)]) + + store = keySvc.load_key_store(self.first_dir)[0] + self.assertEqual(store["version"], 2) + self.assertEqual(len(store["keys"]), 2) + hashes = {entry["hash"] for entry in store["keys"]} + self.assertEqual( + hashes, + {keySvc.hash_api_key(raw_key) for raw_key in raw_keys}, + ) + for entry in store["keys"]: + self.assertEqual( + set(entry["scopes"]), + {"sms:write", "settings:write"}, + ) + + def test_concurrent_processes_can_delete_different_keys(self): + keySvc.create_api_key(self.first_dir, "keep") + first = keySvc.create_api_key(self.first_dir, "delete-first") + second = keySvc.create_api_key(self.first_dir, "delete-second") + + context = multiprocessing.get_context("spawn") + result_queue = context.Queue() + deleters = [ + context.Process( + target=delete_key_worker, + args=(self.first_dir, first["id"], result_queue), + ), + context.Process( + target=delete_key_worker, + args=(self.first_dir, second["id"], result_queue), + ), + ] + for process in deleters: + process.start() + for process in deleters: + process.join(20) + + for process in deleters: + if process.is_alive(): + process.terminate() + process.join() + self.assertEqual(process.exitcode, 0) + + outcomes = [] + for _ in deleters: + try: + outcomes.append(result_queue.get(timeout=5)) + except queue.Empty: + self.fail("A deletion worker did not report") + self.assertEqual(outcomes, [("ok", True), ("ok", True)]) + + names = [ + entry["name"] + for entry in keySvc.load_key_store(self.first_dir)[0]["keys"] + ] + self.assertEqual(names, ["keep"]) + + def test_concurrent_processes_can_rotate_the_phone_key(self): + keySvc.rotate_phone_key(self.first_dir) + keySvc.create_api_key(self.first_dir, "sms-proxy") + + context = multiprocessing.get_context("spawn") + result_queue = context.Queue() + rotators = [ + context.Process( + target=rotate_phone_key_worker, + args=(self.first_dir, result_queue), + ) + for _ in range(4) + ] + for process in rotators: + process.start() + for process in rotators: + process.join(20) + + for process in rotators: + if process.is_alive(): + process.terminate() + process.join() + self.assertEqual(process.exitcode, 0) + + outcomes = [] + for _ in rotators: + try: + outcomes.append(result_queue.get(timeout=5)) + except queue.Empty: + self.fail("A rotation worker did not report") + failures = [ + outcome for outcome in outcomes + if outcome[0] != "ok" + ] + self.assertEqual(failures, []) + + names = [ + entry["name"] + for entry in keySvc.load_key_store(self.first_dir)[0]["keys"] + ] + self.assertEqual(names.count("opensms"), 1) + self.assertEqual(names.count("sms-proxy"), 1) + self.assertEqual(len(names), 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/tests/test_remote_api.py b/app/tests/test_remote_api.py index 099d19f..e4421a2 100644 --- a/app/tests/test_remote_api.py +++ b/app/tests/test_remote_api.py @@ -10,7 +10,7 @@ from api_test_case import ApiTestCase from test_webhook import MockTarget -from services import postApi +from services import keySvc, postApi from services.config import __version__ from services.pathMgr import get_os_platform @@ -22,10 +22,32 @@ def test_request_without_a_key_is_refused(self): "/sms/", json={"number": "+14155552671", "text": "hello"}, ) - self.assertEqual(response.status_code, 403) self.assertNotIn("stat", response.json()) + def test_mutating_key_and_settings_operations_declare_request_bodies(self): + response = self.client.get("/openapi.json") + + self.assertEqual(response.status_code, 200) + openapi = response.json() + paths = openapi["paths"] + for path, method in ( + ("/api/settings", "put"), + ("/api/keys", "post"), + ): + with self.subTest(path=path): + request_body = paths[path][method]["requestBody"] + self.assertIsNotNone(request_body) + self.assertIn( + "application/json", + request_body["content"], + ) + settings_schema = openapi["components"]["schemas"]["SettingsRequest"] + self.assertEqual( + settings_schema["properties"]["revision"]["type"], + "integer", + ) + def test_api_reads_keys_from_the_temporary_config_directory(self): raw_key = postApi.generate_new_api_key() self.assertTrue( @@ -56,6 +78,87 @@ def test_health_refuses_an_invalid_key(self): ) self.assertEqual(response.status_code, 401) + def test_health_ignores_malformed_stored_hashes(self): + malformed_hashes = ( + 123, + None, + {"digest": "a" * 64}, + ["a" * 64], + "a" * 63, + "g" * 64, + ) + for index, malformed_hash in enumerate(malformed_hashes): + with self.subTest(malformed_hash=malformed_hash): + store = { + "version": 2, + "keys": [{ + "id": f"k_{index:08x}", + "name": f"malformed-{index}", + "hash": malformed_hash, + "scopes": ["sms:write", "settings:write"], + "created_at": "2026-01-01T00:00:00+00:00", + "owner": "proxy", + }], + } + with open( + os.path.join(self.config_dir, "keys.json"), + "w", + encoding="utf-8", + ) as keys_file: + json.dump(store, keys_file) + + response = self.client.get( + "/api/health", + headers=self.auth("osms_attempt"), + ) + + self.assertEqual(response.status_code, 401) + + def test_health_accepts_a_valid_hash_after_malformed_entries(self): + raw_key = "osms_valid_after_malformed_http" + store = { + "version": 2, + "keys": [ + { + "id": "k_00000001", + "name": "malformed-type", + "hash": 123, + "scopes": ["sms:write", "settings:write"], + "created_at": "2026-01-01T00:00:00+00:00", + "owner": "proxy", + }, + { + "id": "k_00000002", + "name": "malformed-content", + "hash": "z" * 64, + "scopes": ["sms:write", "settings:write"], + "created_at": "2026-01-01T00:00:00+00:00", + "owner": "proxy", + }, + { + "id": "k_00000003", + "name": "valid", + "hash": keySvc.hash_api_key(raw_key), + "scopes": ["sms:write", "settings:write"], + "created_at": "2026-01-01T00:00:00+00:00", + "owner": "proxy", + }, + ], + } + with open( + os.path.join(self.config_dir, "keys.json"), + "w", + encoding="utf-8", + ) as keys_file: + json.dump(store, keys_file) + + response = self.client.get( + "/api/health", + headers=self.auth(raw_key), + ) + + self.assertEqual(response.status_code, 200) + def test_health_reports_status_version_platform_and_uptime(self): raw_key = self.add_api_key() postApi.app.state.server.started_at = time.time() - 10 @@ -758,10 +861,11 @@ def test_legacy_key_authenticates_and_is_migrated_on_first_use(self): self.assertEqual(store["version"], 2) self.assertEqual(len(store["keys"]), 1) entry = store["keys"][0] - self.assertEqual(entry["hash"], postApi.hash_api_key(raw_key)) + self.assertEqual(entry["hash"], keySvc.hash_api_key(raw_key)) self.assertEqual(entry["scopes"], ["settings:write", "sms:write"]) self.assertTrue(entry["id"].startswith("k_")) self.assertTrue(entry["created_at"]) + self.assertEqual(entry["owner"], "phone") again = self.client.get( "/api/settings", headers=self.auth(raw_key) @@ -994,6 +1098,23 @@ def test_a_non_empty_secret_replaces_the_stored_secret(self): ) self.assertNotIn("new-shared-secret", response.text) + def test_a_null_secret_is_rejected_without_changing_settings(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + before = self.read_config() + + response = self.put( + self.valid_payload(webhook={"secret": None}), raw_key + ) + + self.assertEqual(response.status_code, 422) + self.assertEqual( + response.json()["detail"], + "webhook.secret must be a string", + ) + self.assertEqual(self.read_config(), before) + self.assertEqual(self.tmp_files(), []) + def test_put_rejects_a_secret_longer_than_256_characters(self): self.write_config(self.stored_config()) raw_key = self.add_api_key() @@ -1048,6 +1169,48 @@ def test_put_rejects_invalid_values_and_leaves_settings_unchanged(self): self.assertEqual(self.read_config(), before) self.assertEqual(self.tmp_files(), []) + def test_put_rejects_coercible_integer_and_boolean_values(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + before = self.read_config() + + cases = { + "revision string": {"revision": "7"}, + "revision float": {"revision": 7.0}, + "revision boolean": {"revision": True}, + "revision null": {"revision": None}, + "port string": {"port": "9292"}, + "port float": {"port": 9292.0}, + "port boolean": {"port": True}, + "boot string true": {"boot": "true"}, + "timeout string": {"webhook": {"timeout": "7"}}, + "timeout float": {"webhook": {"timeout": 7.0}}, + "timeout boolean": {"webhook": {"timeout": True}}, + "enabled string true": {"webhook": {"enabled": "true"}}, + "max attempts string": {"webhook": {"max_attempts": "7"}}, + "max attempts float": {"webhook": {"max_attempts": 7.0}}, + "max attempts boolean": {"webhook": {"max_attempts": True}}, + "backoff string": {"webhook": {"backoff": ["7"]}}, + "backoff float": {"webhook": {"backoff": [7.0]}}, + "backoff boolean": {"webhook": {"backoff": [True]}}, + "capacity string": {"webhook": {"capacity": "100"}}, + "capacity float": {"webhook": {"capacity": 100.0}}, + "capacity boolean": {"webhook": {"capacity": True}}, + } + + for name, overrides in cases.items(): + with self.subTest(name): + response = self.put( + self.valid_payload(**overrides), + raw_key, + ) + + self.assertEqual(response.status_code, 422, response.text) + self.assertIsInstance(response.json()["detail"], str) + self.assertTrue(response.json()["detail"]) + self.assertEqual(self.read_config(), before) + self.assertEqual(self.tmp_files(), []) + def test_put_rejects_missing_required_fields(self): raw_key = self.add_api_key() cases = { @@ -1132,7 +1295,9 @@ def test_put_rejects_a_non_object_body(self): ) self.assertEqual(response.status_code, 422) - self.assertIsInstance(response.json()["detail"], str) + self.assertEqual( + response.json()["detail"], "Request body must be a JSON object" + ) def test_put_rejects_malformed_json(self): raw_key = self.add_api_key() @@ -1144,7 +1309,9 @@ def test_put_rejects_malformed_json(self): ) self.assertEqual(response.status_code, 422) - self.assertIsInstance(response.json()["detail"], str) + self.assertEqual( + response.json()["detail"], "Request body must be valid JSON" + ) class SettingsRevisionTests(SettingsWriteTestCase): @@ -1520,6 +1687,32 @@ def record(config, timeout): self.assertEqual(response.status_code, 200) self.assertEqual(calls[0][1], 7) + def test_body_shape_errors_keep_their_messages(self): + raw_key = self.add_api_key() + + response = self.client.post( + "/api/webhook/test", + content=b'{"url": ', + headers={**self.auth(raw_key), "Content-Type": "application/json"}, + ) + self.assertEqual(response.status_code, 422) + self.assertEqual( + response.json()["detail"], "Request body must be valid JSON" + ) + + response = self.post_test(raw_key, ["not", "an", "object"]) + self.assertEqual(response.status_code, 422) + self.assertEqual( + response.json()["detail"], "Request body must be a JSON object" + ) + + response = self.post_test(raw_key, {"z": 1, "a": 2}) + self.assertEqual(response.status_code, 422) + self.assertEqual( + response.json()["detail"], + "Unknown field(s) in request: a, z", + ) + def test_unknown_fields_and_wrong_types_are_rejected(self): raw_key = self.add_api_key() @@ -1802,6 +1995,15 @@ def test_a_duplicate_name_differing_only_by_case_is_refused(self): self.assertEqual(response.status_code, 409) self.assertIsInstance(response.json()["detail"], str) + def test_the_phone_key_name_is_reserved_case_insensitively(self): + admin = self.add_api_key(name="admin") + + for name in ("opensms", "OpenSMS", " OPENSMS "): + with self.subTest(name=name): + response = self.create_key(admin, {"name": name}) + self.assertEqual(response.status_code, 422) + self.assertIn("reserved", response.json()["detail"].lower()) + def test_names_are_trimmed_and_length_checked(self): admin = self.add_api_key(name="admin") @@ -1825,15 +2027,41 @@ def test_create_rejects_unknown_fields_and_a_non_object_body(self): admin = self.add_api_key(name="admin") response = self.create_key( - admin, {"name": "proxy", "unexpected": True} + admin, {"name": "proxy", "unexpected": True, "another": 1} ) self.assertEqual(response.status_code, 422) + self.assertEqual( + response.json()["detail"], + "Unknown field(s) in request: another, unexpected", + ) response = self.client.post( "/api/keys", json=["not", "an", "object"], headers=self.auth(admin), ) self.assertEqual(response.status_code, 422) + self.assertEqual( + response.json()["detail"], "Request body must be a JSON object" + ) + + def test_create_rejects_malformed_json_and_a_missing_name(self): + admin = self.add_api_key(name="admin") + + response = self.client.post( + "/api/keys", + content=b'{"name": ', + headers={**self.auth(admin), "Content-Type": "application/json"}, + ) + self.assertEqual(response.status_code, 422) + self.assertEqual( + response.json()["detail"], "Request body must be valid JSON" + ) + + response = self.create_key(admin, {}) + self.assertEqual(response.status_code, 422) + self.assertEqual( + response.json()["detail"], "Missing required field: name" + ) def test_create_requires_authentication_and_the_settings_scope(self): response = self.client.post( @@ -1853,7 +2081,7 @@ def test_the_stored_key_is_hashed_and_never_returned_again(self): entry = next( key for key in store["keys"] if key["id"] == created["id"] ) - self.assertEqual(entry["hash"], postApi.hash_api_key(created["key"])) + self.assertEqual(entry["hash"], keySvc.hash_api_key(created["key"])) self.assertEqual(entry["scopes"], ["settings:write", "sms:write"]) self.assertNotIn(created["key"], json.dumps(store)) @@ -1880,6 +2108,9 @@ def test_list_never_returns_hashes(self): "scopes": ["settings:write", "sms:write"], "created_at": created["created_at"], }) + self.assertNotIn("owner", entry) + self.assertNotIn("hash", entry) + self.assertNotIn("key", entry) self.assertNotIn("hash", response.text) self.assertNotIn(created["key"], response.text) @@ -1990,7 +2221,7 @@ def test_delete_requires_authentication_and_the_settings_scope(self): class PhoneKeyRotationTests(ApiTestCase): def test_rotation_replaces_only_the_phone_key(self): - old_phone = self.add_api_key(name="opensms") + old_phone = self.add_api_key(name="opensms", owner="phone") proxy = self.add_api_key(name="sms-proxy") new_phone = postApi.generate_new_api_key() @@ -2017,6 +2248,36 @@ def test_rotation_replaces_only_the_phone_key(self): self.assertEqual(names.count("opensms"), 1) self.assertIn("sms-proxy", names) + def test_rotation_preserves_an_existing_proxy_named_opensms(self): + proxy = self.add_api_key(name="OpenSMS", owner="proxy") + + new_phone = postApi.generate_new_api_key() + + self.assertEqual( + self.client.get( + "/api/health", headers=self.auth(proxy) + ).status_code, + 200, + ) + self.assertEqual( + self.client.get( + "/api/health", headers=self.auth(new_phone) + ).status_code, + 200, + ) + entries = self.read_key_store()["keys"] + proxies = [ + entry for entry in entries + if entry.get("owner") == "proxy" + ] + phones = [ + entry for entry in entries + if entry.get("owner") == "phone" + ] + self.assertEqual(len(proxies), 1) + self.assertEqual(proxies[0]["name"], "OpenSMS") + self.assertEqual(len(phones), 1) + def test_rotation_adds_a_phone_key_without_touching_proxy_keys(self): proxy = self.add_api_key(name="sms-proxy") diff --git a/app/tests/test_settings_local_save.py b/app/tests/test_settings_local_save.py index 91ee05e..6d699c8 100644 --- a/app/tests/test_settings_local_save.py +++ b/app/tests/test_settings_local_save.py @@ -15,7 +15,7 @@ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) -from services import settingsSvc +from services import settingsSvc, webhookSvc class LocalSaveTestCase(unittest.TestCase): @@ -91,6 +91,23 @@ def screen_form(self, current: dict, **overrides) -> dict: class WritableSettingsTests(LocalSaveTestCase): + def test_settings_use_the_dispatcher_webhook_defaults(self): + self.assertEqual( + settingsSvc.default_webhook_settings(), + webhookSvc.default_webhook_config(), + ) + + def test_default_backoff_lists_are_not_shared(self): + settings = settingsSvc.default_settings() + settings["webhook"]["backoff"].append(1) + + self.assertEqual( + settingsSvc.default_settings()["webhook"]["backoff"], [5, 30] + ) + self.assertEqual( + webhookSvc.default_webhook_config()["backoff"], [5, 30] + ) + def test_invalid_stored_retry_values_report_the_effective_defaults(self): config = self.stored_config() config["webhook"].update({ @@ -106,14 +123,14 @@ def test_invalid_stored_retry_values_report_the_effective_defaults(self): ) webhook = writable["webhook"] - self.assertEqual(webhook["timeout"], settingsSvc.DEFAULT_TIMEOUT) + self.assertEqual(webhook["timeout"], webhookSvc.DEFAULT_TIMEOUT) self.assertEqual( - webhook["max_attempts"], settingsSvc.DEFAULT_MAX_ATTEMPTS + webhook["max_attempts"], webhookSvc.DEFAULT_MAX_ATTEMPTS ) self.assertEqual( - webhook["backoff"], list(settingsSvc.DEFAULT_BACKOFF) + webhook["backoff"], list(webhookSvc.DEFAULT_BACKOFF) ) - self.assertEqual(webhook["capacity"], settingsSvc.DEFAULT_CAPACITY) + self.assertEqual(webhook["capacity"], webhookSvc.DEFAULT_CAPACITY) class LocalSaveMergeTests(LocalSaveTestCase): diff --git a/app/tests/test_webhook.py b/app/tests/test_webhook.py index b7bd7af..0cc0137 100644 --- a/app/tests/test_webhook.py +++ b/app/tests/test_webhook.py @@ -236,6 +236,26 @@ def test_test_without_url_fails_cleanly(self): self.assertIsNone(status) self.assertTrue(error) + def test_saved_timeout_is_passed_to_the_http_client(self): + self.write_live_webhook(timeout=7) + saved = webhookSvc.get_webhook_config(self.config_path) + calls = [] + + def record(url, body, headers, timeout): + calls.append((url, timeout)) + return True, 204, None + + with mock.patch.object(webhookSvc, "post_json", side_effect=record): + ok, status, error = webhookSvc.send_test_webhook( + {"url": self.target.url, "secret": "s3cret"}, + timeout=saved["timeout"], + ) + + self.assertTrue(ok) + self.assertEqual(status, 204) + self.assertIsNone(error) + self.assertEqual(calls[0][1], 7) + def test_credentialed_target_is_not_posted_by_test_delivery(self): url = self.target.url.replace("http://", "http://user:password@") @@ -440,7 +460,7 @@ def test_invalid_retry_settings_fall_back_to_constants(self): config = webhookSvc.normalize_webhook_config({ "enabled": True, "url": self.target.url, - "timeout": 0, + "timeout": 61, "max_attempts": "many", "backoff": [0, -1], "capacity": 99999, @@ -452,6 +472,33 @@ def test_invalid_retry_settings_fall_back_to_constants(self): self.assertEqual(config["backoff"], list(webhookSvc.DEFAULT_BACKOFF)) self.assertEqual(config["capacity"], webhookSvc.DEFAULT_CAPACITY) + def test_malformed_stored_timeout_values_use_the_default(self): + for timeout in (0, 61, "7", True, 7.0, None): + with self.subTest(timeout=timeout): + config = webhookSvc.normalize_webhook_config({"timeout": timeout}) + self.assertEqual( + config["timeout"], webhookSvc.DEFAULT_TIMEOUT + ) + + def test_missing_config_uses_loaded_timeout_but_malformed_config_does_not(self): + missing_path = os.path.join(self.tmp.name, "missing-config.json") + fallback = {"timeout": 7} + self.assertEqual( + webhookSvc.get_webhook_config( + missing_path, fallback=fallback + )["timeout"], + 7, + ) + + with open(missing_path, "w", encoding="utf-8") as cf: + cf.write("{not json") + self.assertEqual( + webhookSvc.get_webhook_config( + missing_path, fallback=fallback + )["timeout"], + webhookSvc.DEFAULT_TIMEOUT, + ) + def test_malformed_settings_never_crash_the_dispatcher(self): with open(self.config_path, "w", encoding="utf-8") as cf: cf.write("{not json") diff --git a/docs/adr/0002-remote-settings-and-control-api.md b/docs/adr/0002-remote-settings-and-control-api.md index 274aac9..44fcc61 100644 --- a/docs/adr/0002-remote-settings-and-control-api.md +++ b/docs/adr/0002-remote-settings-and-control-api.md @@ -36,9 +36,10 @@ See `docs/remote-api.md` for the contract. `["sms:write"]` but scopes were never read, so every existing install would be locked out of the new API. Migration grants both scopes once; v2 keys honour whatever they are created with. -- **Adding an OS file lock or a new dependency**: rejected. The residual - cross-process race window is small, documented, and cheaper to accept than to - make buildozer ship another native dependency. +- **Adding an OS file lock or a new dependency**: rejected for Settings. The + residual `config.json` cross-process race remains cheap to accept. Key-store + mutations use stdlib `fcntl`/`msvcrt` file locks instead, with no native + package or buildozer dependency. - **Unauthenticated `/api/health`**: rejected. It would reveal the device to any host on the LAN; the proxy already holds a key. - **CORS or a web UI**: rejected. Server-to-server only. diff --git a/docs/remote-api.md b/docs/remote-api.md index 25d15b1..ffb68ec 100644 --- a/docs/remote-api.md +++ b/docs/remote-api.md @@ -128,10 +128,19 @@ See `GLOSSARY.md`: **Settings**, **Revision**, **Scope**, **API key**, - Every route, including `/api/health`, requires `Authorization: Bearer osms_…`. - JSON in, JSON out, UTF-8. -- Error body: `{"detail": "..."}`. Settings validation is done by hand (not by - Pydantic models) so `detail` stays a human-readable string on `422`; - FastAPI's malformed-JSON error may still be a list. Clients must tolerate - both. +- Strict Pydantic request models expose editable JSON bodies for + `PUT /api/settings` and `POST /api/keys`. They reject unknown fields and + lax JSON coercion (including strings/floats/booleans where integers are + required). Pydantic validates only the HTTP wire shape. +- Domain and persistence stay in the owning services: + `settingsSvc.save_settings` owns revision checks, business rules, merge- + preserving unknown stored keys, and the atomic write; `keySvc` owns key + validation and storage. +- Validation order is wire shape/range → `422`, stale revision → `409`, then + Settings business rules → `400`. +- Error body: `{"detail": "..."}`. A shared `RequestValidationError` handler + keeps `422` details human-readable for schema errors and malformed JSON; + clients should not parse Pydantic's internal error-list shape. - Status codes: - `400` business-rule violation - `401` invalid key @@ -393,9 +402,13 @@ when another remains and takes effect immediately. Rules: - Name: trimmed, 2–64 characters, no control characters, unique - case-insensitively; duplicate → `409`. + case-insensitively; `opensms` is reserved case-insensitively for the phone + key and is rejected on proxy-key creation (`422`); duplicate → `409`. - Id: `k_` + 8 lowercase hex (`secrets.token_hex(4)`). - Scopes stored canonical-sorted. +- Ownership stored internally with an `owner` marker (`phone` or `proxy`); + rotation uses that marker, never the display name. Ownership is normalized + for legacy stores. The marker and hashes are never returned by `GET`. - Hash: SHA-256 hex, untruncated (unchanged). - Lookup: scan every entry with `secrets.compare_digest` against the computed hash; do not return early on the first mismatch. @@ -456,7 +469,7 @@ v1 migration (`{hash: {name, scopes}}`): - Converted in memory on first load; persisted as v2 on the first key write or on the first authenticated request (whichever comes first), guarded by a - module lock. + module lock and the shared `keys.json.lock` OS file lock. - Ids are newly generated; `created_at` becomes "now" (original unknown); missing names become `"opensms"`. - Scopes: existing scopes **plus** `settings:write`. This is a one-time @@ -468,12 +481,16 @@ v1 migration (`{hash: {name, scopes}}`): ## 8. Cross-process behaviour -Two processes write `config.json`. There is no OS-level lock (no new -dependency). Accepted model: +Two processes write `config.json`, and the UI and API may mutate `keys.json`. +Accepted model: - **Writers**: the API (one uvicorn thread pool) and the Kivy UI. - **In-process serialisation**: a module lock around read-modify-write in - `settingsSvc`; `keys.json` has its own lock. + `settingsSvc`; `keys.json` mutations use one module lock. +- **Key-store cross-process serialisation**: `keys.json` read-modify-write + operations use a stdlib OS file lock at `keys.json.lock`, with no new + dependency. This covers key creation, deletion, phone-key rotation, + authentication migration, and direct atomic key-store saves. - **Cross-process**: last writer wins, but the window is shrunk to read-fresh-then-write, and every writer bumps `revision` against the value it actually read. The residual race is documented, not hidden. @@ -637,9 +654,9 @@ Core total ≈ 600–900 source lines, 3–4 focused days. the drop policy is unchanged. 7. **`resp.json` is not a heartbeat.** Do not present it as liveness; the response itself proves the API is up. -8. **Unpinned FastAPI/Pydantic** on desktop vs `pydantic==2.12.3` on Android. - Avoid version-specific API usage; request bodies as plain `dict` with manual - validation sidesteps Pydantic v1/v2 differences. +8. **Pydantic request models are an HTTP edge, not a second domain layer.** + Strict types and `extra="forbid"` validate the wire shape; `settingsSvc` and + `keySvc` retain revision, business-rule, merge, and persistence ownership. 9. **Bind errors are swallowed** into a callback (`postApi.py:173-178`). The new status fields make the failure visible; they do not fix it. 10. **Key deletion** can lock out the caller only if it is the last key; `409` From 6116a77f94e72ef27499bff36376e38e2fbcbe47 Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 22:27:30 +0100 Subject: [PATCH 16/20] release: ship 1.2.0 Bump the app version and changelog to 1.2.0, document the remote Settings and control API in the README, and refresh version references. --- .github/workflows/linuxExe.yml | 2 +- .github/workflows/winExe.yml | 2 +- CHANGELOG.md | 6 ++++ README.md | 66 +++++++++++++++++++++++++++++++++- app/services/config.py | 2 +- docs/webhook/receiver_test.md | 2 +- 6 files changed, 75 insertions(+), 5 deletions(-) diff --git a/.github/workflows/linuxExe.yml b/.github/workflows/linuxExe.yml index 3686476..a8585e7 100644 --- a/.github/workflows/linuxExe.yml +++ b/.github/workflows/linuxExe.yml @@ -89,7 +89,7 @@ jobs: ver = os.environ['VERSION'].lstrip('v') with open('CHANGELOG.md', 'r', encoding='utf-8') as f: text = f.read() - # Match from '### 1.1.0' until the next '### ' or '## ' heading + # Match from '### 1.2.0' until the next '### ' or '## ' heading pattern = rf'(?m)^###\s+v?{re.escape(ver)}\b.*?\n(.*?)(?=^###?\s|\Z)' match = re.search(pattern, text, re.DOTALL) notes = match.group(1).strip() if match else f'Release {ver}' diff --git a/.github/workflows/winExe.yml b/.github/workflows/winExe.yml index 342e3b6..b64010e 100644 --- a/.github/workflows/winExe.yml +++ b/.github/workflows/winExe.yml @@ -95,7 +95,7 @@ jobs: ver = os.environ['VERSION'].lstrip('v') with open('CHANGELOG.md', 'r', encoding='utf-8') as f: text = f.read() - # Match from '### 1.1.0' until the next '### ' or '## ' heading + # Match from '### 1.2.0' until the next '### ' or '## ' heading pattern = rf'(?m)^###\s+v?{re.escape(ver)}\b.*?\n(.*?)(?=^###?\s|\Z)' match = re.search(pattern, text, re.DOTALL) notes = match.group(1).strip() if match else f'Release {ver}' diff --git a/CHANGELOG.md b/CHANGELOG.md index d370d64..62ce4a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Changes +### 1.2.0 +- Add a bearer-authenticated remote Settings and control API: `GET /api/health`, `GET /api/status`, `GET/PUT /api/settings`, `POST /api/webhook/test`, and `POST /api/server/restart`, with Revision-based optimistic concurrency and human-readable validation errors. +- Add named API keys with `sms:write` and `settings:write` Scopes, immediate revocation, and phone-key rotation that leaves proxy keys intact. +- Make Webhook retry timeout, attempts, backoff, and Outbox capacity live Settings, so a longer proxy outage does not lose Inbound SMS; reject credentialed Webhook targets. +- Keep the on-device UI consistent with remote changes through fresh read-merge-write saves; `GET /api/status` reports forwarding health and warnings. + ### 1.1.0 - Forward received SMS to a configurable webhook (Android), with optional HMAC-SHA256 signing, ordered delivery, retries and a persisted outbox. See the [README](./README.md#-receiving-sms-android). - Show the last webhook delivery result and a test button in Settings; log inbound SMS and delivery outcomes. diff --git a/README.md b/README.md index 1117c91..28daf9c 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,70 @@ curl -i -X POST 'http://127.0.0.1:9292/sms/' \ -d '{"number": "+1234567890", "text": "Hello from OpenSMS API!"}' ``` +### 🔐 Remote Settings and control API + +The API server can also read and change Settings, manage API keys, test the Webhook, and restart the server. This is meant for a proxy or automation on the **same LAN or VPN** as the phone. The API uses bearer keys over plain HTTP, with no TLS or CORS, so never expose the port to the internet; use a VPN or an authenticated tunnel for remote access. + +Every `/api/` route, including `GET /api/health`, requires an API key with the `settings:write` Scope. `POST /sms/` requires `sms:write`. + +| Scope | Allows | +| --- | --- | +| `sms:write` | `POST /sms/` | +| `settings:write` | every `/api/` route: health, status, Settings, key management, Webhook test, Restart | + +The first API key is generated from the phone UI when the server starts. Create a separate key for each integration; the raw key is returned only once. Set it once in your shell: + +```bash +export OSMS_KEY='osms_…' + +curl -sS -X POST 'http://192.168.1.50:9292/api/keys' \ + -H "Authorization: Bearer $OSMS_KEY" \ + -H 'Content-Type: application/json' \ + -d '{"name": "sms-proxy", "scopes": ["sms:write"]}' +``` + +`GET /api/keys` lists keys without hashes, and `DELETE /api/keys/{id}` revokes one immediately. The last remaining key cannot be deleted. + +Check the phone and read Settings: + +```bash +curl -sS -H "Authorization: Bearer $OSMS_KEY" \ + 'http://192.168.1.50:9292/api/health' + +curl -sS -H "Authorization: Bearer $OSMS_KEY" \ + 'http://192.168.1.50:9292/api/settings' +``` + +`PUT /api/settings` replaces the full writable subset, so send every field you want to keep. Include the `revision` from `GET` for optimistic concurrency; a stale Revision returns `409`. + +```bash +curl -sS -X PUT 'http://192.168.1.50:9292/api/settings' \ + -H "Authorization: Bearer $OSMS_KEY" \ + -H 'Content-Type: application/json' \ + -d '{ + "revision": 7, + "port": 9292, + "boot": true, + "webhook": { + "enabled": true, + "url": "https://proxy.example.lan/hooks/opensms", + "timeout": 10, + "max_attempts": 3, + "backoff": [5, 30], + "capacity": 100 + } + }' +``` + +Omit `webhook.secret` to keep the stored secret, send `""` to clear it, or send a new string to replace it. Webhook and retry changes take effect immediately. A port change is two-step: the response sets `restart_required`, then call: + +```bash +curl -sS -X POST 'http://192.168.1.50:9292/api/server/restart' \ + -H "Authorization: Bearer $OSMS_KEY" +``` + +`GET /api/status` reports the bound and configured port, network addresses, Outbox depth, the last Delivery attempt, and warnings (for example when forwarding is disabled or the Outbox is near capacity). `POST /api/webhook/test` tests a Webhook target without saving it. The full contract, error codes, and persisted schema are in [docs/remote-api.md](./docs/remote-api.md). + ## 📥 Receiving SMS (Android) OpenSMS can forward every SMS received by the phone to your own HTTP endpoint as a webhook. Receiving works independently of the API server: it runs in the same background service, so the API can be stopped while webhooks keep flowing. @@ -153,7 +217,7 @@ Every Inbound SMS produces one `POST` with a JSON body: ```http POST /your-hook HTTP/1.1 Content-Type: application/json -User-Agent: OpenSMS/1.1.0 +User-Agent: OpenSMS/1.2.0 X-OpenSMS-Event: sms.received X-OpenSMS-Delivery: 6f1c2f5e-0d7a-4c55-9f0e-2b1c8b7f0a11 X-OpenSMS-Signature: sha256=... diff --git a/app/services/config.py b/app/services/config.py index b7239b5..f30cc80 100644 --- a/app/services/config.py +++ b/app/services/config.py @@ -1,4 +1,4 @@ """ The main source for app wide config """ -__version__ = "1.1.0" # App version +__version__ = "1.2.0" # App version app_name = "opensms" diff --git a/docs/webhook/receiver_test.md b/docs/webhook/receiver_test.md index 3126028..24814a5 100644 --- a/docs/webhook/receiver_test.md +++ b/docs/webhook/receiver_test.md @@ -19,7 +19,7 @@ uvicorn webhook_receiver:app --host 0.0.0.0 --port 8000 --reload ```bash curl -X POST http://localhost:8000/sms-hook \ -H "Content-Type: application/json" \ - -H "User-Agent: OpenSMS/1.1.0" \ + -H "User-Agent: OpenSMS/1.2.0" \ -H "X-OpenSMS-Event: sms.received" \ -H "X-OpenSMS-Delivery: 6f1c2f5e-0d7a-4c55-9f0e-2b1c8b7f0a11" \ -H "X-OpenSMS-Signature: sha256=dummy" \ From 0a447b864e8ce21143a4d77c0b7887aea5ab0eba Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 22:40:00 +0100 Subject: [PATCH 17/20] fix: widen Webhook URL and secret fields Move both text fields out of MDListItem's trailing slot into full-width rows so long Webhook targets are editable on Android. --- app/screens/settings.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/app/screens/settings.py b/app/screens/settings.py index aa57b45..9e933e0 100644 --- a/app/screens/settings.py +++ b/app/screens/settings.py @@ -133,9 +133,17 @@ text: "Webhook URL" MDListItemSupportingText: text: "http:// or https://" + + MDBoxLayout: + orientation: "vertical" + adaptive_height: True + padding: [dp(16), 0, dp(16), dp(8)] MDTextField: id: webhook_url_inp mode: "outlined" + size_hint_x: 1 + size_hint_y: None + height: dp(56) MDListItem: MDListItemLeadingIcon: @@ -144,10 +152,18 @@ text: "Signing Secret" MDListItemSupportingText: text: "Optional HMAC-SHA256" + + MDBoxLayout: + orientation: "vertical" + adaptive_height: True + padding: [dp(16), 0, dp(16), dp(8)] MDTextField: id: webhook_secret_inp mode: "outlined" password: True + size_hint_x: 1 + size_hint_y: None + height: dp(56) MDListItem: MDListItemLeadingIcon: From 91dc5870f8fbbeeb3798e36140d0931fa995ea92 Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 22:57:08 +0100 Subject: [PATCH 18/20] review: address standards findings Remove unused key adapters, share the health uptime calculation, rename the dispatcher override helper, reuse the default Webhook shape on reset, and refresh the remote API docs. Drop the no-op release-workflow comment edits. --- .github/workflows/linuxExe.yml | 2 +- .github/workflows/winExe.yml | 2 +- README.md | 2 +- app/main.py | 7 +------ app/services/postApi.py | 21 +------------------ app/services/webhookSvc.py | 10 ++++----- .../0002-remote-settings-and-control-api.md | 3 ++- docs/remote-api.md | 4 ++-- 8 files changed, 14 insertions(+), 37 deletions(-) diff --git a/.github/workflows/linuxExe.yml b/.github/workflows/linuxExe.yml index a8585e7..3686476 100644 --- a/.github/workflows/linuxExe.yml +++ b/.github/workflows/linuxExe.yml @@ -89,7 +89,7 @@ jobs: ver = os.environ['VERSION'].lstrip('v') with open('CHANGELOG.md', 'r', encoding='utf-8') as f: text = f.read() - # Match from '### 1.2.0' until the next '### ' or '## ' heading + # Match from '### 1.1.0' until the next '### ' or '## ' heading pattern = rf'(?m)^###\s+v?{re.escape(ver)}\b.*?\n(.*?)(?=^###?\s|\Z)' match = re.search(pattern, text, re.DOTALL) notes = match.group(1).strip() if match else f'Release {ver}' diff --git a/.github/workflows/winExe.yml b/.github/workflows/winExe.yml index b64010e..342e3b6 100644 --- a/.github/workflows/winExe.yml +++ b/.github/workflows/winExe.yml @@ -95,7 +95,7 @@ jobs: ver = os.environ['VERSION'].lstrip('v') with open('CHANGELOG.md', 'r', encoding='utf-8') as f: text = f.read() - # Match from '### 1.2.0' until the next '### ' or '## ' heading + # Match from '### 1.1.0' until the next '### ' or '## ' heading pattern = rf'(?m)^###\s+v?{re.escape(ver)}\b.*?\n(.*?)(?=^###?\s|\Z)' match = re.search(pattern, text, re.DOTALL) notes = match.group(1).strip() if match else f'Release {ver}' diff --git a/README.md b/README.md index 28daf9c..bf757fa 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,7 @@ Every `/api/` route, including `GET /api/health`, requires an API key with the ` | `sms:write` | `POST /sms/` | | `settings:write` | every `/api/` route: health, status, Settings, key management, Webhook test, Restart | -The first API key is generated from the phone UI when the server starts. Create a separate key for each integration; the raw key is returned only once. Set it once in your shell: +The first API key is created from the phone UI the first time you tap Start Server. Create a separate key for each integration; the raw key is returned only once. Set it once in your shell: ```bash export OSMS_KEY='osms_…' diff --git a/app/main.py b/app/main.py index ad67296..ec4f8d8 100644 --- a/app/main.py +++ b/app/main.py @@ -860,13 +860,8 @@ def reset_settings(self, instance=None): "port": defaults["port"], "boot": defaults["boot"], "webhook": { - "enabled": default_webhook["enabled"], - "url": default_webhook["url"], - "secret": default_webhook["secret"], - "timeout": default_webhook["timeout"], - "max_attempts": default_webhook["max_attempts"], + **default_webhook, "backoff": list(default_webhook["backoff"]), - "capacity": default_webhook["capacity"], }, } if not self.persist_settings_form(form): diff --git a/app/services/postApi.py b/app/services/postApi.py index 744e03c..42c9c9a 100644 --- a/app/services/postApi.py +++ b/app/services/postApi.py @@ -152,18 +152,6 @@ def _settings_path() -> str: # Key persistence lives in keySvc. These adapters keep existing server, UI, and # CLI call sites working while binding them to this module's config-directory # seam and activity logger. -def hash_api_key(raw_key: str) -> str: - return keySvc.hash_api_key(raw_key) - - -def load_key_store() -> tuple[dict, bool]: - return keySvc.load_key_store(get_config_dir()) - - -def save_key_store(store: dict): - keySvc.save_key_store(get_config_dir(), store) - - def authenticate_key(raw_key: str) -> dict | None: return keySvc.authenticate_key(get_config_dir(), raw_key) @@ -172,10 +160,6 @@ def has_api_keys() -> bool: return keySvc.has_api_keys(get_config_dir()) -def public_key(entry: dict) -> dict: - return keySvc.public_key(entry) - - def create_api_key(name, scopes=_DEFAULT_SCOPES) -> dict: return keySvc.create_api_key( get_config_dir(), name, scopes, log=log_activities @@ -569,14 +553,11 @@ async def scope_guard( async def api_health( client: dict = Depends(require_scope(SCOPE_SETTINGS)) ): - server = getattr(app.state, "server", None) - started_at = getattr(server, "started_at", None) or _started_at - uptime_s = max(0, int(time.time() - started_at)) if started_at else 0 return { "status": "ok", "version": __version__, "platform": platform, - "uptime_s": uptime_s, + "uptime_s": _status_uptime_s(), } def _status_runtime(name: str, fallback=None): diff --git a/app/services/webhookSvc.py b/app/services/webhookSvc.py index be665d3..42ad4a2 100644 --- a/app/services/webhookSvc.py +++ b/app/services/webhookSvc.py @@ -449,25 +449,25 @@ def __init__( ## Live Settings @staticmethod - def _resolved(override, live_value): + def _override_or_live(override, live_value): """An explicit constructor override always wins over live Settings.""" return live_value if override is None else override def _timeout_for(self, config: dict) -> float: - return self._resolved(self._timeout_override, config["timeout"]) + return self._override_or_live(self._timeout_override, config["timeout"]) def _backoff_for(self, config: dict) -> tuple: - return self._resolved( + return self._override_or_live( self._backoff_override, tuple(config["backoff"]) ) def _max_attempts_for(self, config: dict) -> int: - return self._resolved( + return self._override_or_live( self._max_attempts_override, config["max_attempts"] ) def _capacity_for(self, config: dict) -> int: - return self._resolved( + return self._override_or_live( self._capacity_override, config["capacity"] ) diff --git a/docs/adr/0002-remote-settings-and-control-api.md b/docs/adr/0002-remote-settings-and-control-api.md index 44fcc61..6b223dd 100644 --- a/docs/adr/0002-remote-settings-and-control-api.md +++ b/docs/adr/0002-remote-settings-and-control-api.md @@ -16,7 +16,8 @@ See `docs/remote-api.md` for the contract. - **Writing settings directly from the service, bypassing `config.json`**: rejected. The UI reads the same file, the webhook worker hot-reloads it per delivery, and the port must have one owner. `config.json` stays the single source of truth; - `request.json` carries intents only. + `request.json` carries intents, including the port a Restart should use (a + fallback only). - **PATCH / partial-merge semantics**: rejected. Partial merges make "clear the secret", "leave it alone", and "the field was absent" indistinguishable against a UI that also holds a stale object. The API replaces the writable subset in diff --git a/docs/remote-api.md b/docs/remote-api.md index ffb68ec..b3ecb8e 100644 --- a/docs/remote-api.md +++ b/docs/remote-api.md @@ -1,6 +1,6 @@ # Remote Settings & Control API -**Status:** agreed design, not implemented. +**Status:** implemented; ships as `1.2.0`. **Supersedes:** the handoff brief of 2026-11-26. **Baseline:** `develop` at `f3c7ba1`, app version `1.1.0`. **Target:** ship as `1.2.0`; PRs go to `develop` (see `CONTRIBUTE.md`). @@ -101,7 +101,7 @@ Other facts that constrain the work: | D3 | `PUT /api/settings` replaces the **writable subset** in full. Unknown fields are rejected. Internal fields (`app`, `permissions`) and unknown disk fields are preserved. | Full replace avoids ambiguous patch semantics; preserving internal fields keeps the UI's config intact. | | D4 | Every write bumps `revision`. `PUT` accepts an **optional** top-level `revision`; if present and stale, return `409`. | Two remote writers otherwise last-writer-wins. Optional keeps hand-written clients simple. | | D5 | Restart is explicit and goes through `request.json`. A handler never calls `stop()` on its own server. `409` if already stopping/stopped, or if a restart happened within 5 s. | Stopping uvicorn from inside a request risks answering into a dead socket. | -| D6 | `config.json` is the single source of truth for the port. `request.json` carries intents only. | The UI currently seeds the port twice; one owner removes a class of drift. | +| D6 | `config.json` is the single source of truth for the port. `request.json` carries intents; the Restart intent includes the port to start with, used only as a fallback. | The UI currently seeds the port twice; one owner removes a class of drift. | | D7 | All JSON writes are atomic: temp file in the same directory, `os.replace`. | A 0.2 s poller can otherwise read a partial file. | | D8 | The UI re-reads `config.json` on Settings entry and merges on save through `settingsSvc`, preserving `revision` and unknown fields. | Today the UI holds a stale whole-object cache and clobbers remote changes. | | D9 | `keys.json` v2: array of `{id, name, hash, scopes, created_at}`. Refuse to delete the last key (`409`). UI rotation replaces only the key named `opensms`. | Named keys need stable ids; nuking proxy-owned keys from the phone would be hostile. | From 3a3ac60c932b195343d2deffd1c7ae94bc65d3c4 Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 23:06:58 +0100 Subject: [PATCH 19/20] fix: address spec review findings Write resp.json atomically, give Restart intents an id so a later request is not suppressed, stop persisting a v1 key migration on launch, use only the documented key owner marker, document next-launch boot semantics, and replace private restart state in tests with a clock patch. --- README.md | 2 +- app/services/appSvc.py | 29 +++++++++------- app/services/controlSvc.py | 16 +++++++++ app/services/keySvc.py | 56 +++++-------------------------- app/tests/test_control_svc.py | 26 ++++++++++++++- app/tests/test_key_svc.py | 62 +++++++++++++++++++++++++++++++++++ app/tests/test_remote_api.py | 19 ++++++++--- docs/remote-api.md | 17 ++++++---- 8 files changed, 155 insertions(+), 72 deletions(-) diff --git a/README.md b/README.md index bf757fa..63c8551 100644 --- a/README.md +++ b/README.md @@ -187,7 +187,7 @@ curl -sS -X PUT 'http://192.168.1.50:9292/api/settings' \ }' ``` -Omit `webhook.secret` to keep the stored secret, send `""` to clear it, or send a new string to replace it. Webhook and retry changes take effect immediately. A port change is two-step: the response sets `restart_required`, then call: +Omit `webhook.secret` to keep the stored secret, send `""` to clear it, or send a new string to replace it. Webhook and retry changes take effect immediately. Changing `boot` is read at the next app launch; it does not start or stop the current service. A port change is two-step: the response sets `restart_required`, then call: ```bash curl -sS -X POST 'http://192.168.1.50:9292/api/server/restart' \ diff --git a/app/services/appSvc.py b/app/services/appSvc.py index a48db40..cf7e100 100644 --- a/app/services/appSvc.py +++ b/app/services/appSvc.py @@ -1,10 +1,10 @@ from os.path import join, abspath, exists, dirname from threading import Thread -import json -import time -import sys +import os import signal +import sys +import time # OS specific @@ -28,7 +28,7 @@ ) from services.logSvc import LogService from services.config import app_name -from services import controlSvc +from services import controlSvc, settingsSvc from services.webhookSvc import ( WebhookDispatcher, ack_inbox_message, @@ -46,8 +46,9 @@ api_started = False serial_started = False # True when a handled Restart could not be normalised on disk; the loop then -# suppresses the stale intent instead of restarting again. +# suppresses that same intent instead of restarting again. restart_intent_handled = False +handled_restart_id = None serial_mgr = None sms_receiver = None sms_receiver_context = None @@ -110,22 +111,25 @@ def request_stop(signum=None, frame=None): def write_resp(): """ Write the response json on file. """ global resp_template - with open(resp_file, "w") as rf: - json.dump(resp_template, rf) + settingsSvc.atomic_write_json(resp_file, resp_template) def read_req_file(): """ Read the control file (intents from the API or the main app). """ - global req_data, restart_intent_handled + global req_data, restart_intent_handled, handled_restart_id if not exists(req_file): return req_data = controlSvc.read_control(config_dir) intent = req_data.get(controlSvc.INTENT_KEY) - if restart_intent_handled and intent == controlSvc.INTENT_RESTART: + if restart_intent_handled and controlSvc.matches_restart( + req_data, handled_restart_id + ): # A handled Restart could not be persisted as "start"; do not let the - # stale file restart the server again. + # same stale intent restart the server again. A later Restart carries a + # new id and is handled normally. req_data[controlSvc.INTENT_KEY] = controlSvc.INTENT_START elif intent != controlSvc.INTENT_RESTART: restart_intent_handled = False + handled_restart_id = None def register_sms_receiver(): """Register the Android SMS_RECEIVED receiver in this service process. @@ -199,9 +203,10 @@ def restart_api_server(): The control intent is normalised back to "start" after the new server has been asked to start, so the 0.2 s poll cannot trigger the Restart again. """ - global req_data, restart_intent_handled + global req_data, restart_intent_handled, handled_restart_id port = controlSvc.effective_port(config_dir) req_data["port"] = port + restart_id = req_data.get(controlSvc.RESTART_ID_KEY) if not stop_api_server(): # Never add a second listener while the previous one is still up; the # intent stays "restart" so the next poll retries the stop. @@ -212,8 +217,10 @@ def restart_api_server(): try: controlSvc.normalise_restart(config_dir, port) restart_intent_handled = False + handled_restart_id = None except Exception as e: restart_intent_handled = True + handled_restart_id = restart_id print(f"Could not normalise the Restart intent: {e}") log_activities(f"Could not normalise the Restart intent: {e}") diff --git a/app/services/controlSvc.py b/app/services/controlSvc.py index 879acc6..4407583 100644 --- a/app/services/controlSvc.py +++ b/app/services/controlSvc.py @@ -7,6 +7,7 @@ import json import os +import secrets from services import settingsSvc @@ -16,6 +17,7 @@ INTENT_START = "start" INTENT_STOP = "stop" INTENT_RESTART = "restart" +RESTART_ID_KEY = "restart_id" ## Read and write @@ -78,12 +80,26 @@ def request_restart(config_dir: str, port: int) -> dict: control = read_control(config_dir) control["port"] = port control[INTENT_KEY] = INTENT_RESTART + control[RESTART_ID_KEY] = secrets.token_hex(8) write_control(config_dir, control) return control def restart_pending(config_dir: str) -> bool: return intent(config_dir) == INTENT_RESTART +def matches_restart(control: dict, restart_id) -> bool: + """Whether `control` is the same Restart request as `restart_id`. + + The service uses this to suppress a stale intent that could not be + normalised, while still accepting a later Restart with a new id. + """ + if control.get(INTENT_KEY) != INTENT_RESTART: + return False + if restart_id is None: + # A pre-upgrade intent has no id; treat it as the same stale request. + return RESTART_ID_KEY not in control + return control.get(RESTART_ID_KEY) == restart_id + def normalise_restart(config_dir: str, port: int | None = None) -> bool: """Turn a handled Restart back into a plain start, preserving other keys. diff --git a/app/services/keySvc.py b/app/services/keySvc.py index 72041d5..353f49b 100644 --- a/app/services/keySvc.py +++ b/app/services/keySvc.py @@ -128,45 +128,15 @@ def _now_iso() -> str: def _normalize_owner_value(value) -> str | None: if not isinstance(value, str): return None - normalized = value.strip().casefold().replace("-", "_") - if normalized in { - "phone", - "phone_key", - "phoneowned", - "phone_owned", - }: - return PHONE_KEY_OWNER - if normalized in { - "proxy", - "proxy_key", - "integration", - }: - return PROXY_KEY_OWNER + normalized = value.strip().casefold() + if normalized in {PHONE_KEY_OWNER, PROXY_KEY_OWNER}: + return normalized return None def _entry_owner(entry: dict) -> str | None: - """Read an explicit persisted ownership marker, without inferring by name.""" - explicit_marker = False - for field in (KEY_OWNER_FIELD, "owned_by", "key_owner", "ownership"): - if field not in entry: - continue - explicit_marker = True - owner = _normalize_owner_value(entry.get(field)) - if owner is not None: - return owner - - for field in ("phone_owned", "is_phone_key"): - if field not in entry: - continue - explicit_marker = True - value = entry.get(field) - if isinstance(value, bool): - return PHONE_KEY_OWNER if value else PROXY_KEY_OWNER - - if explicit_marker: - return PROXY_KEY_OWNER - return None + """Read the documented persisted ownership marker.""" + return _normalize_owner_value(entry.get(KEY_OWNER_FIELD)) def _is_phone_owned(entry: dict) -> bool: @@ -175,7 +145,7 @@ def _is_phone_owned(entry: dict) -> bool: def _normalize_v2_keys(entries: list) -> tuple[list, bool]: - """Add explicit ownership to unmarked v2 entries and report pending writes.""" + """Add the documented proxy marker to unmarked v2 entries.""" normalized = [] changed = False for entry in entries: @@ -183,15 +153,7 @@ def _normalize_v2_keys(entries: list) -> tuple[list, bool]: changed = True continue current = dict(entry) - owner = _entry_owner(current) - if owner is None: - name = current.get("name") - owner = ( - PHONE_KEY_OWNER - if isinstance(name, str) - and name.strip().casefold() == PHONE_KEY_NAME - else PROXY_KEY_OWNER - ) + owner = _entry_owner(current) or PROXY_KEY_OWNER if current.get(KEY_OWNER_FIELD) != owner: current[KEY_OWNER_FIELD] = owner changed = True @@ -280,9 +242,7 @@ def authenticate_key(config_dir: str, raw_key: str) -> dict | None: def has_api_keys(config_dir: str) -> bool: with _key_store_lock(config_dir): - store, migrated = load_key_store(config_dir) - if migrated: - _save_key_store(config_dir, store) + store, _ = load_key_store(config_dir) return bool(store["keys"]) diff --git a/app/tests/test_control_svc.py b/app/tests/test_control_svc.py index 46d24f9..f5f9539 100644 --- a/app/tests/test_control_svc.py +++ b/app/tests/test_control_svc.py @@ -11,6 +11,7 @@ import sys import tempfile import unittest +from unittest import mock sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) @@ -112,11 +113,13 @@ def test_requesting_a_restart_preserves_unrelated_keys(self): "unknown_key": "keep me", }) - controlSvc.request_restart(self.config_dir, 9393) + result = controlSvc.request_restart(self.config_dir, 9393) + self.assertTrue(result["restart_id"]) self.assertEqual(self.read_control(), { "port": 9393, "server": "restart", + "restart_id": result["restart_id"], "serial_port": "/dev/ttyUSB0", "baudrate": 9600, "unknown_key": "keep me", @@ -127,6 +130,7 @@ def test_normalising_a_restart_returns_start_and_keeps_other_keys(self): self.write_control({ "port": 9393, "server": "restart", + "restart_id": "deadbeef", "serial_port": "/dev/ttyUSB0", "baudrate": 9600, "unknown_key": "keep me", @@ -138,12 +142,32 @@ def test_normalising_a_restart_returns_start_and_keeps_other_keys(self): self.assertEqual(self.read_control(), { "port": 9393, "server": "start", + "restart_id": "deadbeef", "serial_port": "/dev/ttyUSB0", "baudrate": 9600, "unknown_key": "keep me", }) self.assertEqual(self.tmp_files(), []) + def test_a_new_restart_gets_a_new_id_and_is_not_the_same_intent(self): + with mock.patch.object( + controlSvc.secrets, + "token_hex", + side_effect=["aaaa", "bbbb"], + ): + first = controlSvc.request_restart(self.config_dir, 9393) + second = controlSvc.request_restart(self.config_dir, 9393) + + self.assertEqual(first["restart_id"], "aaaa") + self.assertEqual(second["restart_id"], "bbbb") + self.assertTrue(controlSvc.matches_restart(first, "aaaa")) + self.assertFalse(controlSvc.matches_restart(second, "aaaa")) + self.assertFalse(controlSvc.matches_restart({"server": "start"}, "aaaa")) + self.assertTrue(controlSvc.matches_restart({"server": "restart"}, None)) + self.assertFalse(controlSvc.matches_restart( + {"server": "restart", "restart_id": "aaaa"}, None + )) + def test_normalising_without_a_port_uses_the_effective_port(self): self.write_settings(9393) self.write_control({"port": 9292, "server": "restart"}) diff --git a/app/tests/test_key_svc.py b/app/tests/test_key_svc.py index 28c2d07..5f44f34 100644 --- a/app/tests/test_key_svc.py +++ b/app/tests/test_key_svc.py @@ -293,6 +293,68 @@ def test_concurrent_authentication_migrates_a_legacy_store_once(self): {"sms:write", "settings:write"}, ) + def test_unmarked_v2_phone_aliases_do_not_mark_a_key_as_phone(self): + raw_key = "osms_unmarked_phone_name" + store = { + "version": 2, + "keys": [{ + "id": "k_00000001", + "name": "opensms", + "hash": keySvc.hash_api_key(raw_key), + "scopes": ["sms:write", "settings:write"], + "created_at": "2026-01-01T00:00:00+00:00", + "phone_owned": True, + }], + } + os.makedirs(self.first_dir, exist_ok=True) + with open( + os.path.join(self.first_dir, "keys.json"), + "w", + encoding="utf-8", + ) as keys_file: + json.dump(store, keys_file) + + keySvc.rotate_phone_key(self.first_dir) + + entries = keySvc.load_key_store(self.first_dir)[0]["keys"] + self.assertEqual(len(entries), 2) + old = next(entry for entry in entries if entry["id"] == "k_00000001") + self.assertEqual(old["owner"], "proxy") + self.assertIsNotNone(keySvc.authenticate_key(self.first_dir, raw_key)) + self.assertEqual( + len([entry for entry in entries if entry["owner"] == "phone"]), + 1, + ) + + def test_has_api_keys_does_not_persist_a_legacy_migration(self): + raw_key = "osms_legacy_read_only" + legacy_store = { + keySvc.hash_api_key(raw_key): { + "name": "legacy", + "scopes": ["sms:write"], + }, + } + os.makedirs(self.first_dir, exist_ok=True) + with open( + os.path.join(self.first_dir, "keys.json"), + "w", + encoding="utf-8", + ) as keys_file: + json.dump(legacy_store, keys_file) + + self.assertTrue(keySvc.has_api_keys(self.first_dir)) + + with open( + os.path.join(self.first_dir, "keys.json"), encoding="utf-8" + ) as keys_file: + self.assertEqual(json.load(keys_file), legacy_store) + + self.assertIsNotNone(keySvc.authenticate_key(self.first_dir, raw_key)) + with open( + os.path.join(self.first_dir, "keys.json"), encoding="utf-8" + ) as keys_file: + self.assertEqual(json.load(keys_file)["version"], 2) + def test_concurrent_processes_can_delete_different_keys(self): keySvc.create_api_key(self.first_dir, "keep") first = keySvc.create_api_key(self.first_dir, "delete-first") diff --git a/app/tests/test_remote_api.py b/app/tests/test_remote_api.py index e4421a2..9c90a26 100644 --- a/app/tests/test_remote_api.py +++ b/app/tests/test_remote_api.py @@ -1825,11 +1825,17 @@ def test_restart_is_acknowledged_before_the_intent_is_written(self): self.assertTrue(timer.daemon) self.assertEqual(timer.interval, postApi.RESTART_DELAY_SECONDS) - timer.fire() + with mock.patch.object( + postApi.controlSvc.secrets, + "token_hex", + return_value="deadbeef", + ): + timer.fire() self.assertEqual(self.read_request(), { "port": 9393, "server": "restart", + "restart_id": "deadbeef", "serial_port": "/dev/ttyUSB0", "baudrate": 9600, "unknown_key": "keep me", @@ -1860,10 +1866,13 @@ def test_the_debounce_lifts_after_five_seconds(self): raw_key = self.add_api_key() self.restart(raw_key) - postApi._last_restart_at = ( - time.monotonic() - postApi.RESTART_DEBOUNCE_SECONDS - 1 - ) - second = self.restart(raw_key) + now = time.monotonic() + with mock.patch.object( + postApi.time, + "monotonic", + return_value=now + postApi.RESTART_DEBOUNCE_SECONDS + 1, + ): + second = self.restart(raw_key) self.assertEqual(second.status_code, 202) self.assertEqual(len(FakeTimer.instances), 2) diff --git a/docs/remote-api.md b/docs/remote-api.md index b3ecb8e..3b09d8e 100644 --- a/docs/remote-api.md +++ b/docs/remote-api.md @@ -58,7 +58,7 @@ Other facts that constrain the work: |---|---| | Processes | Kivy UI and the `opensmssvc` foreground service are separate. The API server runs in the service. | | `config.json` | Whole-object writes from the UI (`main.py:353-366`), atomic, no revision, no lock. Webhook config is re-read per delivery attempt (`webhookSvc.py:50-57`). | -| `request.json` | UI→service command channel polled every 0.2 s (`appSvc.py:233-260`); written non-atomically (`main.py:368-370`). | +| `request.json` | UI→service command channel polled every 0.2 s (`appSvc.py:233-260`); written atomically through `controlSvc`. | | Restart | No restart path exists. `api_server_control` handles only `start`/`stop` (`appSvc.py:156-170`), and `start` uses `req_data["port"]`. | | Keys | One key. `generate_new_api_key()` overwrites `keys.json` (`postApi.py:92-109`). Raw format `osms_`. | | Outbox | Capacity drop-oldest at enqueue; `max_attempts` then drop (`webhookSvc.py:318-339`, `386-415`). Retry knobs are constructor-fixed; only `enabled`/`url`/`secret` hot-reload per attempt. | @@ -104,7 +104,7 @@ Other facts that constrain the work: | D6 | `config.json` is the single source of truth for the port. `request.json` carries intents; the Restart intent includes the port to start with, used only as a fallback. | The UI currently seeds the port twice; one owner removes a class of drift. | | D7 | All JSON writes are atomic: temp file in the same directory, `os.replace`. | A 0.2 s poller can otherwise read a partial file. | | D8 | The UI re-reads `config.json` on Settings entry and merges on save through `settingsSvc`, preserving `revision` and unknown fields. | Today the UI holds a stale whole-object cache and clobbers remote changes. | -| D9 | `keys.json` v2: array of `{id, name, hash, scopes, created_at}`. Refuse to delete the last key (`409`). UI rotation replaces only the key named `opensms`. | Named keys need stable ids; nuking proxy-owned keys from the phone would be hostile. | +| D9 | `keys.json` v2: array of `{id, name, hash, scopes, created_at, owner}`. Refuse to delete the last key (`409`). UI rotation replaces only the phone-owned key. | Named keys need stable ids; nuking proxy-owned keys from the phone would be hostile. | | D10 | Status is best-effort: runtime providers first, files second, honest `null`/`"unknown"` when neither exists. Add `warnings[]`. | `resp.json` records transitions, not liveness. | | D11 | Retry policy (`timeout`, `max_attempts`, `backoff`, `capacity`) is a setting, read live per attempt/enqueue. Defaults stay exactly today's constants. | This is the data-loss mitigation; it belongs in the first release, not a follow-up. | | D12 | Tests use `unittest` + `TestClient` against a temporary config dir. `httpx` becomes a dev-only dependency. Add a test workflow. | No Android needed; today nothing runs the suite. | @@ -307,7 +307,8 @@ Write procedure: current state, not about this request: a previously pending port change also reports `true`. -Changing `boot` or the webhook never requires a restart. +Changing `boot` is read at the next app launch; it does not affect the current +service. Changing the Webhook or retry fields never requires a restart. ### 6.6 `POST /api/webhook/test` @@ -344,8 +345,11 @@ Rules: control-file write **after** the response (`RESTART_DELAY = 0.4 s`), and returns. - The intent is written atomically as - `{"port": , "server": "restart"}` merged into the existing - `request.json`, preserving `serial_port`, `baudrate`, and unknown keys. + `{"port": , "server": "restart", "restart_id": ""}` + merged into the existing `request.json`, preserving `serial_port`, + `baudrate`, and unknown keys. The service uses `restart_id` to suppress only + the stale intent that could not be normalised; a later Restart gets a new id + and is handled normally. - The handler never calls `PosiApiServer.stop()`. Service side (`appSvc`): @@ -459,7 +463,8 @@ delivered. Numbers must be E.164. Default SIM only. "name": "sms-proxy", "hash": "", "scopes": ["settings:write", "sms:write"], - "created_at": "2026-11-26T12:00:00+00:00" + "created_at": "2026-11-26T12:00:00+00:00", + "owner": "proxy" } ] } From 3274b7d1905bb2bc4d6983503cd23d0aad5aa2b4 Mon Sep 17 00:00:00 2001 From: jptrs Date: Thu, 26 Nov 2026 23:32:49 +0100 Subject: [PATCH 20/20] fix: address PR review comments Reject Webhook targets without a hostname or with an invalid port; capture the Settings error message before scheduling the toast; keep unsaved port edits on a Webhook-only save; publish the bound port so the UI refreshes after a Restart; fall back to the live server port for restart_required; normalize the Webhook-test timeout; reject Restart when no consumer is registered. --- README.md | 3 ++ app/main.py | 56 ++++++++++++++++++++++++++++++------ app/openSmsCli.py | 10 ++++++- app/services/appSvc.py | 3 ++ app/services/postApi.py | 13 ++++++--- app/services/webhookSvc.py | 19 ++++++++---- app/tests/test_remote_api.py | 46 +++++++++++++++++++++++++++++ app/tests/test_webhook.py | 7 +++++ docs/remote-api.md | 8 ++++-- 9 files changed, 142 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 63c8551..e0bb56c 100644 --- a/README.md +++ b/README.md @@ -194,6 +194,9 @@ curl -sS -X POST 'http://192.168.1.50:9292/api/server/restart' \ -H "Authorization: Bearer $OSMS_KEY" ``` +Restart requires the background service loop; the standalone CLI runs the +server directly and refuses Restart with `409`. + `GET /api/status` reports the bound and configured port, network addresses, Outbox depth, the last Delivery attempt, and warnings (for example when forwarding is disabled or the Outbox is near capacity). `POST /api/webhook/test` tests a Webhook target without saving it. The full contract, error codes, and persisted schema are in [docs/remote-api.md](./docs/remote-api.md). ## 📥 Receiving SMS (Android) diff --git a/app/main.py b/app/main.py index ec4f8d8..ec69299 100644 --- a/app/main.py +++ b/app/main.py @@ -117,6 +117,7 @@ def __init__(self, **kwargs): self.wake_lock = None self.service_stat = False self.api_started = False + self.api_port = None self.key_exists = False self.api_key = None self.serial_started = False @@ -316,17 +317,43 @@ def resp_check_loop(self): # server status server_stat = resp.get("server", "unknown") if server_stat == "started": - if not self.api_started: + reported_port = resp.get("port") + if not isinstance(reported_port, int): + reported_port = None + port_changed = ( + reported_port is not None + and ( + reported_port != self.api_port + or reported_port + != self.req_template.get("port") + ) + ) + if not self.api_started or port_changed: self.api_started = True - api_srv_lbl.text = f"API Server running on port: {self.req_template["port"]}" + if reported_port is not None: + self.api_port = reported_port + display_port = ( + self.api_port + or self.req_template["port"] + ) + api_srv_lbl.text = ( + f"API Server running on port: {display_port}" + ) api_srv_btn.btn_icon = "stop" api_srv_btn.btn_txt = "Stop Server" api_srv_btn.md_bg_color = "orange" - Clock.schedule_once(lambda dt: self.update_api_details()) + if port_changed: + Clock.schedule_once( + lambda dt: self.reload_settings_config() + ) + Clock.schedule_once( + lambda dt: self.update_api_details() + ) #Clock.schedule_once(lambda dt: self.show_toast_msg("API Server Started")) elif server_stat == "stopped": if self.api_started: self.api_started = False + self.api_port = None api_srv_lbl.text = "API Server is not running" api_srv_btn.btn_icon = "play" api_srv_btn.btn_txt = "Start Server" @@ -704,12 +731,14 @@ def read_webhook_form(self): webhook["secret"] = secret return webhook - def persist_settings_form(self, form): + def persist_settings_form(self, form, *, refresh_webhook_only=False): """Merge the form over fresh Settings and persist it atomically.""" saved = self.persist_local_settings(form) if saved is None: return False - self.apply_persisted_settings(saved) + self.apply_persisted_settings( + saved, refresh_webhook_only=refresh_webhook_only + ) return True def persist_local_settings(self, form): @@ -717,18 +746,25 @@ def persist_local_settings(self, form): try: return settingsSvc.save_local_settings(self.app_config, form) except settingsSvc.SettingsValidationError as exc: + message = str(exc) Clock.schedule_once( - lambda dt: self.show_toast_msg(str(exc), is_error=True) + lambda dt: self.show_toast_msg(message, is_error=True) ) return None - def apply_persisted_settings(self, settings: dict): + def apply_persisted_settings( + self, settings: dict, *, refresh_webhook_only: bool = False + ): """Adopt freshly persisted Settings and show them.""" self.config_template = dict(settings) self.req_template["port"] = int( self.config_template.get("port") or settingsSvc.DEFAULT_PORT ) - self.refresh_settings_view() + if refresh_webhook_only: + # A Webhook-only save must not overwrite an unsaved port edit. + self.refresh_webhook_view() + else: + self.refresh_settings_view() def webhook_switch_active(self, instance, value): """Apply the toggle immediately, instead of waiting for Save. @@ -744,7 +780,9 @@ def webhook_switch_active(self, instance, value): instance.active = False self.webhook_switch_guard = False return - if not self.persist_settings_form({"webhook": webhook}): + if not self.persist_settings_form( + {"webhook": webhook}, refresh_webhook_only=True + ): self.refresh_webhook_view() return self.show_toast_msg( diff --git a/app/openSmsCli.py b/app/openSmsCli.py index 9094cb5..91f1b26 100644 --- a/app/openSmsCli.py +++ b/app/openSmsCli.py @@ -12,7 +12,12 @@ # local imports from services.pathMgr import get_os_platform -from services.postApi import PosiApiServer, set_api_logger, set_serial_port +from services.postApi import ( + PosiApiServer, + set_api_logger, + set_runtime_providers, + set_serial_port, +) from services.logSvc import LogService from services.config import app_name @@ -69,6 +74,9 @@ def start_background(serial, baud, host, port): class OpenSmsCliCls: def __init__(self): + # The CLI runs PosiApiServer directly; there is no service loop to + # consume a Restart intent, so /api/server/restart must refuse it. + set_runtime_providers({"restart_consumer": lambda: False}) self.serial_ok = False self.api_server = None diff --git a/app/services/appSvc.py b/app/services/appSvc.py index cf7e100..0fabccf 100644 --- a/app/services/appSvc.py +++ b/app/services/appSvc.py @@ -39,6 +39,7 @@ # global vars resp_template = { "server": "none", + "port": None, "serial": "none", "provider": "none", } @@ -187,6 +188,7 @@ def api_server_control(api_stat: str, port: int | None = None): if api_stat == "stop": if stop_api_server(): resp_template["server"] = "stopped" + resp_template["port"] = None elif api_stat == "start": # Settings own the port; the control file is only a fallback. start_port = ( @@ -195,6 +197,7 @@ def api_server_control(api_stat: str, port: int | None = None): app_api_server.start(start_port) api_started = True resp_template["server"] = "started" + resp_template["port"] = start_port Thread(target=write_resp, daemon=True).start() def restart_api_server(): diff --git a/app/services/postApi.py b/app/services/postApi.py index 42c9c9a..21cf631 100644 --- a/app/services/postApi.py +++ b/app/services/postApi.py @@ -794,6 +794,8 @@ def _settings_log_message(payload: dict) -> str: def _restart_required(settings: dict) -> bool: """True only when the saved port differs from a known live bound port.""" bound_port = get_runtime_provider("bound_port") + if bound_port is None: + bound_port = _live_attr("bound_port") port = settings.get("port") if bound_port is None or port is None: return False @@ -973,10 +975,7 @@ def _resolve_webhook_test_config(settings: dict, overrides: dict) -> tuple: if not isinstance(secret, str): secret = "" secret = overrides.get("secret", secret) - try: - timeout = float(webhook.get("timeout", webhookSvc.DEFAULT_TIMEOUT)) - except (TypeError, ValueError): - timeout = webhookSvc.DEFAULT_TIMEOUT + timeout = webhookSvc.normalize_webhook_config(webhook)["timeout"] return url, secret, timeout @@ -1054,6 +1053,12 @@ async def api_server_restart( detail="The API server is not running", ) + if not _status_runtime("restart_consumer", True): + raise HTTPException( + status_code=409, + detail="Restart is not available on this platform", + ) + now = time.monotonic() with _restart_lock: if ( diff --git a/app/services/webhookSvc.py b/app/services/webhookSvc.py index 42ad4a2..541fcf4 100644 --- a/app/services/webhookSvc.py +++ b/app/services/webhookSvc.py @@ -195,12 +195,19 @@ def target_host(url: str) -> str | None: def is_valid_target(url: str) -> bool: parsed = _parse_target(url) - return ( - parsed is not None - and parsed.scheme in VALID_TARGET_SCHEMES - and bool(parsed.netloc) - and not _parsed_has_credentials(parsed) - ) + if ( + parsed is None + or parsed.scheme not in VALID_TARGET_SCHEMES + or _parsed_has_credentials(parsed) + ): + return False + try: + if not parsed.hostname: + return False + parsed.port # raises ValueError for a non-numeric or out-of-range port + except ValueError: + return False + return True ## Payload diff --git a/app/tests/test_remote_api.py b/app/tests/test_remote_api.py index 9c90a26..e4e0654 100644 --- a/app/tests/test_remote_api.py +++ b/app/tests/test_remote_api.py @@ -1417,6 +1417,15 @@ def test_restart_is_not_required_when_the_bound_port_is_unknown(self): self.assertEqual(response.status_code, 200) self.assertFalse(response.json()["restart_required"]) + def test_restart_uses_the_live_server_port_without_a_provider(self): + postApi.app.state.server.bound_port = 9292 + raw_key = self.add_api_key() + + response = self.put(self.valid_payload(port=9393), raw_key) + + self.assertEqual(response.status_code, 200) + self.assertTrue(response.json()["restart_required"]) + class SettingsWriteAuthTests(SettingsWriteTestCase): @@ -1687,6 +1696,29 @@ def record(config, timeout): self.assertEqual(response.status_code, 200) self.assertEqual(calls[0][1], 7) + def test_an_invalid_saved_timeout_uses_the_normalized_default(self): + raw_key = self.add_api_key() + for timeout in (0, 61): + with self.subTest(timeout=timeout): + self.save_webhook(timeout=timeout) + calls = [] + + def record(config, timeout): + calls.append((config, timeout)) + return True, 204, None + + with mock.patch.object( + postApi.webhookSvc, + "send_test_webhook", + side_effect=record, + ): + response = self.post_test( + raw_key, {"url": self.target.url} + ) + + self.assertEqual(response.status_code, 200) + self.assertEqual(calls[0][1], 10) + def test_body_shape_errors_keep_their_messages(self): raw_key = self.add_api_key() @@ -1903,6 +1935,20 @@ def test_a_restart_is_refused_while_the_server_is_not_running(self): self.assertFalse(os.path.exists(self.request_path())) self.assertEqual(FakeTimer.instances, []) + def test_a_restart_is_refused_without_a_restart_consumer(self): + postApi.set_runtime_providers({ + "running": lambda: True, + "restart_consumer": lambda: False, + }) + raw_key = self.add_api_key() + + response = self.restart(raw_key) + + self.assertEqual(response.status_code, 409) + self.assertIsInstance(response.json()["detail"], str) + self.assertFalse(os.path.exists(self.request_path())) + self.assertEqual(FakeTimer.instances, []) + def test_restart_requires_authentication_and_the_settings_scope(self): response = self.client.post("/api/server/restart") self.assertEqual(response.status_code, 403) diff --git a/app/tests/test_webhook.py b/app/tests/test_webhook.py index 0cc0137..02e7580 100644 --- a/app/tests/test_webhook.py +++ b/app/tests/test_webhook.py @@ -181,6 +181,13 @@ def test_valid_target(self): self.assertFalse(webhookSvc.is_valid_target("ftp://example.com")) self.assertFalse(webhookSvc.is_valid_target("http://[")) self.assertFalse(webhookSvc.is_valid_target(None)) + self.assertFalse(webhookSvc.is_valid_target("http://:9292/hooks")) + self.assertFalse( + webhookSvc.is_valid_target("http://proxy.example.lan:not-a-port/hooks") + ) + self.assertFalse( + webhookSvc.is_valid_target("http://proxy.example.lan:99999/hooks") + ) def test_payload_shape(self): payload = webhookSvc.build_inbound_payload({ diff --git a/docs/remote-api.md b/docs/remote-api.md index 3b09d8e..323931a 100644 --- a/docs/remote-api.md +++ b/docs/remote-api.md @@ -339,8 +339,9 @@ Optional body: Rules: -- `409` if the API is not running (provider) or a restart was requested within - the last 5 seconds. +- `409` if the API is not running (provider), the platform has no Restart + consumer (the CLI runs the server without the service loop), or a restart was + requested within the last 5 seconds. - The handler reads the effective port from `config.json`, schedules the control-file write **after** the response (`RESTART_DELAY = 0.4 s`), and returns. @@ -356,7 +357,8 @@ Service side (`appSvc`): 1. Handle `"restart"`: `stop()`, sleep 0.5 s, start with `load_settings(config.json)["port"]`, falling back to `request.json["port"]`. -2. Write `resp.json` with `"started"`. +2. Write `resp.json` with `"started"` and the effective port so the UI can + refresh when a Restart changes the bound port. 3. Rewrite `request.json` with `"server": "start"` and the effective port, preserving other keys. 4. The 0.2 s loop then sees `"start"` with the server already started and does