feat: verify active opportunity management and prepare versioned resources
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Jobs\ScanDocumentForMalware;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class OpportunityImageProcessor
|
||||
{
|
||||
/** @param array<string,mixed> $input */
|
||||
public function prepare(User $actor, int $opportunityId, string $id, array $input): void
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
abort_unless(function_exists('imagecreatefromstring') && function_exists('imagewebp'), 423, 'GD/WebP não disponível neste processo. Original e metadados preservados; processamento pendente.');
|
||||
$data = validator($input, ['etag' => 'required|string|size:64', 'version' => 'required|integer|min:1', 'reason' => 'required|string|min:20|max:1000'])->validate();
|
||||
$stored = [];
|
||||
$documents = [];
|
||||
try {
|
||||
DB::transaction(function () use ($actor, $opportunityId, $id, $data, &$stored, &$documents) {
|
||||
$o = Opportunity::withTrashed()->whereKey($opportunityId)->lockForUpdate()->firstOrFail();
|
||||
abort_if($o->trashed() || $o->status === 'archived', 409, 'Restaure antes de processar.');
|
||||
abort_unless(hash_equals(app(OpportunityManagement::class)->etag($o), $data['etag']), 409, 'Conflito de versão; preserve os dados.');
|
||||
$image = DB::table('opportunity_images')->where('opportunity_id', $opportunityId)->where('id', $id)->whereNull('deleted_at')->lockForUpdate()->first();
|
||||
abort_unless($image !== null, 404);
|
||||
abort_unless((int) $image->version === (int) $data['version'], 409, 'Imagem alterada.');
|
||||
$doc = DB::table('documents')->where('id', $image->document_id)->first();
|
||||
abort_unless($doc && $doc->status === 'active' && $doc->malware_scan_status === 'clean' && hash_equals(trim($doc->sha256), (string) $doc->malware_scanned_sha256), 423, 'Scan do original pendente ou inseguro.');
|
||||
$disk = Storage::disk('local');
|
||||
$bytes = $doc->storage_encryption === 'laravel' ? Crypt::decryptString($disk->get($doc->storage_key)) : $disk->get($doc->storage_key);
|
||||
abort_unless(hash_equals(trim($doc->sha256), hash('sha256', $bytes)), 409, 'Integridade divergente.');
|
||||
$size = @getimagesizefromstring($bytes);
|
||||
abort_unless($size && $size[0] >= 400 && $size[1] >= 400 && $size[0] * $size[1] <= 40000000, 422, 'Dimensões inválidas ou imagem excessiva para processamento seguro.');
|
||||
$decoded = @imagecreatefromstring($bytes);
|
||||
abort_unless($decoded !== false, 422, 'Não foi possível descodificar a imagem.');
|
||||
$derivatives = [];
|
||||
try {
|
||||
foreach (array_unique(array_map(fn ($width) => min($width, $size[0]), [320, 640, 1280])) as $width) {
|
||||
$w = min($width, $size[0]);
|
||||
$h = max(1, (int) round($size[1] * $w / $size[0]));
|
||||
$canvas = imagecreatetruecolor($w, $h);
|
||||
imagealphablending($canvas, false);
|
||||
imagesavealpha($canvas, true);
|
||||
imagecopyresampled($canvas, $decoded, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);
|
||||
ob_start();
|
||||
$encoded = imagewebp($canvas, null, 85);
|
||||
$webp = ob_get_clean();
|
||||
imagedestroy($canvas);
|
||||
abort_unless($encoded && is_string($webp), 500, 'Falha ao gerar WebP.');
|
||||
$documentId = (string) Str::uuid();
|
||||
$key = 'opportunity-resources/'.$documentId;
|
||||
abort_unless($disk->put($key, Crypt::encryptString($webp)) === true, 500, 'Falha ao guardar derivada cifrada.');
|
||||
$stored[] = $key;
|
||||
$documents[] = $documentId;
|
||||
DB::table('documents')->insert(['id' => $documentId, 'source_system' => 'opportunity-image-derivatives', 'file_name' => 'image-'.$width.'.webp', 'media_type' => 'image/webp', 'storage_key' => $key, 'storage_encryption' => 'laravel', 'sha256' => hash('sha256', $webp), 'status' => 'quarantined', 'data_classification' => 'restricted', 'size_bytes' => strlen($webp), 'uploaded_by' => $actor->id]);
|
||||
$derivatives[] = ['document_id' => $documentId, 'width' => $w, 'height' => $h];
|
||||
}
|
||||
} finally {
|
||||
imagedestroy($decoded);
|
||||
}
|
||||
$payload = json_decode($image->payload, true);
|
||||
$payload['derivatives'] = $derivatives;
|
||||
$payload['derived_from_sha256'] = trim($doc->sha256);
|
||||
$payload['processing_status'] = 'generated_without_original_metadata';
|
||||
DB::table('opportunity_images')->where('id', $id)->update(['payload' => json_encode($payload), 'version' => $image->version + 1, 'updated_at' => now()]);
|
||||
DB::table('audit_events')->insert(['source_system' => 'opportunity-resources', 'entity_type' => 'images', 'action' => 'derivatives_prepared', 'actor_user_id' => $actor->id, 'data_classification' => 'restricted', 'before_data' => json_encode(['snapshot' => Crypt::encryptString(json_encode($image, JSON_THROW_ON_ERROR))]), 'after_data' => json_encode(['opportunity_id' => $opportunityId, 'resource_id' => $id, 'version' => $image->version + 1, 'reason' => Crypt::encryptString($data['reason']), 'snapshot' => Crypt::encryptString(json_encode(DB::table('opportunity_images')->where('id', $id)->first(), JSON_THROW_ON_ERROR))])]);
|
||||
$o->management_version++;
|
||||
$o->save();
|
||||
});
|
||||
} catch (\Throwable $error) {
|
||||
foreach ($stored as $key) {
|
||||
Storage::disk('local')->delete($key);
|
||||
}
|
||||
throw $error;
|
||||
}
|
||||
// Each new byte stream receives its own scan; no automatic clean result inherited from the original.
|
||||
foreach ($documents as $documentId) {
|
||||
try {
|
||||
ScanDocumentForMalware::dispatch($documentId)->afterCommit();
|
||||
} catch (\Throwable) {
|
||||
DB::table('documents')->where('id', $documentId)->update(['malware_scan_status' => 'failed', 'malware_failure_reason' => 'queue_dispatch_failed']);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ class OpportunityResourceInstallation
|
||||
|
||||
public function fingerprint(): string
|
||||
{
|
||||
$files = [__FILE__, app_path('Services/OpportunityResources.php'), app_path('Http/Controllers/OpportunityResourceController.php'), app_path('Jobs/ScanDocumentForMalware.php'), database_path('migrations/'.self::MIGRATION.'.php'), base_path('routes/web.php'), resource_path('js/pages/management/opportunity-resources.tsx'), resource_path('js/pages/management/opportunity-draft.tsx'), resource_path('js/pages/management/opportunity-install.tsx')];
|
||||
$files = [__FILE__, app_path('Services/OpportunityImageProcessor.php'), app_path('Services/OpportunityResources.php'), app_path('Http/Controllers/OpportunityResourceController.php'), app_path('Http/Controllers/OpportunityManagementController.php'), app_path('Jobs/ScanDocumentForMalware.php'), database_path('migrations/'.self::MIGRATION.'.php'), base_path('routes/web.php'), resource_path('js/pages/management/opportunity-resources.tsx'), resource_path('js/pages/management/opportunity-draft.tsx'), resource_path('js/pages/management/opportunity-install.tsx')];
|
||||
|
||||
return hash('sha256', json_encode(array_map(fn ($file) => hash_file('sha256', $file), $files), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
@@ -21,7 +21,7 @@ class OpportunityResourceInstallation
|
||||
public function preview(): array
|
||||
{
|
||||
$path = storage_path('app/private/investmoz-v2/opportunity-resources-activation-proof.json');
|
||||
$proof = is_file($path) ? json_decode(file_get_contents($path), true) : [];
|
||||
$proof = is_file($path) ? json_decode(file_get_contents($path) ?: '{}', true) : [];
|
||||
$identity = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
$code = $this->fingerprint();
|
||||
$ready = ($proof['restore_verified'] ?? false) && ($proof['compatibility_verified'] ?? false) && ($proof['reversal_verified'] ?? false) && ($proof['qa_passed'] ?? false) && ($proof['code_hash'] ?? '') === $code && ($proof['target']['database'] ?? '') === $identity->database && (int) ($proof['target']['port'] ?? 0) === (int) $identity->port && strtotime($proof['verified_at'] ?? '') >= time() - 86400 && is_file($proof['dump_path'] ?? '') && hash_file('sha256', $proof['dump_path']) === ($proof['sha256'] ?? null);
|
||||
|
||||
@@ -32,7 +32,7 @@ class OpportunityResources
|
||||
return 'opportunity_'.($kind === 'locations' ? 'location_drafts' : $kind);
|
||||
}
|
||||
|
||||
/** @return list<object> */
|
||||
/** @return list<\stdClass> */
|
||||
public function listing(int $opportunityId, string $kind): array
|
||||
{
|
||||
$query = DB::table($this->table($kind))->where('opportunity_id', $opportunityId)->orderBy('created_at')->orderBy('id');
|
||||
@@ -44,11 +44,11 @@ class OpportunityResources
|
||||
}
|
||||
}
|
||||
|
||||
return $rows;
|
||||
return array_values($rows);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, int $opportunityId, string $kind, array $input, ?UploadedFile $file = null, ?string $id = null): object
|
||||
public function save(User $actor, int $opportunityId, string $kind, array $input, ?UploadedFile $file = null, ?string $id = null): \stdClass
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
abort_unless($this->installed(), 503);
|
||||
@@ -56,7 +56,7 @@ class OpportunityResources
|
||||
$data = Validator::make($input, [
|
||||
'etag' => 'required|string|size:64', 'version' => ($id ? 'required' : 'nullable').'|integer|min:1',
|
||||
'creation_key' => ($id ? 'nullable' : 'required').'|uuid', 'reason' => 'required|string|min:20|max:1000',
|
||||
'payload' => 'required|array',
|
||||
'payload' => 'present|array',
|
||||
])->validate();
|
||||
$payload = $this->validatePayload($kind, $data['payload'], $opportunityId);
|
||||
$stored = null;
|
||||
@@ -73,6 +73,14 @@ class OpportunityResources
|
||||
abort_if($id && ! $record, 404);
|
||||
abort_if($record && ($record->deleted_at || (int) $record->version !== (int) $data['version']), 409, 'Recurso alterado ou eliminado; preserve o preenchimento e reveja a versão.');
|
||||
$resourceId = $id ?? $data['creation_key'];
|
||||
if ($record && $kind === 'images' && ! $file) {
|
||||
$previous = json_decode($record->payload, true);
|
||||
foreach (['derivatives', 'derived_from_sha256', 'processing_status'] as $computed) {
|
||||
if (isset($previous[$computed])) {
|
||||
$payload[$computed] = $previous[$computed];
|
||||
}
|
||||
}
|
||||
}
|
||||
abort_if(! $id && DB::table($table)->where('id', $resourceId)->exists(), 409, 'Esta criação já foi registada; recupere o recurso existente.');
|
||||
$active = DB::table($table)->where('opportunity_id', $opportunityId)->whereNull('deleted_at');
|
||||
abort_if(! $id && $active->count() >= ($kind === 'locations' ? 50 : ($kind === 'images' ? 20 : 100)), 422, 'Limite de recursos atingido.');
|
||||
@@ -81,7 +89,7 @@ class OpportunityResources
|
||||
foreach ($others as $other) {
|
||||
$otherPayload = json_decode($other->payload, true);
|
||||
$keys = ['province_id', 'district_id', 'admin_post_id', 'locality_id', 'role', 'operational_unit'];
|
||||
abort_if(array_intersect_key($payload, array_flip($keys)) == array_intersect_key($otherPayload, array_flip($keys)), 422, 'Esta localização, papel e unidade já existem.');
|
||||
abort_if(array_map(fn ($key) => $payload[$key] ?? null, $keys) === array_map(fn ($key) => $otherPayload[$key] ?? null, $keys), 422, 'Esta localização, papel e unidade já existem.');
|
||||
abort_if(($payload['is_primary'] ?? false) && ($otherPayload['is_primary'] ?? false), 422, 'Já existe localização principal; altere a anterior antes de escolher outra.');
|
||||
}
|
||||
}
|
||||
@@ -99,7 +107,7 @@ class OpportunityResources
|
||||
throw ValidationException::withMessages(['file' => 'Os mesmos bytes já estão ligados a esta oportunidade; recupere o recurso, sem duplicar.']);
|
||||
}
|
||||
$original = Storage::disk('local')->get($stored);
|
||||
abort_unless(Storage::disk('local')->put($stored, Crypt::encryptString($original)), 500, 'Falha ao cifrar original.');
|
||||
abort_unless(Storage::disk('local')->put($stored, Crypt::encryptString($original)) === true, 500, 'Falha ao cifrar original.');
|
||||
DB::table('documents')->insert(['id' => $documentId, 'source_system' => 'opportunity-resources', 'file_name' => basename($file->getClientOriginalName()), 'media_type' => $file->getMimeType(), 'storage_key' => $stored, 'storage_encryption' => 'laravel', 'sha256' => $hash, 'status' => 'quarantined', 'data_classification' => 'restricted', 'size_bytes' => $file->getSize(), 'uploaded_by' => $actor->id]);
|
||||
}
|
||||
$values = ['payload' => json_encode($payload, JSON_THROW_ON_ERROR), 'version' => $record ? $record->version + 1 : 1, 'updated_at' => now()];
|
||||
@@ -115,9 +123,6 @@ class OpportunityResources
|
||||
$this->audit($actor, $kind, $record, $after, $data['reason'], 'saved');
|
||||
$opportunity->management_version++;
|
||||
$opportunity->save();
|
||||
if ($documentId) {
|
||||
ScanDocumentForMalware::dispatch($documentId)->afterCommit();
|
||||
}
|
||||
|
||||
return $after;
|
||||
});
|
||||
@@ -128,6 +133,14 @@ class OpportunityResources
|
||||
throw $error;
|
||||
}
|
||||
|
||||
if ($documentId) {
|
||||
try {
|
||||
ScanDocumentForMalware::dispatch($documentId)->afterCommit();
|
||||
} catch (\Throwable) {
|
||||
DB::table('documents')->where('id', $documentId)->where('malware_scan_status', '!=', 'clean')->update(['status' => 'quarantined', 'malware_scan_status' => 'failed', 'malware_failure_reason' => 'queue_dispatch_failed', 'updated_at' => now()]);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
@@ -135,16 +148,18 @@ class OpportunityResources
|
||||
public function lifecycle(User $actor, int $opportunityId, string $kind, string $id, array $input): void
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
abort_unless($this->installed(), 503);
|
||||
$data = Validator::make($input, ['etag' => 'required|string|size:64', 'version' => 'required|integer|min:1', 'action' => 'required|in:delete,restore', 'reason' => 'required|string|min:20|max:1000', 'confirm' => 'required|accepted'])->validate();
|
||||
DB::transaction(function () use ($actor, $opportunityId, $kind, $id, $data) {
|
||||
$opportunity = $this->lock($opportunityId, $data['etag']);
|
||||
$table = $this->table($kind);
|
||||
$record = DB::table($table)->where('id', $id)->where('opportunity_id', $opportunityId)->lockForUpdate()->first();
|
||||
abort_unless($record, 404);
|
||||
abort_unless($record !== null, 404);
|
||||
abort_if((int) $record->version !== (int) $data['version'], 409, 'Versão alterada.');
|
||||
abort_if(($data['action'] === 'delete') === ($record->deleted_at !== null), 409, 'Estado já alterado.');
|
||||
$payload = json_decode($record->payload, true);
|
||||
if ($data['action'] === 'restore') {
|
||||
abort_if(DB::table($table)->where('opportunity_id', $opportunityId)->whereNull('deleted_at')->count() >= ($kind === 'locations' ? 50 : ($kind === 'images' ? 20 : 100)), 422, 'Limite de recursos ativos atingido; reconcilie antes de restaurar.');
|
||||
$this->validatePayload($kind, $payload, $opportunityId);
|
||||
// Restoration never silently reclaims a primary/cover/order occupied by another resource.
|
||||
if ($kind === 'images') {
|
||||
@@ -153,6 +168,11 @@ class OpportunityResources
|
||||
}
|
||||
if ($kind === 'locations') {
|
||||
$payload['is_primary'] = false;
|
||||
$keys = ['province_id', 'district_id', 'admin_post_id', 'locality_id', 'role', 'operational_unit'];
|
||||
foreach (DB::table($table)->where('opportunity_id', $opportunityId)->whereNull('deleted_at')->get() as $other) {
|
||||
$otherPayload = json_decode($other->payload, true);
|
||||
abort_if(array_map(fn ($key) => $payload[$key] ?? null, $keys) === array_map(fn ($key) => $otherPayload[$key] ?? null, $keys), 422, 'Outra localização ocupa esta combinação; reconcilie antes de restaurar.');
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($kind === 'locations' && $data['action'] === 'delete') {
|
||||
@@ -160,6 +180,11 @@ class OpportunityResources
|
||||
abort_if((json_decode($image->payload, true)['location_id'] ?? null) === $id, 422, 'Uma imagem usa esta localização; corrija a ligação antes de excluir.');
|
||||
}
|
||||
}
|
||||
if ($kind === 'documents' && $data['action'] === 'delete') {
|
||||
foreach (DB::table('opportunity_images')->where('opportunity_id', $opportunityId)->whereNull('deleted_at')->get() as $image) {
|
||||
abort_if((json_decode($image->payload, true)['rights_document_id'] ?? null) === $id, 422, 'Uma imagem depende deste comprovativo; corrija a ligação antes de excluir.');
|
||||
}
|
||||
}
|
||||
DB::table($table)->where('id', $id)->update(['deleted_at' => $data['action'] === 'delete' ? now() : null, 'version' => $record->version + 1, 'payload' => json_encode($payload), 'updated_at' => now()]);
|
||||
$this->audit($actor, $kind, $record, DB::table($table)->where('id', $id)->first(), $data['reason'], $data['action']);
|
||||
$opportunity->management_version++;
|
||||
@@ -224,7 +249,7 @@ class OpportunityResources
|
||||
if (! $size || $size[0] < 400 || $size[1] < 400) {
|
||||
throw ValidationException::withMessages(['file' => 'Imagem inválida ou inferior a 400 × 400 píxeis.']);
|
||||
}
|
||||
$bytes = file_get_contents($file->getRealPath());
|
||||
$bytes = file_get_contents($file->getRealPath()) ?: '';
|
||||
if (preg_match('/<\?(?:php|=)|<script\b/i', $bytes) || (str_contains($bytes, 'acTL') && $file->getMimeType() === 'image/png') || (str_contains($bytes, 'ANIM') && $file->getMimeType() === 'image/webp')) {
|
||||
throw ValidationException::withMessages(['file' => 'Imagem animada ou com conteúdo executável não permitida.']);
|
||||
}
|
||||
@@ -248,8 +273,8 @@ class OpportunityResources
|
||||
return [$key, $id];
|
||||
}
|
||||
|
||||
private function audit(User $actor, string $kind, ?object $before, object $after, string $reason, string $action): void
|
||||
private function audit(User $actor, string $kind, ?\stdClass $before, \stdClass $after, string $reason, string $action): void
|
||||
{
|
||||
DB::table('audit_events')->insert(['source_system' => 'opportunity-resources', 'entity_type' => $kind, 'actor_user_id' => $actor->id, 'action' => $action, 'data_classification' => 'restricted', 'before_data' => json_encode(['snapshot' => Crypt::encryptString(json_encode($before))]), 'after_data' => json_encode(['opportunity_id' => $after->opportunity_id, 'resource_id' => $after->id, 'version' => $after->version, 'reason' => Crypt::encryptString($reason), 'snapshot' => Crypt::encryptString(json_encode($after))])]);
|
||||
DB::table('audit_events')->insert(['source_system' => 'opportunity-resources', 'entity_type' => $kind, 'actor_user_id' => $actor->id, 'action' => $action, 'data_classification' => 'restricted', 'before_data' => json_encode(['snapshot' => Crypt::encryptString(json_encode($before, JSON_THROW_ON_ERROR))]), 'after_data' => json_encode(['opportunity_id' => $after->opportunity_id, 'resource_id' => $after->id, 'version' => $after->version, 'reason' => Crypt::encryptString($reason), 'snapshot' => Crypt::encryptString(json_encode($after, JSON_THROW_ON_ERROR))])]);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user