commit compras2 2811
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-28 15:45:52 +02:00
parent eb32c74c56
commit 060c119ba1
92 changed files with 4936 additions and 43 deletions
+164
View File
@@ -0,0 +1,164 @@
<?php
namespace App\Services;
use App\Models\PrivateAuditExport;
use App\Models\User;
use Generator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use RuntimeException;
use ZipArchive;
final class PrivateAuditExporter
{
/** @param array<string,mixed> $input */
public function generate(User $candidate, array $input): PrivateAuditExport
{
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'families' => 'required|array|min:1|max:4', 'purpose' => 'nullable|string|max:500'])->validate();
$scope = app(PrivateAuditAccess::class)->authorise($candidate, $data['families']);
$actor = $scope['actor'];
$operation = strtolower($data['operation_key']);
$purpose = trim($data['purpose'] ?? '');
$inputHash = hash('sha256', json_encode(['schema' => 'compras.private-audit.v1', 'tenant' => $actor->tenant_id,
'actor' => $actor->id, 'context' => $scope['context'], 'families' => $scope['families'], 'purpose' => $purpose], JSON_THROW_ON_ERROR));
$existing = PrivateAuditExport::query()->where('created_by', $actor->id)->where('operation_key', $operation)->first();
if ($existing !== null) {
abort_unless(hash_equals($existing->input_hash, $inputHash), 409, 'A operação já corresponde a outra selecção.');
$this->verifiedPath($actor, $existing);
return $existing;
}
abort_unless(class_exists(ZipArchive::class), 503, 'Preparação ZIP indisponível nesta instalação.');
$files = new PrivateAuditFiles($actor);
$archivePath = null;
$keep = [];
try {
$manifest = DB::transaction(function () use ($actor, $scope, $purpose, $files): array {
if (DB::getDriverName() === 'pgsql') {
abort_unless(DB::transactionLevel() === 1, 503, 'A auditoria requer a sua própria leitura consistente.');
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
}
$manifest = ['schema' => 'compras.private-audit.v1', 'generated_at' => now()->toIso8601String(),
'tenant_id' => $actor->tenant_id, 'actor_id' => $actor->id, 'work_context' => $scope['context'], 'families' => $scope['families'], 'purpose' => $purpose,
'source_semantics' => 'Stored source facts and curated history; no new balance calculations or business commands.',
'excluded' => ['complete_bank_registers', 'bank_specific_import_documents', 'private_people_data_and_documents', 'credentials', 'arbitrary_audit_payloads', 'native_storage_paths'],
'original_semantics' => 'Business originals retain their verified bytes; files are not rewritten or certified by this export.',
'datasets' => [], 'originals' => []];
foreach (app(PrivateAuditSourceReader::class)->datasets($actor, $scope['families']) as $dataset) {
$entry = array_intersect_key($dataset, array_flip(['family', 'source', 'state', 'columns', 'missing_columns']));
if ($dataset['rows'] === null) {
$manifest['datasets'][] = [...$entry, 'records' => null];
continue;
}
$count = 0;
$content = static function () use ($dataset, &$count): Generator {
foreach ($dataset['rows'] as $row) {
$count++;
yield json_encode($row, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."\n";
}
};
$written = $files->write($dataset['file'], $content());
$manifest['datasets'][] = [...$entry, 'records' => $count, ...array_intersect_key($written, array_flip(['file', 'size', 'sha256']))];
}
foreach (app(PrivateAuditOriginals::class)->files($actor, $scope['families']) as $original) {
$written = $files->write($original['file'], $original['bytes']);
abort_unless($written['size'] === $original['size'] && hash_equals($original['sha256'], $written['sha256']), 409, 'A cópia do original não coincide com os bytes verificados.');
$manifest['originals'][] = array_intersect_key($original, array_flip(['family', 'source', 'source_id', 'original_name', 'mime_type', 'file', 'size', 'sha256']));
}
return $manifest;
});
// Revalidate after the snapshot, so a concurrent revocation is not hidden by repeatable read.
$fresh = app(PrivateAuditAccess::class)->authorise($actor, $scope['families']);
abort_unless($fresh['context'] === $scope['context'], 409, 'O contexto mudou; prepare uma nova exportação.');
$manifestBytes = json_encode($manifest, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)."\n";
$manifestFile = $files->write('manifesto.json', $manifestBytes);
$archivePath = $files->path('auditoria.zip');
$zip = new ZipArchive;
if ($zip->open($archivePath, ZipArchive::CREATE | ZipArchive::EXCL) !== true) {
throw new RuntimeException('Não foi possível preparar o arquivo ZIP.');
}
$members = [...array_column($manifest['datasets'], 'file'), ...array_column($manifest['originals'], 'file'), 'manifesto.json'];
try {
foreach ($members as $member) {
$path = $member === 'manifesto.json' ? $manifestFile['path'] : Storage::disk('local')->path($files->relative.'/'.$member);
if (! $zip->addFile($path, $member)) {
throw new RuntimeException('Não foi possível incluir um membro do pacote.');
}
}
} finally {
$closed = $zip->close();
if (is_file($archivePath)) {
$files->created($archivePath);
}
if (! $closed) {
throw new RuntimeException('Não foi possível concluir o pacote privado.');
}
}
$sha = hash_file('sha256', $archivePath);
$size = filesize($archivePath);
if ($sha === false || $size === false || $size < 1) {
throw new RuntimeException('Não foi possível verificar o pacote privado.');
}
$export = DB::transaction(function () use ($actor, $scope, $operation, $inputHash, $files, $size, $sha, $manifestBytes, $manifest) {
app(ConflictGuard::class)->lockCompany($actor);
$actor = app(CurrentActor::class)->lock($actor);
$current = app(PrivateAuditAccess::class)->authorise($actor, $scope['families']);
abort_unless($current['context'] === $scope['context'], 409);
$retry = PrivateAuditExport::query()->where('created_by', $actor->id)->where('operation_key', $operation)->first();
if ($retry !== null) {
abort_unless(hash_equals($retry->input_hash, $inputHash), 409);
return $retry;
}
$export = PrivateAuditExport::query()->create(['tenant_id' => $actor->tenant_id, 'created_by' => $actor->id,
'operation_key' => $operation, 'input_hash' => $inputHash, 'work_context' => $scope['context'], 'families' => $scope['families'],
'path' => $files->relative.'/auditoria.zip', 'size' => $size, 'sha256' => $sha,
'manifest_sha256' => hash('sha256', $manifestBytes), 'manifest' => $manifest, 'created_at' => now()]);
app(RequisitionWorkflow::class)->audit($actor, 'audit.private_export_generated', null, null,
['export_id' => $export->id, 'families' => $scope['families'], 'sha256' => $sha, 'manifest_sha256' => $export->manifest_sha256]);
return $export;
});
if ($export->path === $files->relative.'/auditoria.zip') {
$keep = [$archivePath];
}
return $export;
} finally {
$files->cleanup($keep);
}
}
/** Validate both current family authority and the immutable private package before download/replay. */
public function verifiedPath(User $candidate, PrivateAuditExport $export): string
{
$scope = app(PrivateAuditAccess::class)->authorise($candidate, $export->families);
$actor = $scope['actor'];
abort_unless($export->tenant_id === $actor->tenant_id && $export->created_by === $actor->id, 404);
abort_unless($scope['context'] === $export->work_context, 409, 'Seleccione o contexto original da exportação.');
$prefix = 'audit-exports/'.$actor->tenant_id.'/'.$actor->id.'/';
abort_unless(preg_match('/^'.preg_quote($prefix, '/').'[a-f0-9-]{36}\/auditoria\.zip$/D', $export->path) === 1, 409);
$disk = Storage::disk('local');
$root = realpath($disk->path(''));
$path = realpath($disk->path($export->path));
$expected = $root === false ? '' : str_replace('\\', '/', $root).'/'.$prefix;
$normal = $path === false ? '' : str_replace('\\', '/', $path);
$within = PHP_OS_FAMILY === 'Windows' ? str_starts_with(strtolower($normal), strtolower($expected)) : str_starts_with($normal, $expected);
abort_unless($root !== false && $path !== false && $within && is_file($path) && ! is_link($disk->path($export->path))
&& filesize($path) === $export->size && hash_equals($export->sha256, hash_file('sha256', $path) ?: ''), 409, 'O pacote original está indisponível ou alterado.');
$zip = new ZipArchive;
abort_unless($zip->open($path, ZipArchive::RDONLY) === true, 409, 'O pacote original não pôde ser verificado.');
try {
$bytes = $zip->getFromName('manifesto.json');
abort_unless(is_string($bytes) && hash_equals($export->manifest_sha256, hash('sha256', $bytes)), 409, 'O manifesto do pacote mudou.');
} finally {
$zip->close();
}
return $path;
}
}