@@ -0,0 +1,159 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\PrivateAuditExport;
|
||||
use App\Models\SupplierDocument;
|
||||
use App\Models\User;
|
||||
use App\Services\PrivateAuditAccess;
|
||||
use App\Services\PrivateAuditExporter;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
config(['private-audit.qa_enabled' => true]);
|
||||
Storage::fake('local');
|
||||
Storage::fake('supplier_documents');
|
||||
Storage::fake('receipt_documents');
|
||||
$this->f = receiptFixture();
|
||||
$this->actor = $this->f['issuer'];
|
||||
$this->actingAs($this->actor);
|
||||
supplyGrant($this->actor, array_column(PrivateAuditAccess::FAMILIES, 'permission'));
|
||||
if (DB::getDriverName() === 'pgsql') {
|
||||
if (! app()->environment('testing') || DB::connection()->getConfig('host') !== '127.0.0.1'
|
||||
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
|
||||
throw new LogicException('Audit fixtures require the owned disposable PostgreSQL database.');
|
||||
}
|
||||
DB::commit();
|
||||
$this->committedAuditFixture = true;
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
if ($this->committedAuditFixture ?? false) {
|
||||
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getConfig('host') !== '127.0.0.1'
|
||||
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
|
||||
throw new LogicException('Audit fixture cleanup requires its disposable PostgreSQL database.');
|
||||
}
|
||||
DB::statement('DROP SCHEMA public CASCADE');
|
||||
DB::statement('CREATE SCHEMA public');
|
||||
}
|
||||
});
|
||||
|
||||
test('private audit creates a verified immutable package and replays without duplicating or changing business facts', function () {
|
||||
$before = DB::table('purchase_orders')->orderBy('id')->get()->toJson();
|
||||
$input = ['operation_key' => (string) Str::uuid(), 'families' => ['configuration', 'purchasing', 'stock', 'finance'], 'purpose' => 'Synthetic QA audit'];
|
||||
$service = app(PrivateAuditExporter::class);
|
||||
$export = $service->generate($this->actor, $input);
|
||||
$path = $service->verifiedPath($this->actor, $export);
|
||||
$zip = new ZipArchive;
|
||||
expect($zip->open($path, ZipArchive::RDONLY))->toBeTrue();
|
||||
try {
|
||||
$manifest = json_decode($zip->getFromName('manifesto.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
expect($manifest['families'])->toHaveCount(4);
|
||||
foreach ($manifest['datasets'] as $dataset) {
|
||||
if ($dataset['state'] === 'not_installed') {
|
||||
expect($dataset['records'])->toBeNull();
|
||||
|
||||
continue;
|
||||
}
|
||||
$bytes = $zip->getFromName($dataset['file']);
|
||||
expect($bytes)->toBeString()
|
||||
->and(strlen($bytes))->toBe($dataset['size'])
|
||||
->and(hash('sha256', $bytes))->toBe($dataset['sha256'])
|
||||
->and(substr_count($bytes, "\n"))->toBe($dataset['records']);
|
||||
}
|
||||
} finally {
|
||||
$zip->close();
|
||||
}
|
||||
expect($service->generate($this->actor, $input)->id)->toBe($export->id)
|
||||
->and(PrivateAuditExport::query()->count())->toBe(1)
|
||||
->and(DB::table('audit_logs')->where('action', 'audit.private_export_generated')->count())->toBe(1)
|
||||
->and(DB::table('purchase_orders')->orderBy('id')->get()->toJson())->toBe($before)
|
||||
->and(Storage::disk('local')->allFiles())->toBe([$export->path]);
|
||||
try {
|
||||
$service->generate($this->actor, [...$input, 'purpose' => 'Changed purpose']);
|
||||
test()->fail('A different request must not reuse the operation.');
|
||||
} catch (HttpException $error) {
|
||||
expect($error->getStatusCode())->toBe(409);
|
||||
}
|
||||
});
|
||||
|
||||
test('private audit refuses changed package bytes and revoked family authority', function () {
|
||||
$service = app(PrivateAuditExporter::class);
|
||||
$export = $service->generate($this->actor, ['operation_key' => (string) Str::uuid(), 'families' => ['configuration']]);
|
||||
Storage::disk('local')->append($export->path, 'CORRUPTED-SYNTHETIC-QA');
|
||||
try {
|
||||
$service->verifiedPath($this->actor, $export);
|
||||
test()->fail('Changed bytes must be refused.');
|
||||
} catch (HttpException $error) {
|
||||
expect($error->getStatusCode())->toBe(409);
|
||||
}
|
||||
DB::table('organization_memberships')->where('user_id', $this->actor->id)->update(['expires_at' => now()->subMinute()]);
|
||||
try {
|
||||
$service->verifiedPath($this->actor, $export);
|
||||
test()->fail('Revocation must be effective before download.');
|
||||
} catch (HttpException $error) {
|
||||
expect($error->getStatusCode())->toBe(403);
|
||||
}
|
||||
});
|
||||
|
||||
test('private audit verifies original bytes and cleans only its own incomplete preparation', function () {
|
||||
$bytes = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6E4sAAAAASUVORK5CYII=');
|
||||
$supplier = $this->f['order']->supplier_id;
|
||||
$path = $this->actor->tenant_id.'/'.$supplier.'/original.png';
|
||||
Storage::disk('supplier_documents')->put($path, $bytes);
|
||||
$document = SupplierDocument::query()->create(['tenant_id' => $this->actor->tenant_id, 'supplier_id' => $supplier,
|
||||
'uploaded_by' => $this->actor->id, 'document_type' => 'other', 'original_name' => 'original.png', 'path' => $path,
|
||||
'mime_type' => 'image/png', 'size' => strlen($bytes), 'sha256' => hash('sha256', $bytes)]);
|
||||
$service = app(PrivateAuditExporter::class);
|
||||
$export = $service->generate($this->actor, ['operation_key' => (string) Str::uuid(), 'families' => ['purchasing']]);
|
||||
$zip = new ZipArchive;
|
||||
$zip->open($service->verifiedPath($this->actor, $export), ZipArchive::RDONLY);
|
||||
try {
|
||||
expect($zip->getFromName('originais/purchasing/supplier_documents/'.$document->id.'.png'))->toBe($bytes);
|
||||
} finally {
|
||||
$zip->close();
|
||||
}
|
||||
Storage::disk('local')->put('unrelated/keep.txt', 'PRESERVE');
|
||||
$before = Storage::disk('local')->allFiles();
|
||||
Storage::disk('supplier_documents')->put($path, 'ALTERED');
|
||||
try {
|
||||
$service->generate($this->actor, ['operation_key' => (string) Str::uuid(), 'families' => ['purchasing']]);
|
||||
test()->fail('An altered original must prevent a ready package.');
|
||||
} catch (HttpException $error) {
|
||||
expect($error->getStatusCode())->toBe(409);
|
||||
}
|
||||
expect(PrivateAuditExport::query()->count())->toBe(1)
|
||||
->and(Storage::disk('local')->allFiles())->toBe($before)
|
||||
->and(Storage::disk('supplier_documents')->get($path))->toBe('ALTERED');
|
||||
});
|
||||
|
||||
test('private audit HTTP preparation download and private headers preserve verified response bytes', function () {
|
||||
$this->withoutVite();
|
||||
$this->get('/auditoria/privada')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private');
|
||||
$this->post('/auditoria/privada', ['operation_key' => (string) Str::uuid(), 'families' => ['configuration']])->assertRedirect('/auditoria/privada')->assertSessionHasNoErrors();
|
||||
$export = PrivateAuditExport::query()->sole();
|
||||
$response = $this->get('/auditoria/privada/'.$export->id.'/download')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private');
|
||||
Storage::disk('local')->append($export->path, 'LATER-CHANGE');
|
||||
expect(hash('sha256', $response->streamedContent()))->toBe($export->sha256);
|
||||
$this->get('/auditoria/privada/'.$export->id.'/download')->assertStatus(409);
|
||||
DB::table('organization_memberships')->where('user_id', $this->actor->id)->update(['expires_at' => now()->subMinute()]);
|
||||
$this->get('/auditoria/privada')->assertForbidden();
|
||||
$this->get('/auditoria/privada/'.$export->id.'/download')->assertForbidden();
|
||||
});
|
||||
|
||||
test('private audit packages remain personal to their creator even within the same authorised company', function () {
|
||||
$service = app(PrivateAuditExporter::class);
|
||||
$export = $service->generate($this->actor, ['operation_key' => (string) Str::uuid(), 'families' => ['configuration']]);
|
||||
$other = User::factory()->create(['tenant_id' => $this->actor->tenant_id, 'department_id' => $this->actor->department_id,
|
||||
'purchasing_role' => PurchasingRole::Configured]);
|
||||
supplyGrant($other, ['audit_private_configuration_read']);
|
||||
$this->actingAs($other)->get('/auditoria/privada/'.$export->id.'/download')->assertNotFound();
|
||||
$this->withoutVite()->get('/auditoria/privada')->assertOk()->assertViewHas('page', fn (array $page) => $page['props']['exports']['data'] === []);
|
||||
expect(PrivateAuditExport::query()->count())->toBe(1);
|
||||
});
|
||||
Reference in New Issue
Block a user