Files
breadcrumb-the-shire/pages/admin/tenants/create().php
fs fd90065048 fix(security): add CSRF protection to all POST endpoints + contract tests (B2)
CSRF guards added to 16 admin pages that previously accepted POST requests
without token verification (GR-SEC-001): departments, permissions, roles,
settings, tenants, users (create/edit/bulk/tokens), and lang switch.

New contract tests:
- PostEndpointCsrfContractTest: scans all pages/ for POST handlers and
  verifies checkCsrfToken is present (API/data endpoints exempt).
- DatabaseUpdatesContractTest: validates db/updates/ scripts follow naming
  convention and use idempotent SQL patterns (GR-CORE-010).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 15:40:07 +01:00

134 lines
4.9 KiB
PHP

<?php
use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\TenantAuthorizationPolicy;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$request = requestInput();
$currentUserId = (int) ($session['user']['id'] ?? 0);
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$decision = $authorizationService->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_CREATE, [
'actor_user_id' => $currentUserId,
]);
if (!$decision->isAllowed()) {
Guard::deny();
}
$capabilities = $decision->attribute('capabilities', []);
$canManageSso = is_array($capabilities) ? (bool) ($capabilities['can_manage_sso'] ?? false) : false;
$canManageCustomFields = is_array($capabilities) ? (bool) ($capabilities['can_manage_custom_fields'] ?? false) : false;
$tenantSsoService = app(\MintyPHP\Service\Auth\TenantSsoService::class);
$errorBag = formErrors();
$errors = [];
$form = [
'description' => '',
'address' => '',
'postal_code' => '',
'city' => '',
'country' => '',
'region' => '',
'vat_id' => '',
'tax_number' => '',
'phone' => '',
'fax' => '',
'email' => '',
'support_email' => '',
'support_phone' => '',
'billing_email' => '',
'website' => '',
'privacy_url' => '',
'imprint_url' => '',
'primary_color' => '',
'primary_color_use_default' => 0,
'default_theme' => '',
'allow_user_theme_mode' => '',
'status' => 'active',
];
$ssoUiState = $canManageSso ? $tenantSsoService->buildMicrosoftUiState(0, $form) : [];
if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
Flash::error(t('Form expired, please try again'), 'admin/tenants/create', 'csrf_expired');
Router::redirect('admin/tenants/create');
return;
}
if ($request->hasBody('description')) {
$post = $request->bodyAll();
$ssoFields = [
'microsoft_enabled',
'enforce_microsoft_login',
'sync_profile_on_login',
'sync_profile_fields',
'entra_tenant_id',
'allowed_domains',
'use_shared_app',
'client_id_override',
'client_secret_override',
'clear_client_secret_override',
];
foreach ($ssoFields as $ssoField) {
if (array_key_exists($ssoField, $post) && !$canManageSso) {
Router::redirect('error/forbidden');
return;
}
}
$result = app(\MintyPHP\Service\Tenant\TenantService::class)->createFromAdmin($post, $currentUserId);
$form = $result['form'] ?? $form;
$errorBag->merge($result['errors'] ?? []);
if ($canManageSso) {
$form = array_merge($form, [
'microsoft_enabled' => !empty($post['microsoft_enabled']) ? '1' : '0',
'enforce_microsoft_login' => !empty($post['enforce_microsoft_login']) ? '1' : '0',
'sync_profile_on_login' => !empty($post['sync_profile_on_login']) ? '1' : '0',
'sync_profile_fields_list' => $tenantSsoService->normalizeProfileSyncFields($post['sync_profile_fields'] ?? []),
'entra_tenant_id' => trim((string) ($post['entra_tenant_id'] ?? '')),
'allowed_domains' => trim((string) ($post['allowed_domains'] ?? '')),
'use_shared_app' => !empty($post['use_shared_app']) ? '1' : '0',
'client_id_override' => trim((string) ($post['client_id_override'] ?? '')),
]);
$ssoUiState = $tenantSsoService->buildMicrosoftUiState(0, $post);
}
if (($result['ok'] ?? false) && !$errorBag->hasAny()) {
if ($canManageSso) {
$createdTenantId = (int) ($result['id'] ?? 0);
if ($createdTenantId > 0) {
$ssoSaveResult = $tenantSsoService->saveTenantMicrosoftAuth($createdTenantId, $post);
if (!($ssoSaveResult['ok'] ?? false)) {
Flash::error(
(string) (($ssoSaveResult['errors'][0] ?? t('Tenant SSO settings could not be saved'))),
'admin/tenants',
'tenant_sso_create_failed'
);
}
}
}
$action = (string) ($post['action'] ?? 'create');
if ($action === 'create_close') {
Flash::success('Tenant created', 'admin/tenants', 'tenant_created');
Router::redirect('admin/tenants');
} else {
$uuid = (string) ($result['uuid'] ?? '');
if ($uuid !== '') {
$target = "admin/tenants/edit/{$uuid}";
Flash::success('Tenant created', $target, 'tenant_created');
Router::redirect($target);
} else {
Flash::success('Tenant created', 'admin/tenants', 'tenant_created');
Router::redirect('admin/tenants');
}
}
}
}
$validationSummaryErrors = $errorBag->toArray();
$errors = $errorBag->toFlatList();
Buffer::set('title', t('Create tenant'));