"""QA-only bootstrap delta. Preserve root application, fixed candidate and service plan.""" from pathlib import Path import json,re R=Path(__file__).resolve().parent.parent P=R/'storage/app/private/investmoz-v2/portal-audit' plan=json.loads((P/'service-followup-latest.json').read_text(encoding='utf-8')) S=Path(plan['source']) assert S.name.startswith('workflow-service-followup-source-') and plan['target']['port']==55441 p=S/'app/Services/PortalSuperusers.php' t=p.read_text(encoding='utf-8') start=t.index(' public function initialize(') end=t.index(' public function requestReplacement(',start) t=t[:start]+r''' 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]); }); } ''' +t[end:] needle="abort_unless($row !== null, 404);" assert needle in t t=t.replace(needle,needle+"\n abort_unless(in_array($row->kind, ['replacement', 'elevation'], true), 403, 'Use a confirmação específica da inicialização cruzada.');",1) p.write_text(t,encoding='utf-8') p=S/'app/Services/PortalProfileInstallation.php' t=p.read_text(encoding='utf-8') t=t.replace("resource_path('js/pages/profiles/installation.tsx')];","resource_path('js/pages/profiles/installation.tsx'), resource_path('js/pages/profiles/bootstrap-confirmation.tsx'), base_path('routes/web.php')];") t=re.sub(r"'rule' => 'Escolher explicitamente.*?'\];","'rule' => 'O primeiro titular apresenta o pedido com MFA e autorização de instalação; o segundo confirma numa operação separada com MFA. Sem autoaprovação, terceira pessoa obrigatória ou escolha automática.'];",t) start=t.index(' public function bootstrap(') end=t.index(' /** @param array $data',start) t=t[:start]+r''' public function bootstrap(User $actor, array $input): array { $this->authorize($actor, true); $data = Validator::make($input, ['hash' => 'required|string|size:64', 'confirm' => 'required|accepted', 'idempotency_key' => 'required|uuid', 'first_user_id' => 'required|integer|exists:users,id', 'second_user_id' => 'required|integer|different:first_user_id|exists:users,id', 'reason' => 'required|string|min:20|max:1000'])->validate(); abort_unless((int) $data['first_user_id'] === $actor->id, 403, 'O primeiro titular deve apresentar o seu próprio pedido; não é permitido inicializar terceiros.'); return $this->receipt($actor, 'bootstrap-request', $data, function () use ($actor, $data) { $p = $this->preview($actor); abort_unless(hash_equals($p['hash'], $data['hash']), 409, 'Plano alterado.'); abort_unless($p['installed'] && $p['consistent'] && ! $p['bootstrap']['initialized'], 409, 'Schema consistente instalado e dupla não inicializada necessários.'); $second = User::findOrFail($data['second_user_id']); foreach ([$actor, $second] as $user) app(PortalSuperusers::class)->validateBootstrapHolder($user); abort_if(DB::table('portal_security_approvals')->where('kind', 'bootstrap')->whereNull('consumed_at')->where('expires_at', '>', now())->exists(), 409, 'Já existe pedido pendente. Recupere-o; não duplique a cerimónia.'); $id = (string) \Illuminate\Support\Str::uuid(); DB::table('portal_security_approvals')->insert(['id' => $id, 'kind' => 'bootstrap', 'requested_by' => $actor->id, 'subject_user_id' => $second->id, 'scope' => json_encode(['first_user_id' => $actor->id, 'second_user_id' => $second->id, 'code_hash' => $this->fingerprint(), 'target' => $p['target'], 'preview_hash' => $p['hash']], JSON_THROW_ON_ERROR), 'reason' => $data['reason'], 'expires_at' => now()->addMinutes(15), 'created_at' => now(), 'updated_at' => now()]); return ['initialized' => false, 'pending' => true, 'approval_id' => $id, 'confirmation_url' => '/management/profile-install/bootstrap/'.$id, 'holders' => [$actor->id, $second->id], 'expires_in_seconds' => 900, 'flags_changed' => false, 'privileges_granted' => false]; }); } /** Purpose-specific view; designation grants no general management access. */ public function bootstrapPreview(User $actor, string $id): array { abort_unless($actor->hasVerifiedEmail(), 403); $row = DB::table('portal_security_approvals')->where('id', $id)->where('kind', 'bootstrap')->first(); abort_unless($row, 404); abort_unless(in_array($actor->id, [(int) $row->requested_by, (int) $row->subject_user_id], true), 403, 'Apenas os dois titulares designados consultam este pedido.'); app(PortalSuperusers::class)->validateBootstrapHolder($actor); $scope = json_decode($row->scope, true, 512, JSON_THROW_ON_ERROR); $identity = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port'); $current = $scope['code_hash'] === $this->fingerprint() && $scope['target']['database'] === $identity->database && (int) $scope['target']['port'] === (int) $identity->port; $view = ['approval_id' => $id, 'requested_by' => (int) $row->requested_by, 'second_user_id' => (int) $row->subject_user_id, 'reason' => $row->reason, 'expires_at' => $row->expires_at, 'consumed' => $row->consumed_at !== null, 'code_current' => $current, 'expired' => strtotime($row->expires_at) <= time(), 'target' => $identity, 'can_confirm' => $actor->id === (int) $row->subject_user_id && $row->consumed_at === null && strtotime($row->expires_at) > time() && $current, 'mfa_confirmed_in_session' => $this->access->mfa($actor)]; $view['hash'] = hash('sha256', json_encode([$id, $row->requested_by, $row->subject_user_id, $row->scope, $row->reason, $row->expires_at], JSON_THROW_ON_ERROR)); return $view; } public function confirmBootstrap(User $actor, string $id, array $input): array { $view = $this->bootstrapPreview($actor, $id); abort_unless($actor->id === $view['second_user_id'] && $actor->id !== $view['requested_by'], 403, 'O pedido não pode ser autoaprovado.'); abort_unless($this->access->mfa($actor), 403, 'Conclua MFA nesta sessão.'); $data = Validator::make($input, ['hash' => 'required|string|size:64', 'confirm' => 'required|accepted', 'idempotency_key' => 'required|uuid', 'reason' => 'required|string|min:20|max:1000'])->validate(); $data['approval_id'] = $id; return $this->receipt($actor, 'bootstrap-confirm', $data, function () use ($actor, $id, $data) { $row = DB::table('portal_security_approvals')->where('id', $id)->lockForUpdate()->first(); $view = $this->bootstrapPreview($actor, $id); abort_unless(hash_equals($view['hash'], $data['hash']), 409, 'Pedido alterado; consulte novamente.'); abort_unless($view['can_confirm'], 409, 'Pedido expirado, já consumido ou revisão/destino alterados.'); $first = User::findOrFail($row->requested_by); $this->authorize($first); $p = $this->preview($first); abort_unless($p['installed'] && $p['consistent'] && ! $p['bootstrap']['initialized'], 409, 'Dependências ou dupla alteradas.'); app(PortalSuperusers::class)->validateBootstrapHolder($first); DB::table('portal_security_approvals')->where('id', $id)->update(['approved_by' => $actor->id, 'updated_at' => now()]); config(['portal_profiles.bootstrap_authorized' => true]); try { app(PortalSuperusers::class)->initialize($first, $actor, $actor, $id); } finally { config(['portal_profiles.bootstrap_authorized' => false]); } return ['initialized' => true, 'approval_id' => $id, 'holders' => [$first->id, $actor->id], 'version' => 1, 'flags_changed' => false]; }); } ''' +t[end:] p.write_text(t,encoding='utf-8') p=S/'app/Http/Controllers/PortalProfileInstallationController.php' t=p.read_text(encoding='utf-8').rstrip() t=t[:-1]+r''' public function bootstrapPreview(Request $request, string $id, PortalProfileInstallation $installation): JsonResponse|Response { $plan = $installation->bootstrapPreview($request->user(), $id); return $request->expectsJson() ? response()->json($plan) : Inertia::render('profiles/bootstrap-confirmation', $plan); } public function confirmBootstrap(Request $request, string $id, PortalProfileInstallation $installation): JsonResponse { return response()->json($installation->confirmBootstrap($request->user(), $id, $request->all())); } } ''' p.write_text(t,encoding='utf-8') p=S/'routes/web.php' t=p.read_text(encoding='utf-8') needle=" Route::post('/management/profile-install/bootstrap', [PortalProfileInstallationController::class, 'bootstrap']);" assert needle in t t=t.replace(needle,needle+"\n Route::get('/management/profile-install/bootstrap/{id}', [PortalProfileInstallationController::class, 'bootstrapPreview'])->whereUuid('id');\n Route::post('/management/profile-install/bootstrap/{id}/confirm', [PortalProfileInstallationController::class, 'confirmBootstrap'])->whereUuid('id');") p.write_text(t,encoding='utf-8') p=S/'resources/js/pages/profiles/installation.tsx' t=p.read_text(encoding='utf-8') t=t.replace("const [message, setMessage] = useState('');","const [message, setMessage] = useState('');\n const [confirmationUrl, setConfirmationUrl] = useState(null);") t=t.replace("'Dupla inicializada. Inicie uma nova sessão como um dos titulares designados; MFA permanece obrigatório.'","'Pedido registado, sem atribuir privilégios. O segundo titular deve autenticar-se com MFA e confirmar pelo endereço abaixo.'") t=t.replace(" if (!bootstrap)"," if (bootstrap) setConfirmationUrl(result.confirmation_url as string);\n if (!bootstrap)") t=t.replace("Inicializar apenas estas duas contas","Pedir confirmação ao segundo titular") t=t.replace('

{message}

','

{message}

\n {confirmationUrl &&

Endereço para o segundo titular: {confirmationUrl}. O primeiro titular pode consultar, mas não confirmar.

}') p.write_text(t,encoding='utf-8') p=S/'resources/js/pages/profiles/bootstrap-confirmation.tsx' p.write_text(r''' import { useState } from 'react'; import { Management, button, control } from '@/pages/management/shared'; import { profileJson } from '@/lib/profile-json'; import { createOperationKey } from '@/lib/operation-key'; type Plan = {approval_id:string;requested_by:number;second_user_id:number;reason:string;expires_at:string;consumed:boolean;expired:boolean;code_current:boolean;can_confirm:boolean;mfa_confirmed_in_session:boolean;hash:string;target:{database:string;port:number}}; export default function BootstrapConfirmation(plan:Plan) { const [key] = useState(createOperationKey); const [reason,setReason] = useState(''); const [confirmed,setConfirmed] = useState(false); const [busy,setBusy] = useState(false); const [done,setDone] = useState(plan.consumed); const [message,setMessage] = useState(''); async function confirm() { setBusy(true);setMessage(''); try { await profileJson('/management/profile-install/bootstrap/'+plan.approval_id+'/confirm',{hash:plan.hash,confirm:confirmed,idempotency_key:key,reason}); setDone(true);setMessage('Dupla inicializada por confirmação cruzada. Apenas estas duas contas foram designadas; nenhuma flag foi alterada. Inicie uma nova sessão.'); } catch(error) {setMessage(error instanceof Error?error.message:'Resposta indisponível. Recupere este pedido antes de repetir.');} finally {setBusy(false);} } return

Base {plan.target.database}:{plan.target.port}

Pedido apresentado pela conta {plan.requested_by}; confirmação reservada à conta {plan.second_user_id}.

Fundamento do pedido: {plan.reason}

Expira em {plan.expires_at}.

O pedido não atribui privilégios. A confirmação é uma operação distinta, com MFA e auditoria. Não altera a regra de substituição posterior.

{plan.expired &&

Pedido expirado. Prepare novo pedido autorizado.

} {!plan.code_current &&

Revisão ou destino alterados. Este pedido não pode ser confirmado.

} {!plan.mfa_confirmed_in_session &&

Conclua MFA nesta sessão antes de confirmar.

} {!plan.can_confirm && !done &&

Esta conta pode consultar, mas não confirmar o pedido.

}