Make Cloudflare alert delivery webhook only

master
Carlo Costanzo 2 months ago
parent 8966c5f3ca
commit 0541284517

@ -3,17 +3,16 @@
Receives Cloudflare Notifications through a Nabu Casa cloud webhook and validates
the `cf-webhook-auth` header and account identity before producing a
`cloudflare_alert` event. A webhook URL alone cannot launch an investigation.
When webhook destinations are unavailable, an optional read-only `api_token`
polls notification delivery history every five minutes. The token needs
Notifications Read; history-derived notifications never dispatch machine jobs.
Removing this optional token disables polling when direct webhooks are configured.
Delivery is webhook-only. The receiver does not request Cloudflare notification
history, register periodic timers, or require a Cloudflare API token.
The infrastructure package presents each incident as a persistent Repair and HA
notification. Incidents are deduplicated by alert type and resource, survive
restarts, reject older events, and reopen on a later failure. Successful tunnel
and certificate events clear the corresponding incident. For mapped origins,
fresh existing public-website observations can confirm recovery after five
minutes. Unmapped incidents remain open for operator review.
reports from existing public-website probes can confirm recovery after five
minutes. Recovery reacts to state changes and repeated healthy reports without
starting another poll. Unmapped incidents remain open for operator review.
Only explicitly configured `ops_hostnames` and `ops_tunnel_ids` can dispatch an
origin/tunnel investigation through the existing machine dispatch script.
@ -25,11 +24,13 @@ has already dispatched, avoiding a second job from Cloudflare.
Configure the following keys in ignored `secrets.yaml`, then validate configuration
and restart Home Assistant:
When upgrading an existing installation, remove the previous `api_token` entry
from the integration configuration and its unused secret before restarting.
```yaml
cloudflare_alert_webhook_id: <random identifier of at least 32 characters>
cloudflare_alert_webhook_secret: <separate random secret of at least 32 characters>
cloudflare_alert_account_id: <Cloudflare account identifier>
cloudflare_alert_read_token: <read-only Cloudflare API token>
cloudflare_alert_ops_hostnames: [www.example.com]
cloudflare_alert_ops_tunnel_ids: [<owned tunnel identifier>]
cloudflare_alert_recovery_entities:
@ -41,20 +42,21 @@ response to obtain the private delivery URL. Keep that URL and the shared secret
out of logs and documentation. Configure a generic Cloudflare webhook destination
with that URL and secret. Attach it to Passive Origin Monitoring, Tunnel Health,
and Universal SSL policies; omit zone/tunnel filters when future resources should
also receive notification-only coverage. Retain existing email destinations.
also receive notification-only coverage. Use only the authenticated webhook
destination for delivery; email is not needed by this integration.
Use `cloudflare_alerts.get_status` for delivery counts and open incident metadata.
The administrator action `cloudflare_alerts.refresh` performs an immediate history
check and returns the same status. Both status actions require a service response.
The status action requires a service response.
Cloudflare destination tests increment the test count without creating Repairs
or machine jobs. After independently verifying recovery or completing operator
or machine jobs. Policy tests use sample data and may carry a different account
identity; the receiver deliberately rejects a mismatching account ID. To verify
incident handling, use an authenticated synthetic certificate payload with the
configured account ID, confirm the Repair, then resolve only that test incident.
After independently verifying recovery or completing operator
review, call the administrator action `cloudflare_alerts.resolve` with `issue_id`
and `verification` evidence. It only clears incidents created by this receiver.
History polling reports its last success and read failures in delivery status;
a persistent delivery Repair appears on failure and clears only after a
successful API read. The initial window covers the most recent ten minutes,
not historical outages. Successful checkpoints survive restarts; overlapping
reads are deduplicated by delivery identity.
Existing incident records and delivery counts survive the webhook-only upgrade;
obsolete history checkpoints are removed through Home Assistant's storage API.
Alerts never authorize browser interaction, DNS/security/account changes, host
reboots, or new public exposure. No dynamic DNS update integration is installed.

@ -1,33 +1,30 @@
"""Authenticate Cloudflare alerts and relay incident facts to Home Assistant."""
import asyncio
from datetime import UTC, datetime, timedelta
import html
import json
import re
import logging
import time
from aiohttp import ClientError, ClientTimeout, web
from aiohttp import web
import voluptuous as vol
from homeassistant.components import cloud, webhook
from homeassistant.const import EVENT_HOMEASSISTANT_STARTED
from homeassistant.core import HomeAssistant, ServiceCall, SupportsResponse
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.helpers.event import async_track_state_change_event, async_track_state_report_event
from homeassistant.helpers.service import async_register_admin_service
from homeassistant.helpers.storage import Store
from .policy import authentic, dispatch_allowed, identifier, normalize, transition
from .policy import authentic, dispatch_allowed, normalize, transition
DOMAIN = "cloudflare_alerts"
EVENT = "cloudflare_alert"
_LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA = vol.Schema({vol.Required(DOMAIN): vol.Schema({
vol.Required("webhook_id"): vol.All(cv.string, vol.Length(min=32)),
vol.Required("secret"): vol.All(cv.string, vol.Length(min=32)),
vol.Required("account_id"): cv.string,
vol.Optional("api_token"): cv.string,
vol.Optional("ops_hostnames", default=[]): [cv.string],
vol.Optional("ops_tunnel_ids", default=[]): [cv.string],
vol.Optional("recovery_entities", default={}): {cv.string: cv.entity_id},
@ -48,6 +45,7 @@ class AlertReceiver:
async def handle(self, hass, webhook_id, request):
"""Only accept authenticated POSTs from the configured Cloudflare account."""
if not authentic(request.headers.get("cf-webhook-auth", ""), self.config["secret"]):
_LOGGER.warning("Rejected Cloudflare webhook: authentication failed")
return web.Response(status=403)
body = await request.text()
if len(body.encode()) > 65536:
@ -60,6 +58,8 @@ class AlertReceiver:
return web.Response(status=400)
test = set(payload) == {"text"} and isinstance(payload["text"], str)
if not test and payload.get("account_id") != self.config["account_id"]:
_LOGGER.warning("Rejected Cloudflare webhook: account did not match (account present: %s; fields: %s)",
"account_id" in payload, sorted(payload))
return web.Response(status=403)
async with self.lock:
received = time.time()
@ -72,14 +72,14 @@ class AlertReceiver:
self.state["tests"] += 1
await self.store.async_save(self.state)
return web.json_response({"accepted": True, "test": True})
events = self.ingest(normalize(payload, received), allow_dispatch=True)
events = self.ingest(normalize(payload, received))
await self.store.async_save(self.state)
for event in events:
self.hass.bus.async_fire(EVENT, event)
return web.json_response({"accepted": True, "incidents_changed": len(events)})
def ingest(self, notifications: list[dict], *, allow_dispatch: bool) -> list[dict]:
"""Apply the same durable lifecycle to webhook and history observations."""
def ingest(self, notifications: list[dict]) -> list[dict]:
"""Apply the durable incident lifecycle to authenticated webhook observations."""
events = []
for event in notifications:
previous = self.state["incidents"].get(event["issue_id"])
@ -87,7 +87,7 @@ class AlertReceiver:
self.state["incidents"][event["issue_id"]] = record
if not changed:
continue
dispatch = allow_dispatch and first_open and dispatch_allowed(
dispatch = first_open and dispatch_allowed(
event, self.config["ops_hostnames"], self.config["ops_tunnel_ids"])
# The existing HA website automation owns an already dispatched outage.
local = self.hass.states.get(self.config["website_dispatch_entity"])
@ -99,72 +99,6 @@ class AlertReceiver:
events.append({**record, "dispatch": bool(dispatch), "first_open": first_open})
return events
async def poll_history(self, now=None):
"""Read existing Cloudflare deliveries when the account cannot attach webhooks."""
if not self.config.get("api_token"):
return
checked = time.time()
since = self.state.get("history_since", checked - 600)
params = {"per_page": 50, "since": datetime.fromtimestamp(since, UTC).isoformat(),
"before": datetime.fromtimestamp(checked, UTC).isoformat()}
url = f"https://api.cloudflare.com/client/v4/accounts/{self.config['account_id']}/alerting/v3/history"
records = []
error = ""
try:
session = async_get_clientsession(self.hass)
for page in range(1, 21):
async with session.get(url, headers={"Authorization": "Bearer " + self.config["api_token"]},
params={**params, "page": page}, timeout=ClientTimeout(total=20)) as response:
response.raise_for_status()
result = await response.json()
if not result.get("success"):
raise ValueError("Cloudflare rejected notification history")
batch = result.get("result") or []
records.extend(batch)
if len(batch) < 50:
break
else:
raise ValueError("Notification history needs a smaller retrieval window")
except (ClientError, TimeoutError, ValueError) as exc:
error = f"HTTP {exc.status}" if getattr(exc, "status", None) else "History retrieval failed"
async with self.lock:
previous_error = self.state.get("history_error", "")
self.state["history_error"] = error
events = []
if not error:
seen = self.state.setdefault("history_seen", [])
for record in sorted(records, key=lambda item: str(item.get("sent", ""))):
delivery_id = record.get("id")
if not delivery_id or delivery_id in seen:
continue
body = record.get("alert_body") or "Cloudflare sent an alert; review it in the dashboard."
try:
payload = json.loads(body)
except (TypeError, ValueError):
payload = None
if not isinstance(payload, dict):
resource = "notification-" + identifier(delivery_id)
text = html.unescape(re.sub(r"<[^>]+>", " ", str(body)))
payload = {"data": {"hostname": resource, "tunnel_id": resource}, "text": text}
payload = {**payload, "alert_type": record.get("alert_type"), "ts": record.get("sent")}
# Email history lacks a guaranteed structured resource/recovery contract.
# It provides review notifications, never machine authority.
events.extend(self.ingest(normalize(payload, checked), allow_dispatch=False))
seen.append(delivery_id)
self.state["history_seen"] = seen[-1000:]
self.state["history_since"] = checked - 60 # overlap for delayed history writes
self.state["last_history_success"] = checked
await self.store.async_save(self.state)
for event in events:
self.hass.bus.async_fire(EVENT, event)
if bool(error) != bool(previous_error):
self.hass.bus.async_fire(EVENT, {
"issue_id": "cloudflare_alert_delivery", "alert_type": "delivery_health",
"resource": "account", "action": "open" if error else "resolve", "dispatch": False,
"title": "Cloudflare alert delivery needs attention", "severity": "warning",
"description": f"Read-only notification history check: {error or 'verified healthy'}. Review the configured Notifications Read access and connectivity.",
})
async def resolve(self, issue_id: str, verification: str, observation_time: float | None = None):
"""Close only bridge-owned incidents after an authenticated verification."""
async with self.lock:
@ -179,11 +113,13 @@ class AlertReceiver:
await self.store.async_save(self.state)
self.hass.bus.async_fire(EVENT, {**record, "dispatch": False, "first_open": False})
async def recover_origins(self, now):
async def recover_origins(self, event):
"""Reuse fresh public-website observations; do not declare recovery from age."""
reported_entity = event.data["entity_id"] if event else None
for record in list(self.state["incidents"].values()):
entity_id = self.config["recovery_entities"].get(record["resource"])
if record["action"] != "open" or record["alert_type"] != "real_origin_monitoring" or not entity_id:
if (record["action"] != "open" or record["alert_type"] != "real_origin_monitoring"
or not entity_id or reported_entity and entity_id != reported_entity):
continue
state = self.hass.states.get(entity_id)
if (state and state.state == "on" and time.time() - record["received_ts"] >= 300
@ -196,7 +132,12 @@ class AlertReceiver:
async def async_setup(hass: HomeAssistant, config: dict) -> bool:
"""Register a narrow authenticated webhook and operator-only support actions."""
receiver = AlertReceiver(hass, config[DOMAIN])
receiver.state = await receiver.store.async_load() or receiver.state
stored_state = await receiver.store.async_load() or receiver.state
# Retire fallback checkpoints while retaining durable incidents and delivery counts.
receiver.state = {key: value for key, value in stored_state.items()
if not key.startswith("history_") and key != "last_history_success"}
if receiver.state != stored_state:
await receiver.store.async_save(receiver.state)
hass.data[DOMAIN] = receiver
webhook.async_register(hass, DOMAIN, "Cloudflare Alerts", config[DOMAIN]["webhook_id"],
receiver.handle, local_only=False, allowed_methods=["POST"])
@ -213,16 +154,10 @@ async def async_setup(hass: HomeAssistant, config: dict) -> bool:
async def resolve(call: ServiceCall):
await receiver.resolve(call.data["issue_id"], call.data["verification"])
async def refresh(call: ServiceCall):
await receiver.poll_history()
return await get_status(call)
async_register_admin_service(hass, DOMAIN, "create_cloudhook", create_cloudhook,
supports_response=SupportsResponse.ONLY)
hass.services.async_register(DOMAIN, "get_status", get_status,
supports_response=SupportsResponse.ONLY)
async_register_admin_service(hass, DOMAIN, "refresh", refresh,
supports_response=SupportsResponse.ONLY)
async_register_admin_service(hass, DOMAIN, "resolve", resolve, schema=vol.Schema({
vol.Required("issue_id"): cv.string,
vol.Required("verification"): vol.All(cv.string, vol.Length(min=10)),
@ -233,9 +168,8 @@ async def async_setup(hass: HomeAssistant, config: dict) -> bool:
for record in receiver.state["incidents"].values():
if record["action"] == "open":
hass.bus.async_fire(EVENT, {**record, "dispatch": False, "first_open": False})
await receiver.poll_history()
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, restore)
async_track_time_interval(hass, receiver.recover_origins, timedelta(minutes=5))
async_track_time_interval(hass, receiver.poll_history, timedelta(minutes=5))
recovery_entities = set(receiver.config["recovery_entities"].values())
async_track_state_change_event(hass, recovery_entities, receiver.recover_origins)
async_track_state_report_event(hass, recovery_entities, receiver.recover_origins)
return True

@ -6,5 +6,5 @@
"documentation": "https://developers.cloudflare.com/notifications/",
"integration_type": "service",
"iot_class": "cloud_push",
"version": "1.0.0"
"version": "1.1.0"
}

@ -11,9 +11,6 @@ create_cloudhook:
get_status:
name: Get delivery status
description: Return accepted delivery counts and current incidents without credentials.
refresh:
name: Refresh notification history
description: Perform an immediate read-only history check and return delivery status.
resolve:
name: Resolve verified incident
description: Clear a bridge-owned alert only after verifying recovery or completing human review.

@ -14,7 +14,7 @@ sys.path.insert(0, str(config_path))
from homeassistant.core import HomeAssistant
from homeassistant.util.aiohttp import MockRequest
from custom_components.cloudflare_alerts import AlertReceiver, EVENT
from custom_components.cloudflare_alerts import AlertReceiver, DOMAIN, EVENT, async_setup
class ReceiverTests(unittest.IsolatedAsyncioTestCase):
@ -111,66 +111,42 @@ class ReceiverTests(unittest.IsolatedAsyncioTestCase):
await self.receiver.resolve(record["issue_id"], "Earlier probe snapshot", newer["received_ts"] - 1)
self.assertEqual(self.receiver.state["incidents"][record["issue_id"]]["action"], "open")
async def test_notification_history_is_read_only_notification_only_and_durable(self):
self.receiver.config["api_token"] = "fixture-read-token"
sent = datetime.now(UTC).isoformat()
records = [{"id": "delivery-1", "alert_type": "real_origin_monitoring", "sent": sent,
"alert_body": json.dumps({"unreachable_zones": [{"host": "example.com", "zone_name": "example.com"}]})},
{"id": "delivery-2", "alert_type": "tunnel_health_event", "sent": sent,
"alert_body": json.dumps({"tunnel_id": "owned-tunnel", "tunnel_name": "example-tunnel",
"new_status": "TUNNEL_STATUS_TYPE_DEGRADED"})},
{"id": "delivery-3", "alert_type": "universal_ssl_event_type", "sent": sent,
"alert_body": json.dumps({"data": {"id": "certificate-1", "hosts": ["example.com"], "status": ""},
"metadata": {"event": {"type": "ssl.certificate.validation.failed"}}})},
{"id": "delivery-4", "alert_type": "tunnel_health_event", "sent": sent,
"alert_body": "A tunnel needs review"}]
class Response:
async def __aenter__(self): return self
async def __aexit__(self, *args): pass
def raise_for_status(self): pass
async def json(self): return {"success": True, "result": records}
calls = []
class Session:
def get(self, url, **kwargs):
calls.append((url, kwargs))
return Response()
with patch("custom_components.cloudflare_alerts.async_get_clientsession", return_value=Session()):
await self.receiver.poll_history()
await self.hass.async_block_till_done()
self.receiver.state = await self.receiver.store.async_load()
await self.receiver.poll_history()
await self.hass.async_block_till_done()
self.assertEqual(len(self.events), 4)
self.assertEqual([(event["resource"], event["status"]) for event in self.events[:3]],
[("example.com", "unreachable"), ("owned-tunnel", "degraded"),
("certificate-1", "validation.failed")])
self.assertFalse(any(event["dispatch"] for event in self.events))
self.assertEqual(len(self.receiver.state["history_seen"]), 4)
self.assertTrue(all(url.endswith("/alerting/v3/history") for url, _ in calls))
self.assertIn("since", calls[0][1]["params"])
async def test_history_delivery_failure_remains_visible_until_successful_read(self):
self.receiver.config["api_token"] = "fixture-read-token"
healthy = False
class Response:
async def __aenter__(self): return self
async def __aexit__(self, *args): pass
def raise_for_status(self):
if not healthy: raise ValueError("Read failed")
async def json(self): return {"success": True, "result": []}
class Session:
def get(self, *args, **kwargs): return Response()
with patch("custom_components.cloudflare_alerts.async_get_clientsession", return_value=Session()):
await self.receiver.poll_history()
await self.receiver.poll_history()
healthy = True
await self.receiver.poll_history()
await self.hass.async_block_till_done()
self.assertEqual([event["action"] for event in self.events], ["open", "resolve"])
self.assertTrue(all(event["issue_id"] == "cloudflare_alert_delivery" for event in self.events))
async def test_webhook_only_upgrade_preserves_incidents_and_recovers_from_probe_events(self):
await self.send(self.payload())
record = next(iter(self.receiver.state["incidents"].values()))
record["received_ts"] = time.time() - 400
self.receiver.state.update(history_seen=["old-delivery"], history_since=100,
history_error="", last_history_success=200)
await self.receiver.store.async_save(self.receiver.state)
with patch("custom_components.cloudflare_alerts.webhook.async_register"):
await async_setup(self.hass, {DOMAIN: {**self.config, "webhook_id": "fixture-hook"}})
self.receiver = self.hass.data[DOMAIN]
self.assertEqual(self.receiver.state["received"], 1)
self.assertEqual(len(self.receiver.state["incidents"]), 1)
saved = await self.receiver.store.async_load()
self.assertEqual(set(saved), {"incidents", "received", "tests", "last_received",
"last_alert_type", "last_data_fields"})
self.assertFalse(self.hass.services.has_service(DOMAIN, "refresh"))
# Changes from unrelated probes cannot close an owned incident.
self.hass.states.async_set("binary_sensor.unrelated_website", "on")
await self.hass.async_block_till_done()
self.assertEqual(len(self.events), 1)
self.hass.states.async_set("binary_sensor.example_website", "on")
await self.hass.async_block_till_done()
self.assertEqual(self.events[-1]["action"], "resolve")
# An unchanged healthy report still observes the minimum recovery delay.
await self.send(self.payload())
self.hass.states.async_set("binary_sensor.example_website", "on")
await self.hass.async_block_till_done()
self.assertEqual(self.events[-1]["action"], "open")
record = self.receiver.state["incidents"][record["issue_id"]]
record["received_ts"] = time.time() - 400
self.hass.states.async_set("binary_sensor.example_website", "on")
await self.hass.async_block_till_done()
self.assertEqual([event["action"] for event in self.events],
["open", "resolve", "open", "resolve"])
if __name__ == "__main__":

Loading…
Cancel
Save

Powered by TurnKey Linux.