move_detect/tests/test_queue.py
유창욱 c3227c179c fix(security,edge,test): close the confirmed audit backlog; add the guards that prevent recurrence
감사에서 확정된 잔여 항목을 일괄 처리. 이전 커밋이 증상(스테일 번들)을 고쳤다면 이번에는
그것이 조용히 지나가게 만든 구조를 고친다.

보안
- CSP 도입. 인라인 2블록에 per-request nonce, unsafe-inline 없음. 빌드가 없다는 제약이
  nonce를 막지는 않는다. 보안 헤더를 .htaccess 단독에서 PHP로 옮겨 개발/납품이 같아진다.
- /logout에 CSRF. SameSite=Lax가 막아주지만, 사고 대응 중 운영자를 콘솔에서 튕겨내는 건
  이 제품에선 실제 가용성 공격이라 예외로 둘 이유가 없다.
- 잠긴 계정 423 → 401. 아무나 이름을 추측해 5회 실패로 잠근 뒤 423을 계정 실재 확인으로
  쓸 수 있었다. 잠금 사실은 감사 로그에 남고, 익명 호출자는 못 읽는다.

엣지
- 큐 flush에 회당 상한. 정전 복구 직후 2000건을 비우는 동안 감지가 멈추던 구간을 없앤다.
- 타이머 env 전수 검증. COOLDOWN_S=nan은 dedup을 무력화해 매 틱 발보시켰다.
- T2 프레임 스킵(INFER_EVERY). 스킵 틱은 프레임을 읽어 버퍼만 비우고 링버퍼에 넣지 않는다 —
  추론이 없으면 얼굴 박스도 없어 그대로 넣으면 증거 스냅샷에 미블러 얼굴이 실린다.
  T3(모션 게이트)는 의도적으로 미구현: 게이트가 틀리면 '움직이지 않는 쓰러진 작업자'에게
  추론이 안 돈다. 실영상 없이 임계값을 정할 수 없다.
- systemd 워치독(sd_notify) + 메모리 상한. Restart=always는 죽은 프로세스만 잡고
  '살아 있는데 멈춘' 상태는 못 잡는다. UVC 해상도·버퍼 고정(링버퍼 RSS가 웹캠 기본값에 좌우).

테스트 — 감사의 최대 갭
- PDO 통합 테스트가 pdo_sqlite 부재로 통째로 스킵되고 CI도 없어 사실상 한 번도 안 돌았다.
  `-d extension=pdo_sqlite`로 되살리고 리포트·히트맵·익스포트 집계 SQL을 최초로 실행한다.
- 얼굴 블러 테스트가 out is not None만 봤다 — blur()가 무동작이어도 통과. PIPA 대응의
  유일한 실행 가능한 증거였는데 아무것도 증명하지 못했다. 디테일 파괴를 단언하도록 교체.
- index.php 라우트 테이블 대조(프런트 호출 15개 교차검증), dist↔소스 패리티 테스트,
  CI 신설(스킵이 하나라도 있으면 실패).
- ArraySessionStore.regenerate()가 데이터를 지워 실제 session_regenerate_id(true)와
  달랐다. 더블이 실구현과 어긋난 자리 하나를 실제로 잡았다.

프런트
- 이벤트 목록 시그니처 재렌더 스킵 + 포커스 복원. aria-live 영역을 5초마다 통째로 다시
  만들어 스크린리더가 200행을 재낭독하고 키보드 포커스가 body로 날아갔다. 같은 패턴이
  device-tree.js에는 이미 있었다.
- 폴링 중첩 가드(느린 공유호스팅에서 응답 역전), 콜드스타트 실패 표시.

납품
- VERSION 신설, 두 산출물에 version/git_commit/built_at 스탬프. 스테일 번들의 SHA256SUMS는
  자기정합적이라 통과한다 — provenance 없이는 하류에서 탐지할 방법이 없다.
- deploy/README·env.example을 Hailo 단독 번들 실제와 일치(템플릿이 없는 ONNX를 가리켰다).
- 이벤트 보존 정책은 기본 0(영구). 산업안전 기록을 시스템이 임의로 지우지 않는다.

검증: pytest 251 / PHPUnit 162, 스킵 0. CSP nonce 결합은 실제 렌더 경로로 확인.
브라우저 실렌더는 MySQL이 필요해 이 환경에서 미수행.
2026-08-07 23:31:53 +09:00

