move_detect/cloud/tests/PdoIntegrationTest.php
유창욱 9aa7f44ea4 feat(cloud): PDO repositories + schema + Cafe24 deploy doc
Implements Task 16 (final, P1-B): App\Db\Database::connect(Config): PDO
factory and the 9 App\Repository\Pdo\Pdo*Repository classes backing the
repository interfaces consumed by controllers since T1-T15, all-prepared
statements, plus cloud/schema.sql (MySQL 8 DDL) and cloud/docs/cloud-deploy.md.

Security hardening incorporated per accumulated task reviews:
- PdoNonceRepository: nonces.nonce is PK; duplicate remember() throws instead
  of racing seen() (closes T7 TOCTOU).
- PdoRateLimiterRepository::hit(): atomic INSERT ... ON DUPLICATE KEY UPDATE
  upsert on (rate_key, window_start), no read-modify-write race.
- PdoSnapshotRepository::pathByUuid(): validates 32-hex uuid before building
  any filesystem path (closes T12 path-traversal risk).
- PdoZoneRepository::save(): update path is ownership-scoped by
  (zone_id, device_id, camera_id); throws on mismatch instead of silently
  overwriting an unrelated zone (closes T13 cross-tenant overwrite risk).
- Database::connect(): ERRMODE_EXCEPTION, EMULATE_PREPARES=false, FETCH_ASSOC.

cloud/tests/PdoIntegrationTest.php round-trips Nonce/Event/Zone against a
real sqlite :memory: DB, gated via markTestSkipped when pdo_sqlite is
unavailable (this host has pdo_mysql only, no pdo_sqlite) -- suite stays
green with 4 tests skipped.

Full suite: 59 tests, 114 assertions, 4 skipped, 0 failures, 0
warnings/deprecations. php -l passes on all new files and on
cloud/public/index.php (T15), which references all new FQCNs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ne4rU4FToTLHcBUMUvUnT1
2026-07-12 01:58:05 +09:00

169 lines
5.9 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Tests;
use App\Repository\Pdo\{PdoNonceRepository, PdoEventRepository, PdoZoneRepository};
use PDO;
use PHPUnit\Framework\TestCase;
use RuntimeException;
/**
* Gated DB-integration test: exercises the PDO repositories against a real
* sqlite :memory: database instead of the in-memory test doubles used
* elsewhere in the suite. This host has no pdo_sqlite driver loaded
* (PDO::getAvailableDrivers() does not include 'sqlite'), so setUp() skips
* the whole class -- the suite must stay green with this test reported as
* SKIPPED, not failed. On a host with pdo_sqlite available (or in CI), this
* test runs for real and round-trips Nonce, Event, and Zone -- the three
* repositories whose SQL is portable between MySQL and sqlite (no
* MySQL-only `ON DUPLICATE KEY UPDATE`, which PdoRateLimiterRepository uses
* and is therefore intentionally not covered here).
*/
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);
$id = $repo->insert([
'device_id' => 'dev-1',
'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('critical', $found['severity']);
$this->assertSame(['confidence' => 0.9], $found['metrics']);
$this->assertNull($found['acknowledged_by']);
$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).
*/
private static function sqliteSchema(): string
{
return <<<'SQL'
CREATE TABLE nonces (
nonce TEXT PRIMARY KEY,
expires_at INTEGER NOT NULL
);
CREATE TABLE events (
event_id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id TEXT NOT NULL,
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,
acknowledged_by TEXT,
acknowledged_at INTEGER,
received_at INTEGER NOT NULL
);
CREATE TABLE 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,
updated_at INTEGER NOT NULL
);
SQL;
}
}