diff --git a/.env.example b/.env.example index feaf436..8d5d11a 100644 --- a/.env.example +++ b/.env.example @@ -72,8 +72,10 @@ COMMON_PAYABLES_HISTORY_ENABLED=false COMMON_PAYABLES_HISTORY_DECISIONS_ENABLED=false PAYABLE_SOURCE_INSTANCE= -# Adesão voluntária MFA, só depois da migração e validação da instalação. -SGC_TWO_FACTOR_ENABLED=false +# MFA ligado: obrigatório para as funções em SGC_MFA_REQUIRED_FUNCTIONS, voluntário +# para os restantes perfis (decisão de 30/11/2026). Exige a migração dos campos MFA. +SGC_TWO_FACTOR_ENABLED=true +SGC_MFA_REQUIRED_FUNCTIONS=admin,finance # Âmbito da v1: só o núcleo de compras. Módulos laterais desligados por omissão; # activar por instalação quando contratados (ver config/modules.php). diff --git a/app/Http/Controllers/Settings/SecurityController.php b/app/Http/Controllers/Settings/SecurityController.php index b882285..aeb25fb 100644 --- a/app/Http/Controllers/Settings/SecurityController.php +++ b/app/Http/Controllers/Settings/SecurityController.php @@ -3,6 +3,7 @@ namespace App\Http\Controllers\Settings; use App\Http\Controllers\Controller; +use App\Http\Middleware\RequireTwoFactorForSensitiveRoles; use App\Http\Requests\Settings\PasswordUpdateRequest; use App\Http\Requests\Settings\TwoFactorAuthenticationRequest; use App\Models\User; @@ -41,6 +42,7 @@ class SecurityController extends Controller 'twoFactorEnabled' => $actor->hasEnabledTwoFactorAuthentication(), 'twoFactorPending' => $actor->two_factor_secret !== null && ! $actor->hasEnabledTwoFactorAuthentication(), 'requiresConfirmation' => Fortify::confirmsTwoFactorAuthentication(), + 'mfaRequired' => RequireTwoFactorForSensitiveRoles::requiredFor($actor), ]; } diff --git a/app/Http/Middleware/RequireTwoFactorForSensitiveRoles.php b/app/Http/Middleware/RequireTwoFactorForSensitiveRoles.php new file mode 100644 index 0000000..8e12cd1 --- /dev/null +++ b/app/Http/Middleware/RequireTwoFactorForSensitiveRoles.php @@ -0,0 +1,47 @@ +is(...self::ALLOWED)) { + return $next($request); + } + if ($request->expectsJson()) { + abort(403, 'Configure a autenticação de dois factores antes de continuar.'); + } + + return redirect()->route('security.edit'); + } + + public static function applies(Request $request): bool + { + $user = $request->user('web'); + + return $user instanceof User + && Features::enabled(Features::twoFactorAuthentication()) + && ! EvaluationNavigation::local($request) + && self::requiredFor($user); + } + + /** O utilizador tem uma função que exige MFA e ainda não o confirmou. */ + public static function requiredFor(User $user): bool + { + $functions = array_values(array_filter((array) config('mfa.required_functions', []), 'is_string')); + + return $user->two_factor_confirmed_at === null && $functions !== [] && $user->hasFunctions($functions); + } +} diff --git a/bootstrap/app.php b/bootstrap/app.php index 4b7b340..51c1046 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -6,6 +6,7 @@ use App\Http\Middleware\HandleAppearance; use App\Http\Middleware\HandleInertiaRequests; use App\Http\Middleware\PrivateTwoFactorResponse; use App\Http\Middleware\PublicDevelopmentNavigation; +use App\Http\Middleware\RequireTwoFactorForSensitiveRoles; use App\Services\EvaluationNavigation; use Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests; use Illuminate\Foundation\Application; @@ -34,6 +35,7 @@ return Application::configure(basePath: dirname(__DIR__)) EnterLocalEvaluation::class, HandleAppearance::class, HandleInertiaRequests::class, + RequireTwoFactorForSensitiveRoles::class, PrivateTwoFactorResponse::class, AddLinkHeadersForPreloadedAssets::class, ]); diff --git a/config/fortify.php b/config/fortify.php index 5e7b166..8e1e285 100644 --- a/config/fortify.php +++ b/config/fortify.php @@ -146,7 +146,7 @@ return [ 'features' => [ Features::registration(), Features::resetPasswords(), - ...(env('SGC_TWO_FACTOR_ENABLED', false) ? [Features::twoFactorAuthentication([ + ...(env('SGC_TWO_FACTOR_ENABLED', true) ? [Features::twoFactorAuthentication([ 'confirm' => true, 'confirmPassword' => true, ])] : []), diff --git a/config/mfa.php b/config/mfa.php new file mode 100644 index 0000000..a3e5e4c --- /dev/null +++ b/config/mfa.php @@ -0,0 +1,11 @@ + array_values(array_filter(array_map('trim', explode(',', (string) env('SGC_MFA_REQUIRED_FUNCTIONS', 'admin,finance'))))), +]; diff --git a/phpunit.xml b/phpunit.xml index 332adba..274a5f2 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -27,6 +27,8 @@ + + diff --git a/resources/js/pages/settings/security.tsx b/resources/js/pages/settings/security.tsx index 879899e..56cf45a 100644 --- a/resources/js/pages/settings/security.tsx +++ b/resources/js/pages/settings/security.tsx @@ -15,6 +15,7 @@ type Props = { canManageTwoFactor?: boolean; twoFactorEnabled?: boolean; twoFactorPending?: boolean; + mfaRequired?: boolean; }; export default function Security(props: Props) { @@ -28,6 +29,16 @@ export default function Security(props: Props) {

