feat: protect owner-only supply aggregates and record target CAE blocker

This commit is contained in:
2026-11-15 23:10:17 +02:00
parent e0b18413ac
commit c8957ecb9d
15 changed files with 1255 additions and 49 deletions
@@ -0,0 +1,241 @@
<?php
namespace Tests\Feature;
use App\Models\Sector;
use App\Models\User;
use App\Services\ProactiveSupply;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\TestCase;
final class ProtectedSupplyAggregateTest extends TestCase
{
use DatabaseTransactions;
private User $owner;
private array $geo = [];
private array $sectors = [];
private array $activities = [];
private int $observationSequence = 0;
private string $sourceHash;
protected function setUp(): void
{
parent::setUp();
$db = DB::selectOne('select current_database() as name,inet_server_port() as port');
$this->assertSame('sector_context_20261115_test', $db->name);
$this->assertSame(55441, (int) $db->port);
$this->withoutVite();
config(['portal.profile_access_enabled' => true, 'investor-path.enabled' => true, 'investor-path.protected_supply_enabled' => true, 'investor-path.aggregate_supply_qa_enabled' => false]);
$this->owner = User::factory()->create();
foreach (['country' => [null, 'country'], 'province' => ['country', 'province'], 'other_province' => ['country', 'province'], 'small' => ['province', 'district'], 'large' => ['province', 'district'], 'post' => ['large', 'admin_post'], 'locality_a' => ['post', 'locality'], 'locality_b' => ['post', 'locality']] as $key => [$parent, $type]) {
$id = (string) Str::uuid();
$this->geo[$key] = $id;
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent ? $this->geo[$parent] : null, 'name' => 'SYNTHETIC '.$key, 'code' => $id,
'location_type' => $type, 'source_system' => 'cartografia-workbook', 'data_classification' => 'public',
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
}
$catalog = (string) Str::uuid();
DB::table('reference_catalog_versions')->insert(['id' => $catalog, 'catalog_code' => 'qa-'.Str::random(16), 'version_no' => 1, 'source_system' => 'SYNTHETIC', 'source_version' => 'SYNTHETIC', 'source_reference' => 'SYNTHETIC', 'status' => 'published']);
foreach (['agro' => ['A', '01'], 'hotel' => ['I', '55'], 'infrastructure' => ['F', '41'], 'mining' => ['B', '07'], 'energy' => ['D', '35']] as $key => [$section, $division]) {
$sector = Sector::create(['name' => 'SYNTHETIC '.$key, 'slug' => 'qa-'.Str::lower(Str::random(16)), 'is_active' => true]);
$this->sectors[$key] = $sector->id;
$parent = null;
foreach ([$section, $division, $division.'110'] as $index => $code) {
$id = (string) Str::uuid();
DB::table('economic_activities')->insert(['id' => $id, 'parent_id' => $parent, 'sector_id' => $index === 0 ? $sector->id : null,
'catalog_version_id' => $catalog, 'code' => $code, 'label_pt_mz' => 'SYNTHETIC public '.$key.' '.$code,
'status' => 'published', 'valid_from' => '2020-01-01']);
$parent = $id;
}
$this->activities[$key] = $parent;
}
$source = hash('sha256', Str::uuid());
$this->sourceHash = $source;
DB::table('proactive_supply_sources')->insert(['sha256' => $source, 'name' => 'PRIVATE-ORIGINAL.xlsx', 'period' => '2020', 'limitations' => 'SYNTHETIC', 'receipt' => json_encode(['candidate' => 'a022ed9848b41ba342b4209414c2bbf2ebd0a7a3', 'access' => 'internal', 'synthetic' => true], JSON_THROW_ON_ERROR), 'imported_at' => now()]);
foreach (['01', '55', '41', '07', '35'] as $division) {
for ($i = 0; $i < 6; $i++) {
$this->observation($source, $division, 'large-'.$i, $this->geo[$i < 3 ? 'locality_a' : 'locality_b']);
}
for ($i = 0; $i < 4; $i++) {
$this->observation($source, $division, 'small-'.$i, $this->geo['small']);
}
for ($i = 0; $i < 5; $i++) {
$this->observation($source, $division, 'other-'.$i, $this->geo['other_province']);
}
for ($i = 0; $i < 6; $i++) {
$this->observation($source, $division, 'large-0', $this->geo['locality_a']);
}
}
}
private function observation(string $source, string $division, string $entity, string $territory): string
{
$id = hash('sha256', Str::uuid());
DB::table('proactive_supply_observations')->insert(['id' => $id, 'source_hash' => $source, 'sheet' => 'PRIVATE-SHEET', 'row_number' => ++$this->observationSequence,
'entity_key' => hash('sha256', $division.$entity), 'name' => 'PRIVATE-COMPANY-'.$entity, 'province' => 'PRIVATE', 'district' => 'PRIVATE',
'cae' => $division.'110', 'activity' => 'PRIVATE-CONTACT +258000000000', 'sector' => 'PRIVATE-RAW-SECTOR', 'source_date' => '2020', 'fingerprint' => $id,
'duplicate_of' => null, 'identity_conflict' => false, 'territory_id' => $territory, 'territory_resolution' => 'SYNTHETIC']);
return $id;
}
private function dossier(string $sector = 'agro', string $territory = 'locality_a'): string
{
$id = $this->actingAs($this->owner)->postJson('/investimentos', ['title' => 'SYNTHETIC deliberate '.$sector, 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
$v = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json('case.version');
$body = ['version' => $v, 'selection' => ['sector' => 'sector:'.$this->sectors[$sector], 'territory' => 'territory:'.$this->geo[$territory]],
'opportunity_choices' => [], 'declarations' => ['project_title' => 'SYNTHETIC deliberate '.$sector, 'products_services' => 'SYNTHETIC deliberate activity', 'currency' => 'MZN', 'investment_budget_min' => '1000000', 'investment_budget_max' => '5000000']];
$hash = $this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertOk()->json('preview_hash');
$this->postJson('/investimentos/'.$id.'/contexto/confirmar', [...$body, 'preview_hash' => $hash, 'operation_key' => (string) Str::uuid(), 'confirm' => true])->assertOk();
return $id;
}
private function aggregateSnapshot(string $id, array $extra = []): array
{
$version = $this->getJson('/investimentos/'.$id)->assertOk()->json('case.version');
return $this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $version, 'operation_key' => (string) Str::uuid(), ...$extra])->assertOk()->json('analysis');
}
public function test_five_sector_dossiers_save_recover_and_filter_only_protected_statistics(): void
{
$assignments = DB::table('portal_role_assignments')->count();
foreach (array_keys($this->sectors) as $sector) {
$id = $this->dossier($sector);
$a = $this->aggregateSnapshot($id, ['activity_id' => $this->activities[$sector]]);
$this->assertSame(1, $a['privacy_version']);
$this->assertNull($a['entities']);
$this->assertNull($a['repeated']);
$this->assertNull($a['uncertain']);
$this->assertCount(1, $a['groups']);
$this->assertSame('5–9', $a['groups'][0]['entities_band']);
$this->assertSame('10–14', $a['groups'][0]['observations_band']);
$this->assertNull($a['groups'][0]['total']);
$this->assertSame($this->geo['large'], $a['groups'][0]['scope']['id']);
$this->assertTrue($a['broader_context']);
$this->assertSame('2020', $a['source_summary']['period']);
$this->assertSame($this->activities[$sector], $a['filters']['activity_id']);
$this->assertStringNotContainsString('PRIVATE-', json_encode($a, JSON_THROW_ON_ERROR));
$v = $this->getJson('/investimentos/'.$id)->assertOk()->assertJsonCount(1, 'supply_aggregates')->assertJsonPath('supply_aggregates.0.privacy_version', 1)->json('case.version');
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $v - 1, 'operation_key' => $a['operation_key'], 'activity_id' => $this->activities[$sector]])->assertOk()->assertJsonPath('replayed', true);
$this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->assertJsonPath('prefill.simulator.investment_budget_min', '1000000')->assertJsonPath('prefill.simulator.investment_budget_max', '5000000')->assertJsonPath('prefill.simulator.project_title', 'SYNTHETIC deliberate '.$sector);
}
$this->assertSame($assignments, DB::table('portal_role_assignments')->count());
}
public function test_small_cells_and_differencing_do_not_reveal_exact_counts(): void
{
$id = $this->dossier();
$service = app(ProactiveSupply::class);
$fields = ['sector_id' => $this->sectors['agro']];
$before = DB::selectOne("select NULLIF(current_setting('app.actor_user_id',true),'') as actor,NULLIF(current_setting('app.proactive_supply_read',true),'') as scope");
$local = $service->protectedAggregate($this->owner, $id, $this->geo['locality_a'], $fields);
$otherLocal = $service->protectedAggregate($this->owner, $id, $this->geo['locality_b'], $fields);
$district = $service->protectedAggregate($this->owner, $id, $this->geo['large'], $fields);
$province = $service->protectedAggregate($this->owner, $id, $this->geo['province'], $fields);
$small = $service->protectedAggregate($this->owner, $id, $this->geo['small'], $fields);
$this->assertSame($local['groups'], $otherLocal['groups']);
$this->assertSame($local['groups'], $district['groups']);
$this->assertSame($district['groups'], $province['groups']);
$this->assertSame([], $small['groups']);
$this->assertNull($province['entities']);
$this->assertNull($district['groups'][0]['total']);
$this->assertSame((array) $before, (array) DB::selectOne("select NULLIF(current_setting('app.actor_user_id',true),'') as actor,NULLIF(current_setting('app.proactive_supply_read',true),'') as scope"));
}
public function test_owner_isolation_no_raw_access_unknown_filter_rejection_and_disabled_guard(): void
{
$id = $this->dossier();
$version = $this->getJson('/investimentos/'.$id)->json('case.version');
$body = ['version' => $version, 'operation_key' => (string) Str::uuid()];
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', [...$body, 'territory_id' => $this->geo['other_province']])->assertUnprocessable();
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', [...$body, 'activity_id' => $this->activities['hotel']])->assertUnprocessable();
$this->getJson('/minhas-oportunidades/oferta-interna')->assertForbidden();
try {
app(ProactiveSupply::class)->authorize($this->owner);
$this->fail('Aggregate capability must not grant internal source access.');
} catch (HttpException $error) {
$this->assertSame(403, $error->getStatusCode());
}
$this->actingAs(User::factory()->create())->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', $body)->assertForbidden();
$this->getJson('/investimentos/'.$id)->assertForbidden();
$this->actingAs($this->owner);
$a = $this->aggregateSnapshot($id);
config(['investor-path.protected_supply_enabled' => false]);
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', $body)->assertNotFound();
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('supply_aggregates', [])->assertJsonPath('supply_aggregate_enabled', false);
config(['investor-path.protected_supply_enabled' => true]);
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('supply_aggregates.0.operation_key', $a['operation_key']);
}
public function test_no_raw_export_no_guest_access_and_no_legacy_exact_history_disclosure(): void
{
$id = $this->dossier();
$a = $this->aggregateSnapshot($id, ['activity_id' => $this->activities['agro']]);
$version = $this->getJson('/investimentos/'.$id)->json('case.version');
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $version, 'operation_key' => $a['operation_key'], 'activity_id' => null])->assertConflict();
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $version, 'operation_key' => (string) Str::uuid(), 'export' => 'csv'])->assertUnprocessable();
$this->getJson('/investimentos/'.$id.'/contexto/oferta-agregada?export=csv')->assertStatus(405);
$row = [...$a, 'PRIVATE-RAW' => 'PRIVATE-COMPANY', 'entities' => 1];
$row['groups'][0]['total'] = 1;
$row['groups'][0]['PRIVATE-CONTACT'] = 'PRIVATE-CONTACT';
$safe = app(ProactiveSupply::class)->protectedHistory([[...$a, 'privacy_version' => 0], $row]);
$this->assertCount(1, $safe);
$this->assertNull($safe[0]['entities']);
$this->assertNull($safe[0]['groups'][0]['total']);
$this->assertStringNotContainsString('PRIVATE-', json_encode($safe, JSON_THROW_ON_ERROR));
$row['groups'][0]['entities_band'] = '1–1';
$this->assertSame([], app(ProactiveSupply::class)->protectedHistory([$row])[0]['groups']);
$this->app['auth']->forgetGuards();
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $version, 'operation_key' => (string) Str::uuid()])->assertUnauthorized();
}
public function test_unpublished_classification_is_not_presented_as_an_empty_business_result(): void
{
$sector = Sector::create(['name' => 'SYNTHETIC without public CAE', 'slug' => 'qa-'.Str::lower(Str::random(16)), 'is_active' => true]);
$this->sectors['without_cae'] = $sector->id;
$catalog = (string) Str::uuid();
DB::table('reference_catalog_versions')->insert(['id' => $catalog, 'catalog_code' => 'qa-'.Str::random(16), 'version_no' => 1, 'source_system' => 'SYNTHETIC', 'source_version' => 'SYNTHETIC', 'source_reference' => 'SYNTHETIC', 'status' => 'draft']);
DB::table('economic_activities')->insert(['id' => (string) Str::uuid(), 'sector_id' => $sector->id, 'catalog_version_id' => $catalog, 'code' => '01', 'label_pt_mz' => 'SYNTHETIC unpublished division', 'status' => 'draft', 'valid_from' => '2020-01-01']);
$id = $this->dossier('without_cae', 'locality_a');
$before = $this->actingAs($this->owner)->getJson('/investimentos/'.$id)->assertOk()->json();
$response = $this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $before['case']['version'], 'operation_key' => (string) Str::uuid(), 'activity_id' => null])->assertUnprocessable();
$this->assertStringContainsString('não significa ausência de empresas', $response->json('message'));
$after = $this->getJson('/investimentos/'.$id)->assertOk()->json();
$this->assertSame($before['case']['version'], $after['case']['version']);
$this->assertSame([], $after['supply_aggregates']);
$this->assertSame([], $after['supply_activity_options']);
}
public function test_unresolved_observation_keys_conflicts_duplicates_and_unknown_import_contracts_do_not_form_a_publishable_cohort(): void
{
$unknown = hash('sha256', Str::uuid());
DB::table('proactive_supply_sources')->insert(['sha256' => $unknown, 'name' => 'PRIVATE-FUTURE-SOURCE', 'period' => '2025', 'limitations' => 'SYNTHETIC', 'receipt' => json_encode(['candidate' => 'UNKNOWN', 'access' => 'internal'], JSON_THROW_ON_ERROR), 'imported_at' => now()]);
for ($i = 0; $i < 6; $i++) {
$id = $this->observation($this->sourceHash, '01', 'unresolved-'.$i, $this->geo['small']);
$unresolved = hash('sha256', 'unresolved:'.$this->sourceHash.'|PRIVATE-SHEET|'.$this->observationSequence);
DB::table('proactive_supply_observations')->where('id', $id)->update(['entity_key' => $unresolved]);
$conflict = $this->observation($this->sourceHash, '01', 'conflict-'.$i, $this->geo['small']);
DB::table('proactive_supply_observations')->where('id', $conflict)->update(['identity_conflict' => true]);
$duplicate = $this->observation($this->sourceHash, '01', 'duplicate-'.$i, $this->geo['small']);
DB::table('proactive_supply_observations')->where('id', $duplicate)->update(['duplicate_of' => $id]);
$this->observation($unknown, '01', 'unknown-'.$i, $this->geo['small']);
}
$id = $this->dossier('agro', 'small');
$a = $this->aggregateSnapshot($id);
$this->assertSame([], $a['groups']);
$this->assertNull($a['entities']);
$this->assertSame('2020', $a['source_summary']['period']);
$this->assertStringNotContainsString('PRIVATE-', json_encode($a, JSON_THROW_ON_ERROR));
}
}
@@ -0,0 +1,152 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
const file = new URL(
'../../resources/js/components/investment-supply-aggregate.tsx',
import.meta.url,
);
const code = ts.transpileModule(fs.readFileSync(file, 'utf8'), {
compilerOptions: {
jsx: ts.JsxEmit.ReactJSX,
module: ts.ModuleKind.CommonJS,
},
}).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => {
if (name === '@inertiajs/react') return { router: { reload() {} } };
if (name === '@/lib/investor-context') return { contextApi() {} };
if (name === '@/lib/operation-key')
return { createOperationKey: () => 'SYNTHETIC' };
if (name === './catalogue-choice-select')
return {
default: ({ label, options }) =>
React.createElement(
'label',
null,
label,
React.createElement(
'select',
null,
options.map((o) =>
React.createElement(
'option',
{ key: o.value },
o.label,
),
),
),
),
};
return require(name);
},
module,
module.exports,
);
const Component = module.exports.default;
const fixture = () => ({
privacy_version: 1,
privacy_policy: 'fixed_district_cae_division_v1',
context_revision: 1,
recorded_at: '2026-11-15',
requested_territory: { id: 'local', name: 'Local conhecido' },
scope: { id: 'district', name: 'Distrito conhecido', level: 'district' },
broader_context: true,
entities: 987654321,
repeated: 987654321,
uncertain: 987654321,
source_summary: {
label: 'Originais reservados à equipa',
period: '2020',
incomplete_periods: true,
},
filters: {
sector_id: 1,
activity_id: 'published-activity',
activity_label: 'Agricultura',
division_code: '01',
},
groups: [
{
code: '01',
label: 'Agricultura',
total: 987654321,
entities_band: '5–9',
observations_band: '10–14',
scope: {
id: 'district',
name: 'Distrito conhecido',
level: 'district',
},
first_year: 'PRIVATE-DATE',
last_year: null,
},
],
interpretation: 'Não somar grupos nem inferir procura.',
limitations: 'Cobertura desconhecida.',
privacy_notice: 'Grupos pequenos não divulgados.',
});
const render = (history) =>
renderToStaticMarkup(
React.createElement(Component, {
caseId: 'synthetic',
version: 1,
revision: 2,
history,
protectedMode: true,
activityOptions: [
{
id: 'published-activity',
code: '01110',
label: 'Agricultura',
},
],
}),
);
void test('protected presentation shows documentary identities and observations as separate bands, not raw marginal totals or dates', () => {
const html = render([fixture()]);
assert.match(html, /5–9/);
assert.match(html, /10–14/);
assert.match(html, /Identidades documentais/);
assert.match(html, /Observações consolidadas/);
assert.match(html, /Contexto distrital/);
assert.match(html, /Local conhecido/);
assert.match(html, /2020/);
assert.match(html, /períodos não indicados/);
assert.match(html, /O contexto mudou/);
assert.match(html, /Actividade a comparar/);
assert.ok(!html.includes('987654321'));
assert.ok(!html.includes('PRIVATE-DATE'));
});
void test('suppressed and absent results use the same non-inference message, never zero businesses', () => {
const row = fixture();
row.groups = [];
const html = render([row]);
assert.match(html, /podem faltar registos ou existir grupos protegidos/);
assert.match(html, /não significa ausência de empresas/);
assert.ok(!html.includes('987654321'));
});
void test('legacy exact QA snapshots are not displayed in protected mode and current protected history is recoverable', () => {
const legacy = {
...fixture(),
privacy_version: undefined,
entities: 987654321,
};
const html = render([
legacy,
fixture(),
{ ...fixture(), recorded_at: '2026-11-16' },
]);
assert.match(html, /Análise guardada/);
assert.match(html, /2026-11-16/);
assert.ok(!html.includes('987654321'));
assert.ok(!render([legacy]).includes('Identidades documentais'));
});