Files
compras/tests/Feature/AuditMetadataBlockTest.php
T
nala eb32c74c56
tests / ci (push) Waiting to run
commit compras1 2811
2026-11-28 07:11:35 +02:00

155 lines
10 KiB
PHP

<?php
use App\Services\OrganizationAccess;
use Illuminate\Support\Facades\DB;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
function auditMetadataRows(string $csv): array
{
$stream = fopen('php://temp', 'w+');
if ($stream === false) {
throw new LogicException('Synthetic CSV stream unavailable.');
}
try {
fwrite($stream, $csv);
rewind($stream);
$rows = [];
while (($row = fgetcsv($stream, 0, ';', '"', '')) !== false) {
$rows[] = $row;
}
return array_slice($rows, 2);
} finally {
fclose($stream);
}
}
beforeEach(function () {
$this->withoutVite();
$this->f = receiptFixture();
supplyGrant($this->f['receiver'], ['audit_metadata_read']);
$this->actingAs($this->f['receiver']);
$this->ids = [];
foreach (range(1, 30) as $index) {
$this->ids[] = DB::table('audit_logs')->insertGetId(['tenant_id' => $this->f['tenant']->id, 'user_id' => $this->f['receiver']->id,
'action' => $index % 3 === 0 ? 'people.selected' : 'receipt.confirmed', 'created_at' => '2026-11-01 12:00:00',
'before' => json_encode(['bank' => 'PRIVATE-BEFORE']), 'after' => json_encode(['secret' => 'PRIVATE-AFTER'])]);
}
});
test('audit metadata block paginates oldest events and exposes only the four allowed metadata fields', function () {
$before = DB::table('audit_logs')->orderBy('id')->get()->toArray();
$this->get('/auditoria/eventos')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertDontSee('PRIVATE-BEFORE')->assertDontSee('PRIVATE-AFTER')
->assertInertia(fn (Assert $p) => $p->component('audit/metadata')->where('events.total', 30)->has('events.data', 25)
->where('events.data.0.id', $this->ids[0])->where('events.data.24.id', $this->ids[24])
->missing('events.data.0.before')->missing('events.data.0.after')->missing('events.data.0.tenant_id'));
$this->get('/auditoria/eventos?page=2')->assertOk()->assertInertia(fn (Assert $p) => $p->has('events.data', 5)->where('events.data.0.id', $this->ids[25]));
expect(DB::table('audit_logs')->orderBy('id')->get()->toArray())->toEqual($before);
});
test('audit metadata block exports the complete filtered scope independently of the screen page and protects spreadsheet cells', function () {
$query = '?action=people.selected&actor_id='.$this->f['receiver']->id.'&from=2026-11-01&to=2026-11-01';
$this->get('/auditoria/eventos'.$query)->assertOk()->assertInertia(fn (Assert $p) => $p->where('events.total', 10));
$csv = $this->get('/auditoria/eventos.csv'.$query.'&page=2')->assertOk()->streamedContent();
expect(array_count_values(array_column(auditMetadataRows($csv), 2))['people.selected'])->toBe(10)
->and($csv)->not->toContain('receipt.confirmed', 'PRIVATE-BEFORE', 'PRIVATE-AFTER');
$this->get('/auditoria/eventos?to=2026-11-01')->assertOk();
$this->getJson('/auditoria/eventos?from=2026-11-02&to=2026-11-01')->assertUnprocessable();
DB::table('audit_logs')->insert(['tenant_id' => $this->f['tenant']->id, 'user_id' => $this->f['receiver']->id, 'action' => '=1+1', 'created_at' => now(), 'after' => '{}']);
$formula = $this->get('/auditoria/eventos.csv?action='.urlencode('=1+1'))->assertOk()->streamedContent();
expect($formula)->toContain("'=1+1");
$all = $this->get('/auditoria/eventos.csv')->assertOk()->streamedContent();
expect(substr_count($all, 'receipt.confirmed'))->toBe(20)->and(substr_count($all, 'people.selected'))->toBe(10);
});
test('audit metadata block requires an explicit current nonmaintenance grant even for administrators', function (string $mode) {
if ($mode === 'administrator') {
supplyGrant($this->f['issuer'], ['admin']);
$this->actingAs($this->f['issuer']);
} elseif ($mode === 'expired') {
DB::table('organization_memberships')->where('user_id', $this->f['receiver']->id)->update(['expires_at' => now()->subMinute()]);
} elseif ($mode === 'maintenance') {
DB::table('organization_memberships')->where('user_id', $this->f['receiver']->id)->update(['maintenance' => true]);
} else {
DB::table('organization_profiles')->where('tenant_id', $this->f['tenant']->id)->update(['permissions' => '[]']);
}
$this->get('/auditoria/eventos')->assertForbidden();
$this->get('/auditoria/eventos.csv')->assertForbidden();
})->with(['administrator', 'expired', 'maintenance', 'revoked']);
test('audit metadata block isolates companies and adds no grants or audit events during consultation', function () {
$foreign = receiptFixture();
supplyGrant($foreign['receiver'], ['audit_metadata_read']);
DB::table('audit_logs')->insert(['tenant_id' => $foreign['tenant']->id, 'user_id' => $foreign['receiver']->id, 'action' => 'FOREIGN-ONLY', 'created_at' => now(), 'after' => '{}']);
$before = [];
foreach (['audit_logs', 'users', 'organization_profiles', 'organization_memberships', 'approval_steps', 'stock_movements'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toArray();
}
$this->actingAs($this->f['receiver'])->get('/auditoria/eventos')->assertOk()->assertDontSee('FOREIGN-ONLY');
$this->actingAs($foreign['receiver'])->get('/auditoria/eventos')->assertOk()->assertInertia(fn (Assert $p) => $p->where('events.total', 1)->where('events.data.0.action', 'FOREIGN-ONLY'));
expect($this->get('/auditoria/eventos.csv')->assertOk()->streamedContent())->toContain('FOREIGN-ONLY')->not->toContain('people.selected');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toArray())->toEqual($rows);
}
expect(array_key_exists('audit_metadata_read', OrganizationAccess::PERMISSIONS))->toBeTrue();
});
test('auditor investigates one exact request across pages exports the full same scope and opens only an independently visible process', function () {
$own = $this->f;
$source = $own['r'];
$source->update(['number' => 'QA%_AUDIT-REQUEST']);
foreach (range(1, 131) as $index) {
DB::table('audit_logs')->insert(['tenant_id' => $own['tenant']->id, 'requisition_id' => $source->id, 'user_id' => $own['receiver']->id,
'action' => 'requisition.synthetic_checked', 'created_at' => '2026-11-01 12:00:00',
'before' => json_encode(['private' => 'PRIVATE-BEFORE']), 'after' => json_encode(['private' => 'PRIVATE-AFTER'])]);
}
DB::table('audit_logs')->insert(['tenant_id' => $own['tenant']->id, 'requisition_id' => $source->id, 'user_id' => $own['receiver']->id,
'action' => 'requisition.synthetic_checked', 'created_at' => '2026-10-31 12:00:00', 'after' => '{}']);
$foreign = receiptFixture();
$foreign['r']->update(['number' => 'FOREIGN-AUDIT-ONLY']);
// Deliberately malformed synthetic linkage must not expose another company's request through an own-tenant event.
DB::table('audit_logs')->insert(['tenant_id' => $own['tenant']->id, 'requisition_id' => $foreign['r']->id, 'user_id' => $own['receiver']->id,
'action' => 'malformed.foreign_link', 'created_at' => '2026-11-01 12:00:00', 'after' => '{}']);
$this->actingAs($own['receiver']);
$query = '?request_reference='.urlencode($source->number).'&action=requisition.synthetic_checked&actor_id='.$own['receiver']->id.'&from=2026-11-01&to=2026-11-01';
$before = [];
foreach (['audit_logs', 'requisitions', 'users', 'organization_profiles', 'organization_memberships', 'budget_entries', 'stock_movements'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->get('/auditoria/eventos'.$query)->assertOk()->assertViewHas('page', fn ($page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->where('events.total', 131)->has('events.data', 25)
->where('requestContext', null)->missing('events.data.0.before')->missing('events.data.0.after'));
$this->get('/auditoria/eventos'.$query.'&page=2')->assertInertia(fn (Assert $page) => $page->where('events.current_page', 2)->has('events.data', 25));
$csv = $this->get('/auditoria/eventos.csv'.$query.'&page=6')->assertOk()->streamedContent();
expect(auditMetadataRows($csv))->toHaveCount(131)
->and(array_unique(array_column(auditMetadataRows($csv), 2)))->toBe(['requisition.synthetic_checked'])
->and($csv)->toContain('QA%_AUDIT-REQUEST', '2026-11-01')->not->toContain('PRIVATE-BEFORE', 'PRIVATE-AFTER');
$this->get('/requisicoes/'.$source->id)->assertNotFound();
foreach (['FOREIGN-AUDIT-ONLY', 'QA', '0'] as $unknown) {
$this->get('/auditoria/eventos?request_reference='.urlencode($unknown))->assertInertia(fn (Assert $page) => $page
->where('events.total', 0)->where('requestContext', null));
}
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$auditProfile = DB::table('organization_memberships')->where('user_id', $own['receiver']->id)->value('profile_id');
supplyGrant($own['receiver'], ['finance']);
$this->get('/auditoria/eventos'.$query)->assertInertia(fn (Assert $page) => $page
->where('requestContext.number', $source->number)->where('requestContext.href', '/requisicoes/'.$source->id.'#requisition-history'));
$this->get('/requisicoes/'.$source->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('canReadAuditMetadata', true));
DB::table('organization_memberships')->where('user_id', $own['receiver']->id)->where('profile_id', $auditProfile)->update(['expires_at' => now()->subSecond()]);
$this->get('/requisicoes/'.$source->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('canReadAuditMetadata', false));
$this->get('/auditoria/eventos'.$query)->assertForbidden();
});
test('literal zero action remains an exact audit filter and malformed references are refused', function () {
DB::table('audit_logs')->insert(['tenant_id' => $this->f['tenant']->id, 'user_id' => $this->f['receiver']->id, 'action' => '0', 'created_at' => now(), 'after' => '{}']);
$this->get('/auditoria/eventos?action=0')->assertInertia(fn (Assert $page) => $page->where('events.total', 1)->where('events.data.0.action', '0'));
$this->getJson('/auditoria/eventos?request_reference='.str_repeat('x', 101))->assertUnprocessable();
$this->getJson('/auditoria/eventos?request_reference[]=QA')->assertUnprocessable();
});