--- a/app/Console/Commands/ImportDocumentBatch.php +++ b/app/Console/Commands/ImportDocumentBatch.php @@ -14,11 +14,18 @@ class ImportDocumentBatch extends Command { - protected $signature = 'documents:import-batch {manifest : JSON manifest inside storage/app/private/document-import-staging} {--apply : Register private drafts and queue malware scans} {--actor= : Existing user ID responsible for an applied import}'; + protected $signature = 'documents:import-batch {manifest : JSON manifest inside storage/app/private/document-import-staging} {--apply : Register private drafts and queue malware scans} {--actor= : Existing user ID responsible for an applied import} {--pilot-agronegocio : Restrict to the approved two-original pilot} {--backup-proof= : Fresh verified destination backup receipt for active pilot apply}'; protected $description = 'Preview or idempotently import a document batch into the existing private library'; private const MAX_BYTES = 10485760; + + private const PILOT_MANIFEST_SHA256 = '0b720b0a6f7539de1d3eca9e32f89a6b9038848dc0b97ad21ace605154d9ddd8'; + + private const PILOT_HASHES = [ + 'legacy-tempo-post-171985-20260420' => '0929184a6d4645b9046512675394ad4f60575273f6dab0955f71cc7474a6a4e2', + 'legacy-tempo-agronegocio-image-5e3840705cf98226' => '5e3840705cf98226d1f189cf665aaa98cb05da96c645159a1332a1d429d642eb', + ]; public function handle(): int { @@ -43,7 +50,8 @@ } try { - $manifest = json_decode((string) file_get_contents($manifestPath), true, 512, JSON_THROW_ON_ERROR); + $manifestBytes = (string) file_get_contents($manifestPath); + $manifest = json_decode($manifestBytes, true, 512, JSON_THROW_ON_ERROR); } catch (Throwable) { $this->error('Manifest is not valid JSON.'); @@ -57,7 +65,17 @@ $apply = (bool) $this->option('apply'); $actorId = $this->option('actor'); - if ($apply) { + $pilot = (bool) $this->option('pilot-agronegocio'); + if ($pilot) { + try { + $this->validatePilot($manifestPath, $manifestBytes, $manifest, $stagingReal, $apply, $actorId); + } catch (Throwable $exception) { + $this->error('Pilot refused before import: '.$exception->getMessage()); + + return self::FAILURE; + } + } + if ($apply && ! $pilot) { // CLI attribution is not an authenticated active installation. Rehearsals stay isolated. $target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port'); if (! app()->environment('testing') || ! str_ends_with($target->database, '_test') || (int) $target->port !== 55441 @@ -87,6 +105,9 @@ $label = is_array($record) ? (string) ($record['external_id'] ?? '#'.($index + 1)) : '#'.($index + 1); try { $validated = $this->validateRecord($record, $stagingReal); + if ($pilot && ! hash_equals(self::PILOT_HASHES[$validated['external_id']] ?? '', $validated['sha256'])) { + throw new RuntimeException('Approved pilot bytes changed after preview validation.'); + } $hash = $validated['sha256']; if (isset($seenHashes[$hash])) { $this->line($label.' | duplicate bytes within batch; references item '.$seenHashes[$hash]); @@ -215,6 +236,66 @@ return $failures > 0 ? self::FAILURE : self::SUCCESS; } + /** The extra CLI path is a named, byte-bound pilot; it is not a general active import gate. */ + private function validatePilot(string $manifestPath, string $manifestBytes, array $manifest, string $staging, bool $apply, mixed $actorId): void + { + if ($manifestPath !== realpath($staging.'/legacy-agronegocio/manifest.json') + || ! hash_equals(self::PILOT_MANIFEST_SHA256, hash('sha256', $manifestBytes)) + || count($manifest['documents']) !== 2) { + throw new RuntimeException('Only the exact approved agribusiness manifest and its two entries are allowed.'); + } + $target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port'); + $host = config('database.connections.pgsql.host'); + $qa = app()->environment('testing') && str_ends_with($target->database, '_test') && (int) $target->port === 55441; + $active = ! app()->environment('testing') && $target->database === 'investemoz' && (int) $target->port === 5432; + if ((! $qa && ! $active) || ! in_array($host, ['127.0.0.1', 'localhost'], true) || config('database.connections.pgsql.url')) { + throw new RuntimeException('Pilot target identity is not permitted.'); + } + if ($apply || $actorId !== null) { + $actor = is_string($actorId) && preg_match('/^[1-9][0-9]*$/D', $actorId) ? User::find((int) $actorId) : null; + if (! $actor || ! $actor->can('manage-portal')) { + throw new RuntimeException('A real existing account with effective manage-portal authorization is required.'); + } + } + if ($active && $apply) { + $this->validatePilotBackup($this->option('backup-proof')); + } + foreach ($manifest['documents'] as $record) { + $entry = $this->validateRecord($record, $staging); + if (! hash_equals(self::PILOT_HASHES[$entry['external_id']] ?? '', $entry['sha256'])) { + throw new RuntimeException('Article or image differs from the approved SHA-256.'); + } + $existing = DB::table('documents')->where('sha256', $entry['sha256'])->whereNull('deleted_at')->first(); + if ($existing && ($existing->external_id !== $entry['external_id'] + || ! DB::table('portal_resources')->where('document_id', $existing->id)->exists())) { + throw new RuntimeException('Matching bytes have another identity or no library resource; reconcile explicitly.'); + } + if (DB::table('documents')->where('external_id', $entry['external_id'])->whereNull('deleted_at') + ->where('sha256', '!=', $entry['sha256'])->exists() + || (! $existing && DB::table('portal_resources')->where('document_identity_key', $this->identity($entry))->exists())) { + throw new RuntimeException('Existing identity/version conflicts with this pilot; no overwrite or partial preflight import.'); + } + } + } + + private function validatePilotBackup(mixed $path): void + { + if (! is_string($path) || ! is_file($path)) { + throw new RuntimeException('Active pilot apply requires a fresh verified backup/restoration receipt.'); + } + $proof = json_decode((string) file_get_contents($path), true, 512, JSON_THROW_ON_ERROR); + $verified = strtotime($proof['verified_at'] ?? ''); + if (! ($proof['restore_verified'] ?? false) || ! ($proof['files_verified'] ?? false) + || ($proof['target']['database'] ?? '') !== 'investemoz' || (int) ($proof['target']['port'] ?? 0) !== 5432 + || ! str_ends_with($proof['restore_target']['database'] ?? '', '_test') || (int) ($proof['restore_target']['port'] ?? 0) !== 55441 + || $verified === false || $verified > time() || $verified < time() - 86400 + || ! is_file($proof['dump_path'] ?? '') || ! is_file($proof['files_path'] ?? '') + || ! hash_equals($proof['sha256'] ?? '', hash_file('sha256', $proof['dump_path'])) + || ! hash_equals($proof['files_sha256'] ?? '', hash_file('sha256', $proof['files_path']))) { + throw new RuntimeException('Backup/restoration identity, freshness or integrity does not match the active pilot.'); + } + } + /** @return array */ private function validateRecord(mixed $record, string $stagingRoot): array {