Segurança da conta

+ {props.mfaRequired && ( +
+ O seu perfil tem acesso a funções sensíveis. Active e + confirme a autenticação de dois factores para continuar + a usar o SGC. +
+ )} {props.canManageTwoFactor && ( create(['name' => 'Empresa MFA']); + $this->department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => 'Operações']); + $this->user = fn (PurchasingRole $role) => User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => $role]); +}); + +test('sensitive roles without confirmed MFA are sent to the security settings', function (PurchasingRole $role) { + $this->actingAs(($this->user)($role)); + $this->get('/dashboard')->assertRedirect('/settings/security'); + $this->get('/facturas')->assertRedirect('/settings/security'); + $this->getJson('/requisicoes')->assertForbidden(); +})->with([PurchasingRole::Admin, PurchasingRole::Finance]); + +test('the security settings, password confirmation and logout stay reachable while MFA is pending', function () { + $this->actingAs(($this->user)(PurchasingRole::Finance)); + $this->get('/user/confirm-password')->assertOk(); + $this->withSession(['auth.password_confirmed_at' => time()])->get('/settings/security')->assertOk() + ->assertInertia(fn (Assert $page) => $page->component('settings/security')->where('mfaRequired', true)->where('canManageTwoFactor', true)); + $this->post('/logout')->assertRedirect(); + $this->assertGuest(); +}); + +test('confirmed MFA unlocks the application for sensitive roles', function () { + $finance = ($this->user)(PurchasingRole::Finance); + app(EnableTwoFactorAuthentication::class)($finance); + $finance->forceFill(['two_factor_confirmed_at' => now()])->save(); + $this->actingAs($finance)->get('/dashboard')->assertOk(); +}); + +test('other roles keep MFA voluntary', function () { + $this->actingAs(($this->user)(PurchasingRole::Requester))->get('/dashboard')->assertOk(); +}); + +test('nothing is enforced while MFA is switched off for the installation', function () { + config(['fortify.features' => []]); + $this->actingAs(($this->user)(PurchasingRole::Admin))->get('/dashboard')->assertOk(); +});