feat(cloud): ingest controller (HMAC+nonce+ratelimit+reencode+persist)
This commit is contained in:
parent
a0db1e06ca
commit
57cfc64548
2 changed files with 130 additions and 0 deletions
62
cloud/src/Ingest/IngestController.php
Normal file
62
cloud/src/Ingest/IngestController.php
Normal file
|
|
@ -0,0 +1,62 @@
|
||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
namespace App\Ingest;
|
||||||
|
|
||||||
|
use App\Config;
|
||||||
|
use App\Http\{Request, Response};
|
||||||
|
use App\Security\Hmac;
|
||||||
|
use App\Repository\{DeviceRepository, NonceRepository, RateLimiterRepository,
|
||||||
|
EventRepository, SnapshotRepository};
|
||||||
|
|
||||||
|
final class IngestController
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private Config $cfg,
|
||||||
|
private DeviceRepository $devices,
|
||||||
|
private NonceRepository $nonces,
|
||||||
|
private RateLimiterRepository $rateLimiter,
|
||||||
|
private EventRepository $events,
|
||||||
|
private SnapshotRepository $snapshots,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function handle(Request $req, int $now): Response
|
||||||
|
{
|
||||||
|
$payload = $req->json();
|
||||||
|
$deviceId = (string)($payload['device_id'] ?? '');
|
||||||
|
$window = intdiv($now, 60);
|
||||||
|
if ($deviceId !== '' && $this->rateLimiter->hit($deviceId, $window) > $this->cfg->rateLimitPerMin()) {
|
||||||
|
return Response::json(['error' => 'rate_limited'], 429);
|
||||||
|
}
|
||||||
|
|
||||||
|
$nonce = $req->header('X-Nonce') ?? '';
|
||||||
|
$ts = $req->header('X-Timestamp') ?? '';
|
||||||
|
$sig = $req->header('X-Signature') ?? '';
|
||||||
|
$secret = $deviceId !== '' ? $this->devices->secretFor($deviceId) : null;
|
||||||
|
if ($secret === null || $nonce === '' || $ts === '' || $sig === '') {
|
||||||
|
return Response::json(['error' => 'unauthorized'], 401);
|
||||||
|
}
|
||||||
|
if (!Hmac::verify($secret, $nonce, $ts, $req->body(), $sig)) {
|
||||||
|
return Response::json(['error' => 'bad_signature'], 401);
|
||||||
|
}
|
||||||
|
if (abs($now - (int)(float)$ts) > $this->cfg->timestampWindow()) {
|
||||||
|
return Response::json(['error' => 'stale_timestamp'], 401);
|
||||||
|
}
|
||||||
|
if ($this->nonces->seen($nonce)) {
|
||||||
|
return Response::json(['error' => 'replay'], 401);
|
||||||
|
}
|
||||||
|
$this->nonces->remember($nonce, $now + $this->cfg->nonceTtl());
|
||||||
|
|
||||||
|
$v = EventValidator::validate($payload);
|
||||||
|
if (!$v['ok']) return Response::json(['error' => 'invalid', 'details' => $v['errors']], 400);
|
||||||
|
|
||||||
|
$eventId = $this->events->insert($v['clean']);
|
||||||
|
foreach (($payload['snapshots'] ?? []) as $b64) {
|
||||||
|
$img = ImageProcessor::reencode((string)$b64);
|
||||||
|
if (!$img['ok']) continue;
|
||||||
|
$path = rtrim($this->cfg->snapshotDir(), '/\\') . '/' . $img['uuid'] . '.jpg';
|
||||||
|
file_put_contents($path, $img['bytes']);
|
||||||
|
$this->snapshots->add($eventId, $img['uuid'], $img['hash']);
|
||||||
|
}
|
||||||
|
return Response::json(['event_id' => $eventId], 201);
|
||||||
|
}
|
||||||
|
}
|
||||||
68
cloud/tests/IngestControllerTest.php
Normal file
68
cloud/tests/IngestControllerTest.php
Normal file
|
|
@ -0,0 +1,68 @@
|
||||||
|
<?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(); imagedestroy($im); 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);
|
||||||
|
$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 testRejectsBadSignature(): void {
|
||||||
|
[$c] = $this->make();
|
||||||
|
$req = $this->signedReq('WRONG', $this->payload());
|
||||||
|
$this->assertSame(401, $c->handle($req, now: 1000)->status());
|
||||||
|
}
|
||||||
|
public function testRejectsReplayedNonce(): void {
|
||||||
|
[$c] = $this->make();
|
||||||
|
$req = $this->signedReq('sekret', $this->payload());
|
||||||
|
$this->assertSame(201, $c->handle($req, now: 1000)->status());
|
||||||
|
$this->assertSame(401, $c->handle($req, now: 1000)->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)->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)->status());
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue