weitere updates für instanzierbarkeit und sauberes testing

This commit is contained in:
2026-02-24 08:49:40 +01:00
parent 7b53faca37
commit 16759a2732
119 changed files with 6371 additions and 745 deletions

View File

@@ -0,0 +1,471 @@
<?php
namespace MintyPHP\Tests\Architecture;
use PHPUnit\Framework\TestCase;
class AuthzAndApiLoginContractTest extends TestCase
{
public function testUsersDataActionRequiresUsersViewPermission(): void
{
$content = $this->readProjectFile('pages/admin/users/data().php');
$this->assertStringContainsString('Guard::requireLogin();', $content);
$this->assertStringContainsString('createAuthorizationService()', $content);
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_VIEW', $content);
}
public function testUsersExportActionRequiresUsersViewPermission(): void
{
$content = $this->readProjectFile('pages/admin/users/export().php');
$this->assertStringContainsString('Guard::requireLogin();', $content);
$this->assertStringContainsString('createAuthorizationService()', $content);
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_VIEW', $content);
}
public function testUsersActivateActionRequiresUsersUpdatePermission(): void
{
$content = $this->readProjectFile('pages/admin/users/activate($id).php');
$this->assertStringContainsString('createAuthorizationService()', $content);
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_ACTIVATE', $content);
}
public function testUsersDeactivateActionRequiresUsersUpdatePermission(): void
{
$content = $this->readProjectFile('pages/admin/users/deactivate($id).php');
$this->assertStringContainsString('createAuthorizationService()', $content);
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_DEACTIVATE', $content);
}
public function testUsersBulkActionPermissionMappingIsConsistent(): void
{
$content = $this->readProjectFile('pages/admin/users/bulk($action).php');
$this->assertStringContainsString('createAuthorizationService()', $content);
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_BULK', $content);
$this->assertStringContainsString("'bulk_action' => \$action", $content);
}
public function testAdditionalAdminUserActionsUseCentralPolicy(): void
{
$indexContent = $this->readProjectFile('pages/admin/users/index().php');
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_VIEW', $indexContent);
$createContent = $this->readProjectFile('pages/admin/users/create().php');
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_CREATE', $createContent);
$deleteContent = $this->readProjectFile('pages/admin/users/delete($id).php');
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_DELETE', $deleteContent);
$accessPdfContent = $this->readProjectFile('pages/admin/users/access-pdf($id).php');
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_ACCESS_PDF', $accessPdfContent);
$accessPdfBulkContent = $this->readProjectFile('pages/admin/users/access-pdf-bulk().php');
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_ACCESS_PDF_BULK', $accessPdfBulkContent);
$tokenCreateContent = $this->readProjectFile('pages/admin/users/api-token-create($id).php');
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_API_TOKENS_MANAGE', $tokenCreateContent);
$tokenRevokeContent = $this->readProjectFile('pages/admin/users/api-token-revoke($id).php');
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_API_TOKENS_MANAGE', $tokenRevokeContent);
$sendAccessContent = $this->readProjectFile('pages/admin/users/send-access($id).php');
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_SEND_ACCESS', $sendAccessContent);
$forgetTokensContent = $this->readProjectFile('pages/admin/users/forget-tokens($id).php');
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_FORGET_TOKENS', $forgetTokensContent);
}
public function testAdminUserEditUsesContextAndSubmitPolicies(): void
{
$content = $this->readProjectFile('pages/admin/users/edit($id).php');
$this->assertStringContainsString('createAuthorizationService()', $content);
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_EDIT_CONTEXT', $content);
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_EDIT_SUBMIT', $content);
}
public function testAdminUserAvatarEndpointsUseCentralPolicies(): void
{
$uploadContent = $this->readProjectFile('pages/admin/users/avatar($id).php');
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_AVATAR_UPLOAD', $uploadContent);
$deleteContent = $this->readProjectFile('pages/admin/users/avatar-delete($id).php');
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_AVATAR_DELETE', $deleteContent);
$viewContent = $this->readProjectFile('pages/admin/users/avatar-file().php');
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_ADMIN_USERS_AVATAR_VIEW', $viewContent);
}
public function testAdminTenantEditAndCustomFieldActionsUseCentralPolicies(): void
{
$indexContent = $this->readProjectFile('pages/admin/tenants/index().php');
$this->assertStringContainsString('createAuthorizationService()', $indexContent);
$this->assertStringContainsString('TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_VIEW', $indexContent);
$dataContent = $this->readProjectFile('pages/admin/tenants/data().php');
$this->assertStringContainsString('createAuthorizationService()', $dataContent);
$this->assertStringContainsString('TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_VIEW', $dataContent);
$createContent = $this->readProjectFile('pages/admin/tenants/create().php');
$this->assertStringContainsString('createAuthorizationService()', $createContent);
$this->assertStringContainsString('TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_CREATE', $createContent);
$editContent = $this->readProjectFile('pages/admin/tenants/edit($id).php');
$this->assertStringContainsString('createAuthorizationService()', $editContent);
$this->assertStringContainsString('TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_EDIT_CONTEXT', $editContent);
$this->assertStringContainsString('TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_EDIT_SUBMIT', $editContent);
$customFieldCreate = $this->readProjectFile('pages/admin/tenants/custom-field-create($id).php');
$this->assertStringContainsString('TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_CUSTOM_FIELDS_MANAGE', $customFieldCreate);
$customFieldUpdate = $this->readProjectFile('pages/admin/tenants/custom-field-update($id).php');
$this->assertStringContainsString('TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_CUSTOM_FIELDS_MANAGE', $customFieldUpdate);
$customFieldDelete = $this->readProjectFile('pages/admin/tenants/custom-field-delete($id).php');
$this->assertStringContainsString('TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_CUSTOM_FIELDS_MANAGE', $customFieldDelete);
}
public function testAdminTenantTemplatesUseServerCapabilities(): void
{
$indexTemplate = $this->readProjectFile('pages/admin/tenants/index(default).phtml');
$this->assertStringNotContainsString("can('tenants.create')", $indexTemplate);
$this->assertStringContainsString('$canCreateTenants', $indexTemplate);
$createTemplate = $this->readProjectFile('pages/admin/tenants/create(default).phtml');
$this->assertStringNotContainsString("can('custom_fields.manage')", $createTemplate);
$this->assertStringNotContainsString("can('tenants.sso_manage')", $createTemplate);
$this->assertStringContainsString('$canManageCustomFields', $createTemplate);
$this->assertStringContainsString('$canManageSso', $createTemplate);
}
public function testAdminTenantDeleteUsesCentralPolicy(): void
{
$deleteContent = $this->readProjectFile('pages/admin/tenants/delete($id).php');
$this->assertStringContainsString('createAuthorizationService()', $deleteContent);
$this->assertStringContainsString('TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_DELETE', $deleteContent);
}
public function testAdminTenantMediaEndpointsUseCentralPolicies(): void
{
$avatarView = $this->readProjectFile('pages/admin/tenants/avatar-file().php');
$this->assertStringContainsString('TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_AVATAR_VIEW', $avatarView);
$avatarUpload = $this->readProjectFile('pages/admin/tenants/avatar($id).php');
$this->assertStringContainsString('TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_MEDIA_UPDATE', $avatarUpload);
$avatarDelete = $this->readProjectFile('pages/admin/tenants/avatar-delete($id).php');
$this->assertStringContainsString('TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_MEDIA_UPDATE', $avatarDelete);
$faviconUpload = $this->readProjectFile('pages/admin/tenants/favicon($id).php');
$this->assertStringContainsString('TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_MEDIA_UPDATE', $faviconUpload);
$faviconDelete = $this->readProjectFile('pages/admin/tenants/favicon-delete($id).php');
$this->assertStringContainsString('TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_MEDIA_UPDATE', $faviconDelete);
}
public function testAdminDepartmentsEditAndDeleteUseCentralPolicies(): void
{
$indexContent = $this->readProjectFile('pages/admin/departments/index().php');
$this->assertStringContainsString('createAuthorizationService()', $indexContent);
$this->assertStringContainsString('DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_VIEW', $indexContent);
$dataContent = $this->readProjectFile('pages/admin/departments/data().php');
$this->assertStringContainsString('createAuthorizationService()', $dataContent);
$this->assertStringContainsString('DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_VIEW', $dataContent);
$createContent = $this->readProjectFile('pages/admin/departments/create().php');
$this->assertStringContainsString('createAuthorizationService()', $createContent);
$this->assertStringContainsString('DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_CREATE', $createContent);
$editContent = $this->readProjectFile('pages/admin/departments/edit($id).php');
$this->assertStringContainsString('createAuthorizationService()', $editContent);
$this->assertStringContainsString('DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_EDIT_CONTEXT', $editContent);
$this->assertStringContainsString('DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_EDIT_SUBMIT', $editContent);
$deleteContent = $this->readProjectFile('pages/admin/departments/delete($id).php');
$this->assertStringContainsString('createAuthorizationService()', $deleteContent);
$this->assertStringContainsString('DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_DELETE', $deleteContent);
}
public function testAdminDepartmentsListTemplateUsesServerCapabilities(): void
{
$content = $this->readProjectFile('pages/admin/departments/index(default).phtml');
$this->assertStringNotContainsString("can('departments.create')", $content);
$this->assertStringContainsString('$canCreateDepartments', $content);
}
public function testAdminRolesActionsUseCentralPolicies(): void
{
$indexContent = $this->readProjectFile('pages/admin/roles/index().php');
$this->assertStringContainsString('createAuthorizationService()', $indexContent);
$this->assertStringContainsString('RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_VIEW', $indexContent);
$dataContent = $this->readProjectFile('pages/admin/roles/data().php');
$this->assertStringContainsString('createAuthorizationService()', $dataContent);
$this->assertStringContainsString('RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_VIEW', $dataContent);
$createContent = $this->readProjectFile('pages/admin/roles/create().php');
$this->assertStringContainsString('createAuthorizationService()', $createContent);
$this->assertStringContainsString('RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_CREATE', $createContent);
$editContent = $this->readProjectFile('pages/admin/roles/edit($id).php');
$this->assertStringContainsString('createAuthorizationService()', $editContent);
$this->assertStringContainsString('RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_EDIT_CONTEXT', $editContent);
$this->assertStringContainsString('RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_EDIT_SUBMIT', $editContent);
$deleteContent = $this->readProjectFile('pages/admin/roles/delete($id).php');
$this->assertStringContainsString('createAuthorizationService()', $deleteContent);
$this->assertStringContainsString('RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_DELETE', $deleteContent);
}
public function testAdminPermissionsActionsUseCentralPolicies(): void
{
$indexContent = $this->readProjectFile('pages/admin/permissions/index().php');
$this->assertStringContainsString('createAuthorizationService()', $indexContent);
$this->assertStringContainsString('PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_VIEW', $indexContent);
$dataContent = $this->readProjectFile('pages/admin/permissions/data().php');
$this->assertStringContainsString('createAuthorizationService()', $dataContent);
$this->assertStringContainsString('PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_VIEW', $dataContent);
$createContent = $this->readProjectFile('pages/admin/permissions/create().php');
$this->assertStringContainsString('createAuthorizationService()', $createContent);
$this->assertStringContainsString('PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_CREATE', $createContent);
$editContent = $this->readProjectFile('pages/admin/permissions/edit($id).php');
$this->assertStringContainsString('createAuthorizationService()', $editContent);
$this->assertStringContainsString('PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_EDIT_CONTEXT', $editContent);
$this->assertStringContainsString('PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_EDIT_SUBMIT', $editContent);
$deleteContent = $this->readProjectFile('pages/admin/permissions/delete($id).php');
$this->assertStringContainsString('createAuthorizationService()', $deleteContent);
$this->assertStringContainsString('PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_DELETE', $deleteContent);
}
public function testAdminRoleTemplatesUseServerCapabilities(): void
{
$indexTemplate = $this->readProjectFile('pages/admin/roles/index(default).phtml');
$this->assertStringNotContainsString("can('roles.create')", $indexTemplate);
$this->assertStringContainsString('$canCreateRoles', $indexTemplate);
$editTemplate = $this->readProjectFile('pages/admin/roles/edit(default).phtml');
$this->assertStringNotContainsString("can('roles.update')", $editTemplate);
$this->assertStringNotContainsString("can('roles.delete')", $editTemplate);
$this->assertStringContainsString('$canUpdateRole', $editTemplate);
$this->assertStringContainsString('$canDeleteRole', $editTemplate);
}
public function testAdminPermissionTemplatesUseServerCapabilities(): void
{
$indexTemplate = $this->readProjectFile('pages/admin/permissions/index(default).phtml');
$this->assertStringNotContainsString("can('permissions.create')", $indexTemplate);
$this->assertStringContainsString('$canCreatePermissions', $indexTemplate);
$editTemplate = $this->readProjectFile('pages/admin/permissions/edit(default).phtml');
$this->assertStringNotContainsString("can('permissions.update')", $editTemplate);
$this->assertStringNotContainsString("can('permissions.delete')", $editTemplate);
$this->assertStringContainsString('$canUpdatePermission', $editTemplate);
$this->assertStringContainsString('$canDeletePermission', $editTemplate);
}
public function testAdminSettingsActionsUseCentralPolicies(): void
{
$indexContent = $this->readProjectFile('pages/admin/settings/index().php');
$this->assertStringContainsString('createAuthorizationService()', $indexContent);
$this->assertStringContainsString('SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_VIEW', $indexContent);
$this->assertStringContainsString('SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_UPDATE', $indexContent);
$logoUpload = $this->readProjectFile('pages/admin/settings/logo().php');
$this->assertStringContainsString('createAuthorizationService()', $logoUpload);
$this->assertStringContainsString('SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_BRANDING_UPDATE', $logoUpload);
$logoDelete = $this->readProjectFile('pages/admin/settings/logo-delete().php');
$this->assertStringContainsString('SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_BRANDING_UPDATE', $logoDelete);
$faviconUpload = $this->readProjectFile('pages/admin/settings/favicon().php');
$this->assertStringContainsString('SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_BRANDING_UPDATE', $faviconUpload);
$faviconDelete = $this->readProjectFile('pages/admin/settings/favicon-delete().php');
$this->assertStringContainsString('SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_BRANDING_UPDATE', $faviconDelete);
$revokeApiTokens = $this->readProjectFile('pages/admin/settings/revoke-api-tokens().php');
$this->assertStringContainsString('SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_TOKENS_REVOKE', $revokeApiTokens);
$expireRememberTokens = $this->readProjectFile('pages/admin/settings/expire-remember-tokens().php');
$this->assertStringContainsString('SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_TOKENS_REVOKE', $expireRememberTokens);
$runUserLifecycle = $this->readProjectFile('pages/admin/settings/run-user-lifecycle().php');
$this->assertStringContainsString('SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_USER_LIFECYCLE_RUN', $runUserLifecycle);
}
public function testAdminSettingsTemplateUsesServerCapabilities(): void
{
$templateContent = $this->readProjectFile('pages/admin/settings/index(default).phtml');
$this->assertStringNotContainsString("can('settings.update')", $templateContent);
$this->assertStringContainsString('$canUpdateSettings', $templateContent);
}
public function testAdminUserEditTemplateUsesServerCapabilities(): void
{
$content = $this->readProjectFile('pages/admin/users/edit(default).phtml');
$this->assertStringNotContainsString("can('users.", $content);
$this->assertStringNotContainsString("can('permissions.view')", $content);
$this->assertStringContainsString('$canViewSecurityArtifacts', $content);
}
public function testApiLoginIsBootstrappedAsPublic(): void
{
$content = $this->readProjectFile('pages/api/v1/auth/login().php');
$this->assertStringContainsString('ApiBootstrap::init(false);', $content);
}
public function testApiBootstrapSupportsOptionalAuthRequirement(): void
{
$content = $this->readProjectFile('lib/Http/ApiBootstrap.php');
$this->assertStringContainsString('public static function init(bool $requireAuth = true): void', $content);
$this->assertStringContainsString('if ($requireAuth) {', $content);
$this->assertStringContainsString('$authenticated = ApiAuth::authenticate();', $content);
$this->assertStringContainsString('ApiResponse::unauthorized();', $content);
}
public function testApiUsersEndpointsUseCentralUserPolicy(): void
{
$indexContent = $this->readProjectFile('pages/api/v1/users/index().php');
$this->assertStringContainsString('createAuthorizationService()', $indexContent);
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_API_USERS_INDEX_GET', $indexContent);
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_API_USERS_INDEX_POST', $indexContent);
$showContent = $this->readProjectFile('pages/api/v1/users/show($id).php');
$this->assertStringContainsString('createAuthorizationService()', $showContent);
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_GET', $showContent);
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_UPDATE', $showContent);
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_DELETE', $showContent);
}
public function testApiPermissionAndSettingsEndpointsHaveExpectedGuards(): void
{
$permissionContent = $this->readProjectFile('pages/api/v1/permissions/index().php');
$this->assertStringContainsString("ApiResponse::requirePermission(PermissionService::PERMISSIONS_VIEW);", $permissionContent);
$this->assertStringContainsString("foreach ((\$result['data'] ?? []) as \$row)", $permissionContent);
$settingsContent = $this->readProjectFile('pages/api/v1/settings/index().php');
$this->assertStringContainsString("ApiResponse::requirePermission(PermissionService::SETTINGS_VIEW);", $settingsContent);
$this->assertStringContainsString("ApiResponse::requirePermission(PermissionService::SETTINGS_UPDATE);", $settingsContent);
}
public function testApiMeEndpointsUseSelfServicePermissions(): void
{
$meContent = $this->readProjectFile('pages/api/v1/me/index().php');
$this->assertStringContainsString('$method === \'PUT\' || $method === \'PATCH\'', $meContent);
$this->assertStringContainsString('PermissionService::USERS_SELF_UPDATE', $meContent);
$this->assertStringContainsString("ApiResponse::validationError(['profile' => array_values(\$errors)]);", $meContent);
$passwordContent = $this->readProjectFile('pages/api/v1/me/password().php');
$this->assertStringContainsString("ApiResponse::requireMethod('POST');", $passwordContent);
$this->assertStringContainsString('PermissionService::USERS_SELF_UPDATE', $passwordContent);
$avatarContent = $this->readProjectFile('pages/api/v1/me/avatar().php');
$this->assertStringContainsString("define('MINTY_ALLOW_OUTPUT', true);", $avatarContent);
$this->assertStringContainsString('PermissionService::USERS_SELF_UPDATE', $avatarContent);
}
public function testApiAvatarEndpointsUseExpectedAuthorizationModel(): void
{
$userAvatarContent = $this->readProjectFile('pages/api/v1/users/avatar($id).php');
$this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_GET', $userAvatarContent);
$tenantAvatarContent = $this->readProjectFile('pages/api/v1/tenants/avatar($id).php');
$this->assertStringContainsString('PermissionService::TENANTS_VIEW', $tenantAvatarContent);
$this->assertStringContainsString("ApiAuth::requireResourceAccess('tenants', \$tenantId);", $tenantAvatarContent);
}
public function testApiTenantShowExposesFullTenantMasterData(): void
{
$tenantShowContent = $this->readProjectFile('pages/api/v1/tenants/show($id).php');
$this->assertStringContainsString("'region' => \$tenant['region'] ?? ''", $tenantShowContent);
$this->assertStringContainsString("'vat_id' => \$tenant['vat_id'] ?? ''", $tenantShowContent);
$this->assertStringContainsString("'support_email' => \$tenant['support_email'] ?? ''", $tenantShowContent);
$this->assertStringContainsString("'billing_email' => \$tenant['billing_email'] ?? ''", $tenantShowContent);
$this->assertStringContainsString("'primary_color_use_default' => \$primaryColor === ''", $tenantShowContent);
$this->assertStringContainsString("'allow_user_theme_mode' => \$allowUserThemeMode", $tenantShowContent);
$openApiContent = $this->readProjectFile('docs/openapi.yaml');
$this->assertStringContainsString('TenantShowResponse:', $openApiContent);
$this->assertStringContainsString('primary_color_use_default:', $openApiContent);
$this->assertStringContainsString('allow_user_theme_mode:', $openApiContent);
$this->assertStringContainsString('support_email:', $openApiContent);
}
public function testApiUserWriteEndpointsUseUuidAssignmentInput(): void
{
$usersIndex = $this->readProjectFile('pages/api/v1/users/index().php');
$this->assertStringContainsString('normalizeUserWriteInputToInternalIds($input)', $usersIndex);
$this->assertStringContainsString("'tenant_ids' => 'use_tenant_uuids'", $usersIndex);
$this->assertStringContainsString("'role_ids' => 'use_role_uuids'", $usersIndex);
$this->assertStringContainsString("'department_ids' => 'use_department_uuids'", $usersIndex);
$usersShow = $this->readProjectFile('pages/api/v1/users/show($id).php');
$this->assertStringContainsString('normalizeUserWriteInputToInternalIds($input)', $usersShow);
$this->assertStringContainsString("'primary_tenant_id' => 'use_primary_tenant_uuid'", $usersShow);
}
public function testApiDepartmentEndpointsUseTenantUuidAndNoTenantIdExposure(): void
{
$departmentIndex = $this->readProjectFile('pages/api/v1/departments/index().php');
$this->assertStringContainsString("ApiResponse::validationError(['tenant_id' => ['use_tenant_uuid']]);", $departmentIndex);
$this->assertStringContainsString("if (array_key_exists('tenant_uuid', \$input)) {", $departmentIndex);
$departmentShow = $this->readProjectFile('pages/api/v1/departments/show($id).php');
$this->assertStringContainsString("'tenant_uuid' => \$tenantUuid", $departmentShow);
$this->assertStringNotContainsString("'tenant_id' => \$department['tenant_id'] ?? null", $departmentShow);
$this->assertStringContainsString("'cost_center' => \$department['cost_center'] ?? ''", $departmentShow);
}
public function testApiRoleShowIncludesPermissionKeys(): void
{
$roleShow = $this->readProjectFile('pages/api/v1/roles/show($id).php');
$this->assertStringContainsString('createRolePermissionRepository()', $roleShow);
$this->assertStringContainsString('listPermissionKeysByRoleIds([$roleId])', $roleShow);
$this->assertStringContainsString("'permission_keys' => \$permissionKeys", $roleShow);
}
public function testOpenApiMarksLoginAsPublic(): void
{
$content = $this->readProjectFile('docs/openapi.yaml');
$this->assertMatchesRegularExpression('/\/auth\/login:\s+post:.*?security:\s*\[\]/s', $content);
$this->assertStringContainsString('no Authorization header required', $content);
}
public function testOpenApiIncludesNewCriticalFrontendEndpoints(): void
{
$content = $this->readProjectFile('docs/openapi.yaml');
$this->assertStringContainsString('/permissions:', $content);
$this->assertStringContainsString('/me/password:', $content);
$this->assertStringContainsString('/me/avatar:', $content);
$this->assertStringContainsString('/users/avatar/{uuid}:', $content);
$this->assertStringContainsString('/tenants/avatar/{uuid}:', $content);
$this->assertStringContainsString('/settings:', $content);
$this->assertStringContainsString('/settings/public:', $content);
}
public function testOpenApiUsesUuidBasedMasterDataContracts(): void
{
$content = $this->readProjectFile('docs/openapi.yaml');
$this->assertStringContainsString('required: [description, tenant_uuid]', $content);
$this->assertStringContainsString('tenant_uuids:', $content);
$this->assertStringContainsString('primary_tenant_uuid:', $content);
$this->assertStringContainsString('role_uuids:', $content);
$this->assertStringContainsString('department_uuids:', $content);
$this->assertStringContainsString('permission_keys:', $content);
$this->assertStringContainsString('tenant_uuid:', $content);
}
private function readProjectFile(string $path): string
{
$root = realpath(__DIR__ . '/../..');
$this->assertNotFalse($root, 'Project root not found.');
$fullPath = $root . '/' . $path;
$this->assertFileExists($fullPath, 'File not found: ' . $path);
$content = file_get_contents($fullPath);
$this->assertNotFalse($content, 'Could not read file: ' . $path);
return $content;
}
}

View File

@@ -6,7 +6,14 @@ use MintyPHP\Repository\Access\PermissionRepository;
use MintyPHP\Repository\Access\RolePermissionRepository;
use MintyPHP\Repository\Access\UserRoleRepository;
use MintyPHP\Service\Access\AccessServicesFactory;
use MintyPHP\Service\Access\AuthorizationService;
use MintyPHP\Service\Access\DepartmentAuthorizationPolicy;
use MintyPHP\Service\Access\PermissionAuthorizationPolicy;
use MintyPHP\Service\Access\PermissionGateway;
use MintyPHP\Service\Access\RoleAuthorizationPolicy;
use MintyPHP\Service\Access\SettingsAuthorizationPolicy;
use MintyPHP\Service\Access\TenantAuthorizationPolicy;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
use PHPUnit\Framework\TestCase;
class AccessServicesFactoryTest extends TestCase
@@ -29,5 +36,26 @@ class AccessServicesFactoryTest extends TestCase
$this->assertInstanceOf(PermissionGateway::class, $factory->createPermissionGateway());
$this->assertSame($factory->createPermissionGateway(), $factory->createPermissionGateway());
$this->assertInstanceOf(UserAuthorizationPolicy::class, $factory->createUserAuthorizationPolicy());
$this->assertSame($factory->createUserAuthorizationPolicy(), $factory->createUserAuthorizationPolicy());
$this->assertInstanceOf(RoleAuthorizationPolicy::class, $factory->createRoleAuthorizationPolicy());
$this->assertSame($factory->createRoleAuthorizationPolicy(), $factory->createRoleAuthorizationPolicy());
$this->assertInstanceOf(PermissionAuthorizationPolicy::class, $factory->createPermissionAuthorizationPolicy());
$this->assertSame($factory->createPermissionAuthorizationPolicy(), $factory->createPermissionAuthorizationPolicy());
$this->assertInstanceOf(SettingsAuthorizationPolicy::class, $factory->createSettingsAuthorizationPolicy());
$this->assertSame($factory->createSettingsAuthorizationPolicy(), $factory->createSettingsAuthorizationPolicy());
$this->assertInstanceOf(TenantAuthorizationPolicy::class, $factory->createTenantAuthorizationPolicy());
$this->assertSame($factory->createTenantAuthorizationPolicy(), $factory->createTenantAuthorizationPolicy());
$this->assertInstanceOf(DepartmentAuthorizationPolicy::class, $factory->createDepartmentAuthorizationPolicy());
$this->assertSame($factory->createDepartmentAuthorizationPolicy(), $factory->createDepartmentAuthorizationPolicy());
$this->assertInstanceOf(AuthorizationService::class, $factory->createAuthorizationService());
$this->assertSame($factory->createAuthorizationService(), $factory->createAuthorizationService());
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace MintyPHP\Tests\Service\Access;
use MintyPHP\Service\Access\AuthorizationDecision;
use MintyPHP\Service\Access\AuthorizationPolicyInterface;
use MintyPHP\Service\Access\AuthorizationService;
use PHPUnit\Framework\TestCase;
class AuthorizationServiceTest extends TestCase
{
public function testReturnsPolicyDecisionForSupportedAbility(): void
{
$policy = new class implements AuthorizationPolicyInterface {
public function supports(string $ability): bool
{
return $ability === 'users.test';
}
public function authorize(string $ability, array $context = []): AuthorizationDecision
{
return AuthorizationDecision::allow(['ability' => $ability, 'context' => $context]);
}
};
$service = new AuthorizationService([$policy]);
$decision = $service->authorize('users.test', ['actor_user_id' => 12]);
$this->assertTrue($decision->isAllowed());
$this->assertSame('users.test', $decision->attribute('ability'));
$this->assertSame(['actor_user_id' => 12], $decision->attribute('context'));
}
public function testReturnsMissingPolicyDecisionWhenAbilityIsUnknown(): void
{
$policy = new class implements AuthorizationPolicyInterface {
public function supports(string $ability): bool
{
return false;
}
public function authorize(string $ability, array $context = []): AuthorizationDecision
{
return AuthorizationDecision::allow();
}
};
$service = new AuthorizationService([$policy]);
$decision = $service->authorize('unknown.ability');
$this->assertFalse($decision->isAllowed());
$this->assertSame(500, $decision->status());
$this->assertSame('authorization_policy_missing', $decision->error());
}
}

