move_detect/server/schema.sql
유창욱 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

282 lines
17 KiB
SQL

-- cloud/schema.sql
-- MySQL 8.0+ DDL for the P1-B cloud ingest + dashboard subset
-- (backing store for App\Repository\Pdo\* -- see cloud/src/Repository/Pdo/).
--
-- Scope: this is the P1-B subset of the full design-spec schema (design doc §7.4).
-- Tables/columns that belong to later phases are intentionally OMITTED here (YAGNI):
-- sites, escalations, oncall, compliance, retention_policy, audit hash-chaining
-- (prev_hash/hash on audit_log), and events.disposition/is_test/legal_hold/lifecycle_state.
-- See docs/superpowers/specs/2026-07-11-workplace-safety-ai-cctv-design.md §7.4 and the
-- Task 16 brief self-review for the P1-B / P2 / P3 split.
--
-- sqlite compatibility notes (cloud/tests/PdoIntegrationTest.php uses its own minimal
-- sqlite-flavored DDL for the tables it round-trips -- this file targets MySQL only,
-- these notes exist to explain the mechanical translation if that ever needs to grow):
-- * `INT ... AUTO_INCREMENT` -> sqlite: `INTEGER PRIMARY KEY AUTOINCREMENT` (must be the
-- table's sole INTEGER PRIMARY KEY column)
-- * `ENGINE=InnoDB` -> sqlite: omit (no storage engines)
-- * `DEFAULT CHARSET=...` -> sqlite: omit
-- * `JSON` column type -> sqlite: `TEXT` (no native JSON type; app always
-- reads/writes JSON-encoded strings either way)
-- * `DEFAULT (UNIX_TIMESTAMP())` -> sqlite: `DEFAULT (strftime('%s','now'))`
-- * `INSERT ... ON DUPLICATE KEY UPDATE` (rate_limits upsert) -> sqlite:
-- `INSERT ... ON CONFLICT(rate_key, window_start)
-- DO UPDATE SET count = count + 1`
-- * `CHECK (...)` on enum-like columns -> sqlite supports CHECK natively, no change
-- * `TINYINT(1)` -> sqlite: `INTEGER` (0/1)
-- * `BIGINT UNSIGNED` -> sqlite: `INTEGER` (sqlite ints are always 64-bit signed)
--
-- All app-level SQL against this schema uses prepared statements with `?` placeholders --
-- no string interpolation of values anywhere in App\Repository\Pdo\*.
SET NAMES utf8mb4;
-- ---------------------------------------------------------------------------
-- users: dashboard accounts (auth + RBAC + brute-force lockout).
-- No PdoUserRepository::create() exists in P1-B -- the first admin account is
-- provisioned out-of-band via the CLI snippet in cloud/docs/cloud-deploy.md.
-- ---------------------------------------------------------------------------
CREATE TABLE move_users (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(190) NOT NULL,
password_hash VARCHAR(255) NOT NULL, -- Argon2id, see App\Security\Password::hash()
role VARCHAR(32) NOT NULL, -- app-whitelisted: admin|operator|viewer (App\Auth\Rbac)
site_scope VARCHAR(190) NULL,
failed_attempts INT UNSIGNED NOT NULL DEFAULT 0,
locked_until BIGINT UNSIGNED NOT NULL DEFAULT 0, -- unix timestamp; 0 = not locked
created_at BIGINT UNSIGNED NOT NULL DEFAULT (UNIX_TIMESTAMP()),
PRIMARY KEY (id),
UNIQUE KEY uq_users_username (username),
CONSTRAINT chk_users_role CHECK (role IN ('admin','operator','viewer'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- devices: one row per Pi/edge device; holds the per-device HMAC ingest secret.
-- No PdoDeviceRepository::create() exists -- rows are provisioned by an admin
-- (per-device secret issuance) before the device is allowed to sync/ingest.
-- ---------------------------------------------------------------------------
CREATE TABLE move_devices (
device_id VARCHAR(64) NOT NULL,
name VARCHAR(190) NULL,
site VARCHAR(64) NULL, -- access-control scope; matches users.site_scope (NULL = unassigned)
secret VARCHAR(255) NOT NULL, -- per-device HMAC key; rotate via admin CLI, never log
config_version INT UNSIGNED NOT NULL DEFAULT 1, -- authoritative version served by GET /api/config
last_fps DOUBLE NULL,
last_temp DOUBLE NULL,
last_throttle TINYINT(1) NULL,
reported_config_version INT UNSIGNED NULL, -- version the device last claimed via heartbeat
last_heartbeat_at BIGINT UNSIGNED NULL,
created_at BIGINT UNSIGNED NOT NULL DEFAULT (UNIX_TIMESTAMP()),
PRIMARY KEY (device_id),
KEY ix_devices_site (site)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- cameras: per-device camera inventory (design doc §7.4). No dedicated
-- PdoCameraRepository exists in P1-B -- zones/events reference camera_id
-- directly as a free-form string. Kept for documentation/future per-camera
-- config and to avoid a breaking migration when that repository is added.
-- ---------------------------------------------------------------------------
CREATE TABLE move_cameras (
camera_id VARCHAR(64) NOT NULL,
device_id VARCHAR(64) NOT NULL,
name VARCHAR(190) NULL,
role VARCHAR(32) NULL, -- app-whitelisted: fall_critical|zone|low
created_at BIGINT UNSIGNED NOT NULL DEFAULT (UNIX_TIMESTAMP()),
PRIMARY KEY (camera_id),
KEY ix_cameras_device (device_id),
CONSTRAINT chk_cameras_role CHECK (role IS NULL OR role IN ('fall_critical','zone','low'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- zones: polygon regions per camera, edited via the zone-config dashboard.
-- No FK to cameras/devices: zones may legitimately be created before a
-- `cameras` row exists for a given camera_id (no camera-registration flow in
-- P1-B), so a FK here would spuriously reject valid app writes.
-- ---------------------------------------------------------------------------
-- ---------------------------------------------------------------------------
-- Improvement action log (개선 조치): a site fix ("미끄럼 매트 설치") recorded against a
-- camera; the report compares detection density before/after to prove the fix worked.
-- ---------------------------------------------------------------------------
CREATE TABLE move_actions (
action_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
camera_id VARCHAR(64) NOT NULL,
site VARCHAR(64) NULL, -- access-control scope, resolved from the camera's events at insert
note VARCHAR(500) NOT NULL,
taken_at BIGINT UNSIGNED NOT NULL, -- when the fix went in (epoch s)
created_by VARCHAR(190) NOT NULL,
created_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (action_id),
KEY ix_actions_taken (taken_at),
KEY ix_actions_site_taken (site, taken_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE move_zones (
zone_id CHAR(32) NOT NULL, -- bin2hex(random_bytes(16)), same convention as snapshot uuids
device_id VARCHAR(64) NOT NULL,
camera_id VARCHAR(64) NOT NULL,
level VARCHAR(16) NOT NULL, -- app-whitelisted: warning|restricted|pinch (ZoneConfigController::LEVELS)
polygon_json JSON NOT NULL,
rules_json JSON NULL, -- optional occupancy rules: {"min_workers","max_workers","max_dwell_s"} (ZoneConfigController validates)
updated_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (zone_id),
KEY ix_zones_camera (camera_id),
KEY ix_zones_device (device_id),
CONSTRAINT chk_zones_level CHECK (level IN ('warning','restricted','pinch'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- events: ingested detections. event_type/severity are already validated in
-- App\Ingest\EventValidator before insert(); the CHECK constraints below are
-- defense-in-depth only, not the primary validation layer.
-- ---------------------------------------------------------------------------
CREATE TABLE move_events (
event_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
event_uuid CHAR(32) NULL, -- edge-generated idempotency key (dedup a re-sent event); NULL for legacy rows
device_id VARCHAR(64) NOT NULL,
site VARCHAR(64) NULL, -- denormalized from move_devices.site at ingest; access-control scope
camera_id VARCHAR(64) NOT NULL,
event_type VARCHAR(32) NOT NULL,
severity VARCHAR(16) NOT NULL,
track_id INT NULL,
zone_id CHAR(32) NULL,
occurred_at DOUBLE NOT NULL, -- device-reported epoch seconds (float)
duration_s DOUBLE NOT NULL DEFAULT 0,
metrics_json JSON NULL,
spatial_x DOUBLE NULL, -- normalized foot/reference point (0..1 of the frame),
spatial_y DOUBLE NULL, -- heatmap raw material; NULL for legacy/deviceless events
acknowledged_by VARCHAR(190) NULL,
acknowledged_at BIGINT UNSIGNED NULL,
false_positive_by VARCHAR(190) NULL, -- operator's 오탐 tag (per-camera FP-rate stats; no auto-tuning)
false_positive_at BIGINT UNSIGNED NULL,
received_at BIGINT UNSIGNED NOT NULL, -- server receipt time (PHP time()), for clock-skew flagging (design doc §8)
PRIMARY KEY (event_id),
-- Idempotency: a UNIQUE key on event_uuid makes a re-sent event (POST succeeded server-side
-- but the ACK timed out client-side) collide instead of duplicating. MySQL allows multiple
-- NULLs in a UNIQUE index, so legacy rows without a uuid do not conflict.
UNIQUE KEY uq_events_uuid (event_uuid),
KEY ix_events_occurred_at (occurred_at),
KEY ix_events_severity_occurred_at (severity, occurred_at),
KEY ix_events_site_occurred_at (site, occurred_at), -- site-scoped dashboard list (P3-2b)
KEY ix_events_device (device_id),
KEY ix_events_camera (camera_id, event_id), -- zone editor: newest snapshot per camera
CONSTRAINT chk_events_type CHECK (event_type IN (
'fall','no_motion','immobility','ghost','zone_warning',
'zone_restricted','pinch','monitoring_degraded','device_fault',
'lone_worker','overcapacity','overstay','near_fall','ergo_report'
)),
CONSTRAINT chk_events_severity CHECK (severity IN ('critical','high','warning','info'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- event_snapshots: re-encoded JPEG references. Files live under storage/
-- (webroot-adjacent, served only via the authenticated SnapshotProxy). FK to
-- events is safe because IngestController always inserts the parent event row
-- before calling SnapshotRepository::add() for its snapshots.
-- ---------------------------------------------------------------------------
CREATE TABLE move_event_snapshots (
snapshot_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
event_id INT UNSIGNED NOT NULL,
file_uuid CHAR(32) NOT NULL, -- bin2hex(random_bytes(16)); on-disk filename = <uuid>.jpg
content_hash CHAR(64) NOT NULL, -- sha256 of the re-encoded bytes
created_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (snapshot_id),
UNIQUE KEY uq_event_snapshots_uuid (file_uuid),
-- Idempotent snapshot recovery: a re-sent event carries the SAME re-encoded bytes (same
-- content_hash), so this makes a duplicate/racing store collide instead of writing a second
-- copy. Lets the dedup path safely re-store missing evidence without duplication.
UNIQUE KEY uq_event_snapshots_event_hash (event_id, content_hash),
KEY ix_event_snapshots_event (event_id),
KEY ix_event_snapshots_created (created_at), -- retention purge scans WHERE created_at < ?
CONSTRAINT fk_event_snapshots_event FOREIGN KEY (event_id) REFERENCES move_events (event_id)
ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- thresholds: per-device (optionally per-camera/zone) tunables synced via
-- GET /api/config. No PdoThresholdRepository write method exists in P1-B --
-- rows are seeded/edited directly (phpMyAdmin) until a management UI lands.
-- ---------------------------------------------------------------------------
CREATE TABLE move_thresholds (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
device_id VARCHAR(64) NOT NULL,
camera_id VARCHAR(64) NULL,
zone_id CHAR(32) NULL,
`key` VARCHAR(64) NOT NULL,
`value` VARCHAR(255) NOT NULL,
PRIMARY KEY (id),
KEY ix_thresholds_device (device_id),
UNIQUE KEY uq_thresholds_scope_key (device_id, camera_id, zone_id, `key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- nonces: replay-protection store for ingest/config/heartbeat HMAC requests.
-- `nonce` is the PRIMARY KEY (unique) so PdoNonceRepository::remember() is
-- safe against a duplicate-insert race: IngestController already calls
-- seen() before remember(), and a thrown duplicate-key error on a racing
-- remember() is an acceptable, expected outcome (closes the seen()/remember()
-- TOCTOU flagged in the Task 7 review -- the PK uniqueness is the real guard,
-- not the earlier seen() check).
-- ---------------------------------------------------------------------------
CREATE TABLE move_nonces (
nonce VARCHAR(190) NOT NULL,
expires_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (nonce),
KEY ix_nonces_expires_at (expires_at) -- for a periodic `DELETE FROM move_nonces WHERE expires_at < ?` cleanup job
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- rate_limits: per-key sliding-window counters for ingest rate limiting. The
-- (rate_key, window_start) primary key backs an atomic
-- `INSERT ... ON DUPLICATE KEY UPDATE count = count + 1` upsert in
-- PdoRateLimiterRepository::hit() -- no read-modify-write race window.
-- ---------------------------------------------------------------------------
CREATE TABLE move_rate_limits (
rate_key VARCHAR(190) NOT NULL,
window_start BIGINT UNSIGNED NOT NULL, -- floor(now / 60): the minute bucket
count INT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (rate_key, window_start),
-- The reap `DELETE ... WHERE window_start < ?` cannot use the PK (window_start is its trailing
-- column), so give it its own index to avoid a locking full-scan on the pre-auth hot path.
KEY ix_rate_limits_window (window_start)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- audit_log: append-only action log (acknowledge / zone save+delete / login).
-- Tamper-evident hash-chaining (design doc §9.2) is deferred to P3 per the
-- Task 16 brief self-review -- this table is the plain append-only record only.
-- ---------------------------------------------------------------------------
CREATE TABLE move_audit_log (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
actor VARCHAR(190) NOT NULL,
action VARCHAR(64) NOT NULL,
target VARCHAR(190) NOT NULL,
before_json JSON NOT NULL,
after_json JSON NOT NULL,
ts BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (id),
KEY ix_audit_log_ts (ts),
KEY ix_audit_log_actor (actor)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ===========================================================================
-- UPGRADING AN EXISTING DATABASE (fresh installs already have everything above):
-- do NOT copy the statements below by hand — they are SQL comments and will not
-- run. Apply the RUNNABLE migration instead:
--
-- cloud/migrations/2026-07-17-p1-9-p3-2b.sql
-- cloud/migrations/2026-07-20-move-table-prefix.sql (run this one LAST)
--
-- The second migration renames every table to the `move_` prefix used above and
-- by App\Repository\Pdo\* -- an existing DB must be renamed before deploy or all
-- queries fail with "table doesn't exist".
--
-- It adds devices.site / events.site / events.event_uuid, the retention and
-- rate-limit reap indexes, AND backfills events.site from move_devices.site (without
-- that backfill, historical events vanish for a scoped operator). Run it once in
-- phpMyAdmin BEFORE deploying code that reads these columns, then provision:
-- UPDATE move_devices SET site = 'factory-a' WHERE device_id = 'pi-1';
-- UPDATE move_users SET site_scope = 'factory-a' WHERE username = 'operator-a';
-- A user with site_scope = NULL is a global operator; '' is NOT global (matches
-- nothing — a blank scope fails closed).
-- ===========================================================================