move_detect/server/tests/Support/InMemoryRepositories.php
유창욱 6b1f4c483f fix(security,delivery): scope improvement actions by site; correct upgrade procedure
프로젝트 8개 차원 감사(종합 82/100)에서 확정된 상위 3건 수정.

1. 개선 조치(move_actions)가 유일하게 site 스코프 규율에서 이탈 — 스코프 운영자가
   타 현장의 조치 기록(카메라 ID·메모·작성자)을 목록에서 읽고, 타 현장 카메라에
   조치를 기록해 그 현장 리포트의 전후 효과 지표를 오염시킬 수 있었다.
   - move_actions.site 컬럼 + (site, taken_at) 인덱스, 기존 행 백필 마이그레이션
   - 카메라 소유 현장은 이벤트에서 해석 (move_cameras는 등록 플로우가 없어 항상 비어 있음)
   - 오타 카메라는 400: 전후 효과가 영원히 0/0이 되는 조치를 애초에 못 만들게 한다
   - 타 현장 카메라는 404: 존재 여부를 숨기는 기존 규약 유지

2. README-UPLOAD 업그레이드 절차가 마이그레이션 7종 중 1종만 지시했다. move_ 접두
   리네임을 건너뛰면 이후 전부 실패하고 전 요청이 500이 된다 — 순서·적용조건·재실행
   비안전성을 표로 명시. 문서 4곳의 테이블 수(10→11)·비프리픽스 표기도 정정.

3. 두 납품 번들 재생성: 8/6 이후 4개 기능 커밋이 반영되지 않아 Report/Export/Actions
   컨트롤러와 8/7 마이그레이션이 빠진 채였다. 엣지 소스 패리티도 회복.

검증: pytest 235 passed / PHPUnit 147 passed (PDO 4 skip), 번들 산출물 내부 검증
(28 클래스 해석·전 파일 php -l·SHA256SUMS 55행·휠 11개·HEF 다이제스트 일치).
2026-08-07 18:06:32 +09:00

