Two independent adversarial reviews (codex CLI + a 6-dimension verification workflow) of the delivery-hardening branch surfaced ~40 findings; this closes the confirmed correctness/security/deploy blockers plus a codex re-review pass. edge: - geometry: track_displacement per-second threshold recalibrated (0.02->0.25, env-tunable via MOTION_THR, validated finite/positive); confidence-filter keypoints with a bbox-center fallback so hallucinated points don't fake motion - fall: low-confidence frames no longer cancel an active FALLING/FALLEN incident (freeze + reset recovery timer so recovery needs a fresh confident streak); baseline height only seeded from trusted frames - queue: PostClient.send() returns a tri-state SendResult; only definite 4xx count toward the poison drop cap, so a network outage (incl. 408/425/429/5xx) never deletes queued safety events; legacy rows persist their minted uuid - config: reject placeholder / http / short DEVICE_SECRET at startup - zones: warn+skip legacy pixel-space polygons that would silently match nothing cloud: - zone endpoints wired into P3-2b site-scope (cross-site read/write/delete closed) + role gate on list; catch narrowed so DB faults surface as 500 - snapshot purge keeps the DB row when unlink() fails (no untrackable PIPA orphan) - ingest dedup path re-stores missing snapshots (+ short-write guard); UNIQUE (event_id, content_hash) makes recovery idempotent under retry/race - event list cursor carries full-precision occurred_at (no float rounding at the page boundary); string keyset end-to-end - SiteScope '' fails closed (only NULL is global); dashboard fetches full page cap - runnable migration (site/event_uuid + backfill ordering + indexes); rate-limit reap fails open deploy: - offline bundle hashes EVERY file (fatal on missing/failed/injected; models in SBOM; arch in tarball name; REQUIRE_SIGNATURE option) - installer verifies before any mutation, Hailo arch preflight before install, atomic src swap, backend reconcile preserves a working operator choice - systemd DeviceAllow=char-dma_heap (the /dev/dma_heap/ dir form was inert) Verified: edge pytest 165 passed / 2 skipped; cloud phpunit 109 passed / 4 skipped; deploy scripts bash -n clean. Reviewed by codex twice (findings + fixes) with the second-pass findings folded in.
79 lines
3.4 KiB
Python
79 lines
3.4 KiB
Python
import base64
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
from enum import Enum
|
|
|
|
from edge.events import Event
|
|
|
|
# Shared-hosting WAFs (cafe24) frequently block the default "python-requests/x.y" User-Agent
|
|
# with an HTML 403 while curl passes — so every event would silently 403 with a correct HMAC
|
|
# and URL. Send an explicit UA on every request. CloudClient imports this too.
|
|
USER_AGENT = "move-detect-edge/1.0"
|
|
|
|
|
|
class SendResult(Enum):
|
|
"""Outcome of one upload attempt. The offline queue must tell a transient outage (retry
|
|
forever — a real fall alert has to survive an overnight internet outage) apart from a
|
|
permanent rejection (poison — count toward the drop cap), which a bare bool cannot express.
|
|
DELIVERED is the only truthy value, so `if client.send(...)` keeps working unchanged."""
|
|
DELIVERED = "delivered"
|
|
REJECTED = "rejected" # a definite 4xx (not 429): the server will never accept this event
|
|
TRANSIENT = "transient" # network error / timeout / 429 / 5xx — connectivity or server hiccup
|
|
|
|
def __bool__(self) -> bool:
|
|
return self is SendResult.DELIVERED
|
|
|
|
|
|
def sign(secret: str, nonce: str, ts: str, body: str | bytes) -> str:
|
|
if isinstance(body, str):
|
|
body = body.encode()
|
|
msg = nonce.encode() + ts.encode() + body
|
|
return hmac.new(secret.encode(), msg, hashlib.sha256).hexdigest()
|
|
|
|
|
|
class PostClient:
|
|
def __init__(self, url: str, device_id: str, secret: str,
|
|
nonce_fn, now_fn, http_post=None, timeout: float = 5.0):
|
|
self.url = url
|
|
self.device_id = device_id
|
|
self.secret = secret
|
|
self.nonce_fn = nonce_fn
|
|
self.now_fn = now_fn
|
|
self.timeout = timeout
|
|
if http_post is None:
|
|
import requests
|
|
http_post = requests.post
|
|
self._post = http_post
|
|
|
|
def send(self, event: Event, snapshots: list[bytes]) -> SendResult:
|
|
payload = event.to_payload(self.device_id)
|
|
payload["snapshots"] = [base64.b64encode(s).decode() for s in snapshots]
|
|
body = json.dumps(payload, sort_keys=True)
|
|
nonce = self.nonce_fn()
|
|
ts = str(self.now_fn())
|
|
headers = {
|
|
"Content-Type": "application/json",
|
|
"User-Agent": USER_AGENT,
|
|
"X-Nonce": nonce,
|
|
"X-Timestamp": ts,
|
|
"X-Signature": sign(self.secret, nonce, ts, body.encode()),
|
|
}
|
|
try:
|
|
# allow_redirects=False: the .htaccess http->https 302 must not silently become a
|
|
# GET (405/404). A redirect is a CAFE24_URL misconfiguration to surface, not follow.
|
|
resp = self._post(self.url, data=body, headers=headers, timeout=self.timeout,
|
|
allow_redirects=False)
|
|
except Exception:
|
|
# Connection refused / DNS / timeout — the cloud is unreachable, not rejecting us.
|
|
return SendResult.TRANSIENT
|
|
code = resp.status_code
|
|
if 200 <= code < 300:
|
|
return SendResult.DELIVERED
|
|
# Transient — "back off and retry", NOT a permanent verdict on the event: all 5xx plus the
|
|
# 4xx codes that explicitly mean try-again (408 Request Timeout, 425 Too Early, 429 Too
|
|
# Many Requests). Counting these toward the poison drop cap would delete real events during
|
|
# a proxy/server hiccup. Only a definite "bad request" 4xx is a permanent rejection.
|
|
if code in (408, 425, 429) or code >= 500:
|
|
return SendResult.TRANSIENT
|
|
return SendResult.REJECTED
|