move_detect/server/tests/ReadAuditTest.php
유창욱 3aca674a78
Some checks failed
verify / edge (push) Has been cancelled
verify / server (push) Has been cancelled
feat: 이해관계자 페르소나 검증 4건 — 열람 감사 · 증거 보존 · 크론 생존 · 증거 정책 (1.3.0)
앞선 감사 네 번은 "이 코드가 제대로 도는가"를 물었다. 이번엔 작업자·노조·안전관리자·
공장장·설치기사 5인 관점으로 3단논법을 세우고 전제를 코드로 확인한 뒤 반문으로 깼다.
5인 중 2인의 논증이 완전히, 2인이 부분적으로 무너졌다.

읽기 감사 — 이 시스템은 쓰기를 전부 감사했다. 임계값 한 번 바꾼 것까지 해시 체인에
들어간다. 그런데 작업자 사진을 열어보는 것은 하나도 남지 않았다. 감시 시스템과 안전
시스템을 가르는 선이 정확히 거기라서, 나머지 프라이버시 설계(RAM 링버퍼 7.5초·전송 전
얼굴 블러·라이브뷰 부재)가 전부 이 한 줄이 없어서 검증 불가능한 주장에 머물러 있었다.
거부된 열람은 기록하지 않는다 — 그러면 감사 로그가 "본 사람"이 아니라 "요청한 사람"
목록이 되어 정작 누가 봤는지를 묻는 데 못 쓴다.

크론 생존 — 죽은 노드는 스스로 신고할 수 없어서 크론이 하트비트의 부재로 판정한다.
그런데 그 크론이 멈추면 아무도 판정하지 않는다. 통보·5분 확대·장치 이상 발행이 전부 그
한 프로세스에 걸려 있어서, 멈춘 순간부터 화면은 조용해지고 그 침묵은 "사고 없음"과
구별되지 않는다. 감시자의 생존은 감시자가 아닌 쪽이 읽어야 한다.

증거 보존 — 스냅샷 삭제가 나이 하나만 봤다. 기본 7일인데 중대재해 조사는 몇 주에서 몇
달이라, 우리가 내건 목적("사고 후 원인 분석")이 8일째에 스스로 사라졌다. 확인 처리로
자동 연장하지 않는 이유는 자동이면 사실상 전량 보존이 되어 7일 약속이 무너지기 때문이다.

증거 정책 — 프레임이 ergo_report 하나만 빼고 모든 이벤트에 붙었다. 체류 상한 초과도
포함이라, 밀폐공간 프리셋 기본값(30분) 기준으로 정상 작업자가 규정대로 일하는 동안
주기적으로 본인 사진이 서버로 갔다. 위험해서가 아니라 오래 있어서. 기준을 명문화했다:
시간 경과 자체가 조건인 이벤트에는 사진을 붙이지 않는다.

마이그레이션 2026-09-25-evidence-hold-and-view-audit.sql (README-UPLOAD 10번).

검증: phpunit 302 passed(신규 18, 스킵 0) · pytest(신규 18)

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EBjuR7DW6PNNMows4KnbYU
2026-09-25 18:34:26 +09:00