247 lines
15 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Tests\Support;
use App\Repository\{DeviceRepository, NonceRepository, RateLimiterRepository,
EventRepository, SnapshotRepository, UserRepository, ZoneRepository,
ThresholdRepository, AuditRepository, ActionRepository};
final class InMemoryDeviceRepository implements DeviceRepository {
public array $heartbeats = [];
// $statusRows: full device rows for listStatus() (the status panel tests populate it). Kept a
// trailing optional arg so the many existing 3-arg call sites are unaffected.
public function __construct(private array $secrets = [], private array $versions = [],
private array $sites = [], public array $statusRows = []) {}
public function secretFor(string $d): ?string { return $this->secrets[$d] ?? null; }
public function exists(string $d): bool {
// A device is "known" if it appears in any provisioned map the test set up.
return isset($this->secrets[$d]) || isset($this->sites[$d]) || isset($this->versions[$d]);
}
public function siteFor(string $d): ?string { return $this->sites[$d] ?? null; }
public function touchHeartbeat(string $d, array $m): void { $this->heartbeats[$d] = $m; }
public function configVersion(string $d): int { return $this->versions[$d] ?? 1; }
public function listStatus(?string $site): array {
$rows = $this->statusRows;
if ($site !== null) $rows = array_filter($rows, fn($d) => ($d['site'] ?? null) === $site);
return array_values($rows);
}
}
final class InMemoryNonceRepository implements NonceRepository {
public array $store = [];
public function seen(string $n): bool { return isset($this->store[$n]); }
public function remember(string $n, int $exp): void { $this->store[$n] = $exp; }
}
final class InMemoryRateLimiter implements RateLimiterRepository {
public array $counts = [];
public function hit(string $k, int $w): int { $key = "$k:$w"; return $this->counts[$key] = ($this->counts[$key] ?? 0) + 1; }
}
final class InMemoryEventRepository implements EventRepository {
public array $rows = []; private int $seq = 0;
public function insert(array $e): int { $id = ++$this->seq; $this->rows[$id] = $e + ['event_id' => $id, 'acknowledged_by' => null]; return $id; }
public function idByUuid(string $uuid): ?int {
foreach ($this->rows as $id => $r) if (($r['event_uuid'] ?? null) === $uuid) return (int)$id;
return null;
}
public function recent(int $limit, ?string $sev): array {
$r = array_reverse($this->rows, true);
if ($sev !== null) $r = array_filter($r, fn($x) => $x['severity'] === $sev);
return array_slice(array_values($r), 0, $limit);
}
public function page(int $limit, ?string $sev, ?string $beforeTs, ?int $beforeId, ?string $site = null): array {
$r = array_values($this->rows);
if ($sev !== null) $r = array_filter($r, fn($x) => $x['severity'] === $sev);
if ($site !== null) $r = array_filter($r, fn($x) => ($x['site'] ?? null) === $site);
// (occurred_at DESC, event_id DESC); events inserted without occurred_at sort as 0.
usort($r, fn($a, $b) => [$b['occurred_at'] ?? 0, $b['event_id']] <=> [$a['occurred_at'] ?? 0, $a['event_id']]);
if ($beforeTs !== null && $beforeId !== null) {
$bt = (float)$beforeTs; // cursor carries occurred_at as a string; compare numerically
$r = array_filter($r, fn($x) => ($x['occurred_at'] ?? 0) < $bt
|| (($x['occurred_at'] ?? 0) == $bt && $x['event_id'] < $beforeId));
}
return array_slice(array_values($r), 0, $limit);
}
public function find(int $id): ?array { return $this->rows[$id] ?? null; }
public function acknowledge(int $id, string $u): bool { if (!isset($this->rows[$id])) return false; $this->rows[$id]['acknowledged_by'] = $u; $this->rows[$id]['acknowledged_at'] = $this->rows[$id]['acknowledged_at'] ?? time(); return true; }
public function markFalsePositive(int $id, string $user): bool {
if (!isset($this->rows[$id])) return false;
$r = $this->rows[$id];
$r['false_positive_by'] = $r['false_positive_by'] ?? $user;
$r['false_positive_at'] = $r['false_positive_at'] ?? time();
$r['acknowledged_by'] = ($r['acknowledged_by'] ?? null) !== null ? $r['acknowledged_by'] : $user;
$this->rows[$id] = $r;
return true;
}
public function fpStats(float $since, ?string $site): array {
$groups = [];
foreach ($this->rows as $r) {
if (($r['occurred_at'] ?? 0) < $since) continue;
if ($site !== null && ($r['site'] ?? null) !== $site) continue;
$key = ($r['camera_id'] ?? '') . '|' . ($r['event_type'] ?? '');
$groups[$key] = $groups[$key] ?? ['camera_id' => $r['camera_id'], 'event_type' => $r['event_type'], 'total' => 0, 'fp' => 0];
$groups[$key]['total']++;
if (($r['false_positive_by'] ?? null) !== null) $groups[$key]['fp']++;
}
$out = array_values(array_filter($groups, fn($g) => $g['fp'] > 0));
usort($out, fn($a, $b) => $b['fp'] <=> $a['fp']);
return $out;
}
public function reportSummary(float $since, ?string $site, int $topCameras, ?float $until = null): array {
$rows = array_filter($this->rows, fn($r) => ($r['occurred_at'] ?? 0) >= $since
&& ($until === null || ($r['occurred_at'] ?? 0) < $until)
&& ($site === null || ($r['site'] ?? null) === $site));
$byType = []; $byCam = []; $ttaDeltas = []; $ergo = [];
foreach ($rows as $r) {
$tk = ($r['event_type'] ?? '') . '|' . ($r['severity'] ?? '');
$byType[$tk] = $byType[$tk] ?? ['event_type' => $r['event_type'], 'severity' => $r['severity'], 'count' => 0, 'unacked' => 0, 'fp' => 0];
$byType[$tk]['count']++;
if (($r['acknowledged_by'] ?? null) === null) $byType[$tk]['unacked']++;
if (($r['false_positive_by'] ?? null) !== null) $byType[$tk]['fp']++;
$cam = $r['camera_id'] ?? '';
$byCam[$cam] = $byCam[$cam] ?? ['camera_id' => $cam, 'count' => 0, 'critical_high' => 0];
$byCam[$cam]['count']++;
if (in_array($r['severity'] ?? '', ['critical', 'high'], true)) $byCam[$cam]['critical_high']++;
if (in_array($r['severity'] ?? '', ['critical', 'high'], true)
&& ($r['acknowledged_at'] ?? null) !== null && ($r['false_positive_by'] ?? null) === null
&& $r['acknowledged_at'] >= ($r['occurred_at'] ?? 0)) {
$ttaDeltas[] = $r['acknowledged_at'] - $r['occurred_at'];
}
if (($r['event_type'] ?? '') === 'ergo_report') $ergo[] = $r['metrics'] ?? [];
}
$cams = array_values($byCam);
usort($cams, fn($a, $b) => [$b['critical_high'], $b['count']] <=> [$a['critical_high'], $a['count']]);
return [
'by_type' => array_values($byType),
'by_camera' => array_slice($cams, 0, $topCameras),
'tta' => ['acked' => count($ttaDeltas),
'avg_s' => $ttaDeltas ? array_sum($ttaDeltas) / count($ttaDeltas) : null,
'max_s' => $ttaDeltas ? max($ttaDeltas) : null],
'ergo_metrics' => $ergo,
];
}
public function exportRows(float $since, ?string $site, int $limit): array {
$r = array_filter($this->rows, fn($x) => ($x['occurred_at'] ?? 0) >= $since
&& ($site === null || ($x['site'] ?? null) === $site));
usort($r, fn($a, $b) => [$b['occurred_at'] ?? 0, $b['event_id']] <=> [$a['occurred_at'] ?? 0, $a['event_id']]);
return array_slice(array_values($r), 0, $limit);
}
public function countForCamera(string $cam, float $from, float $to, ?string $site): int {
return count(array_filter($this->rows, fn($x) => ($x['camera_id'] ?? '') === $cam
&& ($x['occurred_at'] ?? 0) >= $from && ($x['occurred_at'] ?? 0) < $to
&& ($x['event_type'] ?? '') !== 'ergo_report'
&& ($site === null || ($x['site'] ?? null) === $site)));
}
public function cameraExists(string $cam): bool {
foreach ($this->rows as $r) if (($r['camera_id'] ?? '') === $cam) return true;
return false;
}
public function siteForCamera(string $cam): ?string {
$best = null;
foreach ($this->rows as $r) {
if (($r['camera_id'] ?? '') !== $cam || ($r['site'] ?? null) === null) continue;
if ($best === null || ($r['event_id'] ?? 0) >= ($best['event_id'] ?? 0)) $best = $r;
}
return $best === null ? null : (string)$best['site'];
}
public function occurrenceTimes(float $since, ?string $site, int $limit): array {
$r = array_filter($this->rows, fn($x) => ($x['occurred_at'] ?? 0) >= $since
&& ($x['event_type'] ?? '') !== 'ergo_report'
&& ($site === null || ($x['site'] ?? null) === $site));
usort($r, fn($a, $b) => ($b['occurred_at'] ?? 0) <=> ($a['occurred_at'] ?? 0));
return array_map(fn($x) => ['occurred_at' => (float)($x['occurred_at'] ?? 0),
'event_type' => $x['event_type']], array_slice(array_values($r), 0, $limit));
}
public function heatmapPoints(string $cameraId, float $since, ?string $site, int $limit): array {
$r = array_filter($this->rows, fn($x) => ($x['camera_id'] ?? '') === $cameraId
&& ($x['occurred_at'] ?? 0) >= $since
&& ($x['spatial_x'] ?? null) !== null && ($x['spatial_y'] ?? null) !== null
&& ($site === null || ($x['site'] ?? null) === $site));
usort($r, fn($a, $b) => ($b['occurred_at'] ?? 0) <=> ($a['occurred_at'] ?? 0));
return array_map(fn($x) => ['x' => (float)$x['spatial_x'], 'y' => (float)$x['spatial_y'],
'severity' => $x['severity'], 'event_type' => $x['event_type'],
'occurred_at' => (float)($x['occurred_at'] ?? 0)], array_slice(array_values($r), 0, $limit));
}
}
final class InMemorySnapshotRepository implements SnapshotRepository {
public array $rows = []; public array $paths = []; public array $created = [];
public function add(int $e, string $uuid, string $hash): void {
// Mirror the DB's UNIQUE (event_id, content_hash): a re-sent event's identical bytes
// collide instead of duplicating, so the dedup recovery path is idempotent.
foreach ($this->rows[$e] ?? [] as $r) { if ($r['content_hash'] === $hash) return; }
$this->rows[$e][] = ['file_uuid' => $uuid, 'content_hash' => $hash]; $this->paths[$uuid] = "/tmp/$uuid.jpg"; $this->created[$uuid] = time();
}
public function forEvent(int $e): array { return $this->rows[$e] ?? []; }
public function thumbUuidsFor(array $eventIds): array {
$out = [];
foreach ($eventIds as $e) {
$list = $this->rows[(int)$e] ?? [];
if ($list !== []) $out[(int)$e] = end($list)['file_uuid']; // newest = last appended
}
return $out;
}
public function pathByUuid(string $u): ?string { return $this->paths[$u] ?? null; }
public function eventIdByUuid(string $u): ?int {
foreach ($this->rows as $e => $list) foreach ($list as $r) if ($r['file_uuid'] === $u) return (int)$e;
return null;
}
/** @var array<string,string> file_uuid => camera_id, recorded by the tests that need it */
public array $cameras = [];
/** @var array<string,string> file_uuid => device_id */
public array $devices = [];
public function latestForCamera(string $cameraId): ?array {
// Insert order, newest first -- mirrors the Pdo impl's ORDER BY snapshot_id DESC.
foreach (array_reverse($this->cameras, true) as $uuid => $cam) {
if ($cam === $cameraId) return ['file_uuid' => $uuid, 'device_id' => $this->devices[$uuid] ?? ''];
}
return null;
}
public function uuidsFor(array $eventIds): array {
$out = [];
foreach ($eventIds as $e) {
foreach ($this->rows[(int)$e] ?? [] as $r) $out[(int)$e][] = $r['file_uuid'];
}
return $out;
}
public function purgeOlderThan(int $cutoff): int {
$n = 0;
foreach ($this->created as $uuid => $ts) {
if ($ts >= $cutoff) continue;
unset($this->created[$uuid], $this->paths[$uuid]);
foreach ($this->rows as $e => $list) {
$this->rows[$e] = array_values(array_filter($list, fn($r) => $r['file_uuid'] !== $uuid));
}
$n++;
}
return $n;
}
}
final class InMemoryUserRepository implements UserRepository {
public function __construct(public array $users = []) {}
public function byUsername(string $u): ?array { return $this->users[$u] ?? null; }
public function recordFailure(int $id, int $lock): void { foreach ($this->users as &$row) if ($row['id'] === $id) { $row['failed_attempts'] = ($row['failed_attempts'] ?? 0) + 1; $row['locked_until'] = $lock; } }
public function clearFailures(int $id): void { foreach ($this->users as &$row) if ($row['id'] === $id) { $row['failed_attempts'] = 0; $row['locked_until'] = 0; } }
}
final class InMemoryZoneRepository implements ZoneRepository {
public array $zones = []; private int $seq = 0;
public function forDevice(string $d): array { return array_values(array_filter($this->zones, fn($z) => ($z['device_id'] ?? '') === $d)); }
public function forCamera(string $c): array { return array_values(array_filter($this->zones, fn($z) => $z['camera_id'] === $c)); }
public function find(string $id): ?array { return $this->zones[$id] ?? null; }
public function save(array $z): string { $id = $z['zone_id'] ?? ('z' . (++$this->seq)); $this->zones[$id] = $z + ['zone_id' => $id]; return $id; }
public function delete(string $id): bool { if (!isset($this->zones[$id])) return false; unset($this->zones[$id]); return true; }
}
final class InMemoryActionRepository implements ActionRepository {
public array $rows = []; private int $seq = 0;
public function insert(array $a): int { $id = ++$this->seq; $this->rows[$id] = $a + ['action_id' => $id]; return $id; }
public function recent(int $limit, ?string $site): array {
$r = array_values(array_filter($this->rows,
fn($a) => $site === null || ($a['site'] ?? null) === $site));
usort($r, fn($a, $b) => [$b['taken_at'], $b['action_id']] <=> [$a['taken_at'], $a['action_id']]);
return array_slice($r, 0, $limit);
}
}
final class InMemoryThresholdRepository implements ThresholdRepository {
public function __construct(private array $data = []) {}
public function forDevice(string $d): array { return $this->data[$d] ?? []; }
}
final class InMemoryAuditRepository implements AuditRepository {
public array $log = [];
public function append(string $a, string $act, string $t, array $b, array $af): void { $this->log[] = compact('a', 'act', 't', 'b', 'af'); }
}