198 lines
8.4 KiB
Python

import json
import sqlite3
from edge.events import Event, EventType, Severity
from edge.queue import OfflineQueue
from edge.alert import SendResult
def _event(n=1):
return Event(EventType.FALL, Severity.HIGH, "cam-01", n, None, float(n), 3.0, {}, None)
class _Client:
def __init__(self, fail=False):
self.fail = fail
self.sent = []
def send(self, event, snapshots):
if self.fail:
return False
self.sent.append(event.track_id)
return True
def test_try_send_success_not_queued(tmp_path):
q = OfflineQueue(str(tmp_path / "q.db"), _Client())
assert q.try_send(_event(1), [b"x"]) is True
assert q.pending() == 0
def test_failure_is_queued(tmp_path):
q = OfflineQueue(str(tmp_path / "q.db"), _Client(fail=True))
assert q.try_send(_event(1), [b"x"]) is False
assert q.pending() == 1
def test_flush_resends_when_recovered(tmp_path):
client = _Client(fail=True)
q = OfflineQueue(str(tmp_path / "q.db"), client)
q.try_send(_event(1), [b"x"])
q.try_send(_event(2), [b"y"])
assert q.pending() == 2
client.fail = False
assert q.flush() == 2
assert q.pending() == 0
assert client.sent == [1, 2]
class _PoisonClient:
"""Rejects one specific event forever with a definite 4xx the server will never accept."""
def __init__(self, poison_id):
self.poison = poison_id
self.sent = []
def send(self, event, snapshots):
if event.track_id == self.poison:
return SendResult.REJECTED
self.sent.append(event.track_id)
return SendResult.DELIVERED
def test_queue_is_bounded_and_keeps_newest(tmp_path):
# An extended outage (or a permanent misconfig) must not fill the SD card. The queue caps
# itself, evicting the OLDEST — a fresh fall alert matters more than a stale one.
q = OfflineQueue(str(tmp_path / "q.db"), _Client(fail=True), max_rows=5)
for n in range(20):
q.try_send(_event(n), [b"x"])
assert q.pending() == 5
q.client.fail = False
q.flush()
assert q.client.sent == [15, 16, 17, 18, 19] # the newest 5 survived
def test_event_uuid_survives_the_queue_roundtrip(tmp_path):
# A re-sent event (failed once -> queued -> flushed) must carry the SAME event_uuid so the
# server dedups it instead of storing a duplicate alert. This is the whole point of the key.
class _CaptureClient:
def __init__(self):
self.fail = True
self.uuids = []
def send(self, event, snapshots):
self.uuids.append(event.event_uuid)
return not self.fail
client = _CaptureClient()
q = OfflineQueue(str(tmp_path / "q.db"), client)
ev = _event(1)
q.try_send(ev, [b"x"]) # fails -> queued (1st send attempt)
client.fail = False
assert q.flush() == 1 # re-sent from the queue (2nd send attempt)
assert len(client.uuids) == 2
assert client.uuids[0] == client.uuids[1] == ev.event_uuid
def test_poison_head_is_dropped_and_unblocks_the_queue(tmp_path):
# A permanently-rejected event at the head must not wedge the whole queue forever; after
# max_send_attempts it is dropped so the events behind it can drain.
client = _PoisonClient(99)
q = OfflineQueue(str(tmp_path / "q.db"), client, max_send_attempts=3)
q.enqueue(_event(99), [b"x"]) # poison, at the head
q.enqueue(_event(2), [b"y"]) # good, behind it
for _ in range(3):
q.flush()
assert client.sent == [2] # good event delivered
assert q.pending() == 0 # poison dropped, queue drained
def test_sustained_outage_never_drops_events(tmp_path):
# A transient outage (network down / 5xx) must NEVER poison-drop queued events, no matter how
# long it lasts — a real fall alert has to survive an overnight outage. Only a definite 4xx
# rejection counts toward the drop cap (contrast test_poison_head_is_dropped above).
class _Outage:
up = False
sent = []
def send(self, event, snapshots):
if not _Outage.up:
return SendResult.TRANSIENT
_Outage.sent.append(event.track_id)
return SendResult.DELIVERED
client = _Outage()
q = OfflineQueue(str(tmp_path / "q.db"), client, max_send_attempts=3)
q.enqueue(_event(1), [b"x"])
for _ in range(10): # far beyond max_send_attempts
q.flush()
assert q.pending() == 1 # still queued — a transient failure is never poison-dropped
_Outage.up = True
q.flush()
assert q.pending() == 0 and _Outage.sent == [1] # drains once connectivity returns
def test_undecodable_row_is_dropped_and_unblocks_the_queue(tmp_path):
# A corrupt row (torn SD-card write / schema drift) can never be decoded, so it must not wedge
# every queued safety event behind it forever. flush() drops the single bad row and drains the
# rest — losing one unrecoverable event beats freezing the whole queue.
db = str(tmp_path / "q.db")
con = sqlite3.connect(db)
con.execute("CREATE TABLE queue (id INTEGER PRIMARY KEY AUTOINCREMENT, payload TEXT, "
"snaps TEXT, attempts INTEGER DEFAULT 0)")
con.execute("INSERT INTO queue (payload, snaps) VALUES (?, ?)",
("{not valid json", json.dumps([]))) # poison row at the head
good = {"event_type": "fall", "severity": "high", "camera_id": "cam-01", "track_id": 7,
"zone_id": None, "occurred_at": 100.0, "duration_s": 3.0, "metrics": {},
"spatial": None, "event_uuid": "u7"}
con.execute("INSERT INTO queue (payload, snaps) VALUES (?, ?)",
(json.dumps(good), json.dumps([]))) # good row behind it
con.commit(); con.close()
client = _Client()
q = OfflineQueue(db, client)
assert q.flush() == 1 # the good row drained past the dropped poison row
assert client.sent == [7]
assert q.pending() == 0 # both rows gone: poison dropped, good delivered
def test_legacy_row_without_uuid_reuses_minted_uuid_across_retries(tmp_path):
# A row queued before event_uuid existed has none stored. On first flush a fresh uuid is
# minted; it MUST be persisted so every retry reuses the SAME key — else each failed-then-
# retried delivery sends a different uuid and the server stores duplicates (the P1-9 bug).
db = str(tmp_path / "q.db")
con = sqlite3.connect(db)
con.execute("CREATE TABLE queue (id INTEGER PRIMARY KEY AUTOINCREMENT, payload TEXT, "
"snaps TEXT, attempts INTEGER DEFAULT 0)")
legacy = {"event_type": "fall", "severity": "high", "camera_id": "cam-01", "track_id": 1,
"zone_id": None, "occurred_at": 100.0, "duration_s": 3.0, "metrics": {}, "spatial": None}
con.execute("INSERT INTO queue (payload, snaps) VALUES (?, ?)",
(json.dumps(legacy), json.dumps([])))
con.commit(); con.close()
class _Capture:
up = False
uuids = []
def send(self, event, snapshots):
_Capture.uuids.append(event.event_uuid)
return SendResult.DELIVERED if _Capture.up else SendResult.TRANSIENT
q = OfflineQueue(db, _Capture())
q.flush() # transient -> row stays; uuid minted and persisted
_Capture.up = True
q.flush() # delivered
assert len(_Capture.uuids) == 2
assert _Capture.uuids[0] == _Capture.uuids[1] # same key reused across retries
def test_flush_drains_in_bounded_slices(tmp_path):
# flush() runs inside the single-threaded detection loop, so an unbounded drain after a long
# outage would stall fall detection for minutes at the worst possible moment. Each call must
# send at most max_flush_rows and leave the rest for the next tick.
q = OfflineQueue(str(tmp_path / "q.db"), _Client(), max_flush_rows=3)
for n in range(10):
q.enqueue(_event(n), [])
assert q.pending() == 10
assert q.flush() == 3 # one slice, not the whole queue
assert q.pending() == 7
q.flush(); q.flush()
assert q.pending() == 1 # keeps draining across ticks
q.flush()
assert q.pending() == 0
def test_flush_slice_preserves_fifo_order(tmp_path):
# Bounding the slice must not reorder delivery: the oldest queued alert still goes first.
client = _Client()
q = OfflineQueue(str(tmp_path / "q.db"), client, max_flush_rows=2)
for n in range(4):
q.enqueue(_event(n), [])
q.flush(); q.flush()
assert client.sent == [0, 1, 2, 3]