From 85fc1d3abceba3e31df69b2d0131794e807c2fd7 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Thu, 15 Oct 2026 23:23:13 +0000 Subject: [PATCH] feat(automations): a webhook address per automation trigger A trigger {"on": "webhook"} gets a secret address when its automation is saved (automation_hooks.token_for, revoke for M6). A call to POST /api/v1/automations/hooks/{token} takes JSON, a form or text up to 64 KB, at most 60 calls a minute per hook, checks a Standard Webhooks signature when one is sent (or required), and logs a webhook.received activity once per message id, answering 202 at once. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01QewNs6jxSB2vRoag2EvdyX --- docs/api.md | 19 ++ docs/automations.md | 41 ++- docs/database.md | 3 +- fastapi_backend/app/api/v1/router.py | 2 + .../app/api/v1/routes/automation_hooks.py | 100 +++++++ .../app/domain/automation_hooks.py | 260 ++++++++++++++++++ fastapi_backend/app/domain/events.py | 1 + fastapi_backend/app/domain/events_streams.py | 61 ++++ fastapi_backend/app/domain/store.py | 4 + .../app/schemas/automation_hooks.py | 11 + .../tests/api/test_automation_hooks.py | 179 ++++++++++++ nextjs-frontend/app/openapi-client/index.ts | 7 + nextjs-frontend/app/openapi-client/sdk.gen.ts | 27 ++ .../app/openapi-client/types.gen.ts | 63 +++++ nextjs-frontend/openapi.json | 102 +++++++ threat-model.json | 10 + threat-model.md | 1 + threat-model.yaml | 12 +- 18 files changed, 900 insertions(+), 3 deletions(-) create mode 100644 fastapi_backend/app/api/v1/routes/automation_hooks.py create mode 100644 fastapi_backend/app/domain/automation_hooks.py create mode 100644 fastapi_backend/app/domain/events_streams.py create mode 100644 fastapi_backend/app/schemas/automation_hooks.py create mode 100644 fastapi_backend/tests/api/test_automation_hooks.py diff --git a/docs/api.md b/docs/api.md index 9dd651a6b..e9525b200 100644 --- a/docs/api.md +++ b/docs/api.md @@ -206,6 +206,25 @@ Each person marks activities `reviewed`, `important` or `hidden` for themselves and `POST /activities/mark` with `ids` (up to 500) answers `{marks, unknown}`. `GET /activities` has your marks on the page in `marks` and filters by them with `reviewed`, `important` and `hidden` (true or false). +## automations + +``` +POST /api/v1/automations/hooks/{token} +``` + +An automation's webhook ([Webhook trigger](automations.md#webhook-trigger)): calling the address of a trigger +`{"on": "webhook"}` sets that automation off. No session or API token: the token in the address (`lah_...`, shown +once when the automation is saved) is the credential. Send JSON, a form (text fields) or text, up to 64 KB; the answer +(202) is `{"id"}`, the `webhook.received` activity the call made, before the automation runs. Sign the call the +Standard Webhooks way (`webhook-id`, `webhook-timestamp`, `webhook-signature`, with the secret shown with the +address) and the signature is checked; a `webhook-id` or `Idempotency-Key` makes a retried call count once. 401 for a +token that isn't a webhook's or a signature that doesn't match, 403 while the automation is switched off, 413 over 64 +KB, 415 for other bodies, 429 past 60 calls a minute. + +``` +curl -H "Content-Type: application/json" -d '{"event": "doorbell"}' https://lens.example/api/v1/automations/hooks/lah_... +``` + ## vaults ``` diff --git a/docs/automations.md b/docs/automations.md index 75cfbc92b..9e120cfce 100644 --- a/docs/automations.md +++ b/docs/automations.md @@ -15,7 +15,7 @@ merged is called built. | New assets by kind: emails received, calendar events, files from storage, uploads, pages saved from the web, imports | built | | Runs that finished or failed, deletions and calendar events that moved | built | | Comments, notes written and saved, and changes to the entity graph | built | -| More kinds: sensors, chat, webhooks, system events | planned | +| More kinds: sensors, chat, system events | planned | | The timeline API (`GET /api/v1/activities`), the MCP tools `timeline` and `event_kinds`, the assistant's `timeline` | built | | Review marks on the timeline (reviewed, important, hidden), their filters and `mark_activities` ([Timeline](timeline.md)) | built | | The shapes of triggers, joins, an If, policy and intents, checked (`app/domain/automation_spec.py`) | built | @@ -26,6 +26,7 @@ merged is called built. | Running Lens work: the `run_workflow`, `run_pipeline` and `run_routine` actions | built | | Changing assets and writing notes: the `set_field`, `add_to_collection` and `write_note` actions | built | | Settings → Automations: how often followers look and how long the event log is kept | built | +| A webhook address per automation trigger, and calls to it as `webhook.received` ([Webhook trigger](#webhook-trigger)) | built | | The Timeline page with filters, grouping, review keys and new items, and Home's Latest card ([Timeline](timeline.md)) | built | | Storing and running automations, schedules and timers, joins, approvals, variables, the studio | planned | @@ -101,6 +102,7 @@ and the paths holding outside text are in `GET /api/v1/activities/kinds` (`event | `note.created` | | `note_pages` | a `Page`: `summary`, `about` (what it's the page of), `place`, `author` (person or assistant) | Assistant wrote the note “St Mary's School” | | `note.saved` | | `note_versions` | as `note.created`, with `version` (the page as it was before) and `why` | Sam edited the note “School trip plans” | | `entity.changed` | | `graph` | `op` (created, renamed, merged, split, linked, unlinked, deleted, rolled back, changed), `change` (the graph's own op), `entityType`, `before` (a renamed entity's name), `version`, `count`; tagged with its entities | Sam renamed “St Marys” to “St Mary's School” | +| `webhook.received` | | `log` | `{type: Note, hook: the webhook's id, payload: what was sent (JSON, a form's fields or text), content_type, query}`; the actor is the webhook (`Service`, `lens:automation_hook/`, "Webhook for ") | Webhook for Front door was called | A new asset is one activity, of the most specific kind its row tells, decided by its content type and where it came from, never by reading its file: an email (content type email, or from an IMAP or Gmail mailbox), a calendar event @@ -265,6 +267,41 @@ gives a cleaned copy, or a ValueError naming the first problem. - `check_policy(p, nodes, allow_auto=False)`: `{action node id: ask or auto}`. Only a person in a signed-in session lets a node run on its own; everywhere else (agents, drafts, the workflow API) `auto` is refused. +### Webhook trigger + +Built (`app/domain/automation_hooks.py`, `POST /api/v1/automations/hooks/{token}`). A trigger `{"on": "webhook"}` +is a secret address anything that can send HTTP calls to set the automation off: Home Assistant's `rest_command`, a +phone shortcut, another service. No webhook exists until an automation with such a trigger is saved. + +- `automation_hooks.token_for(db, cfg, automation_id, alias, signed=False)` makes the hook for one trigger when the + automation is saved: `{"hook": id, "url": address, "path": address without the server, "secret": signing secret}`. + The address and secret are shown this once; the row (`automation_hook {automation, alias, token_hash, secret, + signed, created_at, last_called_at, calls}`) keeps only the token's hash and the secret sealed with the server's + key. Calling it again for the same trigger replaces the hook, and the old address stops working. The trigger keeps + the hook's id in `hook`. `automation_hooks.revoke(db, hook)` deletes it (when the trigger or the automation goes); + `for_automation(db, id)` lists an automation's hooks. +- A call needs only the token in the address (`lah_...`). It takes JSON, a form (text fields; files are refused) or + text, up to 64 KB, at most 60 calls a minute per hook (in the API process; 429 with `Retry-After` past it), and + answers 202 `{"id": activity}` at once. 401 for a token that isn't a hook's, 403 while the automation is switched + off, 413 over 64 KB, 415 for anything but JSON, a form or text. +- What was sent becomes a `webhook.received` activity in the event log, with the payload, its content type and the + query as outside text. Its namespace is the automation's (admins see it while the automation isn't stored). +- Signed calls: a caller that signs the Standard Webhooks way (`webhook-id`, `webhook-timestamp` in seconds, + `webhook-signature: v1,..">` keyed with the secret, as Lens signs its + own [notification webhooks](notifications.md#webhooks)) has the signature checked, and the time must be within five minutes. + A hook made with `signed=True` refuses calls that aren't signed. A call naming its message (`webhook-id`, or an + `Idempotency-Key` header) is logged once however often the sender retries it. +- In Docker the API runs no background work, so the worker's automations see the call on their next look (5 + seconds, `events.poll_seconds`). + +Lens has three kinds of webhook address; they don't share tokens or do each other's jobs: + +| Address | Made by | What a call does | +| --- | --- | --- | +| `POST /api/v1/automations/hooks/{token}` | saving an automation with a webhook trigger | sets that automation off with what was sent (`webhook.received`); nothing is kept but the activity | +| `POST /api/v1/sensors/push/{token}` ([Sensors](sensors.md)) | an admin adding a webhook sensor | keeps readings (numbers, on/off, text) for charts, with the sensor's handling | +| `POST /api/v1/hooks/import/{token}` ([Import webhooks](api.md#import-webhooks)) | a namespace's owner | imports files, web pages or text as assets | + ### Run context What an automation's If, its nodes and its templates see (`automation_spec.context_paths()` lists the keys, with @@ -454,3 +491,5 @@ the agent can draft an event as a note. - Changing assets: asking first instead of failing when a move would show an asset to new people (risk that reads the database); fields on collections and files; tags; roles on collections counting for `edit`. - Writing calendar events (a new Google consent, so it changes existing installs). +- Webhook trigger: signed answers to the caller (what the run did); a rate limit shared by every API process (today + each counts its own); showing a hook's last call in the studio. diff --git a/docs/database.md b/docs/database.md index 1d2032b62..3194f56e6 100644 --- a/docs/database.md +++ b/docs/database.md @@ -74,7 +74,8 @@ kept anyway, such as `recording.created_at`. What no row records goes in `event_ of the stream keeps where its next look starts in `event_cursor:` (a position per source), and claims what it handles in `event_claim:`; a claim is a `CREATE` only one process wins, and claims go after a day. Each person's review marks on the timeline ([Timeline](timeline.md#review-marks)) are -`event_mark:`, a row only while one of its flags is set. So that it can be read +`event_mark:`, a row only while one of its flags is set. An automation trigger's +webhook is `automation_hook:` (its automation and trigger, the hash of its token, its signing secret sealed). So that it can be read without opening files, a resource made from an email keeps the message's addressing as it was listed (`recording.mail`) and one made from a calendar event its times, place and people (`recording.event`); both are optional, and older resources simply don't have them. diff --git a/fastapi_backend/app/api/v1/router.py b/fastapi_backend/app/api/v1/router.py index 7210911a6..fd5e983da 100644 --- a/fastapi_backend/app/api/v1/router.py +++ b/fastapi_backend/app/api/v1/router.py @@ -7,6 +7,7 @@ activity, admin, auth, + automation_hooks, backups, batches, browser, @@ -83,6 +84,7 @@ updates, activity, activities, + automation_hooks, budgets, fedora, setup, diff --git a/fastapi_backend/app/api/v1/routes/automation_hooks.py b/fastapi_backend/app/api/v1/routes/automation_hooks.py new file mode 100644 index 000000000..be9b6df9a --- /dev/null +++ b/fastapi_backend/app/api/v1/routes/automation_hooks.py @@ -0,0 +1,100 @@ +"""An automation's webhook (docs/automations.md, Webhook trigger): the address anything that can send HTTP calls to set +an automation off. The token in the address is all a caller needs; the hooks themselves are made and revoked when +automations are saved and deleted (domain/automation_hooks.py).""" + +from __future__ import annotations + +from typing import Any + +from fastapi import APIRouter, HTTPException, Request +from starlette.concurrency import run_in_threadpool +from starlette.formparsers import MultiPartException, MultiPartParser + +from app.api.deps import Cfg, Db +from app.domain import automation_hooks +from app.schemas.automation_hooks import HookCalled + +router = APIRouter(tags=["automations"]) +CALL_BODY = { + "requestBody": { + "required": False, + "content": { + "application/json": {"schema": {}}, + "application/x-www-form-urlencoded": {"schema": {"type": "object", "additionalProperties": {"type": "string"}}}, + "multipart/form-data": {"schema": {"type": "object", "additionalProperties": {"type": "string"}}}, + "text/plain": {"schema": {"type": "string"}}, + }, + } +} + + +async def _body(request: Request) -> bytes: + """The request's body, refused (413) past automation_hooks.MAX_BODY without reading the rest.""" + most = automation_hooks.MAX_BODY + told = request.headers.get("content-length") or "" + if told.isdigit() and int(told) > most: + raise HTTPException(413, f"send at most {most // 1024} KB") + got, n = [], 0 + async for piece in request.stream(): + n += len(piece) + if n > most: + raise HTTPException(413, f"send at most {most // 1024} KB") + got.append(piece) + return b"".join(got) + + +async def _multipart(request: Request, body: bytes) -> dict[str, Any] | None: + """A multipart form's fields ({field: value, or a list of values}); files are refused.""" + if (request.headers.get("content-type") or "").split(";")[0].strip().lower() != "multipart/form-data": + return None + + async def once() -> Any: + yield body + + try: + form = await MultiPartParser(request.headers, once(), max_files=0, max_fields=automation_hooks.MAX_FIELDS).parse() + except MultiPartException as e: + raise HTTPException(400, f"a form of text fields only: {e.message}") from None + out: dict[str, Any] = {} + for k in form: + vals = [str(v) for v in form.getlist(k)] + out[k] = vals[0] if len(vals) == 1 else vals + return out + + +@router.post( + "/automations/hooks/{token}", + status_code=202, + openapi_extra=CALL_BODY, + responses={ + 401: {"description": "not a webhook's token, or a signature that doesn't match"}, + 403: {"description": "the automation is switched off"}, + 413: {"description": "over 64 KB"}, + 415: {"description": "neither JSON, a form nor text"}, + 429: {"description": "over 60 calls a minute to this webhook"}, + }, +) +async def call_automation_hook(token: str, request: Request, db: Db, cfg: Cfg) -> HookCalled: + """Set an automation off: what is sent (JSON, a form or text, up to 64 KB) becomes a `webhook.received` activity + for the automation whose trigger this address is. No session: the token in the address is the credential. Signed + the Standard Webhooks way (webhook-id, webhook-timestamp, webhook-signature), the signature must match the webhook's + secret; `webhook-id` or `Idempotency-Key` makes a retried call count once. Answers at once, before the automation + runs.""" + body = await _body(request) + form = await _multipart(request, body) + try: + aid = await run_in_threadpool( + automation_hooks.receive, + db, + cfg, + token, + body, + request.headers.get("content-type") or "", + request.query_params.multi_items(), + dict(request.headers), + form, + ) + except automation_hooks.Refused as e: + headers = {"Retry-After": "60"} if e.status == 429 else None + raise HTTPException(e.status, str(e), headers=headers) from None + return HookCalled(id=aid) diff --git a/fastapi_backend/app/domain/automation_hooks.py b/fastapi_backend/app/domain/automation_hooks.py new file mode 100644 index 000000000..3160da3fb --- /dev/null +++ b/fastapi_backend/app/domain/automation_hooks.py @@ -0,0 +1,260 @@ +"""Webhook triggers (docs/automations.md, Webhook trigger): a secret address per automation trigger, for anything that +can send HTTP (Home Assistant, a phone shortcut, another service) to set an automation off. + +An automation's trigger `{"on": "webhook"}` gets a hook when the automation is saved (`token_for`): a row in +`automation_hook` with the automation, the trigger's alias, the hash of a token (`lah_...`, in the address and shown +once, as an import hook's is) and a signing secret sealed with the server's key. `revoke` deletes it, and the address +stops working at once. + +A call (`receive`, from `POST /api/v1/automations/hooks/{token}`) needs only the token. It takes JSON, a form or text +up to MAX_BODY, at most PER_MINUTE calls a minute for each hook (in this process), and is written to the event log as +`webhook.received` with what was sent as outside text. When the call is signed the Standard Webhooks way (the +`webhook-id`, `webhook-timestamp` and `webhook-signature` headers; notify.py signs its own deliveries so), the +signature must match the hook's secret and the time be within TOLERANCE; a hook made `signed` refuses calls that +aren't. A call naming its message (`webhook-id`, or `Idempotency-Key`) is logged once however often it is retried. + +The route answers at once: the automation runs where the stream is followed (the worker, in Docker), on its next look. +Nothing here runs an automation, and no hook exists until an automation with a webhook trigger is saved. +""" + +from __future__ import annotations + +import collections +import hashlib +import hmac +import json +import re +import secrets +import threading +import time +import urllib.parse + +from . import events, notify, settings, store + +R = store.R +TOKEN_PREFIX = "lah_" # recognisable in logs and secret scanners +TOKEN_RX = re.compile(r"^lah_[A-Za-z0-9_-]{20,64}$") +ALIAS_RX = re.compile(r"^[a-z][a-z0-9_]{0,39}$") +PATH = "/api/v1/automations/hooks/" +MAX_BODY = 64 * 1024 +PER_MINUTE = 60 +TOLERANCE = 300 # seconds a signed call's time may be off from this server's +MAX_KEY = 200 +MAX_FIELDS = 200 +FIELDS = "record::id(id) AS id, automation, alias, signed, created_at, last_called_at, calls" + +_calls: dict[int, collections.deque] = {} +_lock = threading.Lock() + + +class Refused(ValueError): + """A call this hook won't take: `status` is the HTTP status to answer with.""" + + def __init__(self, status, message): + super().__init__(message) + self.status = status + + +def _hash(token): + return hashlib.sha256(token.encode()).hexdigest() + + +def _secret_context(hid): + return f"automation_hook:{hid}:secret" + + +def _base(cfg, db): + from app.email import app_url + + return app_url(cfg, db) + + +def token_for(db, cfg, automation_id, alias, signed=False): + """A webhook for trigger `alias` of automation `automation_id`: {"hook": its id, "url": its address, "path": the + address without the server, "secret": the signing secret}. The address and secret are shown this once; only the + token's hash is kept. Calling it again for the same trigger replaces its hook, and the old address stops working. + `signed` makes the hook refuse calls that aren't signed with the secret.""" + if not isinstance(automation_id, int) or isinstance(automation_id, bool) or automation_id < 1: + raise ValueError("an automation's id is a whole number") + if not isinstance(alias, str) or not ALIAS_RX.match(alias): + raise ValueError("a trigger's alias is lowercase letters, digits and _ (its `as`)") + hid, token, secret = db.next_id("automation_hook"), TOKEN_PREFIX + secrets.token_urlsafe(32), notify.new_secret() + db.run( + ["DELETE automation_hook WHERE automation = $a AND alias = $al", "CREATE $r CONTENT $d"], + a=automation_id, + al=alias, + r=R("automation_hook", hid), + d={ + "automation": automation_id, + "alias": alias, + "token_hash": _hash(token), + "secret": settings.seal(cfg, secret, _secret_context(hid)), + "signed": bool(signed), + "created_at": store.now(), + "calls": 0, + }, + ) + return {"hook": hid, "url": _base(cfg, db) + PATH + token, "path": PATH + token, "secret": secret} + + +def revoke(db, hook): + """Delete a hook: its address stops working at once. True when there was one.""" + got = db.rows("DELETE $r RETURN BEFORE", r=R("automation_hook", int(hook))) + with _lock: + _calls.pop(int(hook), None) + return bool(got) + + +def get(db, hook): + """A hook (without its token or secret), or None.""" + return db.one(f"SELECT {FIELDS} FROM $r", r=R("automation_hook", int(hook))) + + +def for_automation(db, automation_id): + """An automation's hooks, oldest first.""" + return db.rows(f"SELECT {FIELDS} FROM automation_hook WHERE automation = $a ORDER BY id", a=int(automation_id)) + + +def by_token(db, token): + """The hook whose token this is, with its sealed secret; KeyError for any other.""" + if not isinstance(token, str) or not TOKEN_RX.match(token): + raise KeyError("token") + row = db.one(f"SELECT {FIELDS}, secret FROM automation_hook WHERE token_hash = $h LIMIT 1", h=_hash(token)) + if not row: + raise KeyError("token") + return row + + +def allow(hook, now=None): + """Whether one more call to `hook` fits in PER_MINUTE (counted in this process); counts it when it does.""" + now = time.monotonic() if now is None else now + with _lock: + q = _calls.setdefault(int(hook), collections.deque()) + while q and now - q[0] >= 60: + q.popleft() + if len(q) >= PER_MINUTE: + return False + q.append(now) + if len(_calls) > 10000: # hooks gone quiet + for k in [k for k, v in _calls.items() if not v or now - v[-1] >= 60][:5000]: + _calls.pop(k, None) + return True + + +def _header(headers, name): + v = headers.get(name) + return v.strip() if isinstance(v, str) else None + + +def check_signature(cfg, row, headers, body, now=None): + """The Standard Webhooks message id of a signed call, None for a call that isn't signed; Refused (401) when the + signature doesn't match the hook's secret, the time is off by more than TOLERANCE, or the hook takes only signed + calls.""" + sig = _header(headers, "webhook-signature") + if not sig: + if row.get("signed"): + raise Refused(401, "this webhook takes only signed calls (webhook-id, webhook-timestamp and webhook-signature)") + return None + msg_id, ts = _header(headers, "webhook-id"), _header(headers, "webhook-timestamp") + if not msg_id or not ts or not ts.isdigit(): + raise Refused(401, "a signed call has webhook-id and webhook-timestamp (seconds) too") + if abs((time.time() if now is None else now) - int(ts)) > TOLERANCE: + raise Refused(401, "the call's webhook-timestamp is too far from this server's time") + secret = settings.unseal(cfg, row["secret"], _secret_context(row["id"])) + want = notify.sign(secret, msg_id, ts, body) + given = [s for s in sig.split() if s.startswith("v1,")] + if not any(hmac.compare_digest(want.encode(), s.encode()) for s in given): + raise Refused(401, "the signature doesn't match this webhook's secret") + return msg_id + + +def _form(body): + pairs = urllib.parse.parse_qsl(body.decode("utf-8", "replace"), keep_blank_values=True, max_num_fields=MAX_FIELDS) + out: dict = {} + for k, v in pairs: + out.setdefault(k, []).append(v) + return {k: v[0] if len(v) == 1 else v for k, v in out.items()} + + +def payload(body, content_type, form=None): + """What a call sent, as its content type says: JSON parsed, a form as {field: value, or a list of values}, text as + it is, nothing as None. `form` is a multipart form the route has already read. Refused (400, 415) otherwise.""" + ctype = (content_type or "").split(";")[0].strip().lower() + if form is not None: + return form + if not body.strip(): + return None + if ctype == "application/json" or ctype.endswith("+json") or (not ctype and body.lstrip()[:1] in (b"{", b"[")): + try: + return json.loads(body) + except ValueError: + raise Refused(400, "the body isn't JSON") from None + if ctype == "application/x-www-form-urlencoded": + try: + return _form(body) + except ValueError: + raise Refused(400, f"a form has at most {MAX_FIELDS} fields") from None + if not ctype or ctype.startswith("text/"): + return body.decode("utf-8", "replace") + raise Refused(415, "send JSON, a form or text") + + +def _query(query): + out: dict = {} + for k, v in list(query or [])[:MAX_FIELDS]: + out.setdefault(str(k)[:200], []).append(str(v)[:2000]) + return {k: v[0] if len(v) == 1 else v for k, v in out.items()} + + +def _automation(db, automation_id): + """The automation's name, its namespaces and whether it's switched off, as the automations table keeps them (an + automation not stored there yet is named by its id).""" + try: + row = db.one("SELECT name, spaces, enabled FROM $r", r=R("automation", int(automation_id))) or {} + except Exception: # noqa: BLE001 - no automations table yet + row = {} + spaces = [s for s in row.get("spaces") or [] if isinstance(s, int) and not isinstance(s, bool)] + name = " ".join(str(row.get("name") or "").split())[:120] or f"Automation {automation_id}" + return name, spaces, row.get("enabled") is False + + +def receive(db, cfg, token, body, content_type="", query=(), headers=None, form=None): + """Take a call to a hook: the id of its `webhook.received` activity. Refused with the status to answer otherwise: + 401 for a token that isn't a hook's or a bad signature, 403 while its automation is switched off, 413 over + MAX_BODY, 429 over PER_MINUTE, 400 or 415 for a body it can't read.""" + headers = headers or {} + if len(body) > MAX_BODY: + raise Refused(413, f"send at most {MAX_BODY // 1024} KB") + try: + row = by_token(db, token) + except KeyError: + raise Refused(401, "that token isn't an automation webhook's") from None + name, spaces, off = _automation(db, row["automation"]) + if off: + raise Refused(403, "this webhook's automation is switched off") + if not allow(row["id"]): + raise Refused(429, f"at most {PER_MINUTE} calls a minute to one webhook") + msg_id = check_signature(cfg, row, headers, body) or _header(headers, "idempotency-key") + sent = payload(body, content_type, form) + who = f"Webhook for {name}" + aid = events.emit( + db, + "webhook.received", + actor={"type": "Service", "id": f"lens:automation_hook/{row['id']}", "name": who}, + obj=store.clean( + { + "type": "Note", + "hook": row["id"], + "payload": sent, + "content_type": (content_type or "").split(";")[0].strip().lower()[:100] or None, + "query": _query(query), + } + ), + space=spaces[0] if spaces else None, + spaces=spaces if len(spaces) > 1 else None, + audience=None if spaces else "admins", + summary=f"{who} was called", + key=f"automation_hook:{row['id']}:{msg_id[:MAX_KEY]}" if msg_id else None, + ) + db.q("UPDATE $r SET last_called_at = $t, calls += 1", r=R("automation_hook", row["id"]), t=store.now()) + return aid diff --git a/fastapi_backend/app/domain/events.py b/fastapi_backend/app/domain/events.py index 56a0863ec..77ba89acc 100644 --- a/fastapi_backend/app/domain/events.py +++ b/fastapi_backend/app/domain/events.py @@ -1122,3 +1122,4 @@ def tidy(db, cfg, now=None): from . import events_content # noqa: E402, F401 - the recordings source, registered with the stream once it is loaded +from . import events_streams # noqa: E402, F401 - sensors, chat, webhooks and system kinds, the same way diff --git a/fastapi_backend/app/domain/events_streams.py b/fastapi_backend/app/domain/events_streams.py new file mode 100644 index 000000000..6b63b5359 --- /dev/null +++ b/fastapi_backend/app/domain/events_streams.py @@ -0,0 +1,61 @@ +"""The machine side of Lens as activities (docs/automations.md, Kinds): what reaches Lens from outside that isn't a +file. Every kind here has its source named in the catalog; those read from the event log (`log`) are emitted where the +thing happens. + +- `webhook.received`: a call to an automation's webhook address (automation_hooks.py), emitted by the route that + takes it. Its payload and query are outside text. +""" + +from __future__ import annotations + +from . import events + + +def _s(title, typ="string", **more): + return {"type": typ, "title": title, **more} + + +# ---------- webhooks ---------- +events.kind( + "webhook.received", + label="Webhook called", + source="log", + as_type="Announce", + object_type="Note", + fields={ + "object": { + "type": "object", + "properties": { + "hook": _s("Webhook", "integer"), + "payload": {"title": "What was sent"}, + "content_type": _s("Content type"), + "query": {"type": "object", "title": "Query"}, + }, + } + }, + untrusted=("object.payload", "object.query", "object.content_type"), + sample={ + "id": "log-31", + "type": "Announce", + "kind": "webhook.received", + "published": "2026-10-15T18:02:11.000Z", + "actor": {"type": "Service", "id": "lens:automation_hook/2", "name": "Webhook for Front door"}, + "object": { + "type": "Note", + "hook": 2, + "payload": {"event": "doorbell", "camera": "front"}, + "content_type": "application/json", + "query": {}, + }, + "target": None, + "tag": [], + "summary": "Webhook for Front door was called", + "space": 3, + "lens": { + "source": "log", + "pos": ["2026-10-15T18:02:11+00:00", 31], + "untrusted": ["object.payload", "object.query", "object.content_type"], + "cause": None, + }, + }, +) diff --git a/fastapi_backend/app/domain/store.py b/fastapi_backend/app/domain/store.py index c1500e0db..7bde98726 100644 --- a/fastapi_backend/app/domain/store.py +++ b/fastapi_backend/app/domain/store.py @@ -1264,6 +1264,10 @@ def close(self): "DEFINE TABLE IF NOT EXISTS event_cursor SCHEMALESS", "DEFINE TABLE IF NOT EXISTS event_claim SCHEMALESS", "DEFINE INDEX IF NOT EXISTS event_claim_at ON event_claim FIELDS at", + # an automation trigger's webhook (domain/automation_hooks.py): automation_hook:, the token kept only as a hash + "DEFINE TABLE IF NOT EXISTS automation_hook SCHEMALESS", + "DEFINE INDEX IF NOT EXISTS automation_hook_token ON automation_hook FIELDS token_hash UNIQUE", + "DEFINE INDEX IF NOT EXISTS automation_hook_automation ON automation_hook FIELDS automation", "DEFINE INDEX IF NOT EXISTS upload_recording ON upload FIELDS recording", # review marks on the timeline (domain/event_marks.py, docs/timeline.md): each person's reviewed, important and # hidden flags on an activity, event_mark: (the id keeps the pair unique) diff --git a/fastapi_backend/app/schemas/automation_hooks.py b/fastapi_backend/app/schemas/automation_hooks.py new file mode 100644 index 000000000..0be11a746 --- /dev/null +++ b/fastapi_backend/app/schemas/automation_hooks.py @@ -0,0 +1,11 @@ +"""An automation's webhook (docs/automations.md, Webhook trigger): what a call to it answers.""" + +from __future__ import annotations + +from pydantic import Field + +from app.schemas.common import ResponseModel + + +class HookCalled(ResponseModel): + id: str = Field(description="the webhook.received activity the call made (the same one again for a retried call)") diff --git a/fastapi_backend/tests/api/test_automation_hooks.py b/fastapi_backend/tests/api/test_automation_hooks.py new file mode 100644 index 000000000..afbd31bab --- /dev/null +++ b/fastapi_backend/tests/api/test_automation_hooks.py @@ -0,0 +1,179 @@ +"""An automation's webhook (docs/automations.md#webhook-trigger): a secret address per trigger, made when the automation +is saved; a call to it is a `webhook.received` activity, capped in size and rate, signed when the caller signs, and +logged once however often it is retried.""" + +from __future__ import annotations + +import time + +import pytest + +from app.domain import automation_hooks, events, notify, store + +R = store.R +ADMIN = events.viewer(1, None, admin=True) + + +@pytest.fixture(autouse=True) +def fresh(): + automation_hooks._calls.clear() + events._seen.clear() + events._claimed.clear() + yield + automation_hooks._calls.clear() + + +def _call(client, made, **kw): + return client.post(made["path"], **kw) + + +def _start(db, cfg, consumer): + """A follower's first look marks where it starts: what's logged in that second isn't seen, so wait for the next.""" + assert events.follow(db, cfg, consumer, kinds=["webhook.received"])[0] == [] + t = store.now() + while store.now() == t: + time.sleep(0.05) + + +def _logged(db): + return db.values("SELECT VALUE record::id(id) FROM event_log WHERE kind = 'webhook.received'") + + +def test_a_hook_is_made_for_a_trigger_and_only_its_hash_kept(client, db, cfg): + made = automation_hooks.token_for(db, cfg, 5, "door") + token = made["path"].rsplit("/", 1)[1] + assert token.startswith("lah_") and made["url"].endswith(made["path"]) and made["path"].startswith("/api/v1/automations/hooks/") + assert made["secret"].startswith("whsec_") + row = db.one("SELECT * FROM $r", r=R("automation_hook", made["hook"])) + assert row["automation"] == 5 and row["alias"] == "door" and row["signed"] is False + assert token not in str(row) and made["secret"] not in str(row) # a hash and a sealed secret + assert automation_hooks.get(db, made["hook"])["alias"] == "door" + assert [h["id"] for h in automation_hooks.for_automation(db, 5)] == [made["hook"]] + with pytest.raises(ValueError): + automation_hooks.token_for(db, cfg, 5, "Door!") + with pytest.raises(ValueError): + automation_hooks.token_for(db, cfg, 0, "door") + + # made again for the same trigger: a new address, and the old one stops + again = automation_hooks.token_for(db, cfg, 5, "door") + assert again["hook"] != made["hook"] and again["path"] != made["path"] + assert _call(client, made, json={}).status_code == 401 + assert _call(client, again, json={}).status_code == 202 + assert [h["id"] for h in automation_hooks.for_automation(db, 5)] == [again["hook"]] + + # revoked: gone at once + assert automation_hooks.revoke(db, again["hook"]) is True and automation_hooks.revoke(db, again["hook"]) is False + assert _call(client, again, json={}).status_code == 401 + assert client.post("/api/v1/automations/hooks/not-a-token", json={}).status_code == 401 + + +def test_a_call_is_a_webhook_received_activity(client, db, cfg): + pods = store.ns_id(db, "pods") + db.q("CREATE $r CONTENT $d", r=R("automation", 7), d={"name": "Front door", "spaces": [pods], "enabled": True}) + made = automation_hooks.token_for(db, cfg, 7, "door") + _start(db, cfg, "test.hooks") + + r = _call(client, made, json={"event": "doorbell", "camera": "front"}, params={"source": "ha", "tag": ["a", "b"]}) + assert r.status_code == 202, r.text + aid = r.json()["id"] + got, commit = events.follow(db, cfg, "test.hooks", kinds=["webhook.received"]) + commit() + assert [a["id"] for a in got] == [aid] + a = events.check_activity(got[0]) + assert a["kind"] == "webhook.received" and a["type"] == "Announce" and a["space"] == pods + assert a["actor"] == {"type": "Service", "id": f"lens:automation_hook/{made['hook']}", "name": "Webhook for Front door"} + assert a["object"] == { + "type": "Note", + "hook": made["hook"], + "payload": {"event": "doorbell", "camera": "front"}, + "content_type": "application/json", + "query": {"source": "ha", "tag": ["a", "b"]}, + } + assert a["summary"] == "Webhook for Front door was called" + assert set(a["lens"]["untrusted"]) == {"object.payload", "object.query", "object.content_type"} + assert "audience" not in a["lens"] + assert events.get(db, cfg, aid, ADMIN)["object"]["hook"] == made["hook"] + assert db.one("SELECT calls, last_called_at FROM $r", r=R("automation_hook", made["hook"]))["calls"] == 1 + + # an automation not stored yet is named by its id, and its call is for admins + other = automation_hooks.token_for(db, cfg, 9, "hook") + b = events.get(db, cfg, _call(client, other, json=[1, 2]).json()["id"], ADMIN) + assert b["actor"]["name"] == "Webhook for Automation 9" and b["space"] is None and b["lens"]["audience"] == "admins" + assert b["object"]["payload"] == [1, 2] + + # switched off: refused, so the caller knows + db.q("UPDATE $r SET enabled = false", r=R("automation", 7)) + assert _call(client, made, json={}).status_code == 403 + + +def test_forms_text_and_what_isnt_taken(client, db, cfg): + made = automation_hooks.token_for(db, cfg, 5, "hook") + + def payload(**kw): + r = _call(client, made, **kw) + assert r.status_code == 202, r.text + return events.get(db, cfg, r.json()["id"], ADMIN)["object"].get("payload") + + assert payload(data={"item": "milk", "n": ["1", "2"]}) == {"item": "milk", "n": ["1", "2"]} + assert payload(files={"item": (None, "eggs")}) == {"item": "eggs"} # a multipart form's text fields + assert payload(content="groceries", headers={"Content-Type": "text/plain"}) == "groceries" + assert payload(content=b"") is None + assert _call(client, made, content=b"{nope", headers={"Content-Type": "application/json"}).status_code == 400 + assert _call(client, made, content=b"\x00\x01", headers={"Content-Type": "application/octet-stream"}).status_code == 415 + assert _call(client, made, files={"f": ("a.txt", b"hi", "text/plain")}).status_code == 400 # no files + + +def test_size_and_rate_caps(client, db, cfg, monkeypatch): + made = automation_hooks.token_for(db, cfg, 5, "hook") + big = b'{"x": "' + b"a" * automation_hooks.MAX_BODY + b'"}' + assert _call(client, made, content=big, headers={"Content-Type": "application/json"}).status_code == 413 + + def chunks(): + for _ in range(80): + yield b"a" * 1024 + + assert _call(client, made, content=chunks(), headers={"Content-Type": "text/plain"}).status_code == 413 # no length given + assert not _logged(db) + + monkeypatch.setattr(automation_hooks, "PER_MINUTE", 3) + assert [_call(client, made, json={}).status_code for _ in range(4)] == [202, 202, 202, 429] + r = _call(client, made, json={}) + assert r.status_code == 429 and r.headers["retry-after"] == "60" + assert len(_logged(db)) == 3 + # a minute later there's room again; each hook has its own allowance + t = time.monotonic() + assert automation_hooks.allow(made["hook"], t + 61) is True + assert automation_hooks.allow(made["hook"] + 1, t) is True + + +def test_signed_calls_and_retries(client, db, cfg): + made = automation_hooks.token_for(db, cfg, 5, "hook", signed=True) + body = b'{"temp": 31}' + + def signed(msg_id, ts=None, secret=None, payload=body): + ts = str(int(time.time()) if ts is None else ts) + sig = notify.sign(secret or made["secret"], msg_id, ts, payload) + return { + "webhook-id": msg_id, + "webhook-timestamp": ts, + "webhook-signature": f"v1,bm9wZQ== {sig}", + "Content-Type": "application/json", + } + + assert _call(client, made, content=body, headers={"Content-Type": "application/json"}).status_code == 401 # unsigned + assert _call(client, made, content=body, headers=signed("m1", secret=notify.new_secret())).status_code == 401 + assert _call(client, made, content=body, headers=signed("m1", ts=int(time.time()) - 600)).status_code == 401 + assert _call(client, made, content=b'{"temp": 99}', headers=signed("m1")).status_code == 401 # body changed + first = _call(client, made, content=body, headers=signed("m1")) + assert first.status_code == 202, first.text + # the sender tries again: the same activity, logged once + again = _call(client, made, content=body, headers=signed("m1")) + assert again.status_code == 202 and again.json()["id"] == first.json()["id"] + assert len(_logged(db)) == 1 + + # an unsigned hook takes unsigned calls, checks signed ones, and counts an Idempotency-Key once + plain = automation_hooks.token_for(db, cfg, 6, "hook") + assert _call(client, plain, json={"a": 1}).status_code == 202 + assert _call(client, plain, content=body, headers=signed("m2", secret=made["secret"])).status_code == 401 + ids = {_call(client, plain, json={"a": 2}, headers={"Idempotency-Key": "k-1"}).json()["id"] for _ in range(3)} + assert len(ids) == 1 and len(_logged(db)) == 3 diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index 0186a7826..9d8773e2c 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -6,6 +6,7 @@ export { Activity, Admin, Auth, + Automations, Batches, Browser, Budgets, @@ -241,6 +242,11 @@ export type { BulkUpdateMetadataErrors, BulkUpdateMetadataResponse, BulkUpdateMetadataResponses, + CallAutomationHookData, + CallAutomationHookError, + CallAutomationHookErrors, + CallAutomationHookResponse, + CallAutomationHookResponses, CancelJobData, CancelJobError, CancelJobErrors, @@ -1426,6 +1432,7 @@ export type { HomeSuggestionsErrors, HomeSuggestionsResponse, HomeSuggestionsResponses, + HookCalled, HookItem, HookPushed, HttpsCertificate, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index 5fb6a616a..889235c6b 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -82,6 +82,9 @@ import type { BulkUpdateMetadataData, BulkUpdateMetadataErrors, BulkUpdateMetadataResponses, + CallAutomationHookData, + CallAutomationHookErrors, + CallAutomationHookResponses, CancelJobData, CancelJobErrors, CancelJobResponses, @@ -3789,6 +3792,30 @@ export class Activities { } } +export class Automations { + /** + * Call Automation Hook + * + * Set an automation off: what is sent (JSON, a form or text, up to 64 KB) becomes a `webhook.received` activity + * for the automation whose trigger this address is. No session: the token in the address is the credential. Signed + * the Standard Webhooks way (webhook-id, webhook-timestamp, webhook-signature), the signature must match the webhook's + * secret; `webhook-id` or `Idempotency-Key` makes a retried call count once. Answers at once, before the automation + * runs. + */ + public static callAutomationHook( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/automations/hooks/{token}", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } +} + export class Budgets { /** * Remove Budget diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index b34bf9c89..650c94254 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -6947,6 +6947,19 @@ export type HighlightUpdate = { label?: string | null; }; +/** + * HookCalled + */ +export type HookCalled = { + /** + * Id + * + * the webhook.received activity the call made (the same one again for a retried call) + */ + id: string; + [key: string]: unknown; +}; + /** * HookItem */ @@ -24849,6 +24862,56 @@ export type MarkActivityResponses = { export type MarkActivityResponse = MarkActivityResponses[keyof MarkActivityResponses]; +export type CallAutomationHookData = { + body?: unknown; + path: { + /** + * Token + */ + token: string; + }; + query?: never; + url: "/api/v1/automations/hooks/{token}"; +}; + +export type CallAutomationHookErrors = { + /** + * not a webhook's token, or a signature that doesn't match + */ + 401: unknown; + /** + * the automation is switched off + */ + 403: unknown; + /** + * over 64 KB + */ + 413: unknown; + /** + * neither JSON, a form nor text + */ + 415: unknown; + /** + * Validation Error + */ + 422: HttpValidationError; + /** + * over 60 calls a minute to this webhook + */ + 429: unknown; +}; + +export type CallAutomationHookError = CallAutomationHookErrors[keyof CallAutomationHookErrors]; + +export type CallAutomationHookResponses = { + /** + * Successful Response + */ + 202: HookCalled; +}; + +export type CallAutomationHookResponse = CallAutomationHookResponses[keyof CallAutomationHookResponses]; + export type RemoveBudgetData = { body?: never; path?: never; diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index b74989d6f..53c57818c 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -5202,6 +5202,93 @@ } } }, + "/api/v1/automations/hooks/{token}": { + "post": { + "tags": [ + "automations" + ], + "summary": "Call Automation Hook", + "description": "Set an automation off: what is sent (JSON, a form or text, up to 64 KB) becomes a `webhook.received` activity\nfor the automation whose trigger this address is. No session: the token in the address is the credential. Signed\nthe Standard Webhooks way (webhook-id, webhook-timestamp, webhook-signature), the signature must match the webhook's\nsecret; `webhook-id` or `Idempotency-Key` makes a retried call count once. Answers at once, before the automation\nruns.", + "operationId": "call_automation_hook", + "parameters": [ + { + "name": "token", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Token" + } + } + ], + "responses": { + "202": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HookCalled" + } + } + } + }, + "401": { + "description": "not a webhook's token, or a signature that doesn't match" + }, + "403": { + "description": "the automation is switched off" + }, + "413": { + "description": "over 64 KB" + }, + "415": { + "description": "neither JSON, a form nor text" + }, + "429": { + "description": "over 60 calls a minute to this webhook" + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + }, + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": {} + }, + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "multipart/form-data": { + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "text/plain": { + "schema": { + "type": "string" + } + } + } + } + } + }, "/api/v1/budgets": { "get": { "tags": [ @@ -40676,6 +40763,21 @@ "type": "object", "title": "HighlightUpdate" }, + "HookCalled": { + "properties": { + "id": { + "type": "string", + "title": "Id", + "description": "the webhook.received activity the call made (the same one again for a retried call)" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "id" + ], + "title": "HookCalled" + }, "HookItem": { "properties": { "kind": { diff --git a/threat-model.json b/threat-model.json index 7bf82cc45..7b08e31f8 100644 --- a/threat-model.json +++ b/threat-model.json @@ -131,6 +131,7 @@ { "name": "optional", "entry_points": [ + "POST /automations/hooks/{token} (an automation's webhook)", "MQTT 1883, syslog 5514, POST /sensors/push/{token}/{stream}", "SMB share (port 1445 on the host, 4445 in the worker)" ], @@ -487,6 +488,15 @@ "provenance": "documented", "source": "maintainer ruling, 2026-10" }, + { + "entry_point": "POST /automations/hooks/{token} (an automation's webhook)", + "parameter": "body (JSON, a form's text fields or text), query, Standard Webhooks headers, token in the path", + "attacker_controllable": "yes", + "component": "optional", + "caller_must_enforce": "the person keeps the address and secret to the services that call it; Lens keeps the token hashed, caps size and rate, checks signatures sent, and treats what was sent as outside text", + "provenance": "documented", + "source": "docs/automations.md \"No webhook exists until an automation with such a trigger is saved\"" + }, { "entry_point": "MQTT 1883, syslog 5514, POST /sensors/push/{token}/{stream}", "parameter": "payloads, hub logins, token in the path", diff --git a/threat-model.md b/threat-model.md index faae1de06..731845dd0 100644 --- a/threat-model.md +++ b/threat-model.md @@ -295,6 +295,7 @@ classified by gate only *(inferred, Q8)*; unread modules are listed in Q34. | extensions (prompt, graph and `http` tools, hooks), custom nodes including `template` nodes (Q23) | tool spec, graph JSON, template text | yes, any writer for their own; sharing is gated | callback/code (declarative) | person enables only extensions they trust | *(documented, docs/assistant.md "other people's run only when an admin shared them")* | | Python code tools, shipped and admin-created templates, workflows, pipelines, routines | Python, Jinja source, regexes | admin only | callback/code | admin is trusted | *(maintainer, 2026-10)* | | MQTT 1883, syslog 5514, `POST /sensors/push/{token}/{stream}` | payloads, hub logins, token in the path | yes, once enabled | data, size/rate, x-credential | admin enables; operator firewalls | *(documented, docs/sensors.md "Sensors are off until an admin turns them on")* | +| `POST /automations/hooks/{token}` (an automation's webhook) | body (JSON, a form's text fields or text), query, Standard Webhooks headers, token in the path | yes, anyone given the address | data, size/rate, x-credential, x-prompt-injection | no hook exists until an automation with a webhook trigger is saved; the token is 256 random bits kept only as a hash, and revoked with its trigger; 64 KB and 60 calls a minute per hook; a signature, when sent (or required by a `signed` hook), must match the hook's sealed secret within five minutes; a retried message id is logged once; what was sent is outside text (`lens.untrusted`), wrapped as data in prompts | *(documented, docs/automations.md "No webhook exists until an automation with such a trigger is saved")* | | NFS share (port 12049 on the host, 2049 in the worker) | NFS and MOUNT RPCs, client address | yes, once enabled, from `nfs.allowed_networks` | data, x-network-source | admin enables and picks the account; operator firewalls | *(documented, docs/file-shares.md "NFS has no login")* | | SMB share (port 1445 on the host, 4445 in the worker) | SMB2 requests, NTLM sign-in with a file access key, client address | yes, once enabled, from `smb.allowed_networks` | data, x-credential, x-network-source | admin enables; operator firewalls | *(documented, docs/smb.md "What keeps it safe")* | | S3 9555 and WebDAV 9556 (file shares) | signed S3 requests (SigV4 header or presigned link); WebDAV with an access key as Basic sign-in | yes, once enabled | x-credential, resource-name | admin enables; each request carries a person's own access key; read-only; failed WebDAV sign-ins throttled per address | *(documented, docs/file-tree.md "Off until an admin turns it on")* | diff --git a/threat-model.yaml b/threat-model.yaml index b418d582e..5a09778c2 100644 --- a/threat-model.yaml +++ b/threat-model.yaml @@ -2,7 +2,7 @@ # Authority order: prose > yaml > json. Regenerate whenever the prose changes. schema: threat-model-sidecar/v2 project: lens -prose_version: "threat-model.md@sha256:6f2e5e104620679f5a4d2f0e232a9a4cfdfab594ce55758f4d186bcae9a9492f" +prose_version: "threat-model.md@sha256:4b1a5dd44394f216d19f1ac4d513d101f44165451df7f87070936ccbac0717dc" model_status: under-review triage_policy: strict confidence: {documented: 201, maintainer: 46, inferred: 91, assumption: 8} @@ -417,6 +417,16 @@ entry_points: obligation_id: admin-is-trusted caller_must_enforce: "admin is trusted" provenance: {kind: maintainer, date: "2026-10"} + - id: "POST /automations/hooks/{token} (an automation's webhook)" + component: optional + parameters: + - name: "body (JSON, a form's text fields or text), query, Standard Webhooks headers, token in the path" + attacker_controllable: true + x-condition: "anyone given the address, once an automation with a webhook trigger is saved" + control_kinds: [data, size, rate, x-credential, x-prompt-injection] + obligation_id: keep-hook-addresses-secret + caller_must_enforce: "the person keeps the address and secret to the services that call it; Lens keeps the token hashed, caps size and rate, checks signatures sent, and treats what was sent as outside text" + provenance: {kind: documented, source: 'docs/automations.md "No webhook exists until an automation with such a trigger is saved"'} - id: "MQTT 1883, syslog 5514, POST /sensors/push/{token}/{stream}" component: optional parameters: