@@ -4,41 +4,58 @@ namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Laravel\Fortify\Fortify;
|
||||
|
||||
class PortalSuperusers
|
||||
{
|
||||
public function __construct(private PortalProfileAccess $access, private PortalProfileAdministration $administration) {}
|
||||
|
||||
public function initialize(User $first, User $second, User $approver): void
|
||||
private function mfaSecret(User $user): string
|
||||
{
|
||||
// Bootstrap requires a separately authorized ceremony; never infer real holders.
|
||||
abort_unless(config('portal_profiles.bootstrap_authorized') === true, 403);
|
||||
abort_unless(count(array_unique([$first->id, $second->id, $approver->id])) === 3, 422);
|
||||
foreach ([$first, $second, $approver] as $user) {
|
||||
abort_unless($user->hasVerifiedEmail() && $user->two_factor_secret && $user->two_factor_confirmed_at, 422, 'Contas confirmadas com MFA necessário.');
|
||||
try {
|
||||
$secret = Crypt::decryptString($user->two_factor_secret);
|
||||
} catch (DecryptException) {
|
||||
abort(422, 'Configuração MFA incompatível com este ambiente. Recuperar a conta pelo procedimento existente antes da inicialização.');
|
||||
}
|
||||
abort_unless(strlen($secret) >= 16 && preg_match('/^[A-Z2-7]+=*$/', $secret), 422, 'Configuração MFA inválida.');
|
||||
abort_if(DB::table('portal_role_assignments')->where('user_id', $user->id)->where('role', 'auditor')->whereNull('revoked_at')
|
||||
->where('starts_at', '<=', now())->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))->exists(), 422, 'A restrição do Auditor impede a designação de titular nesta cerimónia.');
|
||||
// Normal Fortify enrollment serializes the string; older QA fixtures used encryptString.
|
||||
// Read either existing envelope without re-encryption, unserializing objects or changing keys.
|
||||
$plain = Fortify::currentEncrypter()->decrypt($user->two_factor_secret, false);
|
||||
abort_unless(is_string($plain), 422, 'Configuração MFA inválida.');
|
||||
if (preg_match('/^s:[0-9]+:"([A-Z2-7]+=*)";$/D', $plain, $matches)
|
||||
&& serialize($matches[1]) === $plain) {
|
||||
return $matches[1];
|
||||
}
|
||||
abort_unless($this->access->mfa($approver), 403);
|
||||
DB::transaction(function () use ($first, $second, $approver) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(101026, 40001)');
|
||||
$existing = DB::table('portal_superuser_pair')->where('id', 1)->first();
|
||||
if ($existing) {
|
||||
abort_unless((int) $existing->first_user_id === $first->id && (int) $existing->second_user_id === $second->id, 409, 'Inicialização já realizada. Use substituição atómica.');
|
||||
|
||||
return;
|
||||
}
|
||||
DB::table('portal_superuser_pair')->insert(['id' => 1, 'first_user_id' => $first->id, 'second_user_id' => $second->id, 'approved_by' => $approver->id, 'created_at' => now(), 'updated_at' => now()]);
|
||||
$this->access->audit($approver, 'superuser_pair_initialized', ['holders' => [$first->id, $second->id], 'version' => 1]);
|
||||
return $plain;
|
||||
}
|
||||
|
||||
|
||||
public function validateBootstrapHolder(User $user): void
|
||||
{
|
||||
abort_unless($user->hasVerifiedEmail() && $user->two_factor_secret && $user->two_factor_confirmed_at, 422, 'Conta confirmada com MFA necessário.');
|
||||
try {
|
||||
$secret = $this->mfaSecret($user);
|
||||
} catch (DecryptException) {
|
||||
abort(422, 'Configuração MFA incompatível com este ambiente. Recuperar pelo procedimento existente.');
|
||||
}
|
||||
abort_unless(strlen($secret) >= 16 && preg_match('/^[A-Z2-7]+=*$/', $secret), 422, 'Configuração MFA inválida.');
|
||||
abort_if(DB::table('portal_role_assignments')->where('user_id', $user->id)->where('role', 'auditor')->whereNull('revoked_at')
|
||||
->where('starts_at', '<=', now())->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))->exists(), 422, 'A restrição do Auditor impede a designação nesta cerimónia.');
|
||||
}
|
||||
|
||||
public function initialize(User $first, User $second, User $confirmer, string $approvalId): void
|
||||
{
|
||||
abort_unless(config('portal_profiles.bootstrap_authorized') === true, 403);
|
||||
abort_unless($first->id !== $second->id && $confirmer->id === $second->id, 403, 'Confirmação pelo segundo titular, distinta do pedido.');
|
||||
foreach ([$first, $second] as $user) $this->validateBootstrapHolder($user);
|
||||
abort_unless($this->access->mfa($confirmer), 403);
|
||||
DB::transaction(function () use ($first, $second, $confirmer, $approvalId) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(101026, 40001)');
|
||||
$approval = DB::table('portal_security_approvals')->where('id', $approvalId)->lockForUpdate()->first();
|
||||
abort_unless($approval && $approval->kind === 'bootstrap' && (int) $approval->requested_by === $first->id
|
||||
&& (int) $approval->subject_user_id === $second->id && (int) $approval->approved_by === $confirmer->id
|
||||
&& $approval->consumed_at === null && strtotime($approval->expires_at) > time(), 409, 'Pedido cruzado inválido, expirado ou já consumido.');
|
||||
abort_if(DB::table('portal_superuser_pair')->where('id', 1)->exists(), 409, 'Dupla existente; use substituição atómica.');
|
||||
DB::table('portal_superuser_pair')->insert(['id' => 1, 'first_user_id' => $first->id, 'second_user_id' => $second->id, 'approved_by' => $confirmer->id, 'created_at' => now(), 'updated_at' => now()]);
|
||||
DB::table('portal_security_approvals')->where('id', $approvalId)->update(['consumed_at' => now(), 'updated_at' => now()]);
|
||||
$this->access->audit($confirmer, 'superuser_pair_initialized', ['approval_id' => $approvalId, 'requested_by' => $first->id, 'holders' => [$first->id, $second->id], 'version' => 1]);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -69,6 +86,7 @@ class PortalSuperusers
|
||||
DB::transaction(function () use ($actor, $id) {
|
||||
$row = DB::table('portal_security_approvals')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($row !== null, 404);
|
||||
abort_unless(in_array($row->kind, ['replacement', 'elevation'], true), 403, 'Use a confirmação específica da inicialização cruzada.');
|
||||
abort_if((int) $row->requested_by === $actor->id || (int) $row->subject_user_id === $actor->id, 403, 'Aprovação independente necessária.');
|
||||
abort_unless($row->consumed_at === null && strtotime($row->expires_at) > time() && $row->approved_by === null, 409);
|
||||
DB::table('portal_security_approvals')->where('id', $id)->update(['approved_by' => $actor->id, 'updated_at' => now()]);
|
||||
@@ -103,7 +121,11 @@ class PortalSuperusers
|
||||
public function requestElevation(User $actor, string $action, ?int $recordId, string $reason): string
|
||||
{
|
||||
$this->administration->administrative($actor);
|
||||
abort_unless(in_array($action, ['create', 'edit', 'validate', 'publish', 'archive'], true) && mb_strlen($reason) >= 20 && mb_strlen($reason) <= 1000, 422);
|
||||
abort_unless(in_array($action, ['view', 'create', 'edit', 'validate', 'publish', 'archive'], true) && mb_strlen($reason) >= 20 && mb_strlen($reason) <= 1000, 422);
|
||||
if ($action === 'view') {
|
||||
$record = $recordId === null ? null : \App\Models\Opportunity::find($recordId);
|
||||
abort_unless($record && $this->access->hasOperationalReadScope($actor, $record) && ! $this->access->has($actor, 'auditor'), 403, 'A consulta exige perfil operacional com âmbito válido; a elevação não o substitui.');
|
||||
}
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('portal_security_approvals')->insert(['id' => $id, 'kind' => 'elevation', 'requested_by' => $actor->id, 'subject_user_id' => $actor->id,
|
||||
'scope' => json_encode(['action' => $action, 'record_id' => $recordId], JSON_THROW_ON_ERROR), 'reason' => $reason,
|
||||
|
||||
Reference in New Issue
Block a user