move_detect/server/tests/PdoIntegrationTest.php
유창욱 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

323 lines
14 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Tests;
use App\Repository\Pdo\{PdoNonceRepository, PdoEventRepository, PdoZoneRepository,
PdoActionRepository, PdoSnapshotRepository};
use PDO;
use PHPUnit\Framework\TestCase;
use RuntimeException;
/**
* DB-integration test: exercises the PDO repositories against a real sqlite :memory: database
* instead of the in-memory doubles used elsewhere. This is the ONLY place the delivered SQL
* actually executes -- every other test asserts against a double that reimplements the query
* semantics in PHP, so a broken query cannot fail them.
*
* RUN IT: `php -d extension=pdo_sqlite vendor/bin/phpunit`. Without that flag the driver is
* absent and setUp() skips the whole class. It used to say "or in CI" -- there was no CI, so
* this file had most likely never run anywhere. `.forgejo/workflows/verify.yml` now loads the
* extension and fails the build on ANY skip, so the coverage cannot silently vanish again.
*
* Covers Nonce, Event (including the report/heatmap/export aggregates), Zone, Action and
* Snapshot. PdoRateLimiterRepository stays out: its `ON DUPLICATE KEY UPDATE` is MySQL-only
* and has no portable sqlite equivalent.
*/
final class PdoIntegrationTest extends TestCase
{
private PDO $pdo;
protected function setUp(): void
{
if (!in_array('sqlite', PDO::getAvailableDrivers(), true)) {
$this->markTestSkipped('pdo_sqlite not available on this host');
}
$this->pdo = new PDO('sqlite::memory:', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$this->pdo->exec(self::sqliteSchema());
}
public function testNonceRoundTrip(): void
{
$repo = new PdoNonceRepository($this->pdo);
$this->assertFalse($repo->seen('n1'));
$repo->remember('n1', 9999999999);
$this->assertTrue($repo->seen('n1'));
}
public function testEventInsertFindAcknowledge(): void
{
$repo = new PdoEventRepository($this->pdo);
$uuid = str_repeat('a', 32);
$id = $repo->insert([
'event_uuid' => $uuid,
'device_id' => 'dev-1',
'site' => 'factory-a',
'camera_id' => 'cam-1',
'event_type' => 'fall',
'severity' => 'critical',
'track_id' => 7,
'zone_id' => null,
'occurred_at' => 1700000000.5,
'duration_s' => 2.5,
'metrics' => ['confidence' => 0.9],
]);
$this->assertGreaterThan(0, $id);
$found = $repo->find($id);
$this->assertNotNull($found);
$this->assertSame('dev-1', $found['device_id']);
$this->assertSame('factory-a', $found['site']);
$this->assertSame($uuid, $found['event_uuid']);
$this->assertSame('critical', $found['severity']);
$this->assertSame(['confidence' => 0.9], $found['metrics']);
$this->assertNull($found['acknowledged_by']);
// Idempotency key lookup (P1-9).
$this->assertSame($id, $repo->idByUuid($uuid));
$this->assertNull($repo->idByUuid(str_repeat('z', 32)));
// Site-scoped page (P3-2b): matches its own site, excluded from another.
$this->assertCount(1, $repo->page(10, null, null, null, 'factory-a'));
$this->assertCount(0, $repo->page(10, null, null, null, 'factory-b'));
$recent = $repo->recent(10, 'critical');
$this->assertCount(1, $recent);
$this->assertSame([], $repo->recent(10, 'info'));
$this->assertTrue($repo->acknowledge($id, 'alice'));
$this->assertSame('alice', $repo->find($id)['acknowledged_by']);
$this->assertFalse($repo->acknowledge(999999, 'bob'));
}
public function testZoneSaveIsOwnershipScoped(): void
{
$repo = new PdoZoneRepository($this->pdo);
$zoneId = $repo->save([
'zone_id' => null,
'device_id' => 'dev-1',
'camera_id' => 'cam-1',
'level' => 'warning',
'polygon_json' => '[[0,0],[1,0],[1,1]]',
]);
$this->assertNotSame('', $zoneId);
$this->assertCount(1, $repo->forCamera('cam-1'));
// Legitimate update by the owning device/camera succeeds.
$again = $repo->save([
'zone_id' => $zoneId,
'device_id' => 'dev-1',
'camera_id' => 'cam-1',
'level' => 'restricted',
'polygon_json' => '[[0,0],[2,0],[2,2]]',
]);
$this->assertSame($zoneId, $again);
// Supplying the same zone_id under a different device/camera must not
// silently overwrite it -- this is the cross-tenant guard from the
// Task 13 review.
$this->expectException(RuntimeException::class);
$repo->save([
'zone_id' => $zoneId,
'device_id' => 'dev-2',
'camera_id' => 'cam-2',
'level' => 'pinch',
'polygon_json' => '[[9,9],[9,8],[8,8]]',
]);
}
public function testZoneDelete(): void
{
$repo = new PdoZoneRepository($this->pdo);
$zoneId = $repo->save([
'zone_id' => null,
'device_id' => 'dev-1',
'camera_id' => 'cam-1',
'level' => 'warning',
'polygon_json' => '[[0,0],[1,0],[1,1]]',
]);
$this->assertTrue($repo->delete($zoneId));
$this->assertFalse($repo->delete($zoneId));
}
/**
* Minimal sqlite-flavored translation of the nonces/events/zones tables
* in ../schema.sql (see that file's "sqlite compatibility notes" header
* for the general MySQL -> sqlite mapping rules applied here).
*/
/** Insert an event with sensible defaults; only the interesting columns need naming. */
private function seedEvent(PdoEventRepository $repo, array $over = []): int
{
static $n = 0;
$n++;
return $repo->insert($over + [
'event_uuid' => str_repeat((string)($n % 10), 32),
'device_id' => 'dev-1', 'site' => 'factory-a', 'camera_id' => 'cam-1',
'event_type' => 'fall', 'severity' => 'critical', 'track_id' => 1, 'zone_id' => null,
'occurred_at' => 1700000000.0, 'duration_s' => 1.0, 'metrics' => [],
]);
}
public function testCameraLookupsBackTheActionOwnershipCheck(): void
{
// These two back ActionsController's unknown_camera 400 and cross-site 404. Cameras have
// no registry table, so events ARE the ownership record — verify against real SQL.
$repo = new PdoEventRepository($this->pdo);
$this->seedEvent($repo, ['camera_id' => 'cam-1', 'site' => 'factory-a']);
$this->assertTrue($repo->cameraExists('cam-1'));
$this->assertFalse($repo->cameraExists('cam-typo'));
$this->assertSame('factory-a', $repo->siteForCamera('cam-1'));
$this->assertNull($repo->siteForCamera('cam-typo'));
// A re-homed camera belongs to the site it reports to NOW (newest event wins).
$this->seedEvent($repo, ['camera_id' => 'cam-1', 'site' => 'factory-b']);
$this->assertSame('factory-b', $repo->siteForCamera('cam-1'));
}
public function testActionRepositoryScopesBySite(): void
{
$repo = new PdoActionRepository($this->pdo);
$repo->insert(['camera_id' => 'cam-a', 'site' => 'factory-a', 'note' => '매트',
'taken_at' => 100, 'created_by' => 'alice']);
$repo->insert(['camera_id' => 'cam-b', 'site' => 'factory-b', 'note' => '난간',
'taken_at' => 200, 'created_by' => 'bob']);
$this->assertCount(2, $repo->recent(10, null)); // global operator
$scoped = $repo->recent(10, 'factory-a');
$this->assertCount(1, $scoped);
$this->assertSame('매트', $scoped[0]['note']);
$this->assertCount(0, $repo->recent(10, 'factory-c'));
// Fail-closed: an empty-string scope is a misconfigured scope, not "everything".
$this->assertCount(0, $repo->recent(10, ''));
}
public function testCountForCameraDrivesTheBeforeAfterEffect(): void
{
$repo = new PdoEventRepository($this->pdo);
$this->seedEvent($repo, ['occurred_at' => 100.0]);
$this->seedEvent($repo, ['occurred_at' => 150.0]);
$this->seedEvent($repo, ['occurred_at' => 300.0]);
$this->seedEvent($repo, ['occurred_at' => 120.0, 'event_type' => 'ergo_report']);
$this->assertSame(2, $repo->countForCamera('cam-1', 0.0, 200.0, null)); // ergo excluded
$this->assertSame(0, $repo->countForCamera('cam-1', 0.0, 200.0, 'factory-b'));
}
public function testAggregatesThatBackTheReportPageRunAgainstRealSql(): void
{
// reportSummary/fpStats/heatmapPoints/occurrenceTimes/exportRows were previously
// exercised ONLY against the in-memory double, which reimplements their semantics in
// PHP — so a broken query could not fail the suite. Round-trip them for real.
$repo = new PdoEventRepository($this->pdo);
$this->seedEvent($repo, ['occurred_at' => 1000.0, 'spatial_x' => 0.4, 'spatial_y' => 0.6]);
$fp = $this->seedEvent($repo, ['occurred_at' => 1100.0, 'severity' => 'warning']);
$repo->markFalsePositive($fp, 'alice');
$this->seedEvent($repo, ['occurred_at' => 1200.0, 'event_type' => 'ergo_report',
'severity' => 'info', 'metrics' => ['bend_s' => 12]]);
$summary = $repo->reportSummary(0.0, null, 5);
$this->assertNotEmpty($summary['by_type']);
$this->assertNotEmpty($summary['by_camera']);
$this->assertArrayHasKey('tta', $summary);
$this->assertNotEmpty($repo->fpStats(0.0, null));
$this->assertCount(1, $repo->heatmapPoints('cam-1', 0.0, null, 100)); // only the spatial row
$this->assertCount(2, $repo->occurrenceTimes(0.0, null, 100)); // ergo excluded
$this->assertCount(3, $repo->exportRows(0.0, null, 100));
// Site scoping must reach every one of them.
$this->assertSame([], $repo->fpStats(0.0, 'factory-b'));
$this->assertSame([], $repo->heatmapPoints('cam-1', 0.0, 'factory-b', 100));
$this->assertSame([], $repo->exportRows(0.0, 'factory-b', 100));
}
public function testEventPurgeIsOptInAndBounded(): void
{
$repo = new PdoEventRepository($this->pdo);
for ($i = 0; $i < 5; $i++) $this->seedEvent($repo, ['occurred_at' => 100.0 + $i]);
$this->seedEvent($repo, ['occurred_at' => 9000.0]);
$this->assertSame(3, $repo->purgeOlderThan(9000.0, 3)); // batch bound respected
$this->assertSame(2, $repo->purgeOlderThan(9000.0, 500));
$this->assertSame(0, $repo->purgeOlderThan(9000.0, 500)); // the newer row survives
$this->assertCount(1, $repo->page(10, null, null, null, null));
}
public function testSnapshotThumbnailLookupAvoidsNPlusOne(): void
{
$events = new PdoEventRepository($this->pdo);
$snaps = new PdoSnapshotRepository($this->pdo, sys_get_temp_dir());
$a = $this->seedEvent($events, ['occurred_at' => 10.0]);
$b = $this->seedEvent($events, ['occurred_at' => 20.0]);
$snaps->add($a, str_repeat('a', 32), 'h1');
$snaps->add($a, str_repeat('b', 32), 'h2'); // newest wins as the thumbnail
$snaps->add($b, str_repeat('c', 32), 'h3');
$thumbs = $snaps->thumbUuidsFor([$a, $b]);
$this->assertSame(str_repeat('b', 32), $thumbs[$a]);
$this->assertSame(str_repeat('c', 32), $thumbs[$b]);
$this->assertCount(2, $snaps->forEvent($a));
}
private static function sqliteSchema(): string
{
return <<<'SQL'
CREATE TABLE move_nonces (
nonce TEXT PRIMARY KEY,
expires_at INTEGER NOT NULL
);
CREATE TABLE move_events (
event_id INTEGER PRIMARY KEY AUTOINCREMENT,
event_uuid TEXT UNIQUE,
device_id TEXT NOT NULL,
site TEXT,
camera_id TEXT NOT NULL,
event_type TEXT NOT NULL,
severity TEXT NOT NULL,
track_id INTEGER,
zone_id TEXT,
occurred_at REAL NOT NULL,
duration_s REAL NOT NULL DEFAULT 0,
metrics_json TEXT,
spatial_x REAL,
spatial_y REAL,
acknowledged_by TEXT,
acknowledged_at INTEGER,
false_positive_by TEXT,
false_positive_at INTEGER,
received_at INTEGER NOT NULL
);
CREATE TABLE move_zones (
zone_id TEXT PRIMARY KEY,
device_id TEXT NOT NULL,
camera_id TEXT NOT NULL,
level TEXT NOT NULL,
polygon_json TEXT NOT NULL,
rules_json TEXT,
updated_at INTEGER NOT NULL
);
CREATE TABLE move_actions (
action_id INTEGER PRIMARY KEY AUTOINCREMENT,
camera_id TEXT NOT NULL,
site TEXT,
note TEXT NOT NULL,
taken_at INTEGER NOT NULL,
created_by TEXT NOT NULL,
created_at INTEGER NOT NULL
);
CREATE TABLE move_event_snapshots (
snapshot_id INTEGER PRIMARY KEY AUTOINCREMENT,
event_id INTEGER NOT NULL,
file_uuid TEXT NOT NULL,
content_hash TEXT,
created_at INTEGER NOT NULL
);
SQL;
}
}