"""Simple JSON-file store for pending requests and issued cert records. A real deployment could swap this for sqlite, but request volume here is tiny (one entry per physical device) so a flat file is fine and easy to inspect/back up. """ import json import os import threading import time STATE_PATH = "/data/state.json" _lock = threading.Lock() def _load(): if not os.path.exists(STATE_PATH): return {"pending": {}, "issued": {}, "revoked": {}, "broker_cert": None} with open(STATE_PATH, "r") as f: state = json.load(f) state.setdefault("broker_cert", None) state.setdefault("revoked", {}) return state def _save(state): tmp_path = STATE_PATH + ".tmp" with open(tmp_path, "w") as f: json.dump(state, f, indent=2) os.replace(tmp_path, STATE_PATH) def add_pending(device_id: str, csr_pem: str, meta: dict): with _lock: state = _load() state["pending"][device_id] = { "csr": csr_pem, "meta": meta or {}, "requested_at": time.time(), } _save(state) def list_pending(): with _lock: return _load()["pending"] def pop_pending(device_id: str): with _lock: state = _load() return state["pending"].pop(device_id, None), state def list_issued(): with _lock: return _load()["issued"] def mark_issued(device_id: str, cert_pem: str, not_after: str, serial: int, state=None): with _lock: state = state or _load() state["issued"][device_id] = { "cert": cert_pem, "not_after": not_after, "issued_at": time.time(), "serial": serial, } _save(state) def reject_pending(device_id: str, reason: str): with _lock: state = _load() state["pending"].pop(device_id, None) _save(state) def get_broker_cert(): with _lock: return _load()["broker_cert"] def set_broker_cert(hostnames: list, not_after: str): with _lock: state = _load() state["broker_cert"] = { "hostnames": hostnames, "not_after": not_after, "issued_at": time.time(), } _save(state) def revoke_device(device_id: str, reason: str): """Move a device from issued -> revoked. Keeps the issued record too (for audit history) but also records it separately so the CRL builder has a fast list to work from. Returns the serial number, or None if the device has no issued cert on record.""" with _lock: state = _load() issued = state["issued"].get(device_id) if not issued: return None state["revoked"][device_id] = { "serial": issued["serial"], "reason": reason, "revoked_at": time.time(), } _save(state) return issued["serial"] def list_revoked(): with _lock: return _load()["revoked"]