move_detect/cloud/tests/IngestControllerTest.php
유창욱 2ea0420de7 fix(delivery): resolve codex + workflow review findings across edge/cloud/deploy
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.
2026-07-17 19:24:42 +09:00

174 lines
10 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Tests;
use App\Config;
use App\Http\Request;
use App\Security\Hmac;
use App\Ingest\IngestController;
use App\Tests\Support\{InMemoryDeviceRepository, InMemoryNonceRepository,
InMemoryRateLimiter, InMemoryEventRepository, InMemorySnapshotRepository};
use PHPUnit\Framework\TestCase;
final class IngestControllerTest extends TestCase
{
private string $dir;
protected function setUp(): void { $this->dir = sys_get_temp_dir() . '/snaps' . bin2hex(random_bytes(4)); mkdir($this->dir); }
private function make(array $secrets = ['pi-1' => 'sekret']): array {
$cfg = Config::fromArray(['snapshot_dir' => $this->dir, 'timestamp_window' => 300, 'rate_limit_per_min' => 60]);
$dev = new InMemoryDeviceRepository($secrets);
$nonce = new InMemoryNonceRepository();
$rl = new InMemoryRateLimiter();
$events = new InMemoryEventRepository();
$snaps = new InMemorySnapshotRepository();
$c = new IngestController($cfg, $dev, $nonce, $rl, $events, $snaps);
return [$c, $events, $snaps, $nonce];
}
private function jpegB64(): string { $im = imagecreatetruecolor(8, 8); ob_start(); imagejpeg($im); $b = ob_get_clean(); return base64_encode($b); }
private function signedReq(string $secret, array $payload, string $nonce = 'n1', string $ts = '1000'): Request {
$body = json_encode($payload, JSON_UNESCAPED_UNICODE);
$sig = Hmac::sign($secret, $nonce, $ts, $body);
return new Request('POST', '/api/events',
['X-Nonce' => $nonce, 'X-Timestamp' => $ts, 'X-Signature' => $sig], $body, [], []);
}
private function payload(): array {
return ['device_id' => 'pi-1', 'camera_id' => 'cam-1', 'event_type' => 'fall',
'severity' => 'high', 'occurred_at' => 1000.0, 'snapshots' => [$this->jpegB64()]];
}
public function testAcceptsValidSignedEvent(): void {
[$c, $events, $snaps] = $this->make();
$res = $c->handle($this->signedReq('sekret', $this->payload()), now: 1000, clientIp: '1.2.3.4');
$this->assertSame(201, $res->status());
$this->assertCount(1, $events->rows);
$id = json_decode($res->body(), true)['event_id'];
$this->assertCount(1, $snaps->forEvent($id)); // snapshot re-encoded + stored
}
public function testDedupPathRestoresMissingSnapshots(): void {
// Simulate a first attempt that stored the event but died before its snapshots (php-fpm
// timeout mid re-encode): the event exists with ZERO evidence images. The edge re-sends
// the identical payload WITH the bytes; the dedup path must store them, not discard them.
[$c, $events, $snaps] = $this->make();
$uuid = str_repeat('a', 32);
$first = $this->payload(); $first['event_uuid'] = $uuid; $first['snapshots'] = [];
$res1 = $c->handle($this->signedReq('sekret', $first, nonce: 'n1'), now: 1000, clientIp: '1.2.3.4');
$this->assertSame(201, $res1->status());
$id = json_decode($res1->body(), true)['event_id'];
$this->assertCount(0, $snaps->forEvent($id)); // no evidence yet
$retry = $this->payload(); $retry['event_uuid'] = $uuid; // same key, now WITH snapshots
$res2 = $c->handle($this->signedReq('sekret', $retry, nonce: 'n2'), now: 1001, clientIp: '1.2.3.4');
$this->assertSame(200, $res2->status());
$this->assertTrue(json_decode($res2->body(), true)['dedup']);
$this->assertCount(1, $snaps->forEvent($id)); // evidence recovered on the retry
}
public function testRejectsBadSignature(): void {
[$c] = $this->make();
$req = $this->signedReq('WRONG', $this->payload());
$this->assertSame(401, $c->handle($req, now: 1000, clientIp: '1.2.3.4')->status());
}
public function testRejectsReplayedNonce(): void {
[$c] = $this->make();
$req = $this->signedReq('sekret', $this->payload());
$this->assertSame(201, $c->handle($req, now: 1000, clientIp: '1.2.3.4')->status());
$this->assertSame(401, $c->handle($req, now: 1000, clientIp: '1.2.3.4')->status()); // same nonce again
}
public function testRejectsStaleTimestamp(): void {
[$c] = $this->make();
$req = $this->signedReq('sekret', $this->payload(), ts: '1000');
$this->assertSame(401, $c->handle($req, now: 5000, clientIp: '1.2.3.4')->status()); // 4000s > 300 window
}
public function testRejectsUnknownDevice(): void {
[$c] = $this->make([]); // no secrets
$this->assertSame(401, $c->handle($this->signedReq('x', $this->payload()), now: 1000, clientIp: '1.2.3.4')->status());
}
public function testRetentionPurgesOldSnapshots(): void {
// PIPA: worker snapshots older than the retention window are purged; recent ones stay.
$cfg = Config::fromArray(['snapshot_dir' => $this->dir, 'timestamp_window' => 300,
'snapshot_retention_days' => 7]);
$snaps = new InMemorySnapshotRepository();
$now = 1_000_000;
$old = str_repeat('a', 32); $recent = str_repeat('b', 32);
$snaps->add(1, $old, 'h'); $snaps->created[$old] = $now - 8 * 86400; // 8d old -> purge
$snaps->add(1, $recent, 'h'); $snaps->created[$recent] = $now - 1 * 86400; // 1d old -> keep
$c = new IngestController($cfg, new InMemoryDeviceRepository(['pi-1' => 'sekret']),
new InMemoryNonceRepository(), new InMemoryRateLimiter(),
new InMemoryEventRepository(), $snaps, purgeGate: fn () => true);
$req = $this->signedReq('sekret', $this->payload(), ts: (string)$now);
$res = $c->handle($req, now: $now, clientIp: '1.2.3.4');
$this->assertSame(201, $res->status());
$this->assertArrayNotHasKey($old, $snaps->created, 'snapshot past the 7-day window must be purged');
$this->assertArrayHasKey($recent, $snaps->created, 'a 1-day-old snapshot must survive');
}
public function testSnapshotIndexFailureCleansOrphanFileButKeepsEvent(): void {
// The file lands, then the DB index throws. The event must still be stored (201) and the
// orphan JPEG must be removed — never left on disk with no row pointing at it.
$cfg = Config::fromArray(['snapshot_dir' => $this->dir, 'timestamp_window' => 300, 'rate_limit_per_min' => 60]);
$throwingSnaps = new class implements \App\Repository\SnapshotRepository {
public function add(int $e, string $u, string $h): void { throw new \RuntimeException('db down'); }
public function forEvent(int $e): array { return []; }
public function pathByUuid(string $u): ?string { return null; }
public function eventIdByUuid(string $u): ?int { return null; }
public function purgeOlderThan(int $c): int { return 0; }
};
$events = new InMemoryEventRepository();
$c = new IngestController($cfg, new InMemoryDeviceRepository(['pi-1' => 'sekret']),
new InMemoryNonceRepository(), new InMemoryRateLimiter(), $events, $throwingSnaps);
$res = $c->handle($this->signedReq('sekret', $this->payload()), now: 1000, clientIp: '1.2.3.4');
$this->assertSame(201, $res->status()); // a snapshot failure never discards the event
$this->assertCount(1, $events->rows);
$this->assertSame([], glob($this->dir . '/*.jpg'),
'orphan snapshot file must be removed when the DB index write fails');
}
public function testDeduplicatesRepeatedEventUuid(): void {
// A POST that succeeded server-side but timed out client-side is re-sent with the SAME
// event_uuid (fresh nonce). The cloud must return the already-stored event, not duplicate.
[$c, $events] = $this->make();
$uuid = str_repeat('a', 32);
$p = $this->payload(); $p['event_uuid'] = $uuid;
$r1 = $c->handle($this->signedReq('sekret', $p, nonce: 'n1'), now: 1000, clientIp: '1.2.3.4');
$this->assertSame(201, $r1->status());
$r2 = $c->handle($this->signedReq('sekret', $p, nonce: 'n2'), now: 1000, clientIp: '1.2.3.4');
$this->assertSame(200, $r2->status());
$this->assertTrue(json_decode($r2->body(), true)['dedup']);
$this->assertCount(1, $events->rows, 'a re-sent event_uuid must not create a second event');
$this->assertSame(
json_decode($r1->body(), true)['event_id'],
json_decode($r2->body(), true)['event_id']);
}
public function testStampsDeviceSiteOntoTheEvent(): void {
// Access control filters events by site, so ingest denormalizes the DEVICE's site onto
// the event (server-derived from the authenticated device_id, not client-supplied).
$cfg = Config::fromArray(['snapshot_dir' => $this->dir, 'timestamp_window' => 300, 'rate_limit_per_min' => 60]);
$dev = new InMemoryDeviceRepository(['pi-1' => 'sekret'], [], ['pi-1' => 'factory-a']);
$events = new InMemoryEventRepository();
$c = new IngestController($cfg, $dev, new InMemoryNonceRepository(),
new InMemoryRateLimiter(), $events, new InMemorySnapshotRepository());
$c->handle($this->signedReq('sekret', $this->payload()), now: 1000, clientIp: '1.2.3.4');
$this->assertCount(1, $events->rows);
$this->assertSame('factory-a', $events->rows[1]['site']);
}
public function testIpFloodRateLimited(): void {
// Attacker without a valid device secret floods from one IP; the pre-auth
// IP limiter must trip BEFORE any HMAC/device-secret work, protecting
// real devices from having their own per-device quota consumed.
$cfg = Config::fromArray(['snapshot_dir' => $this->dir, 'timestamp_window' => 300, 'ingest_ip_rate_limit_per_min' => 2]);
$dev = new InMemoryDeviceRepository(['pi-1' => 'sekret']);
$nonce = new InMemoryNonceRepository();
$rl = new InMemoryRateLimiter();
$events = new InMemoryEventRepository();
$snaps = new InMemorySnapshotRepository();
$c = new IngestController($cfg, $dev, $nonce, $rl, $events, $snaps);
$garbage = new Request('POST', '/api/events', [], 'not-json', [], []);
$this->assertSame(401, $c->handle($garbage, now: 1000, clientIp: '9.9.9.9')->status());
$this->assertSame(401, $c->handle($garbage, now: 1000, clientIp: '9.9.9.9')->status());
$res = $c->handle($garbage, now: 1000, clientIp: '9.9.9.9');
$this->assertSame(429, $res->status()); // 3rd request from same IP: rate limited pre-auth
}
}