Files
virarepo/mqtt-cert-manager/app/mqtt_worker.py
T
eta f53f2f6309
build-and-push / check-branch (push) Successful in 14s
build-and-push / prepare (push) Successful in 10s
build-and-push / build (amd64, linux/amd64) (push) Successful in 1m38s
Improved logging and error handling for mcm
2026-10-11 17:21:34 +03:30

160 lines
7.1 KiB
Python

"""
MQTT side of the enrollment protocol.
Topics (prefix is configurable, default "cert/enroll"):
<prefix>/<device_id>/request node -> here {"csr": "<PEM>", "meta": {...}}
<prefix>/<device_id>/renew node -> here {"csr": "<PEM>", "timestamp": <int>, "signature": "<base64>", "meta": {...}}
<prefix>/<device_id>/issued here -> node {"cert": "<PEM>", "ca": "<PEM>"} (retained)
<prefix>/<device_id>/rejected here -> node {"reason": "..."}
<prefix>/<device_id>/revoked here -> node {"reason": "..."} (best-effort notice; see DEVICE_PROTOCOL.md)
device_id is expected to be unique per physical device (not a shared
bootstrap identity) -- that's what makes per-device topics work without
any extra filtering in the payload. The cert's CN is a separate concern,
set from the CSR by main.py/ca.py, and may deliberately be shared across
many devices (e.g. one CN per device category) -- that has no bearing on
topic routing here.
See DEVICE_PROTOCOL.md for the full spec devices should implement.
"""
import json
import logging
import threading
import time
import paho.mqtt.client as mqtt
import store
log = logging.getLogger("mqtt_worker")
class MqttWorker:
def __init__(self, host, port, username, password, topic_prefix, on_request, on_renew):
self.topic_prefix = topic_prefix.rstrip("/")
self.on_request = on_request # callback(device_id, csr_pem, meta)
self.on_renew = on_renew # callback(device_id, csr_pem, timestamp, signature_b64, meta)
self.client = mqtt.Client(client_id="mqtt-cert-manager")
if username:
self.client.username_pw_set(username, password or None)
self.client.on_connect = self._on_connect
self.client.on_disconnect = self._on_disconnect
self.client.on_message = self._on_message
self.host = host
self.port = port
def start(self):
# Returns immediately: the connect (and its retries) happen in the
# background, so a broker that isn't reachable YET -- e.g. Home
# Assistant just booted and Mosquitto hasn't started -- doesn't
# crash the whole add-on or block the web UI from coming up.
thread = threading.Thread(target=self._run, daemon=True, name="mqtt-worker")
thread.start()
def _run(self):
self.client.reconnect_delay_set(min_delay=1, max_delay=30)
delay = 1
while True:
try:
# This is the plain TCP connect. MQTT itself (CONNECT /
# CONNACK, auth) only starts once this succeeds.
self.client.connect(self.host, self.port, keepalive=60)
except OSError as exc:
# ConnectionRefusedError (nothing listening), gaierror
# (hostname doesn't resolve), timeouts, etc. all land here.
log.warning(
"cannot reach MQTT broker at %s:%s (%s: %s) - retrying in %ss. "
"Check the mqtt_host / mqtt_port options, and that Mosquitto is running.",
self.host, self.port, type(exc).__name__, exc, delay,
)
time.sleep(delay)
delay = min(delay * 2, 30)
continue
# Connected at the TCP level. From here paho handles drops and
# reconnects itself (using reconnect_delay_set above); this only
# returns if disconnect() is ever called explicitly.
self.client.loop_forever()
return
def _on_connect(self, client, userdata, flags, rc):
if rc != 0:
# The TCP connection worked but the BROKER said no -- a different
# failure from "connection refused". Usually bad credentials.
log.error(
"MQTT broker rejected the connection: %s "
"(check the mqtt_username / mqtt_password options)",
mqtt.connack_string(rc),
)
return
request_topic = f"{self.topic_prefix}/+/request"
renew_topic = f"{self.topic_prefix}/+/renew"
client.subscribe(request_topic, qos=1)
client.subscribe(renew_topic, qos=1)
log.info("connected to broker, subscribed to %s and %s", request_topic, renew_topic)
def _on_disconnect(self, client, userdata, rc):
if rc != 0:
log.warning("lost connection to MQTT broker (rc=%s); retrying automatically", rc)
def _on_message(self, client, userdata, msg):
parts = msg.topic.split("/")
if len(parts) < 2:
return
device_id, kind = parts[-2], parts[-1]
try:
payload = json.loads(msg.payload.decode())
except ValueError as exc:
log.warning("malformed payload from %s on %s: %s", device_id, msg.topic, exc)
return
if kind == "request":
try:
csr_pem = payload["csr"]
except KeyError as exc:
log.warning("malformed request from %s: missing %s", device_id, exc)
return
log.info("enrollment request received from %s", device_id)
self.on_request(device_id, csr_pem, payload.get("meta", {}))
elif kind == "renew":
try:
csr_pem = payload["csr"]
timestamp = payload["timestamp"]
signature_b64 = payload["signature"]
except KeyError as exc:
log.warning("malformed renewal from %s: missing %s", device_id, exc)
return
log.info("renewal request received from %s", device_id)
self.on_renew(device_id, csr_pem, timestamp, signature_b64, payload.get("meta", {}))
def publish_issued(self, device_id: str, cert_pem: str, ca_pem: str):
topic = f"{self.topic_prefix}/{device_id}/issued"
payload = json.dumps({"cert": cert_pem, "ca": ca_pem})
self.client.publish(topic, payload, qos=1, retain=True)
log.info("published issued cert for %s", device_id)
def publish_rejected(self, device_id: str, reason: str):
topic = f"{self.topic_prefix}/{device_id}/rejected"
self.client.publish(topic, json.dumps({"reason": reason}), qos=1, retain=False)
log.info("published rejection for %s: %s", device_id, reason)
def publish_revoked(self, device_id: str, reason: str):
"""Notify the device (if online) and clear the retained cert so a
rebooting/reconnecting device doesn't pick the old cert back up.
This is best-effort, not the actual enforcement mechanism — that's
the CRL Mosquitto checks during the TLS handshake. A device that's
offline or already mid-handshake won't see this message.
"""
revoked_topic = f"{self.topic_prefix}/{device_id}/revoked"
self.client.publish(revoked_topic, json.dumps({"reason": reason}), qos=1, retain=False)
# Publishing an empty, retained payload deletes the previous
# retained message on the broker (per MQTT spec).
issued_topic = f"{self.topic_prefix}/{device_id}/issued"
self.client.publish(issued_topic, payload=b"", qos=1, retain=True)
log.info("published revocation for %s and cleared retained cert", device_id)