move_detect/tests/test_config.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

120 lines
5.7 KiB
Python

import pytest
from edge.config import (frame_interval_from_env, load_config, queue_db_path,
require_upload_config)
def test_defaults_when_env_empty():
cfg = load_config({})
assert cfg.device_id == "pi-unknown"
assert cfg.fall.prone_confirm_s == 3.0
assert cfg.fall.no_motion_s == 10.0
assert cfg.camera_id == "cam-01"
assert cfg.cafe24_url == ""
assert cfg.secret == ""
assert cfg.ghost.reappear_s == 10.0
assert cfg.zone.debounce_s == 0.75
assert cfg.engine.cooldown_s == 30.0
def test_env_overrides():
env = {
"DEVICE_ID": "pi-w1", "CAMERA_ID": "cam-9",
"CAFE24_URL": "https://x/api/events", "DEVICE_SECRET": "s",
"FALL_PRONE_S": "2.0", "FALL_NO_MOTION_S": "8",
"IMMOBILE_S": "90", "COOLDOWN_S": "45",
"GHOST_REAPPEAR_S": "7", "ZONE_DEBOUNCE_S": "1.5",
}
cfg = load_config(env)
assert cfg.device_id == "pi-w1"
assert cfg.camera_id == "cam-9"
assert cfg.fall.prone_confirm_s == 2.0
assert cfg.fall.no_motion_s == 8.0
assert cfg.immobility.immobile_s == 90.0
assert cfg.engine.cooldown_s == 45.0
assert cfg.engine.camera_id == "cam-9"
assert cfg.ghost.reappear_s == 7.0
assert cfg.zone.debounce_s == 1.5
def test_require_upload_config_rejects_blank_url_and_secret():
# A blank CAFE24_URL or DEVICE_SECRET must fail LOUD at startup. Left silent, the daemon
# runs green while every upload fails (bad URL -> requests error, caught) and the offline
# queue grows until the SD card is full.
with pytest.raises(ValueError, match="CAFE24_URL"):
require_upload_config(load_config({"DEVICE_SECRET": "s"}))
with pytest.raises(ValueError, match="DEVICE_SECRET"):
require_upload_config(load_config({"CAFE24_URL": "https://x/move_detect"}))
# Whitespace-only is still blank.
with pytest.raises(ValueError):
require_upload_config(load_config({"CAFE24_URL": " ", "DEVICE_SECRET": " "}))
def test_require_upload_config_passes_when_both_present():
# A real per-device secret is a long HMAC-derived hex string, on an https URL.
cfg = load_config({"CAFE24_URL": "https://x/move_detect",
"DEVICE_SECRET": "0123456789abcdef0123"})
require_upload_config(cfg) # must not raise
def test_require_upload_config_rejects_placeholder_and_http():
# Non-empty ship-time placeholders pass a blank check but are never a real value; a unit left
# at one uploads nothing while looking healthy. http would leak worker snapshots in plaintext.
with pytest.raises(ValueError, match="DEVICE_SECRET"):
require_upload_config(load_config({"CAFE24_URL": "https://x/move_detect",
"DEVICE_SECRET": "CHANGEME"}))
with pytest.raises(ValueError, match="CAFE24_URL"):
require_upload_config(load_config({"CAFE24_URL": "https://your-domain.example/move_detect",
"DEVICE_SECRET": "0123456789abcdef0123"}))
with pytest.raises(ValueError, match="https"):
require_upload_config(load_config({"CAFE24_URL": "http://x/move_detect",
"DEVICE_SECRET": "0123456789abcdef0123"}))
with pytest.raises(ValueError, match="too short"):
require_upload_config(load_config({"CAFE24_URL": "https://x/move_detect",
"DEVICE_SECRET": "short"}))
def test_load_config_rejects_non_finite_or_nonpositive_motion_thr():
# A 0 / NaN / inf MOTION_THR would make every track read as "still" -> constant no_motion.
for bad in ("0", "-1", "nan", "inf"):
with pytest.raises(ValueError, match="MOTION_THR"):
load_config({"MOTION_THR": bad})
# A sane value flows through to both detectors.
cfg = load_config({"MOTION_THR": "0.3"})
assert cfg.fall.motion_thr == 0.3 and cfg.immobility.motion_thr == 0.3
def test_frame_interval_defaults_and_validates():
assert frame_interval_from_env({}) == pytest.approx(1 / 12)
assert frame_interval_from_env({"TARGET_FPS": "24"}) == pytest.approx(1 / 24)
# TARGET_FPS=0 -> ZeroDivisionError today -> infinite systemd crash loop; must be rejected.
with pytest.raises(ValueError):
frame_interval_from_env({"TARGET_FPS": "0"})
with pytest.raises(ValueError):
frame_interval_from_env({"TARGET_FPS": "12fps"})
with pytest.raises(ValueError):
frame_interval_from_env({"TARGET_FPS": "-5"})
def test_queue_db_path_defaults_absolute_under_state_dir():
# A relative 'queue.db' is unwritable under the hardened unit (ProtectSystem=strict,
# WorkingDirectory read-only) -> crash loop. Default to the writable StateDirectory.
assert queue_db_path({}) == "/var/lib/move-detect/queue.db"
assert queue_db_path({"QUEUE_DB": "/custom/q.db"}) == "/custom/q.db"
def test_timer_knobs_reject_nan_and_nonpositive():
# NaN makes every `now - started >= limit` comparison False and 0/negative makes it always
# True — a typo in edge.env silently disables a detector or turns it into a permanent alarm
# instead of crashing. COOLDOWN_S=nan is the worst: dedup stops and every tick re-fires.
for key in ("COOLDOWN_S", "IMMOBILE_S", "FALL_PRONE_S", "FALL_NO_MOTION_S",
"GHOST_REAPPEAR_S", "ZONE_DEBOUNCE_S", "MOTION_THR"):
for bad in ("nan", "0", "-1"):
with pytest.raises(ValueError) as ei:
load_config({key: bad})
assert key in str(ei.value) # 어느 키가 문제인지 운영자에게 말해준다
def test_infer_every_defaults_to_every_tick():
assert load_config({}).infer_every == 1
assert load_config({"INFER_EVERY": "3"}).infer_every == 3
with pytest.raises(ValueError):
load_config({"INFER_EVERY": "0"})