184 lines
8.2 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Tests;
use App\Auth\ArraySessionStore;
use App\Tests\Support\{InMemoryEventRepository, InMemorySnapshotRepository, InMemoryAuditRepository};
use App\Dashboard\{SnapshotProxy, ExportController};
use App\Http\Request;
use PHPUnit\Framework\TestCase;
/**
* 읽기도 감사에 남는다.
*
* 이 시스템은 쓰기를 전부 남긴다 — 임계값 한 번 바꾼 것까지 해시 체인에 들어간다. 그런데
* 작업자 사진을 열어보는 것과 사건 전체를 파일로 내보내는 것은 하나도 남지 않았다. 감시
* 시스템과 안전 시스템을 가르는 선이 정확히 거기라서, 나머지 프라이버시 설계(RAM 링버퍼·전송
* 전 얼굴 블러·라이브뷰 부재)가 전부 검증 불가능한 주장에 머물러 있었다.
*
* "안 봤습니다"는 증명이 아니다. 교섭 테이블에서 답이 되는 것은 기록뿐이고, 이 테스트가
* 지키는 것이 그 기록이다.
*/
final class ReadAuditTest extends TestCase
{
private string $dir;
protected function setUp(): void
{
$this->dir = sys_get_temp_dir() . '/move-readaudit-' . bin2hex(random_bytes(6));
mkdir($this->dir);
}
protected function tearDown(): void
{
foreach (glob($this->dir . '/*') ?: [] as $f) @unlink($f);
@rmdir($this->dir);
}
/** @return array{0:SnapshotProxy,1:InMemoryAuditRepository,2:ArraySessionStore,3:string} */
private function proxy(?string $siteScope = null): array
{
$events = new InMemoryEventRepository();
$eventId = $events->insert([
'device_id' => 'pi-01', 'camera_id' => 'cam-01', 'event_type' => 'fall',
'severity' => 'high', 'occurred_at' => 1000.0, 'site' => 'A동',
]);
$uuid = bin2hex(random_bytes(16));
file_put_contents($this->dir . '/' . $uuid . '.jpg', 'jpeg-bytes');
$snaps = new InMemorySnapshotRepository($this->dir);
$snaps->add($eventId, $uuid, str_repeat('a', 64));
$audit = new InMemoryAuditRepository();
$sess = new ArraySessionStore();
$sess->set('user_id', 7);
$sess->set('username', '관리자');
$sess->set('role', 'admin');
$sess->set('site_scope', $siteScope);
return [new SnapshotProxy($snaps, $events, $sess, $audit), $audit, $sess, $uuid];
}
private function req(): Request
{
return new Request('GET', '/snap', [], '', []);
}
public function test_viewing_a_worker_image_is_recorded(): void
{
[$proxy, $audit, , $uuid] = $this->proxy();
$res = $proxy->serve($this->req(), ['uuid' => $uuid]);
$this->assertSame(200, $res->status());
$this->assertCount(1, $audit->log, '사진을 열었는데 감사에 아무것도 남지 않았습니다.');
$this->assertSame('snapshot_view', $audit->log[0]['act']);
$this->assertSame("snapshot:$uuid", $audit->log[0]['t']);
$this->assertSame('관리자', $audit->log[0]['a']);
}
public function test_the_same_image_in_one_session_is_recorded_once(): void
{
// 목록 화면은 5초마다 <img> 를 다시 그린다. 감사 추가는 해시 체인 꼬리에 행 잠금을
// 잡는 작업이라, 장당 한 행씩 쓰면 공유호스팅에서 직렬화된다. "이 로그인 세션에서
// 이 사진을 봤다"가 노조가 묻는 질문에 답하기 충분하다.
[$proxy, $audit, , $uuid] = $this->proxy();
for ($i = 0; $i < 5; $i++) $proxy->serve($this->req(), ['uuid' => $uuid]);
$this->assertCount(1, $audit->log);
}
public function test_a_different_image_is_recorded_separately(): void
{
[$proxy, $audit, , $uuid] = $this->proxy();
$proxy->serve($this->req(), ['uuid' => $uuid]);
// 없는 uuid 는 404 라 기록도 없다 — 기록은 "본 것"이지 "요청한 것"이 아니다.
$missing = $proxy->serve($this->req(), ['uuid' => bin2hex(random_bytes(16))]);
$this->assertSame(404, $missing->status());
$this->assertCount(1, $audit->log);
}
public function test_an_unauthenticated_request_records_nothing(): void
{
[$proxy, $audit, $sess, $uuid] = $this->proxy();
$sess->set('user_id', null);
$this->assertSame(401, $proxy->serve($this->req(), ['uuid' => $uuid])->status());
$this->assertSame([], $audit->log);
}
public function test_a_blocked_cross_site_read_records_nothing(): void
{
// 거부된 열람은 열람이 아니다. 여기서 기록하면 감사 로그가 "본 사람" 목록이 아니라
// "요청한 사람" 목록이 되어, 정작 누가 봤는지를 묻는 데 쓸 수 없게 된다.
[$proxy, $audit, , $uuid] = $this->proxy(siteScope: 'B동');
$this->assertSame(404, $proxy->serve($this->req(), ['uuid' => $uuid])->status());
$this->assertSame([], $audit->log);
}
public function test_a_failing_audit_does_not_block_the_image(): void
{
// 감사가 안전 기능을 죽이면 안 된다 — 사고 조사 중에 DB 가 흔들린다고 사진이 안 열리면
// 그건 프라이버시 보호가 아니라 장애다. 대신 세션 메모에 넣지 않아 다음에 재시도한다.
$events = new InMemoryEventRepository();
$eventId = $events->insert(['device_id' => 'pi-01', 'camera_id' => 'cam-01',
'event_type' => 'fall', 'severity' => 'high', 'occurred_at' => 1000.0, 'site' => null]);
$uuid = bin2hex(random_bytes(16));
file_put_contents($this->dir . '/' . $uuid . '.jpg', 'jpeg-bytes');
$snaps = new InMemorySnapshotRepository($this->dir);
$snaps->add($eventId, $uuid, str_repeat('a', 64));
$audit = new class implements \App\Repository\AuditRepository {
public int $calls = 0;
public function append(string $a, string $act, string $t, array $b, array $af): void
{ $this->calls++; throw new \RuntimeException('db down'); }
};
$sess = new ArraySessionStore();
$sess->set('user_id', 7); $sess->set('username', '관리자'); $sess->set('site_scope', null);
$proxy = new SnapshotProxy($snaps, $events, $sess, $audit);
$this->assertSame(200, $proxy->serve($this->req(), ['uuid' => $uuid])->status());
$proxy->serve($this->req(), ['uuid' => $uuid]);
$this->assertSame(2, $audit->calls, '기록 실패 후 재시도하지 않았습니다 — 조용히 누락됩니다.');
}
public function test_a_bulk_export_is_recorded_with_its_size(): void
{
$events = new InMemoryEventRepository();
for ($i = 0; $i < 3; $i++) {
$events->insert(['device_id' => 'pi-01', 'camera_id' => 'cam-01', 'event_type' => 'fall',
'severity' => 'high', 'occurred_at' => (float)(time() - 100), 'site' => null]);
}
$audit = new InMemoryAuditRepository();
$sess = new ArraySessionStore();
$sess->set('user_id', 7); $sess->set('username', '관리자');
$sess->set('role', 'admin'); $sess->set('site_scope', null);
$export = new ExportController($events, new InMemorySnapshotRepository($this->dir), $sess, $audit);
$res = $export->labels(new Request('GET', '/api/export/labels', [], '', ['days' => '30']));
$this->assertSame(200, $res->status());
$this->assertCount(1, $audit->log, '최대 2만 건이 파일 하나로 나가는데 기록이 없습니다.');
$this->assertSame('label_export', $audit->log[0]['act']);
$this->assertSame(30, $audit->log[0]['af']['days']);
$this->assertSame(3, $audit->log[0]['af']['rows']);
}
public function test_a_forbidden_export_is_not_recorded_as_one(): void
{
$sess = new ArraySessionStore();
$sess->set('user_id', 7); $sess->set('username', '작업자');
$sess->set('role', 'viewer'); $sess->set('site_scope', null);
$audit = new InMemoryAuditRepository();
$export = new ExportController(new InMemoryEventRepository(),
new InMemorySnapshotRepository($this->dir), $sess, $audit);
$res = $export->labels(new Request('GET', '/api/export/labels', [], '', []));
$this->assertSame(403, $res->status());
$this->assertSame([], $audit->log);
}
}