View File

@@ -0,0 +1,253 @@
<?php
namespace MintyPHP\Tests\Service\Access;
use MintyPHP\Service\Access\DepartmentAuthorizationPolicy;
use MintyPHP\Service\Access\PermissionGateway;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Directory\DirectoryScopeGateway;
use PHPUnit\Framework\TestCase;
class DepartmentAuthorizationPolicyTest extends TestCase
{
public function testViewRequiresDepartmentsViewPermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(5, PermissionService::DEPARTMENTS_VIEW)
->willReturn(false);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->never())->method('getUserTenantIds');
$scopeGateway->expects($this->never())->method('isStrict');
$policy = new DepartmentAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_VIEW, [
'actor_user_id' => 5,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('forbidden', $decision->error());
}
public function testViewReturnsCreateCapabilityAndTenantScopeData(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 5) {
return false;
}
return in_array($permission, [PermissionService::DEPARTMENTS_VIEW, PermissionService::DEPARTMENTS_CREATE], true);
});
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('getUserTenantIds')
->with(5)
->willReturn([2, 3]);
$scopeGateway->expects($this->once())
->method('isStrict')
->willReturn(true);
$policy = new DepartmentAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_VIEW, [
'actor_user_id' => 5,
]);
$capabilities = $decision->attribute('capabilities', []);
$this->assertTrue($decision->isAllowed());
$this->assertTrue((bool) ($capabilities['can_create_department'] ?? false));
$this->assertSame([2, 3], $capabilities['allowed_tenant_ids'] ?? []);
$this->assertTrue((bool) ($capabilities['is_strict_scope'] ?? false));
}
public function testCreateRequiresDepartmentsCreatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(7, PermissionService::DEPARTMENTS_CREATE)
->willReturn(false);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->never())->method('getUserTenantIds');
$scopeGateway->expects($this->never())->method('isStrict');
$policy = new DepartmentAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_CREATE, [
'actor_user_id' => 7,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
}
public function testCreateDeniedInStrictScopeWithoutTenantAssignments(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 7 && $permission === PermissionService::DEPARTMENTS_CREATE);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('getUserTenantIds')
->with(7)
->willReturn([]);
$scopeGateway->expects($this->once())
->method('isStrict')
->willReturn(true);
$policy = new DepartmentAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_CREATE, [
'actor_user_id' => 7,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('permission_denied', $decision->error());
}
public function testCreateReturnsScopeCapabilitiesWhenAllowed(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 7 && $permission === PermissionService::DEPARTMENTS_CREATE);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('getUserTenantIds')
->with(7)
->willReturn([4]);
$scopeGateway->expects($this->once())
->method('isStrict')
->willReturn(true);
$policy = new DepartmentAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_CREATE, [
'actor_user_id' => 7,
]);
$capabilities = $decision->attribute('capabilities', []);
$this->assertTrue($decision->isAllowed());
$this->assertSame([4], $capabilities['allowed_tenant_ids'] ?? []);
$this->assertTrue((bool) ($capabilities['is_strict_scope'] ?? false));
}
public function testEditContextRequiresDepartmentsViewPermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->never())->method('canAccess');
$policy = new DepartmentAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_EDIT_CONTEXT, [
'actor_user_id' => 5,
'target_department_id' => 17,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('forbidden', $decision->error());
}
public function testEditContextDeniesOutOfScopeDepartment(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 5 && $permission === PermissionService::DEPARTMENTS_VIEW);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('departments', 17, 5)
->willReturn(false);
$policy = new DepartmentAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_EDIT_CONTEXT, [
'actor_user_id' => 5,
'target_department_id' => 17,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame('permission_denied', $decision->error());
}
public function testEditSubmitRequiresDepartmentsUpdatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 5) {
return false;
}
return $permission === PermissionService::DEPARTMENTS_VIEW;
});
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('departments', 17, 5)
->willReturn(true);
$scopeGateway->expects($this->once())
->method('getUserTenantIds')
->with(5)
->willReturn([2]);
$policy = new DepartmentAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_EDIT_SUBMIT, [
'actor_user_id' => 5,
'target_department_id' => 17,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame('forbidden', $decision->error());
}
public function testDeleteRequiresPermissionAndScope(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 9 && $permission === PermissionService::DEPARTMENTS_DELETE);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('departments', 44, 9)
->willReturn(true);
$policy = new DepartmentAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_DELETE, [
'actor_user_id' => 9,
'target_department_id' => 44,
]);
$this->assertTrue($decision->isAllowed());
}
public function testDeleteDeniesOutOfScopeDepartment(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 9 && $permission === PermissionService::DEPARTMENTS_DELETE);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('departments', 44, 9)
->willReturn(false);
$policy = new DepartmentAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_DELETE, [
'actor_user_id' => 9,
'target_department_id' => 44,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame('permission_denied', $decision->error());
}
}

