diff --git a/CHANGELOG.md b/CHANGELOG.md index 62ce4a4..27d7943 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## Changes +### 1.3.0 +- Add multiple Webhooks with prefix-keyword routing: each Inbound SMS is delivered to exactly one enabled Webhook, with an optional catch-all for unmatched messages. +- Add per-Webhook prefix stripping (`none`, keyword only, keyword and separator), sender allowlists, names, and independent signing secrets. +- Keep one enabled Webhook behaving exactly like 1.2.0 (no keyword required); migrate the legacy single `webhook` config, Outbox records, and status file without losing pending deliveries. +- Partition the Outbox into per-Webhook FIFO lanes so a target in backoff cannot delay another target; capacity remains a global drop-oldest limit. +- Extend the remote API: `webhooks` array plus shared `webhook_delivery` policy, server-assigned ids, per-entry secret sentinel, per-Webhook status, id-based test delivery, and a deprecated one-release legacy `webhook` PUT shim. +- Replace the single Webhook Settings block with collapsible Webhook cards (add, delete, test, last delivery), and save the whole list explicitly. + ### 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. diff --git a/GLOSSARY.md b/GLOSSARY.md index 5914c42..a16c2de 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -1,6 +1,6 @@ # OpenSMS -OpenSMS turns a phone or a USB modem into a local SMS gateway: it sends SMS on request and notifies a configured endpoint when SMS arrives. +OpenSMS turns a phone or a USB modem into a local SMS gateway: it sends SMS on request and notifies one or more configured endpoints when SMS arrives. ## Language @@ -9,8 +9,12 @@ An SMS received by the device's SIM, as opposed to one sent through the OpenSMS _Avoid_: incoming message, received text, downlink **Webhook**: -A notification that OpenSMS delivers over HTTP to announce an event, such as an Inbound SMS. -_Avoid_: callback, post, push +A configured destination and its routing rule. A Webhook has an id, a Webhook target, an optional signing secret, a Route keyword, a prefix stripping mode, and a Sender allowlist. +_Avoid_: callback, endpoint, route + +**Webhook delivery**: +One HTTP notification that OpenSMS attempts for a Webhook, with its own delivery id and status. +_Avoid_: callback, post, push, send **Webhook target**: The URL that Webhooks are delivered to. @@ -20,12 +24,32 @@ _Avoid_: endpoint, destination, webhook URL One HTTP request made while trying to deliver a Webhook. _Avoid_: retry, send, try +**Route keyword**: +The case-insensitive prefix that selects a Webhook when two or more are enabled, such as `#sales`. It must be followed by `:` or whitespace. +_Avoid_: tag, prefix, filter + +**Catch-all Webhook**: +The single Webhook with an empty Route keyword. It receives Inbound SMS that match no other Route keyword when two or more Webhooks are enabled. +_Avoid_: default webhook, fallback + +**Sender allowlist**: +The per-Webhook list of phone numbers or alphanumeric sender IDs whose SMS may be forwarded. An empty list allows every sender. +_Avoid_: whitelist, filter, allowed numbers + +**Delivery policy**: +The shared `timeout`, `max_attempts`, `backoff`, and Outbox `capacity` that apply to every Webhook. +_Avoid_: retry settings, webhook config + +**Outbox lane**: +The per-Webhook FIFO of pending Webhook deliveries. One lane in backoff does not block another lane. +_Avoid_: queue, partition + **Outbox**: -The persisted queue of Webhooks that are waiting to be delivered. +The persisted queue of Webhook deliveries 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. +The operator-chosen configuration that OpenSMS keeps across restarts: the API port, whether the server starts at launch, the Webhooks, and the Delivery policy. _Avoid_: config, preferences, options **Revision**: diff --git a/README.md b/README.md index e0bb56c..1edfa32 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ An open-source cross-platform solution to host a `SMS` API server locally. ### ๐Ÿค” Why would you choose our app? (Features) ๐Ÿ‘‰ Turns your `Android` phone into a SMS API server.
-๐Ÿ‘‰ Forward received SMS to your own HTTP endpoint (webhook).
+๐Ÿ‘‰ Forward received SMS to one or more of your own HTTP endpoints (webhooks), with prefix-keyword routing.
๐Ÿ‘‰ Also available on `Desktop` platforms via [EC200U](https://www.quectel.com/product/lte-ec200u-series/) or similar USB development boards.
๐Ÿ‘‰ Open-source, No advertisements and privacy focused. @@ -176,18 +176,33 @@ curl -sS -X PUT 'http://192.168.1.50:9292/api/settings' \ "revision": 7, "port": 9292, "boot": true, - "webhook": { - "enabled": true, - "url": "https://proxy.example.lan/hooks/opensms", + "webhook_delivery": { "timeout": 10, "max_attempts": 3, "backoff": [5, 30], "capacity": 100 - } + }, + "webhooks": [ + { + "name": "Proxy", + "enabled": true, + "url": "https://proxy.example.lan/hooks/opensms", + "keyword": "#proxy", + "strip_prefix": "keyword_and_separator", + "allowed_senders": ["+14155552671"] + } + ] }' ``` -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: +The `webhooks` array is a full replacement. Entries with an `id` update that +Webhook, entries without one are created with a server-assigned id, and omitted +entries are deleted. Omit `webhooks[].secret` to keep the stored secret for that +id, send `""` to clear it, or send a new string to replace it. The legacy +single-`webhook` body still works for one release (deprecated). 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' \ @@ -197,32 +212,46 @@ curl -sS -X POST 'http://192.168.1.50:9292/api/server/restart' \ 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). +`GET /api/status` reports the bound and configured port, network addresses, per-Webhook last Delivery and pending count, global Outbox depth, and warnings (for example when forwarding is disabled, an enabled target is invalid, routing has no catch-all, or the Outbox is near capacity). `POST /api/webhook/test` tests a saved Webhook by `id`, or a 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. +OpenSMS can forward every SMS received by the phone to one or more of your own HTTP endpoints as Webhooks. Receiving works independently of the API server: it runs in the same background service, so the API can be stopped while Webhooks keep flowing. ### Configure it -1. Open `Settings` and find the **Webhook (Inbound SMS)** section. -2. Enter the **Webhook target** (`http://` or `https://`) without `username:password@` userinfo. +1. Open `Settings` and find the **Webhooks (Inbound SMS)** section. +2. Tap **Add Webhook** and 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"`. +5. Tap the send icon on the card to test that endpoint. This sends `event: "webhook.test"`. -Settings take effect immediately; no restart is needed. The last delivery result is shown under the webhook settings and in the `Logs` screen. +With one enabled Webhook, every Inbound SMS is delivered to it exactly as in +1.2.0. With two or more, each SMS is delivered to **exactly one** Webhook: + +- The SMS may start with a **Route keyword**, for example `#sales: hello`. + Matching is case-insensitive and requires `:` or whitespace after the keyword. +- Otherwise the single **catch-all** Webhook (an empty keyword) receives it. If + no catch-all exists, the SMS is dropped and logged. +- Each Webhook chooses whether to remove the keyword only or the keyword and + separator before forwarding. +- Each Webhook can have an **Allowed senders** list. Empty means all; when set, + only those numbers or alphanumeric sender IDs are forwarded to that Webhook. + +Settings take effect immediately; no restart is needed. Each card shows its own +last delivery result, and the `Logs` screen records every attempt. ### Request format -Every Inbound SMS produces one `POST` with a JSON body: +Every Inbound SMS produces one `POST` per delivered Webhook with a JSON body: ```http POST /your-hook HTTP/1.1 Content-Type: application/json -User-Agent: OpenSMS/1.2.0 +User-Agent: OpenSMS/1.3.0 X-OpenSMS-Event: sms.received X-OpenSMS-Delivery: 6f1c2f5e-0d7a-4c55-9f0e-2b1c8b7f0a11 +X-OpenSMS-Webhook-Id: wh_5b581975 X-OpenSMS-Signature: sha256=... ``` @@ -244,7 +273,7 @@ X-OpenSMS-Signature: sha256=... - A multipart SMS is delivered as **one** webhook with the parts joined in `text` and counted in `parts`. - `sim` is included only when the subscription can be determined. -A `2xx` response means delivered. Anything else (or a timeout after 10 seconds) is retried twice (after 5s and 30s); after three failed attempts the delivery is logged as failed. Redirects are not followed and count as failures. Pending webhooks are kept on disk and survive restarts. At most 100 are queued; when full, the oldest is dropped. Delivery is at-least-once: a crash immediately after persisting a delivery can produce a duplicate, but never a silent loss. +A `2xx` response means delivered. Anything else (or a timeout after 10 seconds) is retried twice (after 5s and 30s); after three failed attempts the delivery is logged as failed. Redirects are not followed and count as failures. Pending deliveries are kept on disk and survive restarts. Each Webhook has its own FIFO lane, so one target in backoff does not delay the others; the shared Outbox holds at most 100 deliveries by default, and when full the oldest is dropped. Delivery is at-least-once: a crash immediately after persisting a delivery can produce a duplicate, but never a silent loss. ### Verify the signature diff --git a/app/main.py b/app/main.py index ec69299..21ee9bf 100644 --- a/app/main.py +++ b/app/main.py @@ -4,6 +4,7 @@ #Config.set("graphics", "multisamples", "0") import sys import json +import re import tempfile from threading import Thread, Lock @@ -37,22 +38,20 @@ # import screens (else pyinstaller may ignore it) from screens.mainScr import ButtonControl, EndPointUrl, DocButton, SerialCard -from screens.settings import SettingsBox, ApiKeyTxtbox +from screens.settings import SettingsBox, ApiKeyTxtbox, WebhookCard # import services 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 from services.webhookSvc import ( - default_webhook_config, + DEFAULT_STRIP_MODE, + MAX_WEBHOOKS, format_webhook_status, - get_webhook_config, is_valid_target, - normalize_webhook_config, - read_webhook_status, + normalize_webhook_delivery, + read_webhook_statuses, send_test_webhook, - target_host, ) # IMPORTANT: Set this property for keyboard behaviour @@ -123,19 +122,10 @@ def __init__(self, **kwargs): self.serial_started = False 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, - "boot": False, - "permissions": False, - "webhook": default_webhook_config(), - } + self.webhook_cards = [] + self.config_template = settingsSvc.default_settings() self.req_template = { "port": 9292, "server": "stop", @@ -231,13 +221,18 @@ def on_start(self): self.config_template["permissions"] = bool( saved_config.get("permissions", False) ) - webhook_cfg = normalize_webhook_config(saved_config.get("webhook")) + webhook_cfg = settingsSvc.writable_settings( + self.config_template + ) + enabled_webhooks = [ + webhook for webhook in webhook_cfg["webhooks"] + if webhook["enabled"] + ] print( "start config check: " f"port={self.config_template['port']}, " f"boot={self.config_template['boot']}, " - f"webhook enabled={webhook_cfg['enabled']}, " - f"target={target_host(webhook_cfg['url']) or 'unknown'}" + f"webhooks enabled={len(enabled_webhooks)}" ) self.req_template["port"] = int(self.config_template["port"]) start_on_launch = self.config_template["boot"] @@ -662,10 +657,21 @@ def start_serial_connection(self, instance=None): ## Settings sections def save_settings(self, instance=None, control_txt="none"): - boot = None if control_txt == "switch": boot = not self.config_template["boot"] - form = self.read_settings_form(boot=boot) + saved = self.persist_local_settings({"boot": boot}) + if saved is None: + self.root.ids.settings_scr.ids.auto_start_sw.active = ( + self.config_template["boot"] + ) + return + self.config_template = dict(saved) + self.boot_loaded = bool(saved.get("boot")) + Clock.schedule_once(lambda dt: self.show_toast_msg( + "Auto start " + ("enabled" if boot else "disabled") + )) + return + form = self.read_settings_form() if form is None: return if not self.persist_settings_form(form): @@ -699,188 +705,257 @@ def read_settings_form(self, boot=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 + form["webhooks"] = [card.read() for card in self.webhook_cards] + form["revision"] = settingsSvc.get_revision(self.config_template) return form - def read_webhook_inputs(self): - settings = self.root.ids.settings_scr.ids - return ( - bool(settings.webhook_sw.active), - settings.webhook_url_inp.text.strip(), - settings.webhook_secret_inp.text.strip(), - ) - - 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, *, refresh_webhook_only=False): + def persist_settings_form(self, form): """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, refresh_webhook_only=refresh_webhook_only - ) + 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.SettingsRevisionConflict: + Clock.schedule_once(lambda dt: self.show_toast_msg( + "Settings changed elsewhere โ€” reloaded", is_error=True + )) + Clock.schedule_once( + lambda dt: self.reload_settings_config() + ) + return None except settingsSvc.SettingsValidationError as exc: message = str(exc) + self._expand_error_card(message) Clock.schedule_once( lambda dt: self.show_toast_msg(message, is_error=True) ) return None - def apply_persisted_settings( - self, settings: dict, *, refresh_webhook_only: bool = False - ): + def _expand_error_card(self, message): + match = re.search(r"webhooks\[(\d+)\]", message or "") + if not match: + return + index = int(match.group(1)) + if 0 <= index < len(self.webhook_cards): + card = self.webhook_cards[index] + card.expanded = True + card.expand_text = "Hide" + + 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 ) - 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. + self.refresh_settings_view() - on_active carries the new value; reading `active` from on_release is - one event too early and saved the previous state. - """ - if self.webhook_switch_guard: - return - webhook = self.read_webhook_form() - if webhook is None: - self.webhook_switch_guard = True - instance.active = False - self.webhook_switch_guard = False - return - if not self.persist_settings_form( - {"webhook": webhook}, refresh_webhook_only=True - ): - self.refresh_webhook_view() + 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.show_toast_msg( - "Webhook enabled" if bool(value) else "Webhook disabled" + self.apply_persisted_settings( + settingsSvc.load_settings(self.app_config) ) - def validate_webhook(self, enabled: bool, url: str) -> bool: - # Turning it off must always be possible, even with a stale URL. - if not enabled: - return True - if not is_valid_target(url): - self.show_toast_msg( - "Add a valid http:// or https:// webhook URL first", - is_error=True, - ) - return False - return True - def refresh_webhook_view(self): - webhook = normalize_webhook_config( - self.config_template.get("webhook") - ) settings = self.root.ids.settings_scr.ids - self.webhook_switch_guard = True - try: - settings.webhook_sw.active = webhook["enabled"] - finally: - 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() + expanded = { + card.webhook.get("id"): card.expanded + for card in self.webhook_cards + if card.webhook.get("id") + } + writable = settingsSvc.writable_settings(self.config_template) + self.webhook_cards = [] + for index, entry in enumerate(writable["webhooks"]): + card = WebhookCard(self, entry, index) + if entry.get("id") in expanded: + card.expanded = expanded[entry["id"]] + card.expand_text = "Hide" if card.expanded else "Edit" + self.webhook_cards.append(card) + self._render_webhook_cards(settings) + + def _render_webhook_cards(self, settings=None): + if settings is None: + settings = self.root.ids.settings_scr.ids + box = settings.webhook_cards_box + box.clear_widgets() + if not self.webhook_cards: + empty = MDLabel( + text=( + "No Webhooks configured yet.\n" + "Add one to forward Inbound SMS." + ), + halign="center", + size_hint_y=None, + height=dp(56), + ) + box.add_widget(empty) + for card in self.webhook_cards: + box.add_widget(card) + self._refresh_routing_visibility() + self._update_add_button(settings) self.refresh_webhook_status() - 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): + def _refresh_routing_visibility(self): + visible = len(self.webhook_cards) >= 2 + for card in self.webhook_cards: + card.set_routing_visible(visible) + + def _update_add_button(self, settings=None): + if settings is None: + settings = self.root.ids.settings_scr.ids + settings.add_webhook_btn.disabled = ( + len(self.webhook_cards) >= MAX_WEBHOOKS + ) + + def add_webhook_card(self, instance=None): + if len(self.webhook_cards) >= MAX_WEBHOOKS: + self.show_toast_msg( + f"At most {MAX_WEBHOOKS} Webhooks are supported", + is_error=True, + ) return - self.apply_persisted_settings( - settingsSvc.load_settings(self.app_config) + entry = { + "name": "", + "enabled": False, + "url": "", + "secret_set": False, + "keyword": "", + "strip_prefix": DEFAULT_STRIP_MODE, + "allowed_senders": [], + } + card = WebhookCard(self, entry, len(self.webhook_cards)) + self.webhook_cards.append(card) + self._render_webhook_cards() + + def delete_webhook_card(self, card): + def confirm(instance=None): + self.txt_dialog_closer() + if card not in self.webhook_cards: + return + self.webhook_cards.remove(card) + for index, remaining in enumerate(self.webhook_cards): + remaining.index = index + remaining._update_title() + self._render_webhook_cards() + + buttons = MDDialogButtonContainer( + Widget(), + MDButton( + MDButtonText(text="Cancel"), + style="text", + on_release=self.txt_dialog_closer, + ), + MDButton( + MDButtonText( + text="Delete", + theme_text_color="Custom", + text_color="red", + ), + style="text", + on_release=confirm, + ), + spacing="8dp", + ) + self.show_text_dialog( + "Delete Webhook", + ( + f"Delete \"{card.title_text}\"? Pending deliveries for this " + "Webhook will be dropped when you Save." + ), + None, + buttons, ) def refresh_webhook_status(self): if not self.webhook_status_path: return - status = read_webhook_status(self.webhook_status_path) - self.root.ids.settings_scr.ids.webhook_status_lbl.text = ( - format_webhook_status(status) - ) + statuses = read_webhook_statuses(self.webhook_status_path) + for card in self.webhook_cards: + webhook_id = card.webhook.get("id") + if not webhook_id: + card.set_status("No deliveries yet") + else: + card.set_status( + format_webhook_status(statuses.get(webhook_id)) + ) 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") + delivery = ( + config_template.get("webhook_delivery") 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. - if not self.validate_webhook(True, webhook_url): + return normalize_webhook_delivery(delivery)["timeout"] + + def test_webhook_card(self, card): + url = (card.ids.url_inp.text or "").strip() + secret = card.ids.secret_inp.text or "" + if ( + not secret + and not card.secret_cleared + and card.webhook.get("id") + and card.webhook.get("secret_set") + ): + current = settingsSvc.load_settings(self.app_config) + for entry in current.get("webhooks") or []: + if ( + isinstance(entry, dict) + and entry.get("id") == card.webhook["id"] + ): + secret = entry.get("secret") or "" + break + if not is_valid_target(url): + card.expanded = True + card.expand_text = "Hide" + self.show_toast_msg( + "Add a valid http:// or https:// webhook URL first", + is_error=True, + ) return - self.root.ids.settings_scr.ids.webhook_status_lbl.text = ( - "Sending test webhook..." - ) - config = {"url": webhook_url, "secret": webhook_secret} - timeout = self.get_webhook_test_timeout() + card.set_status("Sending test webhook...") Thread( target=self.run_webhook_test, - kwargs={"config": config, "timeout": timeout}, + kwargs={ + "config": {"url": url, "secret": secret}, + "timeout": self.get_webhook_test_timeout(), + "webhook_id": card.webhook.get("id"), + "callback": card.set_status, + }, daemon=True, ).start() - def run_webhook_test(self, config: dict, timeout=None): + def run_webhook_test( + self, config: dict, timeout=None, webhook_id=None, callback=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) + timeout = normalize_webhook_delivery( + {"timeout": timeout} + )["timeout"] + ok, status, error = send_test_webhook( + config, timeout=timeout, webhook_id=webhook_id ) - - def show_webhook_test_result(self, ok: bool, status, error): if ok: text = f"Test delivered (HTTP {status})" else: text = f"Test failed: {error or status}" - self.root.ids.settings_scr.ids.webhook_status_lbl.text = text - self.show_toast_msg(text, is_error=not ok) + + def finish(dt): + if callback is not None: + callback(text) + self.show_toast_msg(text, is_error=not ok) + + Clock.schedule_once(finish) def refresh_settings_view(self): auto_start_sw = self.root.ids.settings_scr.ids.auto_start_sw @@ -893,17 +968,20 @@ def refresh_settings_view(self): def reset_settings(self, instance=None): defaults = settingsSvc.default_settings() - default_webhook = defaults["webhook"] - form = { + payload = { "port": defaults["port"], "boot": defaults["boot"], - "webhook": { - **default_webhook, - "backoff": list(default_webhook["backoff"]), - }, + "webhook_delivery": defaults["webhook_delivery"], + "webhooks": [], } - if not self.persist_settings_form(form): + try: + saved = settingsSvc.save_settings(self.app_config, payload) + except settingsSvc.SettingsValidationError as exc: + Clock.schedule_once( + lambda dt: self.show_toast_msg(str(exc), is_error=True) + ) return + self.apply_persisted_settings(saved) print("Settings reset has been done!") Clock.schedule_once(lambda dt: self.show_toast_msg("Settings reset has been done!")) diff --git a/app/main_layout.kv b/app/main_layout.kv index 553c988..ace232b 100644 --- a/app/main_layout.kv +++ b/app/main_layout.kv @@ -70,6 +70,7 @@ MDScreen: MDScreen: name: "Logs" + md_bg_color: self.theme_cls.backgroundColor on_enter: log_scr.log_show(right_dot_menu, top_back_btn) on_leave: log_scr.on_log_scr_exit(right_dot_menu) LogBox: diff --git a/app/screens/logs.py b/app/screens/logs.py index bf28009..e6c04aa 100644 --- a/app/screens/logs.py +++ b/app/screens/logs.py @@ -2,14 +2,17 @@ from kivymd.uix.boxlayout import MDBoxLayout from kivymd.uix.menu import MDDropdownMenu -from kivymd.uix.button import MDButton, MDButtonIcon, MDButtonText from kivy.lang import Builder -from kivy.uix.widget import Widget +from kivy.clock import Clock from kivy.core.clipboard import Clipboard -from kivy.properties import StringProperty, NumericProperty, ObjectProperty, ColorProperty +from kivy.properties import StringProperty from kivy.metrics import dp, sp from kivy.utils import platform +from kivy.uix.boxlayout import BoxLayout +from kivy.uix.label import Label +from kivy.uix.recycleview import RecycleView +from kivy.uix.recycleboxlayout import RecycleBoxLayout # local imports from services.logSvc import LogService @@ -17,27 +20,53 @@ Builder.load_string(''' +: + orientation: "horizontal" + size_hint_y: None + height: dp(32) + canvas.before: + Color: + rgba: 1, 1, 1, 1 + Rectangle: + pos: self.pos + size: self.size + + Label: + text: root.text + color: 0, 0, 0, 1 + font_size: sp(12) + text_size: self.width, None + halign: "left" + valign: "middle" + shorten: True + : orientation: "vertical" - - MDScrollView: - do_scroll_x: False - - MDBoxLayout: - id: log_box + size_hint: 1, 1 + canvas.before: + Color: + rgba: 1, 1, 1, 1 + Rectangle: + pos: self.pos + size: self.size + + RecycleView: + id: log_rv + viewclass: "LogRow" + + RecycleBoxLayout: orientation: "vertical" - adaptive_height: True - - MDLabel: - id: log_container - adaptive_height: True - valign: "top" - text: "No logs yet!" - font_style: "Label" - role: "small" + default_size: None, dp(32) + default_size_hint: 1, None + size_hint_y: None + height: self.minimum_height ''') +class LogRow(BoxLayout): + text = StringProperty("") + + class LogBox(MDBoxLayout): def __init__(self, **kwargs): @@ -58,16 +87,15 @@ def __init__(self, **kwargs): } } self.logger = LogService(self.app_name, platform) + self._refresh_event = None + self._last_lines = None def log_show(self, instance=None, top_back_btn=None): - text_log = "" - container = self.ids.log_container - logs = self.logger.get_api_logs() - for line in reversed(logs): - clean_line = line.strip() - if clean_line: - text_log = text_log + f"{clean_line}\n" - container.text = text_log + self._refresh_text() + if self._refresh_event is None: + self._refresh_event = Clock.schedule_interval( + self._auto_refresh, 2 + ) if instance: if top_back_btn: @@ -90,6 +118,23 @@ def log_show(self, instance=None, top_back_btn=None): ) instance.on_release = self.show_top_menu + def _auto_refresh(self, dt): + self._refresh_text() + + def _refresh_text(self): + logs = [ + line.strip() + for line in self.logger.get_api_logs()[-500:] + if line.strip() + ] + if logs == self._last_lines: + return + self._last_lines = logs + rows = list(reversed(logs)) + if not rows: + rows = ["No logs yet!"] + self.ids.log_rv.data = [{"text": line} for line in rows] + def show_top_menu(self, instance=None): self.top_menu.open() @@ -106,15 +151,18 @@ def top_menu_callback(self, text_item:str): self.log_show() def copy_logs(self): - container = self.ids.log_container - Clipboard.copy(container.text) + Clipboard.copy("\n".join(self.logger.get_api_logs())) def clear_logs(self, instance=None): - container = self.ids.log_container - container.text = "" - Thread(target=self.logger.clear_logs(), daemon=True).start() + self.ids.log_rv.data = [] + self._last_lines = None + Thread(target=self.logger.clear_logs, daemon=True).start() + Clock.schedule_once(lambda dt: self._refresh_text(), 0.3) def on_log_scr_exit(self, instance=None): + if self._refresh_event is not None: + self._refresh_event.cancel() + self._refresh_event = None if instance: # hamburger menu instance.opacity = 0 diff --git a/app/screens/settings.py b/app/screens/settings.py index 9e933e0..c18892f 100644 --- a/app/screens/settings.py +++ b/app/screens/settings.py @@ -1,15 +1,26 @@ from kivymd.uix.boxlayout import MDBoxLayout from kivymd.uix.scrollview import MDScrollView -from kivymd.uix.gridlayout import MDGridLayout from kivymd.uix.button import MDButton, MDButtonIcon, MDButtonText -from kivymd.uix.textfield import MDTextField, MDTextFieldTrailingIcon +from kivymd.uix.textfield import MDTextField from kivymd.uix.list import MDListItem +from kivymd.uix.label import MDLabel +from kivymd.uix.menu import MDDropdownMenu +from kivymd.uix.selectioncontrol import MDSwitch from kivy.lang import Builder -from kivy.uix.widget import Widget -from kivy.properties import StringProperty, NumericProperty, ObjectProperty, ColorProperty +from kivy.properties import StringProperty, BooleanProperty from kivy.metrics import dp, sp -from kivy.utils import platform + +from services.webhookSvc import ( + DEFAULT_STRIP_MODE, + STRIP_MODES, +) + +STRIP_LABELS = { + "none": "Keep the keyword", + "keyword": "Remove keyword only", + "keyword_and_separator": "Remove keyword and separator", +} Builder.load_string(''' @@ -20,6 +31,193 @@ # icon: "content-copy" # on_release: app.copy_api_key() +: + orientation: "vertical" + size_hint_y: None + height: self.minimum_height + padding: dp(8) + spacing: dp(4) + + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + height: dp(48) + spacing: dp(2) + + MDLabel: + text: root.title_text + bold: True + font_size: sp(16) + shorten: True + size_hint_x: 1 + + MDSwitch: + id: enabled_sw + active: root.enabled + on_active: root.enabled = self.active + pos_hint: {"center_y": .5} + + MDButton: + style: "text" + size_hint_x: None + width: dp(64) + on_release: root.toggle_expanded() + MDButtonText: + text: root.expand_text + + MDButton: + style: "text" + size_hint_x: None + width: dp(40) + on_release: root.test_clicked() + MDButtonIcon: + icon: "send" + + MDButton: + style: "text" + size_hint_x: None + width: dp(40) + on_release: root.delete_clicked() + MDButtonIcon: + icon: "delete" + + MDBoxLayout: + id: body + orientation: "vertical" + size_hint_y: None + height: (self.minimum_height + dp(8)) if root.expanded else 0 + opacity: 1 if root.expanded else 0 + disabled: not root.expanded + spacing: dp(4) + + MDLabel: + text: "Name (optional)" + font_size: sp(14) + size_hint_y: None + height: self.texture_size[1] + text_size: self.width, None + + MDTextField: + id: name_inp + mode: "outlined" + size_hint_x: 1 + size_hint_y: None + height: dp(56) + + MDLabel: + text: "Webhook URL (http:// or https://)" + font_size: sp(14) + size_hint_y: None + height: self.texture_size[1] + text_size: self.width, None + + MDTextField: + id: url_inp + mode: "outlined" + font_size: sp(14) + cursor: (0, 0) + size_hint_x: 1 + size_hint_y: None + height: dp(56) + + MDLabel: + text: root.secret_label + font_size: sp(14) + size_hint_y: None + height: self.texture_size[1] + text_size: self.width, None + + MDBoxLayout: + orientation: "horizontal" + size_hint_y: None + height: dp(56) + spacing: dp(4) + + MDTextField: + id: secret_inp + mode: "outlined" + password: True + size_hint_x: 1 + size_hint_y: None + height: dp(56) + + MDButton: + style: "text" + size_hint_x: None + width: dp(64) + on_release: root.clear_secret() + MDButtonIcon: + icon: "close" + + MDBoxLayout: + id: routing_box + orientation: "vertical" + size_hint_y: None + height: (self.minimum_height + dp(8)) if root.routing_visible else 0 + opacity: 1 if root.routing_visible else 0 + disabled: not root.routing_visible + spacing: dp(4) + + MDLabel: + text: "Route keyword (e.g. #sales; empty = catch-all)" + font_size: sp(14) + size_hint_y: None + height: self.texture_size[1] + text_size: self.width, None + + MDTextField: + id: keyword_inp + mode: "outlined" + size_hint_x: 1 + size_hint_y: None + height: dp(56) + + MDLabel: + text: "Prefix handling" + font_size: sp(14) + size_hint_y: None + height: self.texture_size[1] + text_size: self.width, None + + MDButton: + id: strip_btn + style: "tonal" + size_hint_y: None + height: dp(40) + on_release: root.open_strip_menu(self) + MDButtonText: + text: root.strip_label + + MDLabel: + text: "Allowed senders (empty = all; one per line or comma-separated)" + font_size: sp(14) + size_hint_y: None + height: self.texture_size[1] + text_size: self.width, None + + MDTextField: + id: allowed_inp + mode: "outlined" + multiline: True + size_hint_x: 1 + size_hint_y: None + height: dp(96) + + MDLabel: + text: "Last delivery" + font_size: sp(14) + size_hint_y: None + height: self.texture_size[1] + text_size: self.width, None + + MDLabel: + id: status_lbl + text: "No deliveries yet" + font_size: sp(14) + size_hint_y: None + height: self.texture_size[1] + text_size: self.width, None + : orientation: "vertical" @@ -114,65 +312,16 @@ MDListItemLeadingIcon: icon: "webhook" MDListItemHeadlineText: - text: "Webhook (Inbound SMS)" - MDListItemSupportingText: - text: "POST received SMS to a URL" - MDSwitch: - id: webhook_sw - pos_hint: {"center_y": 0.5} - icon_active: "check" - icon_inactive: "close" - icon_active_color: "green" - track_color_active: "green" - on_active: app.webhook_switch_active(self, self.active) - - MDListItem: - MDListItemLeadingIcon: - icon: "link" - MDListItemHeadlineText: - 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: - icon: "lock" - MDListItemHeadlineText: - text: "Signing Secret" + text: "Webhooks (Inbound SMS)" MDListItemSupportingText: - text: "Optional HMAC-SHA256" + text: "With 2+ enabled, a prefix keyword chooses the URL" MDBoxLayout: + id: webhook_cards_box 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: - icon: "information" - MDListItemHeadlineText: - text: "Last Webhook Delivery" - MDListItemSupportingText: - id: webhook_status_lbl - text: "No deliveries yet" + padding: [dp(8), 0, dp(8), 0] + spacing: dp(8) MDBoxLayout: orientation: "vertical" @@ -181,15 +330,14 @@ spacing: dp(8) MDButton: + id: add_webhook_btn style: "filled" pos_hint: {"center_x": .5} - on_release: app.send_webhook_test() + on_release: app.add_webhook_card() MDButtonIcon: - icon: "send" + icon: "plus" MDButtonText: - text: "Send Test Webhook" - - + text: "Add Webhook" ''') @@ -198,3 +346,129 @@ class SettingsBox(MDBoxLayout): class ApiKeyTxtbox(MDTextField): pass + + +class WebhookCard(MDBoxLayout): + """One editable Webhook card in the Settings list.""" + + enabled = BooleanProperty(False) + expanded = BooleanProperty(True) + routing_visible = BooleanProperty(True) + title_text = StringProperty("Webhook") + expand_text = StringProperty("Hide") + strip_label = StringProperty(STRIP_LABELS[DEFAULT_STRIP_MODE]) + secret_label = StringProperty("Signing secret (optional)") + secret_cleared = BooleanProperty(False) + + def __init__(self, app, webhook, index=0, **kwargs): + self.app = app + self.webhook = dict(webhook or {}) + self.index = index + self._strip_mode = self.webhook.get( + "strip_prefix", DEFAULT_STRIP_MODE + ) + if self._strip_mode not in STRIP_MODES: + self._strip_mode = DEFAULT_STRIP_MODE + self._strip_menu = None + self._secret_set = bool(self.webhook.get("secret_set")) + super().__init__(**kwargs) + self.ids.name_inp.text = self.webhook.get("name") or "" + self.ids.url_inp.text = self.webhook.get("url") or "" + self.ids.keyword_inp.text = self.webhook.get("keyword") or "" + self.ids.allowed_inp.text = "\n".join( + self.webhook.get("allowed_senders") or [] + ) + self.ids.url_inp.scroll_x = 0 + self.secret_label = ( + "Signing secret (a secret is set; leave blank to keep it)" + if self._secret_set + else "Signing secret (optional)" + ) + self.enabled = bool(self.webhook.get("enabled", False)) + self.ids.name_inp.bind(text=lambda *_: self._update_title()) + self.ids.url_inp.bind(text=lambda *_: self._update_title()) + self._update_title() + self._update_strip_label() + self.expanded = True + + def _update_title(self): + name = (self.ids.name_inp.text or "").strip() + url = (self.ids.url_inp.text or "").strip() + self.title_text = name or f"Webhook {self.index + 1}" + + def _update_strip_label(self): + self.strip_label = STRIP_LABELS.get( + self._strip_mode, STRIP_LABELS[DEFAULT_STRIP_MODE] + ) + + def toggle_expanded(self): + self.expanded = not self.expanded + self.expand_text = "Hide" if self.expanded else "Edit" + + def set_routing_visible(self, visible: bool): + self.routing_visible = bool(visible) + + def open_strip_menu(self, caller): + items = [ + { + "text": STRIP_LABELS[mode], + "on_release": ( + lambda *args, mode=mode: self.set_strip_mode(mode) + ), + } + for mode in STRIP_MODES + ] + self._strip_menu = MDDropdownMenu( + caller=caller, items=items, position="bottom" + ) + self._strip_menu.open() + + def set_strip_mode(self, mode: str): + if mode not in STRIP_MODES: + return + self._strip_mode = mode + self._update_strip_label() + if self._strip_menu is not None: + self._strip_menu.dismiss() + self._strip_menu = None + + def clear_secret(self): + self.ids.secret_inp.text = "" + self.secret_cleared = True + self.secret_label = "Signing secret (will be removed on Save)" + + def read(self) -> dict: + entry = { + "name": (self.ids.name_inp.text or "").strip(), + "enabled": bool(self.enabled), + "url": (self.ids.url_inp.text or "").strip(), + "keyword": (self.ids.keyword_inp.text or "").strip(), + "strip_prefix": self._strip_mode, + "allowed_senders": self._parse_senders(), + } + if self.webhook.get("id"): + entry["id"] = self.webhook["id"] + secret = self.ids.secret_inp.text or "" + if secret: + entry["secret"] = secret + elif self.secret_cleared: + entry["secret"] = "" + return entry + + def _parse_senders(self) -> list: + text = self.ids.allowed_inp.text or "" + senders = [] + for part in text.replace(",", "\n").splitlines(): + sender = part.strip() + if sender: + senders.append(sender) + return senders + + def test_clicked(self): + self.app.test_webhook_card(self) + + def delete_clicked(self): + self.app.delete_webhook_card(self) + + def set_status(self, text: str): + self.ids.status_lbl.text = text diff --git a/app/services/appSvc.py b/app/services/appSvc.py index 0fabccf..e64410c 100644 --- a/app/services/appSvc.py +++ b/app/services/appSvc.py @@ -106,6 +106,7 @@ def request_stop(signum=None, frame=None): "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(), + "outbox_pending_by_id": lambda: webhook_dispatcher.pending_by_id(), }) ## functions @@ -266,11 +267,15 @@ def process_inbound_inbox(): print(f"Could not enqueue inbound SMS from {payload['from']}: {e}") continue if queued: - print(f"Inbound SMS queued for webhook from: {payload['from']}") + print( + f"Inbound SMS queued for {len(queued)} webhook(s) from: " + f"{payload['from']}" + ) else: print( - "Inbound SMS not forwarded (webhook disabled or target " - f"invalid) from: {payload['from']}" + "Inbound SMS not forwarded (no enabled webhook, no route, " + "sender not allowed, or target invalid) from: " + f"{payload['from']}" ) # Only acknowledge once the Outbox has persisted the delivery. ack_inbox_message(item["path"]) @@ -283,6 +288,7 @@ def app_service_thread(): #global vars global api_started, sms_last_attempt + log_activities("OpenSMS service started") register_sms_receiver() write_resp() # blank the old file @@ -327,6 +333,7 @@ def app_service_thread(): api_server_control("stop") unregister_sms_receiver() webhook_dispatcher.stop() + log_activities("OpenSMS service stopped") print("OpenSMS service stopped") diff --git a/app/services/config.py b/app/services/config.py index f30cc80..fd9d215 100644 --- a/app/services/config.py +++ b/app/services/config.py @@ -1,4 +1,4 @@ """ The main source for app wide config """ -__version__ = "1.2.0" # App version +__version__ = "1.3.0" # App version app_name = "opensms" diff --git a/app/services/postApi.py b/app/services/postApi.py index 21cf631..362c3b2 100644 --- a/app/services/postApi.py +++ b/app/services/postApi.py @@ -1,4 +1,5 @@ import asyncio +import re import time from threading import Thread, Lock, Timer from os.path import join @@ -198,7 +199,45 @@ class SmsData(BaseModel): ] +class WebhookDeliveryRequest(BaseModel): + 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, + ) + capacity: StrictInt = Field( + ge=settingsSvc.CAPACITY_MIN, + le=settingsSvc.CAPACITY_MAX, + ) + + class Config: + extra = "forbid" + + +class WebhookEntryRequest(BaseModel): + id: StrictStr = None + name: StrictStr = None + enabled: StrictBool + url: StrictStr + secret: StrictStr = None + keyword: StrictStr + strip_prefix: StrictStr + allowed_senders: list[StrictStr] + + class Config: + extra = "forbid" + + class WebhookSettingsRequest(BaseModel): + """The deprecated 1.2.0 single-Webhook body.""" + enabled: StrictBool url: StrictStr timeout: StrictInt = Field( @@ -212,8 +251,6 @@ class WebhookSettingsRequest(BaseModel): 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, @@ -224,29 +261,29 @@ class WebhookSettingsRequest(BaseModel): max_length=settingsSvc.SECRET_MAX_LENGTH, ) + def __init__(self, **data): + if ( + "secret" in data + and data["secret"] is None + ): + raise ValueError("webhook.secret must be a string") + super().__init__(**data) + class Config: extra = "forbid" class SettingsRequest(BaseModel): revision: StrictInt = None - port: StrictInt = Field( - ge=settingsSvc.PORT_MIN, - le=settingsSvc.PORT_MAX, - ) + port: StrictInt boot: StrictBool - webhook: WebhookSettingsRequest + webhook_delivery: WebhookDeliveryRequest = None + webhooks: list[WebhookEntryRequest] = None + webhook: WebhookSettingsRequest = None 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: @@ -277,6 +314,16 @@ def _model_dump(model): return model.dict(exclude_unset=True) +def _display_path(parts) -> str: + display = "" + for part in parts: + if part.isdigit(): + display += f"[{part}]" + else: + display += ("." if display else "") + part + return display + + def _request_validation_detail(exc: RequestValidationError) -> str: errors = exc.errors() if not errors: @@ -290,7 +337,7 @@ def _request_validation_detail(exc: RequestValidationError) -> str: for part in loc if str(part) not in ("body", "__root__") ] - field = ".".join(field_parts) + field = _display_path(field_parts) message = str(error.get("msg", "")) if error_type in {"json_invalid", "value_error.jsondecode"}: @@ -304,28 +351,36 @@ def _request_validation_detail(exc: RequestValidationError) -> str: 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 { + grouped = {} + for item in errors: + if str(item.get("type", "")) not 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)}" + }: + continue + parts = [ + str(part) + for part in item.get("loc", ()) + if str(part) not in ("body", "__root__") + ] + if not parts: + continue + parent = _display_path(parts[:-1]) or "request" + grouped.setdefault(parent, set()).add(parts[-1]) + if grouped: + parent, names = next(iter(grouped.items())) + return ( + f"Unknown field(s) in {parent}: " + + ", ".join(sorted(names)) + ) + return "Unknown field(s) in request" if error_type in {"missing", "value_error.missing"}: if not field_parts: return "Request body must be valid JSON" - if "webhook" in field_parts: + if field_parts[0] == "webhook": return f"Missing required webhook field: {field_parts[-1]}" - return f"Missing required field: {field_parts[-1]}" + return f"Missing required field: {field}" if not field_parts and error_type in { "model_attributes_type", @@ -346,50 +401,123 @@ def _request_validation_detail(exc: RequestValidationError) -> str: ) if field == "boot": return "boot must be a boolean" + if field == "webhook_delivery": + return "webhook_delivery must be an object" + if field == "webhooks": + return "webhooks must be a list" 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", - }: + + if field.startswith("webhook_delivery."): + name = field.split(".", 1)[1] + if name == "timeout": return ( - f"webhook.secret must be at most " - f"{settingsSvc.SECRET_MAX_LENGTH} characters" + "webhook_delivery.timeout must be an integer between " + f"{settingsSvc.TIMEOUT_MIN} and {settingsSvc.TIMEOUT_MAX}" ) - return "webhook.secret must be a string" + if name == "max_attempts": + return ( + "webhook_delivery.max_attempts must be an integer between " + f"{settingsSvc.MAX_ATTEMPTS_MIN} and " + f"{settingsSvc.MAX_ATTEMPTS_MAX}" + ) + if name == "backoff": + return ( + "webhook_delivery.backoff must be a list of " + f"{settingsSvc.BACKOFF_MIN_COUNT}-" + f"{settingsSvc.BACKOFF_MAX_COUNT} integers" + ) + if name.startswith("backoff["): + return ( + f"webhook_delivery.{name} must be an integer between 1 and " + f"{settingsSvc.BACKOFF_MAX_SECONDS}" + ) + if name == "capacity": + return ( + "webhook_delivery.capacity must be an integer between " + f"{settingsSvc.CAPACITY_MIN} and {settingsSvc.CAPACITY_MAX}" + ) + + webhook_match = re.match( + r"^webhooks\[(\d+)\](?:\.(.+))?$", field + ) + if webhook_match: + index, name = webhook_match.groups() + prefix = f"webhooks[{index}]" + if not name: + return f"{prefix} must be an object" + if name == "enabled": + return f"{prefix}.enabled must be a boolean" + if name == "url": + return f"{prefix}.url must be a string" + if name == "keyword": + return f"{prefix}.keyword must be a string" + if name == "strip_prefix": + return f"{prefix}.strip_prefix must be a string" + if name == "allowed_senders": + return f"{prefix}.allowed_senders must be a list" + if name.startswith("allowed_senders["): + return f"{prefix}.{name} must be a string" + if name == "id": + return f"{prefix}.id must be a string" + if name == "name": + return f"{prefix}.name must be a string" + if name == "secret": + if error_type in { + "string_too_long", + "value_error.any_str.max_length", + }: + return ( + f"{prefix}.secret must be at most " + f"{settingsSvc.SECRET_MAX_LENGTH} characters" + ) + return f"{prefix}.secret must be a string" + return f"{prefix}.{name}: {message.removeprefix('Value error, ')}" + + if field.startswith("webhook."): + name = field.split(".", 1)[1] + if name == "enabled": + return "webhook.enabled must be a boolean" + if name == "url": + return "webhook.url must be a string" + if name == "timeout": + return ( + "webhook.timeout must be an integer between " + f"{settingsSvc.TIMEOUT_MIN} and {settingsSvc.TIMEOUT_MAX}" + ) + if name == "max_attempts": + return ( + "webhook.max_attempts must be an integer between " + f"{settingsSvc.MAX_ATTEMPTS_MIN} and " + f"{settingsSvc.MAX_ATTEMPTS_MAX}" + ) + if name == "backoff": + return ( + "webhook.backoff must be a list of " + f"{settingsSvc.BACKOFF_MIN_COUNT}-" + f"{settingsSvc.BACKOFF_MAX_COUNT} integers" + ) + if name.startswith("backoff["): + return ( + f"webhook.{name} must be an integer between 1 and " + f"{settingsSvc.BACKOFF_MAX_SECONDS}" + ) + if name == "capacity": + return ( + "webhook.capacity must be an integer between " + f"{settingsSvc.CAPACITY_MIN} and {settingsSvc.CAPACITY_MAX}" + ) + if name == "secret": + if error_type in { + "string_too_long", + "value_error.any_str.max_length", + }: + return ( + "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": @@ -635,9 +763,9 @@ def entries(name: str) -> list: return {"wifi": entries("wifi"), "ethernet": entries("ethernet")} -def _last_delivery(config_dir: str) -> dict | None: +def _last_delivery(config_dir: str, webhook_id: str) -> dict | None: status = webhookSvc.read_webhook_status( - join(config_dir, "webhook_status.json") + join(config_dir, "webhook_status.json"), webhook_id ) if not status: return None @@ -655,31 +783,63 @@ def _last_delivery(config_dir: str) -> dict | None: } -def _webhook_status( +def _webhooks_status( settings: dict | None, config_dir: str, warnings: list ) -> dict: pending = _status_runtime("outbox_pending") - 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 + pending_by_id = _status_runtime("outbox_pending_by_id", {}) + if not isinstance(pending_by_id, dict): + pending_by_id = {} + if settings is None: + delivery = webhookSvc.normalize_webhook_delivery(None) + raw_webhooks = [] 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"]: + delivery = webhookSvc.normalize_webhook_delivery( + settings.get("webhook_delivery") + ) + raw_webhooks = settings.get("webhooks") + if not isinstance(raw_webhooks, list): + raw_webhooks = [] + capacity = delivery["capacity"] + + webhooks = [] + entries = [] + enabled_count = 0 + has_catch_all = False + for index, raw_webhook in enumerate(raw_webhooks): + if not isinstance(raw_webhook, dict): + continue + webhook = webhookSvc.normalize_webhook_entry(raw_webhook, index) + entries.append(webhook) + if webhook["enabled"]: + enabled_count += 1 + if not webhook["keyword"]: + has_catch_all = True + last_delivery = _last_delivery(config_dir, webhook["id"]) + if last_delivery and isinstance(last_delivery.get("error"), str): + error = last_delivery["error"] + if not webhook["url"] and error not in { + "webhook disabled", + "webhook removed", + "retry limit reached", + "dispatcher stopped", + }: + last_delivery["error"] = "Webhook delivery failed." + else: + last_delivery["error"] = _scrub_webhook_target( + webhook["url"], error + ) + webhooks.append({ + "id": webhook["id"], + "name": webhook["name"], + "enabled": webhook["enabled"], + "url_host": webhookSvc.target_host(webhook["url"]), + "secret_set": bool(webhook["secret"]), + "pending": pending_by_id.get(webhook["id"], 0), + "last_delivery": last_delivery, + }) + + if enabled_count == 0: warnings.append({ "code": "webhook_disabled", "message": ( @@ -687,19 +847,31 @@ def _webhook_status( "discarded." ), }) - elif not webhookSvc.is_valid_target(effective_webhook["url"]): - warnings.append({ - "code": "webhook_url_invalid", - "message": ( - "Webhook forwarding is enabled with an invalid Webhook target." - ), - }) + else: + for webhook in entries: + if webhook["enabled"] and not webhookSvc.is_valid_target( + webhook["url"] + ): + warnings.append({ + "code": "webhook_url_invalid", + "webhook_id": webhook["id"], + "message": ( + f"Webhook {webhook['name'] or webhook['id']} is " + "enabled with an invalid Webhook target." + ), + }) + if enabled_count >= 2 and not has_catch_all: + warnings.append({ + "code": "webhook_unrouted", + "message": ( + "No catch-all Webhook is configured: Inbound SMS that " + "match no route keyword are discarded." + ), + }) 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 ): @@ -711,19 +883,10 @@ def _webhook_status( ), }) - 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": enabled, - "url_host": url_host, - "secret_set": secret_set, + "webhooks": webhooks, "outbox_pending": pending, "outbox_capacity": capacity, - "last_delivery": last_delivery, } @@ -739,7 +902,7 @@ async def api_status( warnings: list = [] network = _network_status(warnings) - webhook = _webhook_status(settings, config_dir, warnings) + webhook_status = _webhooks_status(settings, config_dir, warnings) return { "version": __version__, @@ -762,7 +925,9 @@ async def api_status( else None ), "network": network, - "webhook": webhook, + "webhooks": webhook_status["webhooks"], + "outbox_pending": webhook_status["outbox_pending"], + "outbox_capacity": webhook_status["outbox_capacity"], "warnings": warnings, } @@ -775,9 +940,10 @@ async def api_get_settings( def _settings_body(settings: dict) -> dict: writable = settingsSvc.writable_settings(settings) - writable["webhook"]["url"] = webhookSvc.redact_target_credentials( - writable["webhook"]["url"] - ) + for webhook in writable["webhooks"]: + webhook["url"] = webhookSvc.redact_target_credentials( + webhook["url"] + ) return { "revision": settingsSvc.get_revision(settings), "settings": writable, @@ -785,10 +951,18 @@ def _settings_body(settings: dict) -> dict: 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) + fields = ["port", "boot", "webhook_delivery"] + webhooks = payload.get("webhooks") + if isinstance(webhooks, list): + for index, webhook in enumerate(webhooks): + if isinstance(webhook, dict): + fields.extend( + f"webhooks[{index}].{field}" for field in webhook + ) + elif isinstance(payload.get("webhook"), dict): + fields.extend( + f"webhook.{field}" for field in payload["webhook"] + ) return "Settings updated: " + ", ".join(fields) def _restart_required(settings: dict) -> bool: @@ -923,19 +1097,30 @@ async def api_delete_key( if not deleted: raise HTTPException(status_code=404, detail="API key not found") -WEBHOOK_TEST_FIELDS = {"url", "secret"} +WEBHOOK_TEST_FIELDS = {"id", "url", "secret"} 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 "id" in payload: + if not isinstance(payload["id"], str): + raise HTTPException( + status_code=422, detail="id must be a string" + ) + overrides["id"] = payload["id"] 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 "id" in overrides and "url" in overrides: + raise HTTPException( + status_code=422, + detail="id and url cannot be combined", + ) if "secret" in payload: secret = payload["secret"] if not isinstance(secret, str): @@ -955,15 +1140,61 @@ def _webhook_test_overrides(payload: dict) -> dict: def _resolve_webhook_test_config(settings: dict, overrides: dict) -> tuple: - """Resolve the target, secret and timeout for one test delivery. + """Resolve the target, secret, timeout and id 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. + An `id` selects a saved Webhook. With no id and no url, the only configured + Webhook is used; several configured Webhooks require an explicit id. A url + override tests an unsaved target. An empty secret means unsigned delivery. """ - webhook = settings.get("webhook") - if not isinstance(webhook, dict): - webhook = {} - url = overrides.get("url", webhook.get("url", "")) + raw_webhooks = settings.get("webhooks") + if not isinstance(raw_webhooks, list): + raw_webhooks = [] + entries = [ + webhookSvc.normalize_webhook_entry(entry, index) + for index, entry in enumerate(raw_webhooks) + if isinstance(entry, dict) + ] + + selected = None + if "id" in overrides: + selected = next( + ( + entry for entry in entries + if entry["id"] == overrides["id"] + ), + None, + ) + if selected is None: + raise HTTPException( + status_code=404, detail="Webhook not found" + ) + elif "url" not in overrides: + if not entries: + raise HTTPException( + status_code=400, + detail=( + "A valid http(s) Webhook target is required to send a test" + ), + ) + if len(entries) > 1: + raise HTTPException( + status_code=422, + detail=( + "id is required when more than one Webhook is configured" + ), + ) + selected = entries[0] + + if selected is not None: + url = selected["url"] + secret = selected["secret"] + else: + url = "" + secret = entries[0]["secret"] if len(entries) == 1 else "" + + if "url" in overrides: + url = overrides["url"] + secret = overrides.get("secret", secret) if not webhookSvc.is_valid_target(url): raise HTTPException( status_code=400, @@ -971,12 +1202,11 @@ def _resolve_webhook_test_config(settings: dict, overrides: dict) -> tuple: "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) - timeout = webhookSvc.normalize_webhook_config(webhook)["timeout"] - return url, secret, timeout + timeout = webhookSvc.normalize_webhook_delivery( + settings.get("webhook_delivery") + )["timeout"] + webhook_id = selected["id"] if selected is not None else None + return url, secret, timeout, webhook_id def _scrub_webhook_target(url: object, error: str) -> str: @@ -1013,13 +1243,16 @@ async def api_webhook_test( 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) + url, secret, timeout, webhook_id = _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, + webhook_id=webhook_id, ) if ok: log_activities(f"Webhook test delivered (HTTP {status})") diff --git a/app/services/settingsSvc.py b/app/services/settingsSvc.py index a320f77..7194e0a 100644 --- a/app/services/settingsSvc.py +++ b/app/services/settingsSvc.py @@ -8,46 +8,84 @@ import json import math import os +import re import tempfile import threading from services.config import app_name from services.webhookSvc import ( + ALLOWED_SENDERS_MAX, BACKOFF_MAX_COUNT, BACKOFF_MAX_SECONDS, BACKOFF_MIN_COUNT, CAPACITY_MAX, CAPACITY_MIN, + DEFAULT_STRIP_MODE, + KEYWORD_MAX_LENGTH, + LEGACY_WEBHOOK_ID, MAX_ATTEMPTS_MAX, MAX_ATTEMPTS_MIN, + MAX_WEBHOOKS, + NAME_MAX_LENGTH, + SENDER_MAX_LENGTH, + STRIP_MODES, TIMEOUT_MAX, TIMEOUT_MIN, - default_webhook_config, + default_webhook_delivery, has_target_credentials, + is_valid_keyword, is_valid_target, - normalize_webhook_config, + normalize_allowed_senders, + normalize_webhook_delivery, + normalize_webhook_entry, + new_webhook_id, ) -DEFAULT_PORT = 9292 -DEFAULT_BOOT = False - # Port range from the API contract in docs/remote-api.md. The Webhook retry # ranges live with the delivery defaults in webhookSvc. +DEFAULT_PORT = 9292 +DEFAULT_BOOT = False PORT_MIN = 1025 PORT_MAX = 65535 SECRET_MAX_LENGTH = 256 -TOP_LEVEL_FIELDS = {"port", "boot", "webhook", "revision"} -REQUIRED_TOP_LEVEL_FIELDS = ("port", "boot", "webhook") -WRITABLE_WEBHOOK_FIELDS = ( +TOP_LEVEL_FIELDS = { + "port", + "boot", + "webhook_delivery", + "webhooks", + "revision", +} +LEGACY_TOP_LEVEL_FIELDS = TOP_LEVEL_FIELDS | {"webhook"} +REQUIRED_TOP_LEVEL_FIELDS = ("port", "boot", "webhook_delivery", "webhooks") +DELIVERY_FIELDS = {"timeout", "max_attempts", "backoff", "capacity"} +WEBHOOK_ENTRY_FIELDS = { + "id", + "name", + "enabled", + "url", + "secret", + "keyword", + "strip_prefix", + "allowed_senders", +} +REQUIRED_WEBHOOK_ENTRY_FIELDS = ( "enabled", "url", + "keyword", + "strip_prefix", + "allowed_senders", +) +LEGACY_WEBHOOK_FIELDS = { + "enabled", + "url", + "secret", "timeout", "max_attempts", "backoff", "capacity", -) -WEBHOOK_FIELDS = set(WRITABLE_WEBHOOK_FIELDS) | {"secret"} +} +WEBHOOK_ID_PATTERN = re.compile(r"^wh_[a-z0-9]{6,16}$") class SettingsValidationError(ValueError): @@ -76,8 +114,8 @@ class SettingsLoadError(ValueError): ## Defaults def default_webhook_settings() -> dict: - """Return the dispatcher-owned defaults in the persisted Settings shape.""" - return default_webhook_config() + """Return the dispatcher-owned delivery defaults.""" + return default_webhook_delivery() def default_settings() -> dict: return { @@ -86,7 +124,8 @@ def default_settings() -> dict: "boot": DEFAULT_BOOT, "permissions": False, "revision": 0, - "webhook": default_webhook_settings(), + "webhook_delivery": default_webhook_settings(), + "webhooks": [], } ## Load @@ -102,15 +141,56 @@ def _finite_json_float(value: str) -> float: return number +def _legacy_webhook_entry(legacy: dict) -> dict: + """Migrate the single legacy Webhook object into one array entry.""" + extras = { + key: value for key, value in legacy.items() + if key not in LEGACY_WEBHOOK_FIELDS + } + entry = normalize_webhook_entry( + { + **extras, + "id": LEGACY_WEBHOOK_ID, + "enabled": legacy.get("enabled", False), + "url": legacy.get("url", ""), + "secret": legacy.get("secret", ""), + "keyword": "", + "strip_prefix": DEFAULT_STRIP_MODE, + "allowed_senders": [], + }, + keep_unknown=True, + ) + entry["id"] = LEGACY_WEBHOOK_ID + return entry + +def _normalize_stored_webhooks(raw_webhooks) -> list: + if not isinstance(raw_webhooks, list): + return [] + entries = [] + seen_ids = set() + for index, raw_entry in enumerate(raw_webhooks): + if not isinstance(raw_entry, dict): + continue + entry = normalize_webhook_entry( + raw_entry, index, keep_unknown=True + ) + if entry["id"] in seen_ids: + entry["id"] = f"wh_{index:08x}" + while entry["id"] in seen_ids: + entry["id"] = new_webhook_id() + seen_ids.add(entry["id"]) + entries.append(entry) + return entries + 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 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. + Unknown fields, at the top level and inside each Webhook entry, are kept + so a later write can preserve them. A missing file always means defaults. + A legacy single `webhook` object is migrated to a one-element `webhooks` + array; the next write persists the new shape. With ``strict=True``, an + existing file that cannot be read as a JSON object raises + ``SettingsLoadError`` so callers can report unknown instead of defaults. """ settings = default_settings() try: @@ -133,15 +213,39 @@ def load_settings(config_path: str, *, strict: bool = False) -> dict: if strict: raise SettingsLoadError("Existing Settings must be a JSON object") return settings + for key, value in raw.items(): - if key == "webhook": + if key in ("webhook", "webhooks", "webhook_delivery"): continue settings[key] = value - 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 + + legacy = raw.get("webhook") + if "webhooks" in raw: + if isinstance(legacy, dict): + print( + "Both webhooks and a legacy webhook exist in config; " + "using webhooks and ignoring the legacy object." + ) + settings["webhooks"] = _normalize_stored_webhooks(raw.get("webhooks")) + delivery_raw = raw.get("webhook_delivery") + if isinstance(delivery_raw, dict): + settings["webhook_delivery"] = normalize_webhook_delivery( + delivery_raw, keep_unknown=True + ) + elif isinstance(legacy, dict): + settings["webhook_delivery"] = normalize_webhook_delivery(legacy) + else: + settings["webhook_delivery"] = normalize_webhook_delivery(None) + elif isinstance(legacy, dict): + settings["webhooks"] = [_legacy_webhook_entry(legacy)] + settings["webhook_delivery"] = normalize_webhook_delivery(legacy) + else: + settings["webhooks"] = [] + delivery_raw = raw.get("webhook_delivery") + settings["webhook_delivery"] = normalize_webhook_delivery( + delivery_raw, + keep_unknown=isinstance(delivery_raw, dict), + ) return settings def get_revision(settings: dict) -> int: @@ -167,143 +271,357 @@ def _unknown_field_error(prefix: str, unknown) -> SettingsValidationError: 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_valid_port(port): +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"port must be an integer between {PORT_MIN} and {PORT_MAX}" + f"{name} must be an integer between {low} and {high}" ) + return value - 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: +def _validate_backoff(value, prefix: str = "webhook_delivery.backoff") -> list: + if not isinstance(value, list) or not ( + BACKOFF_MIN_COUNT <= len(value) <= BACKOFF_MAX_COUNT + ): + raise SettingsValidationError( + f"{prefix} 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"Missing required webhook field: {field}" + f"{prefix}[{index}] must be an integer between 1 and " + f"{BACKOFF_MAX_SECONDS}" ) + normalized.append(wait_for) + return normalized - 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, +def _validate_delivery(value) -> dict: + if not isinstance(value, dict): + raise SettingsValidationError("webhook_delivery must be an object") + unknown = set(value) - DELIVERY_FIELDS + if unknown: + raise _unknown_field_error("webhook_delivery", unknown) + missing = DELIVERY_FIELDS - set(value) + if missing: + raise SettingsValidationError( + "Missing required webhook_delivery field: " + + ", ".join(sorted(missing)) + ) + return { "timeout": _validate_int_range( - webhook["timeout"], - "webhook.timeout", + value["timeout"], + "webhook_delivery.timeout", TIMEOUT_MIN, TIMEOUT_MAX, ), "max_attempts": _validate_int_range( - webhook["max_attempts"], - "webhook.max_attempts", + value["max_attempts"], + "webhook_delivery.max_attempts", MAX_ATTEMPTS_MIN, MAX_ATTEMPTS_MAX, ), - "backoff": _validate_backoff(webhook["backoff"]), + "backoff": _validate_backoff(value["backoff"]), "capacity": _validate_int_range( - webhook["capacity"], - "webhook.capacity", + value["capacity"], + "webhook_delivery.capacity", CAPACITY_MIN, CAPACITY_MAX, ), } - if "secret" in webhook: - secret = webhook["secret"] + +def _validate_webhook_entry( + value, index: int, *, check_secret_length: bool = True +) -> dict: + prefix = f"webhooks[{index}]" + if not isinstance(value, dict): + raise SettingsValidationError(f"{prefix} must be an object") + unknown = set(value) - WEBHOOK_ENTRY_FIELDS + if unknown: + raise _unknown_field_error(prefix, unknown) + missing = [ + field for field in REQUIRED_WEBHOOK_ENTRY_FIELDS + if field not in value + ] + if missing: + raise SettingsValidationError( + f"Missing required {prefix} field: " + ", ".join(missing) + ) + + enabled = value["enabled"] + if not isinstance(enabled, bool): + raise SettingsValidationError(f"{prefix}.enabled must be a boolean") + + url = value["url"] + if not isinstance(url, str): + raise SettingsValidationError(f"{prefix}.url must be a string") + + keyword = value["keyword"] + if not isinstance(keyword, str): + raise SettingsValidationError(f"{prefix}.keyword must be a string") + keyword = keyword.strip() + if not is_valid_keyword(keyword): + raise SettingsValidationError( + f"{prefix}.keyword must be 1-{KEYWORD_MAX_LENGTH} characters: " + "letters, digits, #, _ or - (empty means catch-all)" + ) + + strip_prefix = value["strip_prefix"] + if strip_prefix not in STRIP_MODES: + raise SettingsValidationError( + f"{prefix}.strip_prefix must be one of: " + + ", ".join(STRIP_MODES) + ) + + allowed_senders = value["allowed_senders"] + if not isinstance(allowed_senders, list): + raise SettingsValidationError( + f"{prefix}.allowed_senders must be a list of strings" + ) + if len(allowed_senders) > ALLOWED_SENDERS_MAX: + raise SettingsValidationError( + f"{prefix}.allowed_senders must hold at most " + f"{ALLOWED_SENDERS_MAX} entries" + ) + normalized_senders = [] + for sender_index, sender in enumerate(allowed_senders): + if not isinstance(sender, str): + raise SettingsValidationError( + f"{prefix}.allowed_senders[{sender_index}] must be a string" + ) + sender = sender.strip() + if not sender or len(sender) > SENDER_MAX_LENGTH: + raise SettingsValidationError( + f"{prefix}.allowed_senders[{sender_index}] must be 1-" + f"{SENDER_MAX_LENGTH} characters" + ) + normalized_senders.append(sender) + normalized_senders = normalize_allowed_senders(normalized_senders) + + normalized = { + "enabled": enabled, + "url": url.strip(), + "keyword": keyword, + "strip_prefix": strip_prefix, + "allowed_senders": normalized_senders, + } + if "id" in value: + webhook_id = value["id"] + if not isinstance(webhook_id, str) or not WEBHOOK_ID_PATTERN.match( + webhook_id + ): + raise SettingsValidationError( + f"{prefix}.id must look like wh_ followed by 6-16 lowercase " + "letters or digits" + ) + normalized["id"] = webhook_id + if "name" in value: + name = value["name"] + if not isinstance(name, str): + raise SettingsValidationError(f"{prefix}.name must be a string") + if len(name.strip()) > NAME_MAX_LENGTH: + raise SettingsValidationError( + f"{prefix}.name must be at most {NAME_MAX_LENGTH} characters" + ) + normalized["name"] = name.strip() + if "secret" in value: + secret = value["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" + f"{prefix}.secret must be a string" ) - normalized_webhook["secret"] = secret + if check_secret_length and len(secret) > SECRET_MAX_LENGTH: + raise SettingsValidationError( + f"{prefix}.secret must be at most " + f"{SECRET_MAX_LENGTH} characters" + ) + normalized["secret"] = secret + return normalized + + +def _validate_webhooks(value, *, check_secret_length: bool = True) -> list: + if not isinstance(value, list): + raise SettingsValidationError("webhooks must be a list") + if len(value) > MAX_WEBHOOKS: + raise SettingsValidationError( + f"webhooks must hold at most {MAX_WEBHOOKS} entries" + ) + normalized = [] + seen_ids = set() + for index, entry in enumerate(value): + normalized_entry = _validate_webhook_entry( + entry, index, check_secret_length=check_secret_length + ) + webhook_id = normalized_entry.get("id") + if webhook_id is not None: + if webhook_id in seen_ids: + raise SettingsValidationError( + f"Duplicate webhook id: {webhook_id}" + ) + seen_ids.add(webhook_id) + normalized.append(normalized_entry) + return normalized + + +def _validate_legacy_webhook(value) -> dict: + if not isinstance(value, dict): + raise SettingsValidationError("webhook must be an object") + unknown = set(value) - LEGACY_WEBHOOK_FIELDS + if unknown: + raise _unknown_field_error("webhook", unknown) + required = ("enabled", "url", "timeout", "max_attempts", "backoff", "capacity") + for field in required: + if field not in value: + raise SettingsValidationError( + f"Missing required webhook field: {field}" + ) + entry = _validate_webhook_entry( + { + "enabled": value["enabled"], + "url": value["url"], + "keyword": "", + "strip_prefix": _default_strip_mode(), + "allowed_senders": [], + **( + {"secret": value["secret"]} + if "secret" in value + else {} + ), + }, + 0, + ) + delivery = _validate_delivery({ + "timeout": value["timeout"], + "max_attempts": value["max_attempts"], + "backoff": value["backoff"], + "capacity": value["capacity"], + }) + return {"webhook": entry, "webhook_delivery": delivery} + + +def _default_strip_mode() -> str: + return DEFAULT_STRIP_MODE + + +def validate_settings_payload( + payload, *, check_secret_length: bool = True +) -> 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`. + The legacy single `webhook` object is accepted as a one-release shim and + marked with an internal `_legacy_shim` flag for id reuse. + """ + if not isinstance(payload, dict): + raise SettingsValidationError("Request body must be a JSON object") + + allowed_top_level = ( + LEGACY_TOP_LEVEL_FIELDS if "webhook" in payload else TOP_LEVEL_FIELDS + ) + unknown = set(payload) - allowed_top_level + if unknown: + raise _unknown_field_error("request", unknown) + + if "webhook" in payload: + if "webhooks" in payload or "webhook_delivery" in payload: + raise SettingsValidationError( + "webhook cannot be combined with webhooks or webhook_delivery" + ) + for field in ("port", "boot", "webhook"): + 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") + legacy = _validate_legacy_webhook(payload["webhook"]) + normalized = { + "port": _validate_port(payload["port"]), + "boot": _validate_boot(payload["boot"]), + "webhook_delivery": legacy["webhook_delivery"], + "webhooks": [legacy["webhook"]], + "_legacy_shim": True, + } + if "revision" in payload: + normalized["revision"] = revision + return normalized + + 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") normalized = { - "port": port, - "boot": boot, - "webhook": normalized_webhook, + "port": _validate_port(payload["port"]), + "boot": _validate_boot(payload["boot"]), + "webhook_delivery": _validate_delivery(payload["webhook_delivery"]), + "webhooks": _validate_webhooks( + payload["webhooks"], check_secret_length=check_secret_length + ), } 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: +def _validate_port(value) -> int: + if not is_valid_port(value): raise SettingsValidationError( - f"{name} must be an integer between {low} and {high}" + f"port must be an integer between {PORT_MIN} and {PORT_MAX}" ) 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_boot(value) -> bool: + if not isinstance(value, bool): + raise SettingsValidationError("boot must be a boolean") + return value 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" - ) + webhooks = writable["webhooks"] + seen_keywords = {} + catch_all_index = None + for index, webhook in enumerate(webhooks): + prefix = f"webhooks[{index}]" + if has_target_credentials(webhook["url"]): + raise SettingsRuleError( + f"{prefix}.url must not contain credentials" + ) + if webhook["enabled"] and not is_valid_target(webhook["url"]): + raise SettingsRuleError( + f"{prefix}.url must be a valid http(s) URL when " + f"{prefix}.enabled is true" + ) + keyword = webhook["keyword"] + if not keyword: + if catch_all_index is not None: + raise SettingsRuleError( + "Only one catch-all Webhook (empty keyword) is allowed; " + f"{prefix} duplicates webhooks[{catch_all_index}]" + ) + catch_all_index = index + continue + folded = keyword.casefold() + if folded in seen_keywords: + raise SettingsRuleError( + f"Duplicate Webhook keyword: {keyword} " + f"({prefix} duplicates webhooks[{seen_keywords[folded]}])" + ) + seen_keywords[folded] = index def validate_merged_settings(settings: dict): @@ -313,46 +631,67 @@ def validate_merged_settings(settings: dict): 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(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({ - "port": settings.get("port"), - "boot": settings.get("boot"), - "webhook": { - field: webhook.get(field) - for field in WRITABLE_WEBHOOK_FIELDS + webhooks = settings.get("webhooks") + if not isinstance(webhooks, list): + raise SettingsValidationError("webhooks must be a list") + validate_settings_payload( + { + "port": settings.get("port"), + "boot": settings.get("boot"), + "webhook_delivery": { + field: (settings.get("webhook_delivery") or {}).get(field) + for field in DELIVERY_FIELDS + }, + "webhooks": [ + { + key: value + for key, value in webhook.items() + if key in WEBHOOK_ENTRY_FIELDS + } + for webhook in webhooks + ], }, - }) + check_secret_length=False, + ) ## API shape def writable_settings(settings: dict) -> dict: - """Return only the writable subset, with the secret masked. + """Return only the writable subset, with every 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 = {} - retry = normalize_webhook_config(webhook) + delivery = normalize_webhook_delivery( + settings.get("webhook_delivery") + ) + raw_webhooks = settings.get("webhooks") + entries = [] + if isinstance(raw_webhooks, list): + for index, raw_entry in enumerate(raw_webhooks): + entry = normalize_webhook_entry(raw_entry, index) + entries.append({ + "id": entry["id"], + "name": entry["name"], + "enabled": entry["enabled"], + "url": entry["url"], + "secret_set": bool(entry["secret"]), + "keyword": entry["keyword"], + "strip_prefix": entry["strip_prefix"], + "allowed_senders": list(entry["allowed_senders"]), + }) 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": retry["timeout"], - "max_attempts": retry["max_attempts"], - "backoff": list(retry["backoff"]), - "capacity": retry["capacity"], + "webhook_delivery": { + "timeout": delivery["timeout"], + "max_attempts": delivery["max_attempts"], + "backoff": list(delivery["backoff"]), + "capacity": delivery["capacity"], }, + "webhooks": entries, } ## Writes @@ -362,39 +701,102 @@ def writable_settings(settings: dict) -> dict: _write_lock = threading.Lock() +def _existing_webhook_entries(settings: dict) -> dict: + raw = settings.get("webhooks") + if not isinstance(raw, list): + return {} + entries = {} + for index, entry in enumerate(raw): + if isinstance(entry, dict): + normalized = normalize_webhook_entry(entry, index) + entries[normalized["id"]] = normalized + return entries + + 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. + The secret follows sentinel semantics: absent from an entry keeps that + Webhook's stored secret, so this function only writes it when the payload + carried it. Unknown fields are preserved per Webhook id. """ updated = dict(settings) + updated.pop("webhook", None) 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 + + existing_delivery = updated.get("webhook_delivery") + delivery = ( + dict(existing_delivery) + if isinstance(existing_delivery, dict) + else {} + ) + incoming_delivery = writable["webhook_delivery"] + for field in DELIVERY_FIELDS: + delivery[field] = incoming_delivery[field] + delivery["backoff"] = list(incoming_delivery["backoff"]) + updated["webhook_delivery"] = delivery + + existing = _existing_webhook_entries(updated) + previous_raw = {} + if isinstance(updated.get("webhooks"), list): + for index, entry in enumerate(updated["webhooks"]): + if isinstance(entry, dict): + normalized = normalize_webhook_entry(entry, index) + previous_raw[normalized["id"]] = entry + entries = [] + for incoming in writable["webhooks"]: + webhook_id = incoming.get("id") + if webhook_id: + merged = dict(previous_raw.get(webhook_id, {})) + else: + merged = {} + for field in ( + "name", "enabled", "url", "keyword", "strip_prefix", + "allowed_senders", + ): + if field in incoming: + merged[field] = ( + list(incoming[field]) + if field == "allowed_senders" + else incoming[field] + ) + if "secret" in incoming: + merged["secret"] = incoming["secret"] + elif webhook_id and webhook_id in existing: + merged["secret"] = existing[webhook_id]["secret"] + else: + merged.setdefault("secret", "") + if webhook_id: + merged["id"] = webhook_id + else: + merged["id"] = _new_unique_id(existing, entries) + entries.append(merged) + updated["webhooks"] = entries return updated +def _new_unique_id(existing: dict, entries: list) -> str: + used = set(existing) + used.update(entry["id"] for entry in entries) + webhook_id = new_webhook_id() + while webhook_id in used: + webhook_id = new_webhook_id() + return webhook_id + + 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. + delivery policy, secrets the form left untouched, and every internal or + unknown on-disk field. A full `webhooks` list replaces the list by id, so + removing a card removes that Webhook. """ if not isinstance(form, dict): raise SettingsValidationError("Request body must be a JSON object") - unknown = set(form) - TOP_LEVEL_FIELDS + unknown = set(form) - LEGACY_TOP_LEVEL_FIELDS if unknown: raise _unknown_field_error("request", unknown) @@ -402,24 +804,52 @@ def merge_local_settings(current: dict, form: dict) -> dict: merged = { "port": fresh["port"], "boot": fresh["boot"], - "webhook": { - field: fresh["webhook"][field] - for field in WRITABLE_WEBHOOK_FIELDS + "webhook_delivery": { + field: ( + list(fresh["webhook_delivery"][field]) + if field == "backoff" + else fresh["webhook_delivery"][field] + ) + for field in DELIVERY_FIELDS }, + "webhooks": [ + { + key: value + for key, value in entry.items() + if key != "secret_set" + } + for entry in fresh["webhooks"] + ], } 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) + if "webhook_delivery" in form: + merged["webhook_delivery"] = form["webhook_delivery"] + if "webhooks" in form: + form_webhooks = form["webhooks"] + if not isinstance(form_webhooks, list): + raise SettingsValidationError("webhooks must be a list") + fresh_by_id = { + entry["id"]: { + key: value + for key, value in entry.items() + if key != "secret_set" + } + for entry in fresh["webhooks"] + } + incoming = [] + for entry in form_webhooks: + if not isinstance(entry, dict): + raise SettingsValidationError( + "webhooks entries must be objects" + ) + base = fresh_by_id.get(entry.get("id"), {}) + merged_entry = {**base, **entry} + incoming.append(merged_entry) + merged["webhooks"] = incoming return merged @@ -428,13 +858,17 @@ def _store_writable( writable: dict, expected_revision: int | None, permissions: bool | None = None, + current: dict | None = 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) + writable = dict(writable) + writable.pop("_legacy_shim", None) + if current is None: + current = load_settings(config_path) if expected_revision is None: expected_revision = writable.get("revision") if ( @@ -444,6 +878,21 @@ def _store_writable( raise SettingsRevisionConflict( expected_revision, get_revision(current) ) + + existing_ids = set(_existing_webhook_entries(current)) + for entry in writable["webhooks"]: + webhook_id = entry.get("id") + if webhook_id and webhook_id not in existing_ids: + raise SettingsValidationError(f"Unknown Webhook id: {webhook_id}") + used_ids = set(existing_ids) + for entry in writable["webhooks"]: + if not entry.get("id"): + webhook_id = new_webhook_id() + while webhook_id in used_ids: + webhook_id = new_webhook_id() + entry["id"] = webhook_id + used_ids.add(entry["id"]) + validate_business_rules(writable) merged = apply_writable_settings(current, writable) if permissions is not None: @@ -464,7 +913,14 @@ def save_settings(config_path: str, payload, expected_revision: int | None = Non """ writable = validate_settings_payload(payload) with _write_lock: - return _store_writable(config_path, writable, expected_revision) + current = load_settings(config_path) + if writable.pop("_legacy_shim", False): + existing = list(_existing_webhook_entries(current)) + if existing: + writable["webhooks"][0]["id"] = existing[0] + return _store_writable( + config_path, writable, expected_revision, current=current + ) def save_local_settings( @@ -472,8 +928,8 @@ def save_local_settings( ) -> dict: """Save on-device fields over a fresh read of Settings. - `form` carries only the fields the screen owns (port, boot, and some - Webhook fields), plus internal fields owned by the permission flow. + `form` carries only the fields the screen owns (port, boot, and the full + Webhook list), 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. @@ -493,7 +949,8 @@ def save_local_settings( merge_local_settings(current, form) ) return _store_writable( - config_path, writable, expected_revision, permissions + config_path, writable, expected_revision, permissions, + current=current, ) diff --git a/app/services/webhookSvc.py b/app/services/webhookSvc.py index 541fcf4..9bad828 100644 --- a/app/services/webhookSvc.py +++ b/app/services/webhookSvc.py @@ -8,12 +8,11 @@ import hmac import json import os -import queue import re import threading import time import uuid -from collections import OrderedDict +from collections import OrderedDict, deque from datetime import datetime, timezone from urllib import error as urlerror from urllib import request as urlrequest @@ -31,6 +30,21 @@ ) VALID_TARGET_SCHEMES = ("http", "https") +# Webhook routing values +LEGACY_WEBHOOK_ID = "wh_legacy" +MAX_WEBHOOKS = 20 +KEYWORD_MAX_LENGTH = 32 +NAME_MAX_LENGTH = 64 +ALLOWED_SENDERS_MAX = 100 +SENDER_MAX_LENGTH = 64 +_KEYWORD_PATTERN = re.compile(r"^#?[A-Za-z0-9][A-Za-z0-9_-]*$") + +STRIP_NONE = "none" +STRIP_KEYWORD = "keyword" +STRIP_KEYWORD_AND_SEPARATOR = "keyword_and_separator" +STRIP_MODES = (STRIP_NONE, STRIP_KEYWORD, STRIP_KEYWORD_AND_SEPARATOR) +DEFAULT_STRIP_MODE = STRIP_KEYWORD_AND_SEPARATOR + # Delivery semantics (see docs/adr/0001-inbound-sms-webhook.md) DEFAULT_TIMEOUT = 10 DEFAULT_BACKOFF = (5, 30) @@ -50,17 +64,36 @@ ## Config -def default_webhook_config() -> dict: +def default_webhook_delivery() -> dict: + """The dispatcher-owned retry policy shared by every Webhook.""" return { - "enabled": False, - "url": "", - "secret": "", "timeout": DEFAULT_TIMEOUT, "max_attempts": DEFAULT_MAX_ATTEMPTS, "backoff": list(DEFAULT_BACKOFF), "capacity": DEFAULT_CAPACITY, } +def default_webhook_entry() -> dict: + """A new, disabled Webhook entry before Settings assigns it an id.""" + return { + "id": "", + "name": "", + "enabled": False, + "url": "", + "secret": "", + "keyword": "", + "strip_prefix": DEFAULT_STRIP_MODE, + "allowed_senders": [], + } + +def new_webhook_id() -> str: + return f"wh_{uuid.uuid4().hex[:8]}" + +def _fallback_webhook_id(index: int, url) -> str: + """A stable id for a hand-written entry that has none.""" + seed = f"{index}|{url if isinstance(url, str) else ''}" + return "wh_" + hashlib.sha256(seed.encode("utf-8")).hexdigest()[:8] + def _int_setting(value, default: int, low: int, high: int) -> int: """Return `value` when it is an in-range JSON integer, else `default`.""" if ( @@ -88,53 +121,184 @@ def _backoff_setting(value) -> list: normalized.append(wait_for) return normalized -def normalize_webhook_config(raw: dict | None) -> dict: - """Normalize the Webhook object, falling back to today's constants. +def normalize_webhook_delivery( + raw: dict | None, fallback: dict | None = None, *, + keep_unknown: bool = False, +) -> dict: + """Normalize the shared delivery policy, falling back to the 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 = default_webhook_delivery() + source = raw if isinstance(raw, dict) else None + if source is None and isinstance(fallback, dict): + source = fallback + if source is not None: config["timeout"] = _int_setting( - raw.get("timeout"), DEFAULT_TIMEOUT, TIMEOUT_MIN, TIMEOUT_MAX + source.get("timeout"), DEFAULT_TIMEOUT, TIMEOUT_MIN, TIMEOUT_MAX ) config["max_attempts"] = _int_setting( - raw.get("max_attempts"), + source.get("max_attempts"), DEFAULT_MAX_ATTEMPTS, MAX_ATTEMPTS_MIN, MAX_ATTEMPTS_MAX, ) - config["backoff"] = _backoff_setting(raw.get("backoff")) + config["backoff"] = _backoff_setting(source.get("backoff")) config["capacity"] = _int_setting( - raw.get("capacity"), DEFAULT_CAPACITY, CAPACITY_MIN, CAPACITY_MAX + source.get("capacity"), DEFAULT_CAPACITY, CAPACITY_MIN, CAPACITY_MAX ) + if keep_unknown and source is not None: + preserved = dict(source) + preserved.update(config) + return preserved return config -def get_webhook_config( +def normalize_allowed_senders(value) -> list: + if not isinstance(value, list): + return [] + normalized = [] + seen = set() + for item in value: + if not isinstance(item, str): + continue + sender = item.strip() + if not sender or len(sender) > SENDER_MAX_LENGTH: + continue + key = normalize_sender(sender) + if key in seen: + continue + seen.add(key) + normalized.append(sender) + if len(normalized) >= ALLOWED_SENDERS_MAX: + break + return normalized + +def normalize_keyword(value) -> str: + if not isinstance(value, str): + return "" + return value.strip() + +def normalize_strip_prefix(value) -> str: + if isinstance(value, str) and value in STRIP_MODES: + return value + return DEFAULT_STRIP_MODE + +def is_valid_keyword(value) -> bool: + if not isinstance(value, str): + return False + keyword = value.strip() + if not keyword: + return True + return ( + len(keyword) <= KEYWORD_MAX_LENGTH + and bool(_KEYWORD_PATTERN.match(keyword)) + ) + +def normalize_webhook_entry( + raw: dict | None, index: int = 0, *, keep_unknown: bool = False +) -> dict: + """Normalize one Webhook entry without validating it for a write.""" + source = raw if isinstance(raw, dict) else {} + entry = dict(source) if keep_unknown else {} + entry.update({ + "id": ( + source.get("id").strip() + if isinstance(source.get("id"), str) and source.get("id").strip() + else _fallback_webhook_id(index, source.get("url")) + ), + "name": ( + source.get("name").strip() + if isinstance(source.get("name"), str) + else "" + ), + "enabled": bool(source.get("enabled", False)), + "url": ( + source.get("url").strip() + if isinstance(source.get("url"), str) + else "" + ), + "secret": ( + source.get("secret") + if isinstance(source.get("secret"), str) + else "" + ), + "keyword": normalize_keyword(source.get("keyword")), + "strip_prefix": normalize_strip_prefix(source.get("strip_prefix")), + "allowed_senders": normalize_allowed_senders( + source.get("allowed_senders") + ), + }) + return entry + +def _legacy_entry(legacy: dict) -> dict: + return normalize_webhook_entry({ + "id": LEGACY_WEBHOOK_ID, + "enabled": legacy.get("enabled", False), + "url": legacy.get("url", ""), + "secret": legacy.get("secret", ""), + "keyword": "", + "strip_prefix": DEFAULT_STRIP_MODE, + "allowed_senders": [], + }) + +def normalize_app_webhook_config(app_config, fallback=None) -> dict: + """Read either Settings shape and return Webhooks plus delivery policy. + + The new `webhooks` array wins when both shapes are present. The legacy + single `webhook` object is migrated to one entry and still supplies the + retry policy when `webhook_delivery` is absent. + """ + raw = app_config if isinstance(app_config, dict) else {} + if not raw and isinstance(fallback, dict): + raw = fallback + legacy = raw.get("webhook") + + if isinstance(raw.get("webhooks"), list): + webhooks = [ + normalize_webhook_entry(entry, index) + for index, entry in enumerate(raw["webhooks"]) + ] + delivery_raw = raw.get("webhook_delivery") + if not isinstance(delivery_raw, dict) and isinstance(legacy, dict): + delivery_raw = legacy + delivery = normalize_webhook_delivery(delivery_raw) + return {"webhooks": webhooks, "webhook_delivery": delivery} + + if isinstance(legacy, dict): + return { + "webhooks": [_legacy_entry(legacy)], + "webhook_delivery": normalize_webhook_delivery(legacy), + } + + return { + "webhooks": [], + "webhook_delivery": normalize_webhook_delivery( + raw.get("webhook_delivery") + ), + } + +def get_webhook_runtime_config( config_path: str, fallback: dict | None = None ) -> dict: - """Read the current webhook config from the app config file (hot reload). + """Read the live Webhook configuration from the app config file. ``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. + unreadable or malformed file keeps dispatcher-owned defaults. """ if not config_path: - return normalize_webhook_config(fallback) + return normalize_app_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) + return normalize_app_webhook_config(fallback) except Exception: - return default_webhook_config() + return normalize_app_webhook_config(None) if not isinstance(app_config, dict): - return default_webhook_config() - return normalize_webhook_config(app_config.get("webhook")) + return normalize_app_webhook_config(None) + return normalize_app_webhook_config(app_config) def _parse_target(url: str) -> ParseResult | None: if not isinstance(url, str): @@ -209,6 +373,96 @@ def is_valid_target(url: str) -> bool: return False return True +## Routing + +def normalize_sender(value) -> str: + """Normalize a sender for allowlist comparison. + + Numeric senders compare by digits only, so `+1 (555) 123-4567` matches + `15551234567`. Alphanumeric sender IDs compare case-insensitively. + """ + text = str(value or "").strip() + if not text: + return "" + compact = re.sub(r"[\s\-().]", "", text) + if compact.startswith("+"): + compact = compact[1:] + if compact.isdigit(): + return compact + return text.casefold() + +def sender_allowed(sender, allowed_senders) -> bool: + """An empty list allows every sender; otherwise the list is exhaustive.""" + if not allowed_senders: + return True + normalized = normalize_sender(sender) + return any( + normalize_sender(allowed) == normalized + for allowed in allowed_senders + ) + +def keyword_matches(text: str, keyword: str) -> str | None: + """Return the message with leading whitespace if `keyword` routes it. + + The keyword must be at the start (after optional whitespace) and be + followed by `:`, whitespace, or the end of the message, so `#sales` does + not match `#salesforce`. + """ + if not isinstance(text, str) or not keyword: + return None + candidate = text.lstrip() + if not candidate.casefold().startswith(keyword.casefold()): + return None + rest = candidate[len(keyword):] + if rest and rest[0] != ":" and not rest[0].isspace(): + return None + return candidate + +def strip_route_prefix(text: str, keyword: str, mode: str) -> str: + """Remove the route keyword according to the Webhook's strip mode. + + `keyword` keeps the separator exactly as the sender wrote it; only + `keyword_and_separator` removes one separator character and at most one + following space. The rest of the message whitespace is preserved. + """ + if mode == STRIP_NONE: + return text + candidate = text.lstrip() + rest = candidate[len(keyword):] + if mode == STRIP_KEYWORD: + return rest + if rest[:1] == ":": + rest = rest[1:] + elif rest[:1] and rest[0].isspace(): + rest = rest[1:] + if rest[:1] == " ": + rest = rest[1:] + return rest + +def route_inbound(text: str, webhooks) -> tuple | None: + """Choose the one enabled Webhook for an Inbound SMS. + + With exactly one enabled Webhook, keyword routing and stripping are + ignored, as if the feature did not exist. With two or more, the unique + keyword match wins, then the single catch-all (empty keyword). + """ + enabled = [ + webhook for webhook in webhooks or [] if webhook.get("enabled") + ] + if len(enabled) == 1: + return enabled[0], text + for webhook in enabled: + keyword = webhook.get("keyword") or "" + if keyword and keyword_matches(text, keyword) is not None: + return ( + webhook, + strip_route_prefix(text, keyword, webhook["strip_prefix"]), + ) + for webhook in enabled: + if not (webhook.get("keyword") or ""): + return webhook, text + return None + ## Payload def iso_now() -> str: @@ -228,11 +482,12 @@ def iso_from_millis_local(timestamp_ms) -> str | None: timestamp_ms / 1000 ).astimezone().isoformat(timespec="seconds") -def build_inbound_payload(message: dict) -> dict: +def build_inbound_payload(message: dict, text: str | None = None) -> dict: """Turn a stored inbound message into the public webhook payload. `message` is what the Android receiver wrote to the inbox spool. The sender - is kept verbatim because it may be an alphanumeric sender ID. + is kept verbatim because it may be an alphanumeric sender ID. `text` + overrides the routed text after prefix stripping. """ payload = { "event": EVENT_INBOUND, @@ -242,7 +497,7 @@ def build_inbound_payload(message: dict) -> dict: ), "sent_at": iso_from_millis(message.get("sent_at_ms")), "from": message.get("from") or "unknown", - "text": message.get("text") or "", + "text": text if text is not None else (message.get("text") or ""), "parts": int(message.get("parts") or 1), } sim = {} @@ -279,13 +534,18 @@ def sign_body(secret: str, body: bytes) -> str | None: digest = hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest() return f"sha256={digest}" -def build_headers(payload: dict, body: bytes, secret: str = "") -> dict: +def build_headers( + payload: dict, body: bytes, secret: str = "", + webhook_id: str | None = None, +) -> dict: headers = { "Content-Type": "application/json", "User-Agent": f"OpenSMS/{__version__}", "X-OpenSMS-Event": payload["event"], "X-OpenSMS-Delivery": payload["delivery_id"], } + if webhook_id: + headers["X-OpenSMS-Webhook-Id"] = webhook_id signature = sign_body(secret, body) if signature: headers["X-OpenSMS-Signature"] = signature @@ -333,13 +593,63 @@ def _atomic_write(path: str, text: str): tf.write(text) os.replace(tmp_path, path) -def read_webhook_status(status_path: str) -> dict | None: +def read_webhook_statuses(status_path: str) -> dict: + """Return every Webhook's last Delivery status, keyed by Webhook id. + + The legacy single-object file is returned under the migrated id, so an + upgrade does not lose the last-delivery display. + """ try: with open(status_path, "r", encoding="utf-8") as sf: status = json.load(sf) - return status if isinstance(status, dict) else None except Exception: - return None + return {} + if not isinstance(status, dict): + return {} + statuses = status.get("webhooks") + if isinstance(statuses, dict): + return { + key: value + for key, value in statuses.items() + if isinstance(value, dict) + } + return {LEGACY_WEBHOOK_ID: status} + +def read_webhook_status( + status_path: str, webhook_id: str | None = None +) -> dict | None: + statuses = read_webhook_statuses(status_path) + if webhook_id is None: + return statuses.get(LEGACY_WEBHOOK_ID) + return statuses.get(webhook_id) + +def write_webhook_status(status_path: str, webhook_id: str, payload: dict): + statuses = read_webhook_statuses(status_path) + statuses[webhook_id] = payload + _atomic_write( + status_path, + json.dumps({"webhooks": statuses}, ensure_ascii=False), + ) + +def remove_webhook_status(status_path: str, webhook_id: str): + statuses = read_webhook_statuses(status_path) + if statuses.pop(webhook_id, None) is not None: + _atomic_write( + status_path, + json.dumps({"webhooks": statuses}, ensure_ascii=False), + ) + +def prune_webhook_statuses(status_path: str, valid_ids) -> None: + statuses = read_webhook_statuses(status_path) + valid = set(valid_ids) + pruned = { + key: value for key, value in statuses.items() if key in valid + } + if pruned != statuses: + _atomic_write( + status_path, + json.dumps({"webhooks": pruned}, ensure_ascii=False), + ) def scrub_webhook_error(error: str) -> str: """Remove credentialed target URLs from human-readable delivery errors.""" @@ -412,7 +722,7 @@ def ack_inbox_message(path: str): ## Dispatcher class WebhookDispatcher: - """Single ordered worker that delivers Enqueued webhooks from an outbox.""" + """Single worker that delivers Outbox records in per-Webhook FIFO lanes.""" def __init__( self, @@ -441,10 +751,11 @@ def __init__( 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() self._stop = threading.Event() self._outbox: OrderedDict = OrderedDict() + self._lanes: OrderedDict = OrderedDict() + self._last_reconcile = 0.0 self._load_outbox() self._thread = threading.Thread( target=self._run, @@ -460,22 +771,24 @@ 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._override_or_live(self._timeout_override, config["timeout"]) + def _timeout_for(self, delivery: dict) -> float: + return self._override_or_live( + self._timeout_override, delivery["timeout"] + ) - def _backoff_for(self, config: dict) -> tuple: + def _backoff_for(self, delivery: dict) -> tuple: return self._override_or_live( - self._backoff_override, tuple(config["backoff"]) + self._backoff_override, tuple(delivery["backoff"]) ) - def _max_attempts_for(self, config: dict) -> int: + def _max_attempts_for(self, delivery: dict) -> int: return self._override_or_live( - self._max_attempts_override, config["max_attempts"] + self._max_attempts_override, delivery["max_attempts"] ) - def _capacity_for(self, config: dict) -> int: + def _capacity_for(self, delivery: dict) -> int: return self._override_or_live( - self._capacity_override, config["capacity"] + self._capacity_override, delivery["capacity"] ) ## Outbox @@ -496,8 +809,24 @@ def _load_outbox(self): url = record.get("url") if not delivery_id or not isinstance(payload, dict) or not url: continue + webhook_id = record.get("webhook_id") + if not isinstance(webhook_id, str) or not webhook_id: + # Records persisted before multi-Webhook routing used the + # single migrated Webhook and its live secret. + webhook_id = LEGACY_WEBHOOK_ID + record["webhook_id"] = webhook_id + try: + record["attempts"] = max(0, int(record.get("attempts") or 0)) + except (TypeError, ValueError): + record["attempts"] = 0 + try: + record["next_attempt_at"] = float( + record.get("next_attempt_at") or 0 + ) + except (TypeError, ValueError): + record["next_attempt_at"] = 0 self._outbox[delivery_id] = record - self._queue.put(record) + self._lanes.setdefault(webhook_id, deque()).append(delivery_id) def _persist_outbox(self): _atomic_write( @@ -505,115 +834,270 @@ def _persist_outbox(self): json.dumps(list(self._outbox.values()), ensure_ascii=False), ) + def _drop_oldest_locked(self): + dropped_id, dropped = self._outbox.popitem(last=False) + webhook_id = dropped.get("webhook_id") + lane = self._lanes.get(webhook_id) + if lane is not None: + try: + lane.remove(dropped_id) + except ValueError: + pass + if not lane: + self._lanes.pop(webhook_id, None) + self.log( + f"Webhook outbox full, dropped {dropped.get('event')} " + f"{dropped_id}" + ) + + def _remove_record_locked(self, delivery_id: str) -> dict | None: + record = self._outbox.pop(delivery_id, None) + if record is None: + return None + webhook_id = record.get("webhook_id") + lane = self._lanes.get(webhook_id) + if lane is not None: + try: + lane.remove(delivery_id) + except ValueError: + pass + if not lane: + self._lanes.pop(webhook_id, None) + return record + ## Public API - def enqueue(self, payload: dict) -> bool: - config = get_webhook_config(self.config_path) - if not config["enabled"] or not is_valid_target(config["url"]): - return False + def enqueue(self, payload: dict) -> list: + """Route an Inbound SMS and persist one delivery per matching Webhook. + + Returns the delivery ids that were queued. A disabled or unmatched + configuration returns an empty list, matching the old boolean API's + truthiness for callers that only care whether anything was queued. + """ + config = get_webhook_runtime_config(self.config_path) + routed = route_inbound(payload.get("text") or "", config["webhooks"]) + if routed is None: + return [] + webhook, text = routed + if not sender_allowed( + payload.get("from"), webhook["allowed_senders"] + ): + self.log( + "Inbound SMS not forwarded: sender is not allowed for " + f"Webhook {webhook['id']}" + ) + return [] + if not is_valid_target(webhook["url"]): + return [] + record = { - "delivery_id": payload["delivery_id"], + "delivery_id": str(uuid.uuid4()), "event": payload["event"], - "url": config["url"], - "payload": payload, + "webhook_id": webhook["id"], + "url": webhook["url"], + "payload": {**payload, "text": text}, "attempts": 0, + "next_attempt_at": 0, } + record["payload"]["delivery_id"] = record["delivery_id"] with self._lock: - capacity = self._capacity_for(config) + capacity = self._capacity_for(config["webhook_delivery"]) while len(self._outbox) >= capacity: - dropped_id, dropped = self._outbox.popitem(last=False) - self.log( - f"Webhook outbox full, dropped {dropped.get('event')} " - f"{dropped_id}" - ) + self._drop_oldest_locked() self._outbox[record["delivery_id"]] = record + self._lanes.setdefault( + webhook["id"], deque() + ).append(record["delivery_id"]) self._persist_outbox() - self._queue.put(record) - return True + return [record["delivery_id"]] def pending_count(self) -> int: with self._lock: return len(self._outbox) + def pending_for(self, webhook_id: str) -> int: + with self._lock: + lane = self._lanes.get(webhook_id) + return len(lane) if lane else 0 + + def pending_by_id(self) -> dict: + with self._lock: + return { + webhook_id: len(lane) + for webhook_id, lane in self._lanes.items() + if lane + } + def stop(self): self._stop.set() - self._queue.put(None) self._thread.join(timeout=5) ## Worker + def _reconcile_targets(self): + """Fail queued deliveries whose Webhook is gone or disabled. + + This must not wait for the record's retry deadline, or a disabled + target would keep occupying global Outbox capacity for up to an hour + and a quick re-enable could revive deliveries that should have failed. + """ + now = time.time() + if now - self._last_reconcile < 0.2: + return + self._last_reconcile = now + try: + with open(self.config_path, "r", encoding="utf-8") as cf: + app_config = json.load(cf) + except Exception: + # A missing or unreadable config must not discard pending work; + # delivery-time checks still handle it. + return + if not isinstance(app_config, dict): + return + config = normalize_app_webhook_config(app_config) + live = { + webhook["id"]: webhook for webhook in config["webhooks"] + } + failed = [] + with self._lock: + for webhook_id in list(self._lanes.keys()): + webhook = live.get(webhook_id) + if webhook is not None and webhook["enabled"]: + continue + error = ( + "webhook removed" if webhook is None + else "webhook disabled" + ) + lane = self._lanes.pop(webhook_id, None) or deque() + while lane: + delivery_id = lane.popleft() + record = self._outbox.pop(delivery_id, None) + if record is not None: + failed.append((record, error)) + if failed: + self._persist_outbox() + for record, error in failed: + self._write_status(record, False, None, error) + self.log( + f"Webhook {record.get('event')} " + f"({record.get('delivery_id')}) to " + f"{record.get('webhook_id')} dropped: {error}" + ) + + def _next_due_record(self) -> tuple: + """Return the next due record and the soonest future due time. + + Lanes are rotated so one busy Webhook cannot starve the others. + """ + now = time.time() + soonest = None + with self._lock: + for webhook_id in list(self._lanes.keys()): + lane = self._lanes.get(webhook_id) + if not lane: + self._lanes.pop(webhook_id, None) + continue + record = self._outbox.get(lane[0]) + if record is None: + lane.popleft() + continue + try: + due = float(record.get("next_attempt_at") or 0) + except (TypeError, ValueError): + due = 0 + if due <= now: + self._lanes.move_to_end(webhook_id) + return record, None + soonest = due if soonest is None else min(soonest, due) + return None, soonest + def _run(self): while not self._stop.is_set(): - try: - record = self._queue.get(timeout=0.2) - except queue.Empty: - continue + self._reconcile_targets() + record, soonest = self._next_due_record() if record is None: - break - delivery_id = record.get("delivery_id") - with self._lock: - current = self._outbox.get(delivery_id) - if not current: + if soonest is None: + wait_for = 0.2 + else: + wait_for = max(0.0, min(0.2, soonest - time.time())) + self._stop.wait(wait_for) continue - ok, status, error, interrupted = self._deliver(current) - if interrupted: - # Leave the record in the Outbox so it is delivered after the - # next service start instead of being reported as failed. - break - with self._lock: - self._outbox.pop(delivery_id, None) + self._process_record(record) + + def _process_record(self, record: dict): + delivery_id = record.get("delivery_id") + ok, status, error, permanent = self._deliver(record) + config = get_webhook_runtime_config(self.config_path) + with self._lock: + current = self._outbox.get(delivery_id) + if current is None: + return + if ok or permanent: + self._remove_record_locked(delivery_id) self._persist_outbox() + else: + backoff = self._backoff_for(config["webhook_delivery"]) + attempt = int(current.get("attempts") or 0) + wait_for = ( + backoff[min(attempt - 1, len(backoff) - 1)] + if backoff else 0 + ) + current["next_attempt_at"] = time.time() + wait_for + self._persist_outbox() + if ok or permanent: self._write_status(current, ok, status, error) if ok: self.log( f"Webhook delivered: {current.get('event')} " - f"({delivery_id})" + f"({delivery_id}) to {current.get('webhook_id')}" ) else: self.log( f"Webhook failed: {current.get('event')} " - f"({delivery_id}) after " + f"({delivery_id}) to {current.get('webhook_id')} after " f"{current.get('attempts', 0)} attempt(s): {error}" ) def _deliver(self, record: dict) -> tuple: - """Attempt delivery. Returns (ok, status, error, interrupted).""" - status = None - error = None + """Attempt delivery once. Returns (ok, status, error, permanent).""" + config = get_webhook_runtime_config(self.config_path) + delivery = config["webhook_delivery"] + webhook_id = record.get("webhook_id") + webhook = next( + ( + entry for entry in config["webhooks"] + if entry["id"] == webhook_id + ), + None, + ) + if webhook is None: + return False, None, "webhook removed", True + if not webhook["enabled"]: + return False, None, "webhook disabled", True + target = record.get("url") + if not isinstance(target, str) or not is_valid_target(target): + return False, None, _INVALID_TARGET_ERROR, True + max_attempts = self._max_attempts_for(delivery) 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 - 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 - 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_for(config) - ) - if ok: - return True, status, None, False - if self._stop.is_set(): - return False, status, "dispatcher stopped", True - 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 + if attempt > max_attempts: + return False, None, "retry limit reached", True + record["attempts"] = attempt + with self._lock: + self._persist_outbox() + body = encode_payload(record["payload"]) + headers = build_headers( + record["payload"], body, webhook["secret"], webhook_id + ) + ok, status, error = post_json( + target, body, headers, self._timeout_for(delivery) + ) + if ok: + return True, status, None, False + if self._stop.is_set(): + return False, status, "dispatcher stopped", False + if attempt >= max_attempts: + return False, status, error, True + return False, status, error, False def _write_status(self, record: dict, ok: bool, status, error): payload = { @@ -626,14 +1110,31 @@ def _write_status(self, record: dict, ok: bool, status, error): "at": iso_now(), } try: - _atomic_write(self.status_path, json.dumps(payload, ensure_ascii=False)) + write_webhook_status( + self.status_path, + record.get("webhook_id") or LEGACY_WEBHOOK_ID, + payload, + ) except Exception as exc: self.log(f"Webhook status write failed: {exc}") + def prune_statuses(self): + """Drop last-delivery entries for Webhooks no longer configured.""" + config = get_webhook_runtime_config(self.config_path) + prune_webhook_statuses( + self.status_path, + [webhook["id"] for webhook in config["webhooks"]], + ) + ## Test delivery (Settings "Send test" runs this in the UI process) -def send_test_webhook(config: dict, timeout: float = DEFAULT_TIMEOUT) -> tuple: +def send_test_webhook( + config: dict, timeout: float = DEFAULT_TIMEOUT, + webhook_id: str | None = None, +) -> tuple: payload = build_test_payload() body = encode_payload(payload) - headers = build_headers(payload, body, config.get("secret", "")) + headers = build_headers( + payload, body, config.get("secret", ""), webhook_id + ) return post_json(config["url"], body, headers, timeout) diff --git a/app/tests/test_remote_api.py b/app/tests/test_remote_api.py index e4e0654..b39859f 100644 --- a/app/tests/test_remote_api.py +++ b/app/tests/test_remote_api.py @@ -182,19 +182,33 @@ def config(self, **overrides) -> dict: "boot": True, "permissions": True, "revision": 5, - "webhook": { - "enabled": False, - "url": "", - "secret": "", + "webhook_delivery": { "timeout": 10, "max_attempts": 3, "backoff": [5, 30], "capacity": 100, }, + "webhooks": [ + { + "id": "wh_1111aaaa", + "name": "Proxy", + "enabled": False, + "url": "", + "secret": "", + "keyword": "", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + }, + ], } webhook_overrides = overrides.pop("webhook", None) if webhook_overrides: - config["webhook"].update(webhook_overrides) + config["webhooks"][0].update(webhook_overrides) + delivery_overrides = overrides.pop("delivery", None) + if delivery_overrides: + config["webhook_delivery"].update(delivery_overrides) + if "webhooks" in overrides: + config["webhooks"] = overrides.pop("webhooks") config.update(overrides) return config @@ -262,8 +276,8 @@ def test_missing_settings_file_reports_the_documented_defaults(self): "boot": False, "revision": 0, }) - self.assertFalse(body["webhook"]["enabled"]) - self.assertEqual(body["webhook"]["outbox_capacity"], 100) + self.assertEqual(body["webhooks"], []) + self.assertEqual(body["outbox_capacity"], 100) self.assertIn("webhook_disabled", self.warning_codes(body)) def test_an_unreadable_existing_settings_file_is_unknown(self): @@ -283,7 +297,7 @@ def test_non_finite_settings_numbers_are_unknown(self): "overflowing port": '{"port": 1e999, "boot": false}', "infinite revision": '{"revision": Infinity, "boot": false}', "not-a-number capacity": ( - '{"boot": false, "webhook": {"capacity": NaN}}' + '{"boot": false, "webhook_delivery": {"capacity": NaN}}' ), } raw_key = self.add_api_key() @@ -330,34 +344,21 @@ def test_corrupt_settings_are_unknown_but_other_status_is_preserved(self): 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.assertEqual(body["webhooks"], []) + self.assertEqual(body["outbox_pending"], 2) + self.assertEqual(body["outbox_capacity"], 100) 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): + self.write_config(self.config()) 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"]) + self.assertIsNone(body["outbox_pending"]) + self.assertEqual(body["webhooks"][0]["pending"], 0) def test_status_reports_service_transitions_and_unknowns(self): self.write_json("resp.json", { @@ -443,31 +444,38 @@ def test_default_network_discovery_failure_is_distinguishable(self): 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): + def test_status_reports_each_last_delivery_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", + "webhooks": { + "wh_1111aaaa": { + "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, + "outbox_pending_by_id": lambda: {"wh_1111aaaa": 3}, }) - 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"], { + self.assertEqual(body["outbox_pending"], 3) + self.assertEqual(body["outbox_capacity"], 100) + self.assertEqual(body["webhooks"][0]["pending"], 3) + self.assertEqual(body["webhooks"][0]["last_delivery"], { "ok": False, "event": "sms.received", "delivery_id": "d-1", @@ -477,7 +485,39 @@ def test_status_reports_the_last_delivery_attempt_and_outbox_depth(self): "at": "2026-11-26T12:34:56+00:00", }) + def test_a_legacy_status_file_is_shown_for_the_migrated_webhook(self): + self.write_config({ + "app": "opensms", + "port": 9393, + "boot": True, + "revision": 5, + "webhook": { + "enabled": True, + "url": "https://proxy.example.lan/hooks/opensms", + "secret": "", + "timeout": 10, + "max_attempts": 3, + "backoff": [5, 30], + "capacity": 100, + }, + }) + self.write_json("webhook_status.json", { + "ok": True, + "http_status": 204, + "at": "2026-11-26T12:34:56+00:00", + }) + raw_key = self.add_api_key() + + body = self.status(raw_key).json() + + self.assertEqual(len(body["webhooks"]), 1) + self.assertEqual(body["webhooks"][0]["id"], "wh_legacy") + self.assertEqual( + body["webhooks"][0]["last_delivery"]["http_status"], 204 + ) + def test_an_unreadable_delivery_status_is_null(self): + self.write_config(self.config()) with open( os.path.join(self.config_dir, "webhook_status.json"), "w", @@ -488,7 +528,7 @@ def test_an_unreadable_delivery_status_is_null(self): body = self.status(raw_key).json() - self.assertIsNone(body["webhook"]["last_delivery"]) + self.assertIsNone(body["webhooks"][0]["last_delivery"]) def test_status_reports_only_the_webhook_host_and_secret_presence(self): credentialed_url = ( @@ -503,9 +543,13 @@ def test_status_reports_only_the_webhook_host_and_secret_presence(self): }, )) self.write_json("webhook_status.json", { - "ok": False, - "error": f"Could not deliver to {credentialed_url}", - "at": "2026-11-26T12:34:56+00:00", + "webhooks": { + "wh_1111aaaa": { + "ok": False, + "error": f"Could not deliver to {credentialed_url}", + "at": "2026-11-26T12:34:56+00:00", + }, + }, }) raw_key = self.add_api_key() @@ -513,9 +557,14 @@ def test_status_reports_only_the_webhook_host_and_secret_presence(self): self.assertEqual(response.status_code, 200) body = response.json() - self.assertEqual(body["webhook"]["url_host"], "proxy.example.lan") - self.assertTrue(body["webhook"]["secret_set"]) + self.assertEqual( + body["webhooks"][0]["url_host"], "proxy.example.lan" + ) + self.assertTrue(body["webhooks"][0]["secret_set"]) self.assertIn("webhook_url_invalid", self.warning_codes(body)) + self.assertEqual( + body["warnings"][0]["webhook_id"], "wh_1111aaaa" + ) for sensitive in ( "SENSITIVE-PATH", "SENSITIVE-TOKEN", @@ -534,11 +583,15 @@ def test_status_scrubs_credentials_from_a_previous_target_error(self): "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" - ), + "webhooks": { + "wh_1111aaaa": { + "ok": False, + "error": ( + "Could not deliver to " + "http://old-user:old-password@old.example.lan/hook" + ), + }, + }, }) raw_key = self.add_api_key() @@ -554,7 +607,6 @@ def test_forwarding_disabled_warns_that_new_inbound_sms_are_discarded(self): 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"] @@ -575,85 +627,31 @@ 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"), - ) + def test_two_enabled_webhooks_without_a_catch_all_warn_about_unrouted_sms(self): + self.write_config(self.config(webhooks=[ + { + "id": "wh_1111aaaa", + "enabled": True, + "url": "https://one.example.lan/hook", + "keyword": "#one", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + }, + { + "id": "wh_2222bbbb", + "enabled": True, + "url": "https://two.example.lan/hook", + "keyword": "#two", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + }, + ])) 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) + body = self.status(raw_key).json() - 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) - ) + self.assertIn("webhook_unrouted", self.warning_codes(body)) + self.assertNotIn("webhook_disabled", self.warning_codes(body)) def test_a_malformed_stored_target_type_is_safe_and_warns(self): cases = { @@ -670,18 +668,22 @@ def test_a_malformed_stored_target_type_is_safe_and_warns(self): webhook={"enabled": True, "url": url}, )) self.write_json("webhook_status.json", { - "ok": False, - "error": f"Could not deliver to {url}", + "webhooks": { + "wh_1111aaaa": { + "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"]) + self.assertIsNone(body["webhooks"][0]["url_host"]) if not isinstance(url, str): self.assertEqual( - body["webhook"]["last_delivery"]["error"], + body["webhooks"][0]["last_delivery"]["error"], "Webhook delivery failed.", ) self.assertIn( @@ -704,8 +706,8 @@ def test_an_outbox_near_capacity_is_a_warning(self): webhook={ "enabled": True, "url": "https://proxy.example.lan/hooks/opensms", - "capacity": 10, }, + delivery={"capacity": 10}, )) raw_key = self.add_api_key() @@ -716,8 +718,8 @@ def test_an_outbox_near_capacity_is_a_warning(self): 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) + self.assertEqual(body["outbox_pending"], 8) + self.assertEqual(body["outbox_capacity"], 10) class SettingsReadTests(ApiTestCase): @@ -735,18 +737,16 @@ def test_settings_defaults_when_no_config_exists(self): self.assertEqual(body["settings"], { "port": 9292, "boot": False, - "webhook": { - "enabled": False, - "url": "", - "secret_set": False, + "webhook_delivery": { "timeout": 10, "max_attempts": 3, "backoff": [5, 30], "capacity": 100, }, + "webhooks": [], }) - def test_settings_masks_the_secret_and_hides_internal_fields(self): + def test_settings_masks_every_secret_and_hides_internal_fields(self): self.write_config({ "app": "opensms", "port": 9393, @@ -754,16 +754,26 @@ def test_settings_masks_the_secret_and_hides_internal_fields(self): "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", + "webhook_delivery": { + "timeout": 10, + "max_attempts": 3, + "backoff": [5, 30], + "capacity": 100, + "unknown_delivery": "internal", }, + "webhooks": [ + { + "id": "wh_1111aaaa", + "name": "Proxy", + "enabled": True, + "url": "https://proxy.example.lan/hooks/opensms", + "secret": "topsecret", + "keyword": "#proxy", + "strip_prefix": "keyword", + "allowed_senders": ["+14155552671"], + "unknown_webhook": "internal", + }, + ], }) raw_key = self.add_api_key() @@ -772,35 +782,52 @@ def test_settings_masks_the_secret_and_hides_internal_fields(self): ) 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_redacts_userinfo_from_a_legacy_target(self): - credentialed_url = ( - "http://proxy-user:proxy-pass@proxy.example.lan:8080/" - "hooks/opensms?token=SENSITIVE-TOKEN" - ) - config = { + self.assertEqual(body["settings"]["port"], 9393) + self.assertTrue(body["settings"]["boot"]) + self.assertEqual(body["settings"]["webhook_delivery"], { + "timeout": 10, + "max_attempts": 3, + "backoff": [5, 30], + "capacity": 100, + }) + self.assertEqual(body["settings"]["webhooks"], [{ + "id": "wh_1111aaaa", + "name": "Proxy", + "enabled": True, + "url": "https://proxy.example.lan/hooks/opensms", + "secret_set": True, + "keyword": "#proxy", + "strip_prefix": "keyword", + "allowed_senders": ["+14155552671"], + }]) + self.assertNotIn("topsecret", response.text) + self.assertNotIn("unknown_top_level", response.text) + self.assertNotIn("unknown_webhook", response.text) + self.assertNotIn("unknown_delivery", response.text) + + def test_settings_redacts_userinfo_from_a_target(self): + self.write_config({ "port": 9292, "boot": False, - "revision": 4, - "webhook": { - "enabled": True, - "url": credentialed_url, - "secret": "topsecret", + "webhook_delivery": { + "timeout": 10, + "max_attempts": 3, + "backoff": [5, 30], + "capacity": 100, }, - } - self.write_config(config) + "webhooks": [{ + "id": "wh_1111aaaa", + "enabled": True, + "url": ( + "http://user:password@proxy.example.lan/hooks/SECRET" + ), + "keyword": "", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + }], + }) raw_key = self.add_api_key() response = self.client.get( @@ -808,43 +835,48 @@ def test_settings_redacts_userinfo_from_a_legacy_target(self): ) self.assertEqual(response.status_code, 200) - self.assertEqual( - response.json()["settings"]["webhook"]["url"], - ( - "http://proxy.example.lan:8080/hooks/opensms" - "?token=SENSITIVE-TOKEN" - ), + self.assertNotIn("user", response.text) + self.assertNotIn("password", response.text) + self.assertIn( + "http://proxy.example.lan/hooks/SECRET", + response.json()["settings"]["webhooks"][0]["url"], ) - 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", "port": 9393, "boot": True, "webhook": { - "enabled": False, - "url": "", - "secret": "", + "enabled": True, + "url": "https://proxy.example.lan/hooks/opensms", + "secret": "legacy-secret", + "timeout": 7, + "max_attempts": 4, + "backoff": [1, 2], + "capacity": 250, }, }) raw_key = self.add_api_key() - response = self.client.get( + body = self.client.get( "/api/settings", headers=self.auth(raw_key) - ) + ).json() - 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) + self.assertEqual(body["settings"]["webhook_delivery"], { + "timeout": 7, + "max_attempts": 4, + "backoff": [1, 2], + "capacity": 250, + }) + self.assertEqual(len(body["settings"]["webhooks"]), 1) + webhook = body["settings"]["webhooks"][0] + self.assertEqual(webhook["id"], "wh_legacy") + self.assertTrue(webhook["enabled"]) + self.assertTrue(webhook["secret_set"]) + self.assertEqual(webhook["keyword"], "") + self.assertEqual(webhook["strip_prefix"], "keyword_and_separator") + self.assertEqual(webhook["allowed_senders"], []) + self.assertNotIn("legacy-secret", body and str(body)) class KeyMigrationTests(ApiTestCase): @@ -941,22 +973,48 @@ def text(self) -> str: class SettingsWriteTestCase(ApiTestCase): - def valid_payload(self, **overrides) -> dict: + WEBHOOK_ID = "wh_1111aaaa" + + def webhook(self, **overrides) -> dict: + entry = { + "id": self.WEBHOOK_ID, + "name": "Proxy", + "enabled": False, + "url": "", + "keyword": "", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + } + entry.update(overrides) + return entry + + def valid_payload(self, webhook=None, delivery=None, **overrides) -> dict: + entry = self.webhook() + try: + current = self.read_config() + except FileNotFoundError: + current = None + if not (current and current.get("webhooks")): + entry.pop("id", None) payload = { "port": 9292, "boot": False, - "webhook": { - "enabled": False, - "url": "", + "webhook_delivery": { "timeout": 10, "max_attempts": 3, "backoff": [5, 30], "capacity": 100, }, + "webhooks": [entry], } - webhook_overrides = overrides.pop("webhook", None) - if webhook_overrides: - payload["webhook"].update(webhook_overrides) + if webhook: + for key, value in webhook.items(): + if key in ("timeout", "max_attempts", "backoff", "capacity"): + payload["webhook_delivery"][key] = value + else: + payload["webhooks"][0][key] = value + if delivery: + payload["webhook_delivery"].update(delivery) payload.update(overrides) return payload @@ -968,16 +1026,26 @@ def stored_config(self) -> dict: "permissions": True, "revision": 3, "unknown_top_level": "internal", - "webhook": { - "enabled": False, - "url": "", - "secret": "old-secret", + "webhook_delivery": { "timeout": 10, "max_attempts": 3, "backoff": [5, 30], "capacity": 100, - "unknown_webhook": "internal", + "unknown_delivery": "internal", }, + "webhooks": [ + { + "id": self.WEBHOOK_ID, + "name": "Proxy", + "enabled": False, + "url": "", + "secret": "old-secret", + "keyword": "", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + "unknown_webhook": "internal", + }, + ], } def put(self, payload: dict, raw_key: str): @@ -999,8 +1067,12 @@ def test_put_replaces_the_writable_subset_and_bumps_the_revision(self): port=9393, boot=True, webhook={ + "name": "New", "enabled": True, "url": "https://proxy.example.lan/hooks/opensms", + "keyword": "#proxy", + "strip_prefix": "keyword", + "allowed_senders": ["+1 555 123 4567"], "timeout": 7, "max_attempts": 4, "backoff": [1, 2, 3], @@ -1008,20 +1080,27 @@ def test_put_replaces_the_writable_subset_and_bumps_the_revision(self): }, ), raw_key) - self.assertEqual(response.status_code, 200) + self.assertEqual(response.status_code, 200, response.text) 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, + self.assertEqual(body["settings"]["webhook_delivery"], { "timeout": 7, "max_attempts": 4, "backoff": [1, 2, 3], "capacity": 250, }) + self.assertEqual(body["settings"]["webhooks"], [{ + "id": self.WEBHOOK_ID, + "name": "New", + "enabled": True, + "url": "https://proxy.example.lan/hooks/opensms", + "secret_set": True, + "keyword": "#proxy", + "strip_prefix": "keyword", + "allowed_senders": ["+1 555 123 4567"], + }]) self.assertNotIn("old-secret", response.text) on_disk = self.read_config() @@ -1031,14 +1110,18 @@ def test_put_replaces_the_writable_subset_and_bumps_the_revision(self): 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( + on_disk["webhooks"][0]["unknown_webhook"], "internal" + ) + self.assertEqual(on_disk["webhook_delivery"]["unknown_delivery"], + "internal") + self.assertEqual(on_disk["webhooks"][0]["secret"], "old-secret") self.assertEqual(self.tmp_files(), []) - def test_put_replacing_a_legacy_credentialed_target_never_echoes_it(self): + def test_put_replacing_a_credentialed_target_never_echoes_it(self): config = self.stored_config() - config["webhook"]["enabled"] = True - config["webhook"]["url"] = ( + config["webhooks"][0]["enabled"] = True + config["webhooks"][0]["url"] = ( "http://legacy-user:legacy-password@proxy.example.lan/hooks/old" ) self.write_config(config) @@ -1051,13 +1134,13 @@ def test_put_replacing_a_legacy_credentialed_target_never_echoes_it(self): self.assertEqual(response.status_code, 200, response.text) self.assertEqual( - response.json()["settings"]["webhook"]["url"], + response.json()["settings"]["webhooks"][0]["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"], + self.read_config()["webhooks"][0]["url"], "https://proxy.example.lan/hooks/new", ) @@ -1068,8 +1151,12 @@ def test_omitting_the_secret_keeps_the_stored_secret(self): 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") + self.assertTrue( + response.json()["settings"]["webhooks"][0]["secret_set"] + ) + self.assertEqual( + self.read_config()["webhooks"][0]["secret"], "old-secret" + ) def test_an_empty_secret_clears_the_stored_secret(self): self.write_config(self.stored_config()) @@ -1080,21 +1167,26 @@ def test_an_empty_secret_clears_the_stored_secret(self): ) self.assertEqual(response.status_code, 200) - self.assertFalse(response.json()["settings"]["webhook"]["secret_set"]) - self.assertEqual(self.read_config()["webhook"]["secret"], "") + self.assertFalse( + response.json()["settings"]["webhooks"][0]["secret_set"] + ) + self.assertEqual(self.read_config()["webhooks"][0]["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.valid_payload(webhook={"secret": "new-shared-secret"}), + raw_key, ) self.assertEqual(response.status_code, 200) - self.assertTrue(response.json()["settings"]["webhook"]["secret_set"]) + self.assertTrue( + response.json()["settings"]["webhooks"][0]["secret_set"] + ) self.assertEqual( - self.read_config()["webhook"]["secret"], "new-shared-secret" + self.read_config()["webhooks"][0]["secret"], "new-shared-secret" ) self.assertNotIn("new-shared-secret", response.text) @@ -1110,7 +1202,7 @@ def test_a_null_secret_is_rejected_without_changing_settings(self): self.assertEqual(response.status_code, 422) self.assertEqual( response.json()["detail"], - "webhook.secret must be a string", + "webhooks[0].secret must be a string", ) self.assertEqual(self.read_config(), before) self.assertEqual(self.tmp_files(), []) @@ -1125,7 +1217,61 @@ def test_put_rejects_a_secret_longer_than_256_characters(self): self.assertEqual(response.status_code, 422) self.assertIsInstance(response.json()["detail"], str) - self.assertEqual(self.read_config()["webhook"]["secret"], "old-secret") + self.assertEqual( + self.read_config()["webhooks"][0]["secret"], "old-secret" + ) + + def test_the_legacy_single_webhook_body_is_accepted(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + + response = self.put({ + "port": 9292, + "boot": False, + "webhook": { + "enabled": True, + "url": "https://legacy.example.lan/hook", + "timeout": 7, + "max_attempts": 4, + "backoff": [1, 2], + "capacity": 250, + }, + }, raw_key) + + self.assertEqual(response.status_code, 200, response.text) + body = response.json() + self.assertEqual( + body["settings"]["webhooks"][0]["id"], self.WEBHOOK_ID + ) + self.assertEqual( + body["settings"]["webhooks"][0]["url"], + "https://legacy.example.lan/hook", + ) + self.assertEqual(body["settings"]["webhook_delivery"], { + "timeout": 7, + "max_attempts": 4, + "backoff": [1, 2], + "capacity": 250, + }) + + def test_the_legacy_shim_cannot_be_combined_with_the_new_shape(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + + payload = self.valid_payload() + payload["webhook"] = { + "enabled": False, + "url": "", + "timeout": 10, + "max_attempts": 3, + "backoff": [5, 30], + "capacity": 100, + } + + response = self.put(payload, raw_key) + + self.assertEqual(response.status_code, 422) + self.assertIn("cannot be combined", response.json()["detail"]) class SettingsValidationTests(SettingsWriteTestCase): @@ -1157,6 +1303,23 @@ def test_put_rejects_invalid_values_and_leaves_settings_unchanged(self): "capacity above range": {"webhook": {"capacity": 5001}}, "unknown top-level field": {"unknown_top_level": 1}, "unknown webhook field": {"webhook": {"unknown_webhook": 1}}, + "unknown delivery field": {"delivery": {"unknown_delivery": 1}}, + "keyword is not a string": {"webhook": {"keyword": 42}}, + "keyword has a space": {"webhook": {"keyword": "#bad keyword"}}, + "strip mode is unknown": {"webhook": {"strip_prefix": "partial"}}, + "allowed senders is not a list": { + "webhook": {"allowed_senders": "123"} + }, + "allowed sender is not a string": { + "webhook": {"allowed_senders": [123]} + }, + "empty allowed sender": { + "webhook": {"allowed_senders": [""]} + }, + "webhook id is malformed": {"webhook": {"id": "bad-id"}}, + "webhook id is duplicated": { + "webhooks": [self.webhook(), self.webhook()], + }, } for name, overrides in cases.items(): @@ -1216,27 +1379,27 @@ def test_put_rejects_missing_required_fields(self): 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"), + "webhook_delivery": "webhook_delivery", + "webhooks": "webhooks", + "enabled": ("webhook", "enabled"), + "url": ("webhook", "url"), + "keyword": ("webhook", "keyword"), + "strip_prefix": ("webhook", "strip_prefix"), + "allowed_senders": ("webhook", "allowed_senders"), } for name, path in cases.items(): with self.subTest(name): payload = self.valid_payload() if isinstance(path, tuple): - del payload[path[0]][path[1]] + del payload["webhooks"][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"]) + self.assertIn(name, response.json()["detail"]) def test_put_rejects_enabling_forwarding_without_a_valid_target(self): self.write_config(self.stored_config()) @@ -1251,7 +1414,9 @@ def test_put_rejects_enabling_forwarding_without_a_valid_target(self): }.items(): with self.subTest(name): response = self.put( - self.valid_payload(webhook={"enabled": True, "url": url}), + self.valid_payload( + webhook={"enabled": True, "url": url} + ), raw_key, ) @@ -1286,6 +1451,74 @@ def test_put_rejects_a_credentialed_target_even_when_disabled(self): self.assertEqual(self.read_config(), before) self.assertEqual(self.tmp_files(), []) + def test_put_rejects_duplicate_keywords_and_catch_alls(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + before = self.read_config() + + cases = { + "duplicate keyword": [ + self.webhook(keyword="#SALES"), + { + key: value + for key, value in self.webhook( + keyword="#sales", + url="https://two.example.lan/hook", + ).items() + if key != "id" + }, + ], + "two catch-alls": [ + self.webhook(keyword=""), + { + key: value + for key, value in self.webhook( + keyword="", url="https://two.example.lan/hook" + ).items() + if key != "id" + }, + ], + } + for name, webhooks in cases.items(): + with self.subTest(name): + response = self.put( + self.valid_payload(webhooks=webhooks), raw_key + ) + self.assertEqual(response.status_code, 400, response.text) + self.assertEqual(self.read_config(), before) + + def test_put_rejects_unknown_and_duplicate_webhook_ids(self): + self.write_config(self.stored_config()) + raw_key = self.add_api_key() + before = self.read_config() + + for name, webhooks in { + "unknown id": [self.webhook(id="wh_9999ffff")], + "duplicate id": [self.webhook(), self.webhook()], + }.items(): + with self.subTest(name): + response = self.put( + self.valid_payload(webhooks=webhooks), raw_key + ) + self.assertEqual(response.status_code, 422, response.text) + self.assertEqual(self.read_config(), before) + + def test_put_rejects_more_than_twenty_webhooks(self): + raw_key = self.add_api_key() + webhooks = [ + self.webhook( + id=f"wh_{index:08x}", + keyword=f"#k{index}", + url=f"https://{index}.example.lan/hook", + ) + for index in range(21) + ] + + response = self.put(self.valid_payload(webhooks=webhooks), raw_key) + + self.assertEqual(response.status_code, 422) + self.assertIn("at most 20", response.json()["detail"]) + def test_put_rejects_a_non_object_body(self): raw_key = self.add_api_key() @@ -1470,7 +1703,8 @@ def test_logs_name_fields_without_the_secret_or_the_body(self): logged = logger.text() self.assertIn("Settings updated", logged) self.assertIn("port", logged) - self.assertIn("webhook", logged) + self.assertIn("webhook_delivery", logged) + self.assertIn("webhooks[0]", logged) self.assertNotIn("super-duper-secret", logged) self.assertNotIn("SENSITIVE-PATH", logged) self.assertNotIn("old-secret", logged) @@ -1478,6 +1712,8 @@ def test_logs_name_fields_without_the_secret_or_the_body(self): class WebhookTestTests(ApiTestCase): + WEBHOOK_ID = "wh_test0001" + def setUp(self): super().setUp() self.target = MockTarget() @@ -1494,18 +1730,68 @@ def post_test(self, raw_key: str, payload=None): return self.client.post("/api/webhook/test", **kwargs) def save_webhook(self, **overrides) -> dict: - webhook = { + entry = { + "id": self.WEBHOOK_ID, + "name": "Proxy", "enabled": False, "url": self.target.url, "secret": "saved-secret", + "keyword": "", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + } + delivery = { "timeout": 5, "max_attempts": 3, "backoff": [5, 30], "capacity": 100, } - webhook.update(overrides) - self.write_config({"webhook": webhook}) - return webhook + for key, value in overrides.items(): + if key in delivery: + delivery[key] = value + else: + entry[key] = value + self.write_config({ + "port": 9292, + "boot": False, + "webhook_delivery": delivery, + "webhooks": [entry], + }) + return entry + + def save_two_webhooks(self) -> None: + self.write_config({ + "port": 9292, + "boot": False, + "webhook_delivery": { + "timeout": 5, + "max_attempts": 3, + "backoff": [5, 30], + "capacity": 100, + }, + "webhooks": [ + { + "id": self.WEBHOOK_ID, + "name": "First", + "enabled": False, + "url": self.target.url, + "secret": "first-secret", + "keyword": "#first", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + }, + { + "id": "wh_test0002", + "name": "Second", + "enabled": False, + "url": "http://127.0.0.1:1/unreachable", + "secret": "second-secret", + "keyword": "#second", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + }, + ], + }) def signature_for(self, secret: str, body: bytes) -> str: digest = hmac.new( @@ -1573,7 +1859,7 @@ def test_an_unreachable_target_reports_no_http_status(self): self.assertIsNone(body["http_status"]) self.assertTrue(body["error"]) - def test_no_body_uses_the_saved_target_and_secret(self): + def test_no_body_uses_the_only_saved_target_and_secret(self): self.save_webhook(enabled=False, secret="saved-secret") before = self.read_config() raw_key = self.add_api_key() @@ -1586,6 +1872,9 @@ def test_no_body_uses_the_saved_target_and_secret(self): request["headers"]["x-opensms-signature"], self.signature_for("saved-secret", request["body"]), ) + self.assertEqual( + request["headers"]["x-opensms-webhook-id"], self.WEBHOOK_ID + ) self.assertEqual(self.read_config(), before) def test_an_override_is_used_for_the_test_only(self): @@ -1628,9 +1917,54 @@ def test_an_empty_secret_tests_unsigned_delivery(self): request = self.target.next_request() self.assertNotIn("x-opensms-signature", request["headers"]) self.assertEqual( - self.read_config()["webhook"]["secret"], "saved-secret" + self.read_config()["webhooks"][0]["secret"], "saved-secret" ) + def test_multiple_webhooks_require_an_id(self): + self.save_two_webhooks() + raw_key = self.add_api_key() + + response = self.post_test(raw_key) + + self.assertEqual(response.status_code, 422) + self.assertIn("id is required", response.json()["detail"]) + + def test_an_id_selects_the_saved_target_and_secret(self): + self.save_two_webhooks() + raw_key = self.add_api_key() + + response = self.post_test(raw_key, {"id": self.WEBHOOK_ID}) + + self.assertEqual(response.status_code, 200, response.text) + request = self.target.next_request() + self.assertEqual( + request["headers"]["x-opensms-signature"], + self.signature_for("first-secret", request["body"]), + ) + self.assertEqual( + request["headers"]["x-opensms-webhook-id"], self.WEBHOOK_ID + ) + + def test_an_unknown_id_is_not_found(self): + self.save_two_webhooks() + raw_key = self.add_api_key() + + response = self.post_test(raw_key, {"id": "wh_9999ffff"}) + + self.assertEqual(response.status_code, 404) + + def test_id_and_url_cannot_be_combined(self): + self.save_two_webhooks() + raw_key = self.add_api_key() + + response = self.post_test(raw_key, { + "id": self.WEBHOOK_ID, + "url": self.target.url, + }) + + self.assertEqual(response.status_code, 422) + self.assertIn("cannot be combined", response.json()["detail"]) + def test_credentialed_targets_are_rejected_without_posting(self): raw_key = self.add_api_key() port = self.target.server.server_address[1] @@ -1684,8 +2018,8 @@ def test_the_saved_timeout_is_used(self): raw_key = self.add_api_key() calls = [] - def record(config, timeout): - calls.append((config, timeout)) + def record(config, timeout, webhook_id=None): + calls.append((config, timeout, webhook_id)) return True, 204, None with mock.patch.object( @@ -1703,8 +2037,8 @@ def test_an_invalid_saved_timeout_uses_the_normalized_default(self): self.save_webhook(timeout=timeout) calls = [] - def record(config, timeout): - calls.append((config, timeout)) + def record(config, timeout, webhook_id=None): + calls.append((config, timeout, webhook_id)) return True, 204, None with mock.patch.object( @@ -1753,6 +2087,7 @@ def test_unknown_fields_and_wrong_types_are_rejected(self): "url not a string": {"url": 42}, "secret not a string": {"secret": 42}, "secret too long": {"secret": "x" * 257}, + "id not a string": {"id": 42}, } for name, payload in cases.items(): with self.subTest(name): diff --git a/app/tests/test_settings_local_save.py b/app/tests/test_settings_local_save.py index 6d699c8..eebf429 100644 --- a/app/tests/test_settings_local_save.py +++ b/app/tests/test_settings_local_save.py @@ -36,16 +36,26 @@ def stored_config(self) -> dict: "permissions": True, "revision": 3, "unknown_top_level": "internal", - "webhook": { - "enabled": True, - "url": "https://remote.example.lan/hooks/opensms", - "secret": "remote-secret", + "webhook_delivery": { "timeout": 7, "max_attempts": 4, "backoff": [1, 2, 3], "capacity": 250, - "unknown_webhook": "internal", + "unknown_delivery": "internal", }, + "webhooks": [ + { + "id": "wh_11111111", + "name": "Remote", + "enabled": True, + "url": "https://remote.example.lan/hooks/opensms", + "secret": "remote-secret", + "keyword": "#remote", + "strip_prefix": "keyword_and_separator", + "allowed_senders": ["+14155552671"], + "unknown_webhook": "internal", + }, + ], } def write_config(self, config: dict): @@ -56,12 +66,28 @@ 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: + def writable_webhooks(self, current: dict) -> list: + return [ + { + key: value + for key, value in entry.items() + if key != "secret_set" + } + for entry in settingsSvc.writable_settings(current)["webhooks"] + ] + + def write_remote_settings(self, **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) + delivery_overrides = overrides.pop("delivery", None) + if delivery_overrides: + remote_settings["webhook_delivery"].update(delivery_overrides) + webhook_overrides = overrides.pop("webhook", None) + remote_settings["webhooks"] = self.writable_webhooks(current) + if webhook_overrides: + remote_settings["webhooks"][0].update(webhook_overrides) + remote_settings.update(overrides) return settingsSvc.save_settings(self.config_path, remote_settings) def tmp_files(self) -> list: @@ -77,40 +103,42 @@ def screen_form(self, current: dict, **overrides) -> dict: form = { "port": writable["port"], "boot": writable["boot"], - "webhook": { - "enabled": writable["webhook"]["enabled"], - "url": writable["webhook"]["url"], - }, + "revision": current["revision"], + "webhooks": self.writable_webhooks(current), } - webhook_overrides = overrides.pop("webhook", None) - if webhook_overrides: - form["webhook"].update(webhook_overrides) form.update(overrides) return form + def webhook_form(self, **overrides) -> dict: + current = settingsSvc.load_settings(self.config_path) + entry = self.writable_webhooks(current)[0] + entry.update(overrides) + return {"webhooks": [entry]} + class WritableSettingsTests(LocalSaveTestCase): - def test_settings_use_the_dispatcher_webhook_defaults(self): + def test_settings_use_the_dispatcher_delivery_defaults(self): self.assertEqual( settingsSvc.default_webhook_settings(), - webhookSvc.default_webhook_config(), + webhookSvc.default_webhook_delivery(), ) def test_default_backoff_lists_are_not_shared(self): settings = settingsSvc.default_settings() - settings["webhook"]["backoff"].append(1) + settings["webhook_delivery"]["backoff"].append(1) self.assertEqual( - settingsSvc.default_settings()["webhook"]["backoff"], [5, 30] + settingsSvc.default_settings()["webhook_delivery"]["backoff"], + [5, 30], ) self.assertEqual( - webhookSvc.default_webhook_config()["backoff"], [5, 30] + webhookSvc.default_webhook_delivery()["backoff"], [5, 30] ) def test_invalid_stored_retry_values_report_the_effective_defaults(self): config = self.stored_config() - config["webhook"].update({ + config["webhook_delivery"].update({ "timeout": 0, "max_attempts": "many", "backoff": [], @@ -122,15 +150,15 @@ def test_invalid_stored_retry_values_report_the_effective_defaults(self): settingsSvc.load_settings(self.config_path) ) - webhook = writable["webhook"] - self.assertEqual(webhook["timeout"], webhookSvc.DEFAULT_TIMEOUT) + delivery = writable["webhook_delivery"] + self.assertEqual(delivery["timeout"], webhookSvc.DEFAULT_TIMEOUT) self.assertEqual( - webhook["max_attempts"], webhookSvc.DEFAULT_MAX_ATTEMPTS + delivery["max_attempts"], webhookSvc.DEFAULT_MAX_ATTEMPTS ) self.assertEqual( - webhook["backoff"], list(webhookSvc.DEFAULT_BACKOFF) + delivery["backoff"], list(webhookSvc.DEFAULT_BACKOFF) ) - self.assertEqual(webhook["capacity"], webhookSvc.DEFAULT_CAPACITY) + self.assertEqual(delivery["capacity"], webhookSvc.DEFAULT_CAPACITY) class LocalSaveMergeTests(LocalSaveTestCase): @@ -143,67 +171,66 @@ def test_entering_then_saving_keeps_a_remote_webhook_target(self): self.assertEqual(saved["revision"], 4) self.assertEqual(saved["port"], 9393) - webhook = saved["webhook"] + webhook = saved["webhooks"][0] 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") + self.assertEqual(on_disk["webhooks"][0]["url"], webhook["url"]) + self.assertEqual(on_disk["webhooks"][0]["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. + # A port-only local save must not touch the Webhooks at all. form = {"port": 9393} saved = settingsSvc.save_local_settings(self.config_path, form) - webhook = saved["webhook"] + webhook = saved["webhooks"][0] 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["webhook_delivery"]["timeout"], 7) + self.assertEqual(saved["webhook_delivery"]["max_attempts"], 4) + self.assertEqual(saved["webhook_delivery"]["backoff"], [1, 2, 3]) + self.assertEqual(saved["webhook_delivery"]["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", - } - } + form = self.webhook_form( + url="https://new.example.lan/hooks/opensms" + ) saved = settingsSvc.save_local_settings(self.config_path, form) self.assertEqual( - saved["webhook"]["url"], + saved["webhooks"][0]["url"], "https://new.example.lan/hooks/opensms", ) - self.assertEqual(saved["webhook"]["secret"], "remote-secret") + self.assertEqual(saved["webhooks"][0]["secret"], "remote-secret") def test_an_edited_secret_replaces_the_stored_value(self): - form = {"webhook": {"secret": "local-secret"}} + form = self.webhook_form(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") + self.assertEqual(saved["webhooks"][0]["secret"], "local-secret") + self.assertEqual( + self.read_config()["webhooks"][0]["secret"], "local-secret" + ) def test_clearing_the_secret_field_clears_the_stored_secret(self): - form = {"webhook": {"secret": ""}} + form = self.webhook_form(secret="") saved = settingsSvc.save_local_settings(self.config_path, form) - self.assertEqual(saved["webhook"]["secret"], "") - self.assertEqual(self.read_config()["webhook"]["secret"], "") + self.assertEqual(saved["webhooks"][0]["secret"], "") + self.assertEqual(self.read_config()["webhooks"][0]["secret"], "") def test_a_legacy_config_gains_defaults_and_keeps_a_saved_port(self): self.write_config({ @@ -217,53 +244,101 @@ def test_a_legacy_config_gains_defaults_and_keeps_a_saved_port(self): }, }) - saved = settingsSvc.save_local_settings(self.config_path, {"port": 9393}) + 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) + self.assertEqual(saved["webhooks"][0]["id"], "wh_legacy") + self.assertEqual(saved["webhook_delivery"]["timeout"], 10) + self.assertEqual(saved["webhook_delivery"]["max_attempts"], 3) + self.assertEqual( + saved["webhook_delivery"]["backoff"], [5, 30] + ) + self.assertEqual(saved["webhook_delivery"]["capacity"], 100) + + def test_a_local_save_adds_and_removes_webhooks(self): + current = settingsSvc.load_settings(self.config_path) + form = self.screen_form(current) + form["webhooks"] = [ + { + "name": "Second", + "enabled": True, + "url": "https://second.example.lan/hook", + "keyword": "#second", + "strip_prefix": "keyword", + "allowed_senders": [], + } + ] + + saved = settingsSvc.save_local_settings(self.config_path, form) + + self.assertEqual(len(saved["webhooks"]), 1) + self.assertEqual(saved["webhooks"][0]["name"], "Second") + self.assertNotEqual(saved["webhooks"][0]["id"], "wh_11111111") + self.assertEqual(saved["webhooks"][0]["secret"], "") 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} + def test_a_stale_full_save_is_rejected(self): + current = settingsSvc.load_settings(self.config_path) + stale_form = self.screen_form(current, 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, + webhook={ + "url": "https://remote-after-open.example.lan/hooks/opensms", + }, + delivery={ + "timeout": 11, + "max_attempts": 6, + "backoff": [2, 4, 8], + "capacity": 300, + }, ) + before = self.read_config() - saved = settingsSvc.save_local_settings(self.config_path, stale_form) + with self.assertRaises(settingsSvc.SettingsRevisionConflict): + settingsSvc.save_local_settings(self.config_path, stale_form) - self.assertEqual(saved["revision"], 5) - self.assertEqual(saved["port"], 9393) - webhook = saved["webhook"] + self.assertEqual(self.read_config(), before) + self.assertEqual(before["revision"], 4) self.assertEqual( - webhook["url"], "https://remote-after-open.example.lan/hooks/opensms" + before["webhooks"][0]["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(before["webhook_delivery"]["timeout"], 11) self.assertEqual(self.tmp_files(), []) + def test_a_save_without_a_revision_still_keeps_remote_webhook_changes(self): + # The auto-start switch and permission flow deliberately write only + # their own field, without a Revision, and must not replace cards. + self.write_remote_settings( + webhook={ + "url": "https://remote-after-open.example.lan/hooks/opensms", + }, + delivery={"timeout": 11}, + ) + + saved = settingsSvc.save_local_settings( + self.config_path, {"boot": True} + ) + + self.assertTrue(saved["boot"]) + self.assertEqual( + saved["webhooks"][0]["url"], + "https://remote-after-open.example.lan/hooks/opensms", + ) + self.assertEqual(saved["webhook_delivery"]["timeout"], 11) + self.assertEqual(saved["webhooks"][0]["secret"], "remote-secret") + 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, + webhook={ + "url": "https://remote-after-open.example.lan/hooks/opensms", + }, + delivery={"timeout": 11}, ) before = self.read_config() @@ -273,12 +348,12 @@ def test_an_invalid_stale_form_rejects_the_whole_save(self): self.assertEqual(self.read_config(), before) self.assertEqual(before["revision"], 4) self.assertEqual( - before["webhook"]["url"], + before["webhooks"][0]["url"], "https://remote-after-open.example.lan/hooks/opensms", ) - self.assertEqual(before["webhook"]["timeout"], 11) + self.assertEqual(before["webhook_delivery"]["timeout"], 11) self.assertEqual(before["unknown_top_level"], "internal") - self.assertEqual(before["webhook"]["unknown_webhook"], "internal") + self.assertEqual(before["webhooks"][0]["unknown_webhook"], "internal") self.assertEqual(self.tmp_files(), []) @@ -290,12 +365,16 @@ def test_permission_confirmation_preserves_a_remote_write_after_a_stale_read(sel stale = settingsSvc.load_settings(self.config_path) 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, + webhook={ + "url": "https://remote-after-open.example.lan/hooks/opensms", + "secret": "remote-after-open-secret", + }, + delivery={ + "timeout": 11, + "max_attempts": 6, + "backoff": [2, 4, 8], + "capacity": 300, + }, ) saved = settingsSvc.save_local_settings( @@ -304,15 +383,15 @@ def test_permission_confirmation_preserves_a_remote_write_after_a_stale_read(sel self.assertEqual(saved["revision"], 5) self.assertEqual(saved["permissions"], True) - webhook = saved["webhook"] + webhook = saved["webhooks"][0] 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["webhook_delivery"]["timeout"], 11) + self.assertEqual(saved["webhook_delivery"]["max_attempts"], 6) + self.assertEqual(saved["webhook_delivery"]["backoff"], [2, 4, 8]) + self.assertEqual(saved["webhook_delivery"]["capacity"], 300) self.assertEqual(saved["unknown_top_level"], "internal") self.assertEqual(webhook["unknown_webhook"], "internal") self.assertEqual(self.read_config(), saved) @@ -357,12 +436,7 @@ 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, - } - }, + self.webhook_form(enabled=True, url=url), settingsSvc.SettingsRuleError, ) @@ -372,18 +446,16 @@ def test_a_credentialed_target_rejects_the_whole_local_save(self): ) 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}}, + self.webhook_form( + enabled=enabled, url=credentialed_url + ), settingsSvc.SettingsRuleError, ) def test_an_unrelated_save_cannot_preserve_a_legacy_credentialed_target(self): config = self.stored_config() - config["webhook"]["url"] = ( + config["webhooks"][0]["url"] = ( "http://legacy-user:legacy-password@remote.example.lan/" "hooks/opensms" ) diff --git a/app/tests/test_webhook.py b/app/tests/test_webhook.py index 02e7580..48684e3 100644 --- a/app/tests/test_webhook.py +++ b/app/tests/test_webhook.py @@ -127,6 +127,22 @@ def write_config(self, enabled=True, url=None, secret="", **retry): "webhook": webhook, }, cf) + def write_multi_config(self, webhooks, **delivery): + config = { + "port": 9292, + "boot": False, + "webhook_delivery": { + "timeout": webhookSvc.DEFAULT_TIMEOUT, + "max_attempts": webhookSvc.DEFAULT_MAX_ATTEMPTS, + "backoff": list(webhookSvc.DEFAULT_BACKOFF), + "capacity": webhookSvc.DEFAULT_CAPACITY, + **delivery, + }, + "webhooks": webhooks, + } + with open(self.config_path, "w", encoding="utf-8") as cf: + json.dump(config, cf) + def write_live_webhook(self, **overrides): webhook = { "enabled": True, @@ -166,9 +182,18 @@ def wait_for_status(self, timeout=5): while time.time() < deadline: try: with open(self.status_path, encoding="utf-8") as sf: - return json.load(sf) + data = json.load(sf) + if isinstance(data, dict) and isinstance( + data.get("webhooks"), dict + ): + statuses = list(data["webhooks"].values()) + if statuses: + return statuses[0] + elif isinstance(data, dict): + return data except Exception: - time.sleep(0.02) + pass + time.sleep(0.02) self.fail("webhook status was not written") ## Contract @@ -189,6 +214,64 @@ def test_valid_target(self): webhookSvc.is_valid_target("http://proxy.example.lan:99999/hooks") ) + def test_keyword_matching_is_case_insensitive_and_start_anchored(self): + self.assertIsNotNone(webhookSvc.keyword_matches("#Sales: hi", "#sales")) + self.assertIsNotNone(webhookSvc.keyword_matches(" #sales hi", "#sales")) + self.assertIsNotNone(webhookSvc.keyword_matches("#sales", "#sales")) + self.assertIsNone(webhookSvc.keyword_matches("#salesforce hi", "#sales")) + self.assertIsNone(webhookSvc.keyword_matches("hi #sales", "#sales")) + + def test_strip_prefix_modes(self): + text = "#sales: hi" + self.assertEqual( + webhookSvc.strip_route_prefix(text, "#sales", "none"), text + ) + self.assertEqual( + webhookSvc.strip_route_prefix(text, "#sales", "keyword"), ": hi" + ) + self.assertEqual( + webhookSvc.strip_route_prefix( + text, "#sales", "keyword_and_separator" + ), + "hi", + ) + self.assertEqual( + webhookSvc.strip_route_prefix( + "#sales hello", "#sales", "keyword" + ), + " hello", + ) + self.assertEqual( + webhookSvc.strip_route_prefix( + "#sales hello", "#sales", "keyword" + ), + " hello", + ) + self.assertEqual( + webhookSvc.strip_route_prefix( + "#sales: hello", "#sales", "keyword_and_separator" + ), + " hello", + ) + self.assertEqual( + webhookSvc.strip_route_prefix( + "#sales hello", "#sales", "keyword_and_separator" + ), + "hello", + ) + + def test_sender_allowlist_normalizes_numbers_and_sender_ids(self): + self.assertTrue(webhookSvc.sender_allowed("x", [])) + self.assertTrue(webhookSvc.sender_allowed( + "+1 (555) 123-4567", ["15551234567"] + )) + self.assertTrue(webhookSvc.sender_allowed( + "BANKALERT", ["bankalert"] + )) + self.assertFalse(webhookSvc.sender_allowed( + "+15550000000", ["15551234567"] + )) + def test_payload_shape(self): payload = webhookSvc.build_inbound_payload({ "from": "BANKALERT", @@ -245,7 +328,9 @@ def test_test_without_url_fails_cleanly(self): 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) + saved = webhookSvc.get_webhook_runtime_config( + self.config_path + )["webhook_delivery"] calls = [] def record(url, body, headers, timeout): @@ -292,7 +377,10 @@ def test_delivers_signed_payload(self): self.assertEqual(body["from"], "+14155552671") self.assertEqual( request["headers"]["x-opensms-delivery"], - payload["delivery_id"], + body["delivery_id"], + ) + self.assertEqual( + request["headers"]["x-opensms-webhook-id"], "wh_legacy" ) self.assertTrue( request["headers"]["x-opensms-signature"].startswith("sha256=") @@ -373,8 +461,7 @@ def test_resume_honours_persisted_attempts(self): dispatcher = self.make_dispatcher(max_attempts=3) self.assertTrue(wait_for(lambda: dispatcher.pending_count() == 0)) self.assertEqual(self.target.count, 1) - with open(self.status_path, encoding="utf-8") as sf: - status = json.load(sf) + status = self.wait_for_status() self.assertFalse(status["ok"]) self.assertEqual(status["attempts"], 3) @@ -444,7 +531,7 @@ def _deliver(self, record): ) self.dispatchers.append(blocking) first = webhookSvc.build_inbound_payload({"from": "a", "text": "1"}) - blocking.enqueue(first) + queued = blocking.enqueue(first) self.assertTrue(wait_for(lambda: blocking.pending_count() == 1)) blocking.enqueue(webhookSvc.build_inbound_payload({"from": "b", "text": "2"})) blocking.enqueue(webhookSvc.build_inbound_payload({"from": "c", "text": "3"})) @@ -455,7 +542,9 @@ def _deliver(self, record): def test_missing_retry_settings_use_constants(self): self.write_config(enabled=True) - config = webhookSvc.get_webhook_config(self.config_path) + config = webhookSvc.get_webhook_runtime_config( + self.config_path + )["webhook_delivery"] self.assertEqual(config["timeout"], webhookSvc.DEFAULT_TIMEOUT) self.assertEqual( config["max_attempts"], webhookSvc.DEFAULT_MAX_ATTEMPTS @@ -464,9 +553,7 @@ def test_missing_retry_settings_use_constants(self): 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, + config = webhookSvc.normalize_webhook_delivery({ "timeout": 61, "max_attempts": "many", "backoff": [0, -1], @@ -482,7 +569,7 @@ def test_invalid_retry_settings_fall_back_to_constants(self): 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}) + config = webhookSvc.normalize_webhook_delivery({"timeout": timeout}) self.assertEqual( config["timeout"], webhookSvc.DEFAULT_TIMEOUT ) @@ -491,18 +578,18 @@ 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"], + webhookSvc.get_webhook_runtime_config( + missing_path, fallback={"webhook": fallback} + )["webhook_delivery"]["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.get_webhook_runtime_config( + missing_path, fallback={"webhook": fallback} + )["webhook_delivery"]["timeout"], webhookSvc.DEFAULT_TIMEOUT, ) @@ -531,7 +618,7 @@ def test_malformed_settings_do_not_crash_a_queued_delivery(self): self.assertTrue(wait_for(lambda: dispatcher.pending_count() == 0)) status = self.wait_for_status() self.assertFalse(status["ok"]) - self.assertEqual(status["error"], "webhook disabled") + self.assertEqual(status["error"], "webhook removed") def test_live_timeout_is_read_per_attempt(self): dispatcher = self.make_dispatcher(timeout=None) @@ -563,21 +650,35 @@ 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 + started = time.time() + dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": "y", + })) + self.assertTrue(wait_for(lambda: self.target.count == 1, timeout=2)) - with mock.patch.object(threading.Event, "wait", fake_wait): - dispatcher.enqueue(webhookSvc.build_inbound_payload({ - "from": "x", "text": "y", - })) - status = self.wait_for_status() + def first_attempt_persisted(): + try: + with open(self.outbox_path, encoding="utf-8") as of: + records = json.load(of) + except Exception: + return False + return bool( + records + and records[0].get("attempts") == 1 + and records[0].get("next_attempt_at", 0) > 0 + ) - self.assertTrue(status["ok"]) - self.assertEqual(status["attempts"], 2) - self.assertEqual([wait for wait in waits if wait is not None], [7]) + self.assertTrue(wait_for(first_attempt_persisted, timeout=2)) + with open(self.outbox_path, encoding="utf-8") as of: + outbox = json.load(of) + # The delivery is still in the Outbox, scheduled with the live 7s + # backoff, and the worker does not block other lanes while it waits. + self.assertEqual(len(outbox), 1) + self.assertEqual(outbox[0]["attempts"], 1) + self.assertGreaterEqual( + outbox[0]["next_attempt_at"] - started, 6.5 + ) + dispatcher.stop() def test_live_capacity_drops_oldest(self): class BlockingDispatcher(webhookSvc.WebhookDispatcher): @@ -598,7 +699,7 @@ def _deliver(self, record): self.dispatchers.append(dispatcher) self.write_live_webhook(capacity=10) first = webhookSvc.build_inbound_payload({"from": "a", "text": "1"}) - dispatcher.enqueue(first) + queued = dispatcher.enqueue(first) self.assertTrue(wait_for(lambda: dispatcher.pending_count() == 1)) for index in range(2, 12): dispatcher.enqueue(webhookSvc.build_inbound_payload({ @@ -609,7 +710,7 @@ def _deliver(self, record): 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) + self.assertNotIn(queued[0], delivery_ids) dispatcher.release.set() def test_explicit_max_attempts_wins_over_live_settings(self): @@ -623,6 +724,296 @@ def test_explicit_max_attempts_wins_over_live_settings(self): self.assertEqual(status["attempts"], 1) self.assertEqual(self.target.count, 1) + ## Routing + + def test_single_webhook_ignores_keyword_and_stripping(self): + self.write_multi_config([ + { + "id": "wh_solo", + "enabled": True, + "url": self.target.url, + "secret": "", + "keyword": "#sales", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + }, + ]) + dispatcher = self.make_dispatcher() + queued = dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": "#sales: hello", + })) + self.assertEqual(len(queued), 1) + request = self.target.next_request() + body = json.loads(request["body"]) + self.assertEqual(body["text"], "#sales: hello") + self.assertEqual( + request["headers"]["x-opensms-webhook-id"], "wh_solo" + ) + + def test_single_webhook_honours_its_sender_allowlist(self): + self.write_multi_config([ + { + "id": "wh_solo", + "enabled": True, + "url": self.target.url, + "secret": "", + "keyword": "#ignored", + "strip_prefix": "keyword_and_separator", + "allowed_senders": ["+15551234567"], + }, + ]) + dispatcher = self.make_dispatcher() + + self.assertEqual(dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "+15550000000", "text": "hello", + })), []) + self.assertEqual(self.target.count, 0) + + queued = dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "+1 (555) 123-4567", "text": "#ignored: hello", + })) + self.assertEqual(len(queued), 1) + request = self.target.next_request() + self.assertEqual(json.loads(request["body"])["text"], "#ignored: hello") + + def test_multiple_webhooks_route_by_keyword_and_strip(self): + second = MockTarget() + self.addCleanup(second.close) + self.write_multi_config([ + { + "id": "wh_a", + "enabled": True, + "url": self.target.url, + "secret": "", + "keyword": "#sales", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + }, + { + "id": "wh_b", + "enabled": True, + "url": second.url, + "secret": "", + "keyword": "#ops", + "strip_prefix": "keyword", + "allowed_senders": [], + }, + ]) + dispatcher = self.make_dispatcher() + + dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": "#sales: hello", + })) + first = self.target.next_request() + self.assertEqual(json.loads(first["body"])["text"], "hello") + self.assertEqual( + first["headers"]["x-opensms-webhook-id"], "wh_a" + ) + + dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": "#OPS: hello", + })) + second_request = second.next_request() + self.assertEqual(json.loads(second_request["body"])["text"], ": hello") + self.assertEqual( + second_request["headers"]["x-opensms-webhook-id"], "wh_b" + ) + + def test_keyword_match_needs_a_separator_and_catch_all_gets_the_rest(self): + self.write_multi_config([ + { + "id": "wh_a", + "enabled": True, + "url": self.target.url, + "secret": "", + "keyword": "#sales", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + }, + { + "id": "wh_catch", + "enabled": True, + "url": self.target.url, + "secret": "", + "keyword": "", + "strip_prefix": "none", + "allowed_senders": [], + }, + ]) + dispatcher = self.make_dispatcher() + + dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": "#salesforce hi", + })) + request = self.target.next_request() + self.assertEqual( + json.loads(request["body"])["text"], "#salesforce hi" + ) + self.assertEqual( + request["headers"]["x-opensms-webhook-id"], "wh_catch" + ) + + def test_unmatched_message_without_catch_all_is_dropped(self): + self.write_multi_config([ + { + "id": "wh_a", + "enabled": True, + "url": self.target.url, + "secret": "", + "keyword": "#sales", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + }, + { + "id": "wh_b", + "enabled": True, + "url": self.target.url, + "secret": "", + "keyword": "#ops", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + }, + ]) + dispatcher = self.make_dispatcher() + queued = dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": "hello", + })) + self.assertEqual(queued, []) + self.assertEqual(dispatcher.pending_count(), 0) + with self.assertRaises(queue.Empty): + self.target.next_request(timeout=0.3) + + def test_sender_allowlist_blocks_without_falling_through(self): + self.write_multi_config([ + { + "id": "wh_a", + "enabled": True, + "url": self.target.url, + "secret": "", + "keyword": "#vip", + "strip_prefix": "keyword_and_separator", + "allowed_senders": ["+1 (555) 123-4567"], + }, + { + "id": "wh_catch", + "enabled": True, + "url": self.target.url, + "secret": "", + "keyword": "", + "strip_prefix": "none", + "allowed_senders": [], + }, + ]) + dispatcher = self.make_dispatcher() + + queued = dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "+15551234567", "text": "#vip: hello", + })) + self.assertEqual(len(queued), 1) + request = self.target.next_request() + self.assertEqual(json.loads(request["body"])["text"], "hello") + + queued = dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "+15550000000", "text": "#vip: blocked", + })) + self.assertEqual(queued, []) + with self.assertRaises(queue.Empty): + self.target.next_request(timeout=0.3) + + def test_a_backing_off_webhook_does_not_block_another_lane(self): + second = MockTarget() + self.addCleanup(second.close) + self.target.queue_statuses(500) + self.write_multi_config( + [ + { + "id": "wh_bad", + "enabled": True, + "url": self.target.url, + "secret": "", + "keyword": "#bad", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + }, + { + "id": "wh_good", + "enabled": True, + "url": second.url, + "secret": "", + "keyword": "#good", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + }, + ], + backoff=[30], + ) + dispatcher = self.make_dispatcher(backoff=None) + + bad_queued = dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": "#bad: hello", + })) + good_queued = dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": "#good: hello", + })) + self.assertEqual(len(bad_queued), 1) + self.assertEqual(len(good_queued), 1) + + self.assertTrue(wait_for(lambda: second.count == 1, timeout=5)) + self.assertTrue(wait_for(lambda: self.target.count == 1, timeout=5)) + self.assertTrue(wait_for( + lambda: dispatcher.pending_for("wh_good") == 0, timeout=5 + )) + self.assertEqual(dispatcher.pending_for("wh_bad"), 1) + + def test_disabling_a_target_fails_its_backing_off_records(self): + self.write_live_webhook(max_attempts=3, backoff=[30]) + self.target.queue_statuses(500) + dispatcher = self.make_dispatcher(backoff=None) + dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": "y", + })) + self.assertTrue(wait_for(lambda: self.target.count == 1, timeout=3)) + + self.write_config(enabled=False) + self.assertTrue(wait_for( + lambda: dispatcher.pending_count() == 0, timeout=3 + )) + status = self.wait_for_status() + self.assertFalse(status["ok"]) + self.assertEqual(status["error"], "webhook disabled") + + self.write_config(enabled=True) + time.sleep(1) + self.assertEqual(self.target.count, 1) + self.assertEqual(dispatcher.pending_count(), 0) + + def test_deleting_a_target_drops_its_backing_off_records(self): + self.write_multi_config([ + { + "id": "wh_gone", + "enabled": True, + "url": self.target.url, + "secret": "", + "keyword": "", + "strip_prefix": "keyword_and_separator", + "allowed_senders": [], + }, + ], max_attempts=3, backoff=[30]) + self.target.queue_statuses(500) + dispatcher = self.make_dispatcher(backoff=None) + dispatcher.enqueue(webhookSvc.build_inbound_payload({ + "from": "x", "text": "y", + })) + self.assertTrue(wait_for(lambda: self.target.count == 1, timeout=3)) + + self.write_multi_config([]) + self.assertTrue(wait_for( + lambda: dispatcher.pending_count() == 0, timeout=3 + )) + status = self.wait_for_status() + self.assertFalse(status["ok"]) + self.assertEqual(status["error"], "webhook removed") + ## 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 2896f0a..f50592f 100644 --- a/docs/adr/0001-inbound-sms-webhook.md +++ b/docs/adr/0001-inbound-sms-webhook.md @@ -2,7 +2,7 @@ OpenSMS was outbound-only: a sticky foreground service on Android runs the FastAPI sender and survives the UI being closed. To forward Inbound SMS, that service registers an `SMS_RECEIVED` receiver at runtime; the receiver writes one spool file per SMS (temp file + rename, so a partial record is never visible), and the service claims each file, persists a Webhook delivery in the Outbox, then acknowledges the file. The Outbox is a single ordered worker with bounded retries. The app deliberately does not become the default SMS app: that role would require handling `SMS_DELIVER` and the whole messaging surface. The receiver never does network I/O, and delivery stays outside the API server so Webhooks work whether or not the HTTP API is running. -**Status**: accepted +**Status**: accepted (multi-Webhook routing and per-target Outbox lanes supersede parts of this decision in ADR 0003) ## Considered options diff --git a/docs/adr/0003-multi-webhook-routing.md b/docs/adr/0003-multi-webhook-routing.md new file mode 100644 index 0000000..74ea6c1 --- /dev/null +++ b/docs/adr/0003-multi-webhook-routing.md @@ -0,0 +1,27 @@ +# Prefix-routed multi-Webhook delivery + +OpenSMS 1.2.0 delivered every Inbound SMS to one `webhook` object: one target, one secret, one retry policy. Operators with several receivers (a CRM, a spreadsheet, an alerting service) had to run their own fan-out proxy. 1.3.0 replaces the single object with a `webhooks` array whose entries can be selected by a prefix keyword in the SMS, can strip that keyword, and can restrict delivery to a Sender allowlist. + +**Status**: accepted + +## Decisions + +- **Storage.** `settings.webhook` becomes `settings.webhooks`, an array of entries with `id`, optional `name`, `enabled`, `url`, `secret`, `keyword`, `strip_prefix`, and `allowed_senders`. The retry policy moves to top-level `webhook_delivery` (`timeout`, `max_attempts`, `backoff`, `capacity`). A legacy `config.json` single-`webhook` object is migrated on load to a one-element array with id `wh_legacy`; the next write persists the new shape and migration never bumps the Revision. +- **API.** `GET /api/settings` returns the array shape. `PUT /api/settings` is a full replacement: entries with an `id` update, entries without one are created, omitted entries are deleted. Server ids are opaque and immutable (`wh_` + 8 lowercase hex); unknown or duplicate ids are `422`. Secrets use per-entry sentinel semantics: omitted keeps by id, `""` clears, a non-empty string replaces. A legacy single-`webhook` PUT body is accepted for one release as a one-entry shim and cannot be combined with the new shape; it is deprecated with removal targeted at 1.4.0. +- **Routing.** Exactly one enabled Webhook receives each Inbound SMS. With one enabled Webhook, keyword matching and stripping are ignored, preserving 1.2.0 behaviour. With two or more, the unique case-insensitive Route keyword wins, then the single catch-all (empty keyword); otherwise the SMS is dropped and logged. A keyword matches only at the start after optional whitespace and must be followed by `:`, whitespace, or end-of-message, so `#sales` does not match `#salesforce`. Keywords are unique across all entries, including disabled ones, and at most one entry may be a catch-all. +- **Prefix stripping.** Per Webhook: `none`, `keyword` (keep the separator), or `keyword_and_separator` (remove both, then trim one following space). Stripping changes only the payload `text`; matching always uses the original message. +- **Sender allowlist.** Empty means every sender. Numeric senders compare by digits after removing formatting and a leading `+`; alphanumeric sender IDs compare case-insensitively. A blocked sender is dropped, never rerouted to the catch-all. +- **Delivery.** One persisted Outbox, partitioned into per-Webhook FIFO lanes processed by one round-robin worker, so a target in backoff does not block the others. Capacity remains a global drop-oldest limit. Each `(Inbound SMS, Webhook)` delivery gets its own `delivery_id`; the text may differ after stripping. Status is stored per Webhook id, and `GET /api/status` returns a `webhooks` array. +- **Payload.** The JSON keys are unchanged. Delivery adds `X-OpenSMS-Webhook-Id` so a receiver can identify the route without depending on stripped text. +- **Limits.** 20 Webhooks, 32-character keyword, 64-character name, 100 allowlist entries per Webhook, 256-character secret. +- **UI.** The Settings screen shows a dynamic list of collapsible Webhook cards with add, delete, per-card test, and last-delivery status. Keyword and strip fields appear when two or more Webhooks are configured. All edits stay local until Save; enabling a card no longer auto-saves. Delete warns that pending deliveries for that Webhook will be dropped. + +## Consequences + +- One enabled Webhook keeps the 1.2.0 contract and does not require a keyword. +- Multiple enabled Webhooks without a catch-all silently discard unmatched SMS; `/api/status` exposes `webhook_unrouted` to make that visible. +- The legacy PUT shim is destructive on a multi-Webhook install: a single `webhook` body replaces the whole array. It is documented and deprecated. +- Deleting a Webhook drops its pending deliveries; disabling one fails them with `webhook disabled`. Editing a URL or secret leaves already-enqueued records on their captured URL and payload, reading the secret live by id. +- The Outbox still has a single worker. A slow HTTP call occupies it up to the configured timeout, though a target in backoff no longer blocks other lanes. +- Per-entry unknown disk fields are preserved by id. Deleting and recreating the same semantic target produces a new id and loses them, as expected from full-replacement semantics. +- At-least-once delivery is unchanged: a crash after persisting a delivery can duplicate it, but never loses it silently. diff --git a/docs/remote-api.md b/docs/remote-api.md index 323931a..6aace4c 100644 --- a/docs/remote-api.md +++ b/docs/remote-api.md @@ -1,9 +1,10 @@ # Remote Settings & Control API -**Status:** implemented; ships as `1.2.0`. +**Status:** implemented; ships as `1.3.0` (1.2.0 remote API plus multi-Webhook +routing). **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`). +**Baseline:** `develop` at `12d8fd3`, app version `1.2.0`. +**Target:** ship as `1.3.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 @@ -15,14 +16,14 @@ questions the brief left open. 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. +`POST /sms/` and forwards inbound SMS to one or more Webhooks, 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 and write the writable settings (port, launch behaviour, Webhook list, + per-Webhook secrets and routing rules, shared retry policy); - read health and status; - test the webhook; - restart the API server after a port change; @@ -111,11 +112,29 @@ Other facts that constrain the work: | 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. | +### 4.1 1.3.0 multi-Webhook decisions + +| # | Decision | Why | +|---|---|---| +| D15 | Replace the single `webhook` object with a `webhooks` array; move retry policy to top-level `webhook_delivery`. | Retry policy is shared by every target; a target owns only its URL, secret, and routing rule. | +| D16 | Migrate a legacy `config.json` `webhook` object to a one-element array with id `wh_legacy` on load; the next write persists the new shape. Never bump the Revision on load. | Existing installs keep working, including pending Outbox records. | +| D17 | `PUT /api/settings` keeps accepting the legacy single `webhook` body for one release, but not combined with `webhooks`/`webhook_delivery`; the shim reuses the first existing id. | Protects existing scripts while the new contract lands. Deprecated; removal targeted at 1.4.0. | +| D18 | With exactly one enabled Webhook, keyword routing and prefix stripping are ignored and the full text is delivered. With two or more, exactly one target is chosen: unique case-insensitive prefix keyword, then the single catch-all (empty keyword). | The single-target case needs no routing and must behave like 1.2.0. Exactly-one avoids duplicate deliveries. | +| D19 | A keyword matches only at the start after optional whitespace, followed by `:`, whitespace, or end-of-message. Keywords are unique across all entries, including disabled ones. | `#sales` must not match `#salesforce`; uniqueness keeps routing deterministic. | +| D20 | Per-Webhook `strip_prefix` is `none`, `keyword`, or `keyword_and_separator`; stripping affects only the payload `text`, never matching. | The receiver chooses how much of the route prefix remains. | +| D21 | `allowed_senders` is a per-Webhook list; empty means all. Numeric senders compare by digits, alphanumeric sender IDs case-insensitively. A blocked sender is dropped, with no fallback to the catch-all. | The route decision comes first; silently rerouting a blocked sender would defeat the allowlist. | +| D22 | The Outbox stays one persisted file but is partitioned into per-target FIFO lanes processed by one round-robin worker. Capacity is global drop-oldest. | A target in backoff must not block deliveries to the other targets, and per-target order still matters. | +| D23 | Each target delivery gets its own `delivery_id`; status is stored per Webhook id; `GET /api/status` returns a `webhooks` array. | Text may differ after stripping, and each HTTP request is its own Delivery. | +| D24 | Delivery adds `X-OpenSMS-Webhook-Id`; the JSON payload keys are unchanged. | Receivers can identify the route without depending on stripped text. | +| D25 | Limits: 20 Webhooks, 32-character keyword, 64-character name, 100 allowlist entries per Webhook. | Bounds the Settings screen and the per-entry validation cost. | + --- ## 5. Vocabulary -See `GLOSSARY.md`: **Settings**, **Revision**, **Scope**, **API key**, +See `GLOSSARY.md`: **Webhook**, **Webhook delivery**, **Webhook target**, +**Route keyword**, **Catch-all Webhook**, **Sender allowlist**, **Delivery +policy**, **Outbox lane**, **Settings**, **Revision**, **Scope**, **API key**, **Restart**. **Outbox** remains webhook-only. --- @@ -156,7 +175,7 @@ See `GLOSSARY.md`: **Settings**, **Revision**, **Scope**, **API key**, ### 6.2 `GET /api/health` ```json -{"status": "ok", "version": "1.2.0", "platform": "android", "uptime_s": 812} +{"status": "ok", "version": "1.3.0", "platform": "android", "uptime_s": 812} ``` `uptime_s` is seconds since the current `PosiApiServer` instance started; `0` @@ -166,7 +185,7 @@ when unknown. `platform` comes from `get_os_platform()`. ```json { - "version": "1.2.0", + "version": "1.3.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}, @@ -174,18 +193,23 @@ when unknown. `platform` comes from `get_os_platform()`. "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" + "webhooks": [ + { + "id": "wh_5b581975", + "name": "Proxy", + "enabled": true, + "url_host": "proxy.example.lan", + "secret_set": true, + "pending": 0, + "last_delivery": { + "ok": true, "event": "sms.received", "delivery_id": "...", + "http_status": 204, "attempts": 1, "error": null, + "at": "2026-11-26T12:34:56+01:00" + } } - }, + ], + "outbox_pending": 0, + "outbox_capacity": 100, "warnings": [] } ``` @@ -200,16 +224,21 @@ Rules: - `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. Credentialed target URLs and - details of the current target are scrubbed from its error text. -- `outbox_pending`: provider value, `null` when unavailable. +- `webhooks`: one entry per configured Webhook, in Settings order. + `url_host` is `urlparse(url).hostname`, `null` if empty or invalid. Never + path, query, or credentials. `pending` is the number of deliveries for that + target, `0` when unavailable. +- `last_delivery`: `null` when no status exists for that Webhook. Credentialed + target URLs and details of the current target are scrubbed from its error + text. +- `outbox_pending`: global 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`. + - `webhook_disabled` โ€” no Webhook is enabled, so every new Inbound SMS is + discarded, with a message saying exactly that. + - `webhook_url_invalid` โ€” one enabled Webhook has a target that fails + `is_valid_target`; the warning carries its `webhook_id`. + - `webhook_unrouted` โ€” two or more Webhooks are enabled and no catch-all + exists, so SMS that match no keyword are discarded. - `outbox_near_capacity` โ€” `pending >= 0.8 * capacity`. ### 6.4 `GET /api/settings` @@ -220,22 +249,31 @@ Rules: "settings": { "port": 9292, "boot": true, - "webhook": { - "enabled": true, - "url": "https://proxy.example.lan/hooks/opensms", - "secret_set": true, + "webhook_delivery": { "timeout": 10, "max_attempts": 3, "backoff": [5, 30], "capacity": 100 - } + }, + "webhooks": [ + { + "id": "wh_5b581975", + "name": "Proxy", + "enabled": true, + "url": "https://proxy.example.lan/hooks/opensms", + "secret_set": true, + "keyword": "#proxy", + "strip_prefix": "keyword_and_separator", + "allowed_senders": ["+14155552671"] + } + ] } } ``` -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. +Never include `permissions`, `app`, or any raw secret. If a stored target +contains URL userinfo, that entry's `url` is returned with the userinfo removed; +the persisted value remains unchanged and invalid for forwarding. ### 6.5 `PUT /api/settings` @@ -244,24 +282,40 @@ removed; the persisted value remains unchanged and invalid for forwarding. "revision": 7, "port": 9292, "boot": true, - "webhook": { - "enabled": true, - "url": "https://proxy.example.lan/hooks/opensms", - "secret": "new-shared-secret", + "webhook_delivery": { "timeout": 10, "max_attempts": 3, "backoff": [5, 30], "capacity": 100 - } + }, + "webhooks": [ + { + "id": "wh_5b581975", + "name": "Proxy", + "enabled": true, + "url": "https://proxy.example.lan/hooks/opensms", + "secret": "new-shared-secret", + "keyword": "#proxy", + "strip_prefix": "keyword_and_separator", + "allowed_senders": ["+14155552671"] + } + ] } ``` -Required: `port`, `boot`, `webhook` and all webhook fields except `secret`. -Optional: `revision`, `webhook.secret`. +Required: `port`, `boot`, `webhook_delivery` and all four delivery fields, and +`webhooks` (the array may be empty). For each entry, required: `enabled`, `url`, +`keyword`, `strip_prefix`, `allowed_senders`. Optional per entry: `id`, `name`, +`secret`. -Secret sentinel: +The array is a **full replacement**: entries with an `id` update that Webhook, +entries without an `id` are created, and an omitted entry is deleted. Server ids +are opaque and immutable (`wh_` + 8 lowercase hex). An unknown or duplicate id +is a `422`. -- omitted โ†’ keep the stored secret +Secret sentinel, per entry: + +- omitted โ†’ keep the stored secret for that id - `""` โ†’ clear it - non-empty string โ†’ replace it (max 256 characters) @@ -271,26 +325,39 @@ Validation: |---|---|---| | `port` | integer, `1025 <= port <= 65535` | `422` | | `boot` | JSON boolean | `422` | -| `webhook.enabled` | JSON boolean | `422` | -| `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` | -| `webhook.backoff` | list of 1โ€“8 positive integers, each โ‰ค 3600 | `422` | -| `webhook.capacity` | integer 10โ€“5000 | `422` | +| `webhook_delivery.timeout` | integer 1โ€“60 (seconds) | `422` | +| `webhook_delivery.max_attempts` | integer 1โ€“50 | `422` | +| `webhook_delivery.backoff` | list of 1โ€“8 positive integers, each โ‰ค 3600 | `422` | +| `webhook_delivery.capacity` | integer 10โ€“5000 | `422` | +| `webhooks` | list of at most 20 entries | `422` | +| `webhooks[].id` | `wh_` + 6โ€“16 lowercase alphanumerics; unknown/duplicate โ†’ `422` | `422` | +| `webhooks[].name` | string, โ‰ค 64 chars; optional | `422` | +| `webhooks[].enabled` | JSON boolean | `422` | +| `webhooks[].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 | +| `webhooks[].secret` | string, โ‰ค 256 chars, per-entry sentinel | `422` | +| `webhooks[].keyword` | empty (catch-all) or 1โ€“32 chars matching `^#?[A-Za-z0-9][A-Za-z0-9_-]*$`; unique case-insensitively; at most one empty | `422` for shape; `400` for duplicate keyword or a second catch-all | +| `webhooks[].strip_prefix` | `none`, `keyword`, or `keyword_and_separator` | `422` | +| `webhooks[].allowed_senders` | list of at most 100 non-empty strings, each โ‰ค 64 chars; duplicates normalized away | `422` | | unknown key, any level | rejected | `422` | | `revision` | integer; if present and โ‰  current โ†’ conflict | `409` | +The legacy body shape (`webhook` with embedded retry fields) is accepted for one +release as a one-entry shim; it cannot be combined with `webhooks` or +`webhook_delivery`. Deprecated; removal is targeted at 1.4.0. + 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. +2. Apply the writable fields; preserve `app`, `permissions`, and unknown keys + (including unknown keys inside each Webhook entry, matched by id). +3. Re-validate the merged object, without re-checking the length of an + already-stored secret. 4. `revision = current.revision + 1`; atomic write. -5. Log field names only: `Settings updated: port=9292 webhook.enabled=true secret=set`. +5. Log field names only: + `Settings updated: port, boot, webhook_delivery, webhooks[0].url`. `200`: @@ -308,21 +375,37 @@ current state, not about this request: a previously pending port change also reports `true`. 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. +service. Changing any Webhook or delivery field never requires a restart. +Deleting a Webhook drops its pending deliveries; disabling one fails them with +`webhook disabled`. Editing a target or secret leaves already-enqueued records +on their captured URL and payload, reading the secret live by id. ### 6.6 `POST /api/webhook/test` Optional body: +```json +{"id": "wh_5b581975", "secret": "..."} +``` + +or, to test an unsaved target: + ```json {"url": "https://proxy.example.lan/hooks/opensms", "secret": "..."} ``` -- No body โ†’ saved webhook target and secret. +- `id` selects a saved Webhook. When more than one Webhook is configured, `id` + is required; with exactly one configured it is the default. Unknown id โ†’ + `404`. +- `id` and `url` cannot be combined (`422`). - `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`. +- Uses the saved `webhook_delivery.timeout`. +- The test payload bypasses keyword routing and sender allowlists; it has no + `from`. +- When `id` is used, the request carries `X-OpenSMS-Webhook-Id`; URL-only tests + do not. `200`: `{"ok": true, "http_status": 204, "error": null}` `502`: `{"ok": false, "http_status": 500, "error": "HTTP 500"}` @@ -429,7 +512,7 @@ delivered. Numbers must be E.164. Default SIM only. ## 7. Persisted schemas -`config.json` (v1 gains `revision` and webhook retry fields): +`config.json` (v2 since 1.3.0; v1 had a single `webhook` object): ```json { @@ -438,21 +521,41 @@ delivered. Numbers must be E.164. Default SIM only. "boot": false, "permissions": false, "revision": 7, - "webhook": { - "enabled": false, - "url": "", - "secret": "", + "webhook_delivery": { "timeout": 10, "max_attempts": 3, "backoff": [5, 30], "capacity": 100 - } + }, + "webhooks": [ + { + "id": "wh_5b581975", + "name": "Proxy", + "enabled": false, + "url": "https://proxy.example.lan/hooks/opensms", + "secret": "plaintext-secret", + "keyword": "#proxy", + "strip_prefix": "keyword_and_separator", + "allowed_senders": ["+14155552671"] + } + ] } ``` - 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. +- Missing delivery fields โ†’ current constants. Unknown top-level, delivery, and + per-Webhook fields are preserved; unknown fields are matched to a Webhook by + id. +- A legacy `webhook` object is migrated on load to a one-element array with id + `wh_legacy`, and supplies `webhook_delivery` when that object is absent. The + next write persists the new shape. +- If both `webhooks` and `webhook` exist, `webhooks` wins; the legacy object is + ignored (and a warning is logged by the runtime loader). +- Secrets stay plaintext at rest, as before. Masking is API-level only. +- The legacy `webhook_status.json` single object maps to the migrated + Webhook; the new format is `{"webhooks": {"": {...}}}`. +- Legacy Outbox records without `webhook_id` are attached to `wh_legacy` and + delivered to their captured URL with that Webhook's live secret. `keys.json` v2: @@ -506,14 +609,17 @@ 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. + the Webhook card list, and each card's last-delivery label. +2. On save: build the full `webhooks` array from the cards (ids for existing + entries, no id for new ones; secrets only when the operator typed or cleared + one), plus changed `port`/`boot`, then call + `settingsSvc.save_local_settings(config_path, form)`. +3. Invalid port (< 1025 or > 65535), a bad keyword, or an enabled Webhook + without a valid URL rejects the **whole** save with a toast; the offending + card is expanded. No partial write. 4. Adopt the returned object into `config_template` and refresh the views. +5. Adding or deleting a card is local until Save. Delete asks for confirmation + and explains that pending deliveries for that Webhook will be dropped. `write_request()` becomes atomic and writes `port` from the last loaded settings. @@ -522,6 +628,11 @@ settings. ## 9. File-by-file change plan +The table below describes the 1.2.0 remote API delivery. The 1.3.0 multi-Webhook +change touches `settingsSvc`, `webhookSvc`, `postApi`, `appSvc`, `main.py`, +`screens/settings.py`, the tests, and the docs; its contract is in ยง4.1 and +ยง6.3โ€“ยง7. + | 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`. | @@ -593,6 +704,27 @@ Required cases: from `config.json` when constructor args are absent; constructor args still override (existing tests must pass unchanged). +1.3.0 multi-Webhook cases: + +13. Routing: one enabled Webhook ignores keyword/stripping; two or more match + case-insensitively only at the start, require a separator, strip according + to the mode, use the single catch-all for unmatched SMS, and drop when + nothing matches. +14. Sender allowlists: empty allows all; numeric values normalize formatting; + a blocked sender is dropped without fallback. +15. Per-target lanes: a Webhook in backoff does not delay another Webhook's + delivery; capacity remains global drop-oldest. +16. Migration: legacy `config.json` โ†’ `webhooks` with `wh_legacy`, legacy + Outbox records attached to it, legacy status file displayed for it, and no + Revision bump on load. +17. API schema: full-array PUT, id creation/reuse, unknown/duplicate id `422`, + per-entry secret sentinel, one-release legacy `webhook` shim, and + `POST /api/webhook/test` id selection/404/id+url `422`. +18. Status: per-Webhook `last_delivery`/`pending`, `webhook_url_invalid` with + `webhook_id`, `webhook_unrouted`, and `webhook_disabled`. +19. UI merge: adding, editing, and deleting cards through + `save_local_settings`, preserving secrets and unknown per-entry fields. + Run: ```bash @@ -626,11 +758,11 @@ 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 + writable setting, test any Webhook, restart the server, and manage keys. +2. `GET /api/settings` never reveals a secret; `GET /api/keys` never reveals hashes; raw keys appear only in the creation response. -3. Webhook target/secret/enable and retry changes take effect on the next inbound - SMS without a restart. +3. Webhook target/secret/enable, routing rules, 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. @@ -641,6 +773,11 @@ Core total โ‰ˆ 600โ€“900 source lines, 3โ€“4 focused days. 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. +11. One enabled Webhook behaves exactly like 1.2.0: keyword and stripping are + ignored. Two or more route to exactly one target, with optional catch-all. +12. A legacy 1.2.0 `config.json`, Outbox, and status file upgrade without losing + pending deliveries or the last-delivery display. +13. No target's retry backoff delays another target's deliveries. --- @@ -655,10 +792,11 @@ Core total โ‰ˆ 600โ€“900 source lines, 3โ€“4 focused days. ~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. +5. **Ack-on-disabled discards SMS.** A remote client that disables every + Webhook destroys every SMS received while they are off. The status warning + must say so. +6. **Outbox full drops the oldest** record across all lanes. Capacity is + 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. **Pydantic request models are an HTTP edge, not a second domain layer.** @@ -670,6 +808,18 @@ Core total โ‰ˆ 600โ€“900 source lines, 3โ€“4 focused days. 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. +12. **Misconfigured routing can silently discard SMS.** Two or more enabled + Webhooks without a catch-all drop unmatched messages; `/api/status` exposes + `webhook_unrouted` so an operator can see it. +13. **Legacy PUT shim is destructive on a multi-Webhook install.** A legacy + single-`webhook` body replaces the whole array (reusing the first id). + Documented and deprecated; removal at 1.4.0. +14. **One Webhook in backoff no longer blocks others**, but a slow HTTP call + still occupies the single worker. The timeout bounds that delay; a fully + non-blocking worker is out of scope. +15. **Per-entry unknown fields are preserved by id.** A client that deletes and + recreates the same semantic target gets a new id and loses those fields; + this is intentional full-replacement semantics. --- diff --git a/docs/webhook/receiver_test.md b/docs/webhook/receiver_test.md index 24814a5..91ff48e 100644 --- a/docs/webhook/receiver_test.md +++ b/docs/webhook/receiver_test.md @@ -19,9 +19,10 @@ 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.2.0" \ + -H "User-Agent: OpenSMS/1.3.0" \ -H "X-OpenSMS-Event: sms.received" \ -H "X-OpenSMS-Delivery: 6f1c2f5e-0d7a-4c55-9f0e-2b1c8b7f0a11" \ + -H "X-OpenSMS-Webhook-Id: wh_5b581975" \ -H "X-OpenSMS-Signature: sha256=dummy" \ -d '{ "event": "sms.received",