View File

@@ -0,0 +1,137 @@
<?php
namespace MintyPHP\Tests\Service\Access;
use MintyPHP\Service\Access\PermissionAuthorizationPolicy;
use MintyPHP\Service\Access\PermissionGateway;
use MintyPHP\Service\Access\PermissionService;
use PHPUnit\Framework\TestCase;
class PermissionAuthorizationPolicyTest extends TestCase
{
public function testAdminViewRequiresPermissionsViewPermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(9, PermissionService::PERMISSIONS_VIEW)
->willReturn(false);
$policy = new PermissionAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_VIEW, [
'actor_user_id' => 9,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('forbidden', $decision->error());
}
public function testAdminViewIncludesCreateCapability(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 9) {
return false;
}
return in_array($permission, [PermissionService::PERMISSIONS_VIEW, PermissionService::PERMISSIONS_CREATE], true);
});
$policy = new PermissionAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_VIEW, [
'actor_user_id' => 9,
]);
$this->assertTrue($decision->isAllowed());
$this->assertTrue((bool) ($decision->attribute('capabilities', [])['can_create_permission'] ?? false));
}
public function testAdminCreateRequiresPermissionsCreatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(3, PermissionService::PERMISSIONS_CREATE)
->willReturn(false);
$policy = new PermissionAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_CREATE, [
'actor_user_id' => 3,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
}
public function testEditContextReturnsCapabilitiesAndSystemDeleteRestriction(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 5) {
return false;
}
return in_array($permission, [
PermissionService::PERMISSIONS_VIEW,
PermissionService::PERMISSIONS_UPDATE,
PermissionService::PERMISSIONS_DELETE,
], true);
});
$policy = new PermissionAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_EDIT_CONTEXT, [
'actor_user_id' => 5,
'target_permission_id' => 21,
'target_is_system' => true,
]);
$capabilities = $decision->attribute('capabilities', []);
$this->assertTrue($decision->isAllowed());
$this->assertTrue((bool) ($capabilities['can_update_permission'] ?? false));
$this->assertFalse((bool) ($capabilities['can_delete_permission'] ?? true));
}
public function testEditSubmitRequiresPermissionsUpdatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 5) {
return false;
}
return $permission === PermissionService::PERMISSIONS_VIEW;
});
$policy = new PermissionAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_EDIT_SUBMIT, [
'actor_user_id' => 5,
'target_permission_id' => 21,
'target_is_system' => false,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('forbidden', $decision->error());
}
public function testDeleteRequiresPermissionsDeletePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(12, PermissionService::PERMISSIONS_DELETE)
->willReturn(false);
$policy = new PermissionAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_DELETE, [
'actor_user_id' => 12,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
}
}

View File

@@ -0,0 +1,149 @@
<?php
namespace MintyPHP\Tests\Service\Access;
use MintyPHP\Service\Access\PermissionGateway;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Access\RoleAuthorizationPolicy;
use PHPUnit\Framework\TestCase;
class RoleAuthorizationPolicyTest extends TestCase
{
public function testAdminViewRequiresRolesViewPermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(7, PermissionService::ROLES_VIEW)
->willReturn(false);
$policy = new RoleAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_VIEW, [
'actor_user_id' => 7,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('forbidden', $decision->error());
}
public function testAdminViewIncludesCreateCapability(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 7) {
return false;
}
return in_array($permission, [PermissionService::ROLES_VIEW, PermissionService::ROLES_CREATE], true);
});
$policy = new RoleAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_VIEW, [
'actor_user_id' => 7,
]);
$this->assertTrue($decision->isAllowed());
$this->assertTrue((bool) ($decision->attribute('capabilities', [])['can_create_role'] ?? false));
}
public function testAdminCreateRequiresRolesCreatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(11, PermissionService::ROLES_CREATE)
->willReturn(false);
$policy = new RoleAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_CREATE, [
'actor_user_id' => 11,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
}
public function testEditContextRequiresTargetRoleId(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->never())->method('userHas');
$policy = new RoleAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_EDIT_CONTEXT, [
'actor_user_id' => 5,
'target_role_id' => 0,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
}
public function testEditContextReturnsCapabilities(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 5) {
return false;
}
return in_array($permission, [
PermissionService::ROLES_VIEW,
PermissionService::ROLES_UPDATE,
], true);
});
$policy = new RoleAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_EDIT_CONTEXT, [
'actor_user_id' => 5,
'target_role_id' => 22,
]);
$capabilities = $decision->attribute('capabilities', []);
$this->assertTrue($decision->isAllowed());
$this->assertTrue((bool) ($capabilities['can_edit_role'] ?? false));
$this->assertFalse((bool) ($capabilities['can_delete_role'] ?? true));
}
public function testEditSubmitRequiresRolesUpdatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 5) {
return false;
}
return $permission === PermissionService::ROLES_VIEW;
});
$policy = new RoleAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_EDIT_SUBMIT, [
'actor_user_id' => 5,
'target_role_id' => 22,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('forbidden', $decision->error());
}
public function testDeleteRequiresRolesDeletePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(6, PermissionService::ROLES_DELETE)
->willReturn(false);
$policy = new RoleAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_DELETE, [
'actor_user_id' => 6,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
}
}

View File

@@ -0,0 +1,118 @@
<?php
namespace MintyPHP\Tests\Service\Access;
use MintyPHP\Service\Access\PermissionGateway;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Access\SettingsAuthorizationPolicy;
use PHPUnit\Framework\TestCase;
class SettingsAuthorizationPolicyTest extends TestCase
{
public function testViewRequiresSettingsViewPermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(4, PermissionService::SETTINGS_VIEW)
->willReturn(false);
$policy = new SettingsAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_VIEW, [
'actor_user_id' => 4,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('forbidden', $decision->error());
}
public function testViewReturnsUpdateCapability(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 4) {
return false;
}
return in_array($permission, [PermissionService::SETTINGS_VIEW, PermissionService::SETTINGS_UPDATE], true);
});
$policy = new SettingsAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_VIEW, [
'actor_user_id' => 4,
]);
$this->assertTrue($decision->isAllowed());
$this->assertTrue((bool) ($decision->attribute('capabilities', [])['can_update_settings'] ?? false));
}
public function testUpdateRequiresSettingsUpdatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(8, PermissionService::SETTINGS_UPDATE)
->willReturn(false);
$policy = new SettingsAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_UPDATE, [
'actor_user_id' => 8,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
}
public function testBrandingUpdateRequiresSettingsUpdatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(8, PermissionService::SETTINGS_UPDATE)
->willReturn(false);
$policy = new SettingsAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_BRANDING_UPDATE, [
'actor_user_id' => 8,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
}
public function testTokenRevokeRequiresSettingsUpdatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(8, PermissionService::SETTINGS_UPDATE)
->willReturn(false);
$policy = new SettingsAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_TOKENS_REVOKE, [
'actor_user_id' => 8,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
}
public function testUserLifecycleRunRequiresSettingsUpdatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(8, PermissionService::SETTINGS_UPDATE)
->willReturn(false);
$policy = new SettingsAuthorizationPolicy($permissionGateway);
$decision = $policy->authorize(SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_USER_LIFECYCLE_RUN, [
'actor_user_id' => 8,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
}
}

View File

@@ -0,0 +1,310 @@
<?php
namespace MintyPHP\Tests\Service\Access;
use MintyPHP\Service\Access\PermissionGateway;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Access\TenantAuthorizationPolicy;
use MintyPHP\Service\Directory\DirectoryScopeGateway;
use PHPUnit\Framework\TestCase;
class TenantAuthorizationPolicyTest extends TestCase
{
public function testViewRequiresTenantsViewPermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(11, PermissionService::TENANTS_VIEW)
->willReturn(false);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->never())->method('getUserTenantIds');
$scopeGateway->expects($this->never())->method('isStrict');
$scopeGateway->expects($this->never())->method('hasGlobalAccess');
$policy = new TenantAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_VIEW, [
'actor_user_id' => 11,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('forbidden', $decision->error());
}
public function testViewReturnsCapabilitiesAndScopeData(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 11) {
return false;
}
return in_array($permission, [PermissionService::TENANTS_VIEW, PermissionService::TENANTS_CREATE], true);
});
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('getUserTenantIds')
->with(11)
->willReturn([2, 3]);
$scopeGateway->expects($this->once())
->method('isStrict')
->willReturn(true);
$scopeGateway->expects($this->once())
->method('hasGlobalAccess')
->with(11)
->willReturn(false);
$policy = new TenantAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_VIEW, [
'actor_user_id' => 11,
]);
$capabilities = $decision->attribute('capabilities', []);
$this->assertTrue($decision->isAllowed());
$this->assertTrue((bool) ($capabilities['can_create_tenant'] ?? false));
$this->assertSame([2, 3], $capabilities['allowed_tenant_ids'] ?? []);
$this->assertTrue((bool) ($capabilities['is_strict_scope'] ?? false));
$this->assertFalse((bool) ($capabilities['has_global_access'] ?? true));
}
public function testCreateRequiresTenantsCreatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(11, PermissionService::TENANTS_CREATE)
->willReturn(false);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$policy = new TenantAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_CREATE, [
'actor_user_id' => 11,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
}
public function testCreateReturnsSsoAndCustomFieldCapabilities(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 11) {
return false;
}
return in_array($permission, [PermissionService::TENANTS_CREATE, PermissionService::TENANTS_SSO_MANAGE], true);
});
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$policy = new TenantAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_CREATE, [
'actor_user_id' => 11,
]);
$capabilities = $decision->attribute('capabilities', []);
$this->assertTrue($decision->isAllowed());
$this->assertTrue((bool) ($capabilities['can_manage_sso'] ?? false));
$this->assertFalse((bool) ($capabilities['can_manage_custom_fields'] ?? true));
}
public function testEditContextAllowsInScopeViewer(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 11 && $permission === PermissionService::TENANTS_VIEW);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('tenants', 22, 11)
->willReturn(true);
$policy = new TenantAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_EDIT_CONTEXT, [
'actor_user_id' => 11,
'target_tenant_id' => 22,
]);
$this->assertTrue($decision->isAllowed());
$capabilities = $decision->attribute('capabilities', []);
$this->assertTrue((bool) ($capabilities['can_view_page'] ?? false));
$this->assertFalse((bool) ($capabilities['can_update_tenant'] ?? true));
}
public function testEditContextDeniesOutOfScopeTenant(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('tenants', 22, 11)
->willReturn(false);
$policy = new TenantAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_EDIT_CONTEXT, [
'actor_user_id' => 11,
'target_tenant_id' => 22,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('permission_denied', $decision->error());
}
public function testEditSubmitRequiresTenantsUpdatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 11 && $permission === PermissionService::TENANTS_VIEW);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('tenants', 22, 11)
->willReturn(true);
$policy = new TenantAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_EDIT_SUBMIT, [
'actor_user_id' => 11,
'target_tenant_id' => 22,
'input' => ['description' => 'Tenant A'],
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('forbidden', $decision->error());
}
public function testEditSubmitDeniesSsoFieldsWithoutSsoPermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
return $userId === 11 && ($permission === PermissionService::TENANTS_VIEW || $permission === PermissionService::TENANTS_UPDATE);
});
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('tenants', 22, 11)
->willReturn(true);
$policy = new TenantAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_EDIT_SUBMIT, [
'actor_user_id' => 11,
'target_tenant_id' => 22,
'input' => ['microsoft_enabled' => '1'],
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('forbidden', $decision->error());
}
public function testCustomFieldsManageRequiresPermissionAndScope(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 9 && $permission === PermissionService::CUSTOM_FIELDS_MANAGE);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('tenants', 5, 9)
->willReturn(true);
$policy = new TenantAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_CUSTOM_FIELDS_MANAGE, [
'actor_user_id' => 9,
'target_tenant_id' => 5,
]);
$this->assertTrue($decision->isAllowed());
}
public function testCustomFieldsManageDeniedWhenOutOfScope(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 9 && $permission === PermissionService::CUSTOM_FIELDS_MANAGE);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('tenants', 5, 9)
->willReturn(false);
$policy = new TenantAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_CUSTOM_FIELDS_MANAGE, [
'actor_user_id' => 9,
'target_tenant_id' => 5,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame('permission_denied', $decision->error());
}
public function testAvatarViewAllowsTenantViewerInScope(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 15 && $permission === PermissionService::TENANTS_VIEW);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('tenants', 9, 15)
->willReturn(true);
$policy = new TenantAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_AVATAR_VIEW, [
'actor_user_id' => 15,
'target_tenant_id' => 9,
]);
$this->assertTrue($decision->isAllowed());
}
public function testMediaUpdateRequiresTenantsUpdatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->never())->method('canAccess');
$policy = new TenantAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_MEDIA_UPDATE, [
'actor_user_id' => 15,
'target_tenant_id' => 9,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame('forbidden', $decision->error());
}
public function testDeleteRequiresPermissionAndScope(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 5 && $permission === PermissionService::TENANTS_DELETE);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('tenants', 17, 5)
->willReturn(true);
$policy = new TenantAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_DELETE, [
'actor_user_id' => 5,
'target_tenant_id' => 17,
]);
$this->assertTrue($decision->isAllowed());
}
}

View File

@@ -0,0 +1,576 @@
<?php
namespace MintyPHP\Tests\Service\Access;
use MintyPHP\Service\Access\PermissionGateway;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
use MintyPHP\Service\Directory\DirectoryScopeGateway;
use PHPUnit\Framework\TestCase;
class UserAuthorizationPolicyTest extends TestCase
{
public function testAdminViewRequiresUsersViewPermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(13, PermissionService::USERS_VIEW)
->willReturn(false);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_VIEW, [
'actor_user_id' => 13,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('forbidden', $decision->error());
}
public function testAdminCreateRequiresUsersCreatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(13, PermissionService::USERS_CREATE)
->willReturn(false);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_CREATE, [
'actor_user_id' => 13,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
}
public function testAdminActivateRequiresUsersUpdatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(11, PermissionService::USERS_UPDATE)
->willReturn(false);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->never())->method('canAccess');
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_ACTIVATE, [
'actor_user_id' => 11,
'target_user_id' => 22,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('forbidden', $decision->error());
}
public function testAdminActivateReturnsPermissionDeniedWhenTenantScopeFails(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 11 && $permission === PermissionService::USERS_UPDATE);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('users', 22, 11)
->willReturn(false);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_ACTIVATE, [
'actor_user_id' => 11,
'target_user_id' => 22,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('permission_denied', $decision->error());
}
public function testAdminDeactivateAllowsSelfWithoutScopeLookup(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 9 && $permission === PermissionService::USERS_UPDATE);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->never())->method('canAccess');
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_DEACTIVATE, [
'actor_user_id' => 9,
'target_user_id' => 9,
]);
$this->assertTrue($decision->isAllowed());
}
public function testAdminBulkDeleteRequiresUsersDeletePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(7, PermissionService::USERS_DELETE)
->willReturn(false);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_BULK, [
'actor_user_id' => 7,
'bulk_action' => 'delete',
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
}
public function testAdminDeleteReturnsPermissionDeniedWhenTenantScopeFails(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 7 && $permission === PermissionService::USERS_DELETE);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('users', 17, 7)
->willReturn(false);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_DELETE, [
'actor_user_id' => 7,
'target_user_id' => 17,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('permission_denied', $decision->error());
}
public function testAdminAccessPdfBulkRequiresPermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->expects($this->once())
->method('userHas')
->with(21, PermissionService::USERS_ACCESS_PDF)
->willReturn(false);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->never())->method('canAccess');
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_ACCESS_PDF_BULK, [
'actor_user_id' => 21,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
}
public function testAdminApiTokensManageRequiresScopeForOtherUsers(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 8 && $permission === PermissionService::API_TOKENS_MANAGE);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('users', 18, 8)
->willReturn(false);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_API_TOKENS_MANAGE, [
'actor_user_id' => 8,
'target_user_id' => 18,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame('permission_denied', $decision->error());
}
public function testAdminSendAccessAllowsSelfWithSelfUpdatePermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 30) {
return false;
}
if ($permission === PermissionService::USERS_SELF_UPDATE) {
return true;
}
return false;
});
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->never())->method('canAccess');
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_SEND_ACCESS, [
'actor_user_id' => 30,
'target_user_id' => 30,
]);
$this->assertTrue($decision->isAllowed());
}
public function testEditContextAllowsOwnAccountWithUsersSelfUpdate(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 30) {
return false;
}
return $permission === PermissionService::USERS_SELF_UPDATE;
});
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->never())->method('canAccess');
$scopeGateway->expects($this->once())
->method('getUserTenantIds')
->with(30)
->willReturn([2, 3]);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_EDIT_CONTEXT, [
'actor_user_id' => 30,
'target_user_id' => 30,
]);
$capabilities = $decision->attribute('capabilities', []);
$this->assertTrue($decision->isAllowed());
$this->assertTrue($capabilities['is_own_account'] ?? false);
$this->assertTrue($capabilities['can_edit_user'] ?? false);
$this->assertTrue($capabilities['can_view_page'] ?? false);
$this->assertTrue($capabilities['can_view_security_artifacts'] ?? false);
$this->assertSame([2, 3], $capabilities['allowed_tenant_ids'] ?? []);
}
public function testEditContextReturnsPermissionDeniedWhenTargetIsOutOfScope(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('users', 66, 33)
->willReturn(false);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_EDIT_CONTEXT, [
'actor_user_id' => 33,
'target_user_id' => 66,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('permission_denied', $decision->error());
}
public function testEditContextHidesSecurityArtifactsWithoutAuditPermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 9) {
return false;
}
return $permission === PermissionService::USERS_VIEW;
});
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('users', 55, 9)
->willReturn(true);
$scopeGateway->expects($this->once())
->method('getUserTenantIds')
->with(9)
->willReturn([1]);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_EDIT_CONTEXT, [
'actor_user_id' => 9,
'target_user_id' => 55,
]);
$this->assertTrue($decision->isAllowed());
$this->assertFalse((bool) ($decision->attribute('capabilities', [])['can_view_security_artifacts'] ?? true));
}
public function testEditContextShowsSecurityArtifactsWithAuditPermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 9) {
return false;
}
return in_array($permission, [PermissionService::USERS_VIEW, PermissionService::USERS_VIEW_AUDIT], true);
});
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('users', 55, 9)
->willReturn(true);
$scopeGateway->expects($this->once())
->method('getUserTenantIds')
->with(9)
->willReturn([1]);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_EDIT_CONTEXT, [
'actor_user_id' => 9,
'target_user_id' => 55,
]);
$this->assertTrue($decision->isAllowed());
$this->assertTrue((bool) ($decision->attribute('capabilities', [])['can_view_security_artifacts'] ?? false));
}
public function testEditSubmitRejectsUserWithoutEditCapability(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission): bool {
if ($userId !== 9) {
return false;
}
return $permission === PermissionService::USERS_VIEW;
});
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('users', 55, 9)
->willReturn(true);
$scopeGateway->expects($this->once())
->method('getUserTenantIds')
->with(9)
->willReturn([1]);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_EDIT_SUBMIT, [
'actor_user_id' => 9,
'target_user_id' => 55,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('forbidden', $decision->error());
}
public function testAvatarUploadAllowsOwnAccountWithSelfUpdate(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 19 && $permission === PermissionService::USERS_SELF_UPDATE);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->never())->method('canAccess');
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_AVATAR_UPLOAD, [
'actor_user_id' => 19,
'target_user_id' => 19,
]);
$this->assertTrue($decision->isAllowed());
}
public function testAvatarDeleteReturnsPermissionDeniedOutOfScope(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('users', 42, 7)
->willReturn(false);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_AVATAR_DELETE, [
'actor_user_id' => 7,
'target_user_id' => 42,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame('permission_denied', $decision->error());
}
public function testAvatarViewAllowsInScopeAddressBookViewer(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 5 && $permission === PermissionService::ADDRESS_BOOK_VIEW);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('users', 70, 5)
->willReturn(true);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_AVATAR_VIEW, [
'actor_user_id' => 5,
'target_user_id' => 70,
]);
$this->assertTrue($decision->isAllowed());
}
public function testAvatarViewRejectsInScopeUserWithoutAnyRelevantPermission(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')->willReturn(false);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('users', 70, 5)
->willReturn(true);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_AVATAR_VIEW, [
'actor_user_id' => 5,
'target_user_id' => 70,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame('forbidden', $decision->error());
}
public function testApiShowReturnsNotFoundWhenTenantScopeFails(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 4 && $permission === PermissionService::USERS_VIEW);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('users', 44, 4)
->willReturn(false);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_GET, [
'actor_user_id' => 4,
'target_user_id' => 44,
'scoped_tenant_id' => null,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(404, $decision->status());
$this->assertSame('not_found', $decision->error());
}
public function testApiShowReturnsNotFoundForScopedTokenCrossTenantResource(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 4 && $permission === PermissionService::USERS_VIEW);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('users', 44, 4)
->willReturn(true);
$scopeGateway->expects($this->once())
->method('resourceBelongsToTenant')
->with('users', 44, 2)
->willReturn(false);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_GET, [
'actor_user_id' => 4,
'target_user_id' => 44,
'scoped_tenant_id' => 2,
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(404, $decision->status());
$this->assertSame('not_found', $decision->error());
}
public function testApiCreateForScopedTokenRejectsOutOfScopeTenantIds(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 5 && $permission === PermissionService::USERS_CREATE);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_API_USERS_INDEX_POST, [
'actor_user_id' => 5,
'scoped_tenant_id' => 9,
'input' => ['tenant_ids' => [9, 10]],
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('tenant_scoped_token_forbidden', $decision->error());
}
public function testApiCreateForScopedTokenEnforcesScopedTenantInInput(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 5 && $permission === PermissionService::USERS_CREATE);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_API_USERS_INDEX_POST, [
'actor_user_id' => 5,
'scoped_tenant_id' => 9,
'input' => ['first_name' => 'Ada', 'tenant_ids' => [9]],
]);
$this->assertTrue($decision->isAllowed());
$this->assertSame([9], $decision->attribute('input')['tenant_ids'] ?? []);
$this->assertSame(9, $decision->attribute('input')['primary_tenant_id'] ?? null);
}
public function testApiUpdateForScopedTokenRejectsOutOfScopePrimaryTenant(): void
{
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 6 && $permission === PermissionService::USERS_UPDATE);
$scopeGateway = $this->createMock(DirectoryScopeGateway::class);
$scopeGateway->expects($this->once())
->method('canAccess')
->with('users', 42, 6)
->willReturn(true);
$scopeGateway->expects($this->once())
->method('resourceBelongsToTenant')
->with('users', 42, 2)
->willReturn(true);
$policy = new UserAuthorizationPolicy($permissionGateway, $scopeGateway);
$decision = $policy->authorize(UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_UPDATE, [
'actor_user_id' => 6,
'target_user_id' => 42,
'scoped_tenant_id' => 2,
'input' => ['primary_tenant_id' => 7],
]);
$this->assertFalse($decision->isAllowed());
$this->assertSame(403, $decision->status());
$this->assertSame('tenant_scoped_token_forbidden', $decision->error());
}
}

View File

@@ -0,0 +1,142 @@
<?php
namespace MintyPHP\Tests\Service\Tenant;
use MintyPHP\Repository\Org\DepartmentRepository;
use MintyPHP\Repository\Tenant\TenantRepository;
use MintyPHP\Repository\Tenant\UserTenantRepository;
use MintyPHP\Service\Access\PermissionGateway;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Tenant\TenantScopeService;
use PHPUnit\Framework\TestCase;
class TenantScopeServiceTest extends TestCase
{
public function testLegacyPermissionsDoNotGrantGlobalAccess(): void
{
$checkedPermissions = [];
$tenantRepository = $this->createMock(TenantRepository::class);
$tenantRepository->method('listIds')->willReturn([1, 2, 3]);
$tenantRepository->method('listActiveIdsByIds')
->willReturnCallback(static fn (array $ids): array => array_values(array_intersect([1, 2, 3], $ids)));
$departmentRepository = $this->createMock(DepartmentRepository::class);
$userTenantRepository = $this->createMock(UserTenantRepository::class);
$userTenantRepository->method('listTenantIdsByUserId')
->willReturnCallback(static function (int $userId): array {
if ($userId === 10) {
return [1];
}
if ($userId === 99) {
return [2];
}
return [];
});
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static function (int $userId, string $permission) use (&$checkedPermissions): bool {
$checkedPermissions[] = $permission;
if ($userId !== 10) {
return false;
}
return in_array($permission, [PermissionService::SETTINGS_UPDATE, PermissionService::TENANTS_UPDATE], true);
});
$service = new TenantScopeService(
$tenantRepository,
$departmentRepository,
$userTenantRepository,
$permissionGateway
);
$this->assertFalse($service->hasGlobalAccess(10));
$this->assertFalse($service->canAccess('users', 99, 10));
$this->assertNotEmpty($checkedPermissions);
$this->assertSame(
[PermissionService::TENANT_SCOPE_GLOBAL],
array_values(array_unique($checkedPermissions))
);
}
public function testGlobalPermissionGrantsBypass(): void
{
$tenantRepository = $this->createMock(TenantRepository::class);
$departmentRepository = $this->createMock(DepartmentRepository::class);
$userTenantRepository = $this->createMock(UserTenantRepository::class);
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 77 && $permission === PermissionService::TENANT_SCOPE_GLOBAL);
$service = new TenantScopeService(
$tenantRepository,
$departmentRepository,
$userTenantRepository,
$permissionGateway
);
$this->assertTrue($service->hasGlobalAccess(77));
$this->assertTrue($service->canAccess('users', 12345, 77));
}
public function testGetUserTenantIdsReturnsAllActiveTenantsWhenGlobalPermissionIsPresent(): void
{
$tenantRepository = $this->createMock(TenantRepository::class);
$tenantRepository->expects($this->once())
->method('listIds')
->willReturn([1, 2, 3]);
$tenantRepository->expects($this->once())
->method('listActiveIdsByIds')
->with([1, 2, 3])
->willReturn([1, 3]);
$departmentRepository = $this->createMock(DepartmentRepository::class);
$userTenantRepository = $this->createMock(UserTenantRepository::class);
$userTenantRepository->expects($this->never())->method('listTenantIdsByUserId');
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')
->willReturnCallback(static fn (int $userId, string $permission): bool => $userId === 55 && $permission === PermissionService::TENANT_SCOPE_GLOBAL);
$service = new TenantScopeService(
$tenantRepository,
$departmentRepository,
$userTenantRepository,
$permissionGateway
);
$this->assertSame([1, 3], $service->getUserTenantIds(55));
}
public function testGetUserTenantIdsWithoutGlobalPermissionUsesAssignedTenantsOnly(): void
{
$tenantRepository = $this->createMock(TenantRepository::class);
$tenantRepository->expects($this->once())
->method('listActiveIdsByIds')
->with([2, 4])
->willReturn([2]);
$tenantRepository->expects($this->never())->method('listIds');
$departmentRepository = $this->createMock(DepartmentRepository::class);
$userTenantRepository = $this->createMock(UserTenantRepository::class);
$userTenantRepository->expects($this->once())
->method('listTenantIdsByUserId')
->with(88)
->willReturn([2, 4, 4]);
$permissionGateway = $this->createMock(PermissionGateway::class);
$permissionGateway->method('userHas')->willReturn(false);
$service = new TenantScopeService(
$tenantRepository,
$departmentRepository,
$userTenantRepository,
$permissionGateway
);
$this->assertSame([2], $service->getUserTenantIds(88));
}
}