diff --git a/composer.json b/composer.json index 63cc9fa..e996e96 100644 --- a/composer.json +++ b/composer.json @@ -54,7 +54,8 @@ }, "autoload-dev": { "psr-4": { - "App\\Tests\\": "tests/" + "App\\Tests\\": "tests/", + "Functional\\": "tests/Functional/" } }, "replace": { diff --git a/config/api_platform/BootServer.yaml b/config/api_platform/BootServer.yaml index 058339d..2f8d11b 100644 --- a/config/api_platform/BootServer.yaml +++ b/config/api_platform/BootServer.yaml @@ -13,17 +13,22 @@ resources: ApiPlatform\Metadata\Get: provider: App\State\Provider\BootServerProvider ApiPlatform\Metadata\Put: + security: 'is_granted("ROLE_SUPER_ADMIN")' provider: App\State\Provider\BootServerProvider ApiPlatform\Metadata\Patch: + security: 'is_granted("ROLE_SUPER_ADMIN")' provider: App\State\Provider\BootServerProvider - ApiPlatform\Metadata\Post: ~ - ApiPlatform\Metadata\Delete: ~ + ApiPlatform\Metadata\Post: + security: 'is_granted("ROLE_SUPER_ADMIN")' + ApiPlatform\Metadata\Delete: + security: 'is_granted("ROLE_SUPER_ADMIN")' oglives_sync: shortName: BootServer class: ApiPlatform\Metadata\Post method: POST input: false + security: 'is_granted("ROLE_SUPER_ADMIN")' uriTemplate: /boot-servers/{uuid}/oglives/sync controller: App\Controller\OgBoot\OgLive\SyncAction @@ -32,6 +37,7 @@ resources: class: ApiPlatform\Metadata\Post method: POST input: false + security: 'is_granted("ROLE_SUPER_ADMIN")' uriTemplate: /boot-servers/{uuid}/pxe-templates/sync controller: App\Controller\OgBoot\PxeTemplate\SyncAction diff --git a/config/api_platform/Client.yaml b/config/api_platform/Client.yaml index c8a2963..f3cfc0d 100644 --- a/config/api_platform/Client.yaml +++ b/config/api_platform/Client.yaml @@ -24,7 +24,8 @@ resources: provider: App\State\Provider\ClientProvider validationContext: groups: [ 'client:patch' ] - ApiPlatform\Metadata\Post: ~ + ApiPlatform\Metadata\Post: + security: 'is_granted("ROLE_SUPER_ADMIN") or is_granted("ROLE_ORGANIZATIONAL_UNIT_ADMIN")' ApiPlatform\Metadata\Delete: ~ delete_multiple_clients: diff --git a/config/api_platform/Command.yaml b/config/api_platform/Command.yaml index c89428b..eb18403 100644 --- a/config/api_platform/Command.yaml +++ b/config/api_platform/Command.yaml @@ -20,11 +20,15 @@ resources: ApiPlatform\Metadata\Get: provider: App\State\Provider\CommandProvider ApiPlatform\Metadata\Put: + security: 'is_granted("ROLE_SUPER_ADMIN")' provider: App\State\Provider\CommandProvider ApiPlatform\Metadata\Patch: + security: 'is_granted("ROLE_SUPER_ADMIN")' provider: App\State\Provider\CommandProvider - ApiPlatform\Metadata\Post: ~ - ApiPlatform\Metadata\Delete: ~ + ApiPlatform\Metadata\Post: + security: 'is_granted("ROLE_SUPER_ADMIN")' + ApiPlatform\Metadata\Delete: + security: 'is_granted("ROLE_SUPER_ADMIN")' command_execute: class: ApiPlatform\Metadata\Post diff --git a/config/api_platform/DhcpServer.yaml b/config/api_platform/DhcpServer.yaml index 2208b65..ef4d0d5 100644 --- a/config/api_platform/DhcpServer.yaml +++ b/config/api_platform/DhcpServer.yaml @@ -15,19 +15,24 @@ resources: provider: App\State\Provider\DhcpServerProvider ApiPlatform\Metadata\Put: + security: 'is_granted("ROLE_SUPER_ADMIN")' provider: App\State\Provider\DhcpServerProvider ApiPlatform\Metadata\Patch: + security: 'is_granted("ROLE_SUPER_ADMIN")' provider: App\State\Provider\DhcpServerProvider - ApiPlatform\Metadata\Post: ~ - ApiPlatform\Metadata\Delete: ~ + ApiPlatform\Metadata\Post: + security: 'is_granted("ROLE_SUPER_ADMIN")' + ApiPlatform\Metadata\Delete: + security: 'is_granted("ROLE_SUPER_ADMIN")' subnet_sync: shortName: DhcpServer class: ApiPlatform\Metadata\Post method: POST input: false + security: 'is_granted("ROLE_SUPER_ADMIN")' uriTemplate: /dhcp-servers/{uuid}/sync controller: App\Controller\OgDhcp\Subnet\SyncAction diff --git a/config/api_platform/ImageRepository.yaml b/config/api_platform/ImageRepository.yaml index f2cc348..ae8ba9f 100644 --- a/config/api_platform/ImageRepository.yaml +++ b/config/api_platform/ImageRepository.yaml @@ -18,11 +18,15 @@ resources: ApiPlatform\Metadata\Get: provider: App\State\Provider\ImageRepositoryProvider ApiPlatform\Metadata\Put: + security: 'is_granted("ROLE_SUPER_ADMIN")' provider: App\State\Provider\ImageRepositoryProvider ApiPlatform\Metadata\Patch: + security: 'is_granted("ROLE_SUPER_ADMIN")' provider: App\State\Provider\ImageRepositoryProvider - ApiPlatform\Metadata\Post: ~ - ApiPlatform\Metadata\Delete: ~ + ApiPlatform\Metadata\Post: + security: 'is_granted("ROLE_SUPER_ADMIN")' + ApiPlatform\Metadata\Delete: + security: 'is_granted("ROLE_SUPER_ADMIN")' image_ogrepository_sync: shortName: OgRepository Server diff --git a/config/api_platform/OrganizationalUnit.yaml b/config/api_platform/OrganizationalUnit.yaml index b383a20..17e304b 100644 --- a/config/api_platform/OrganizationalUnit.yaml +++ b/config/api_platform/OrganizationalUnit.yaml @@ -26,8 +26,11 @@ resources: provider: App\State\Provider\OrganizationalUnitProvider validationContext: groups: ['organizational-unit:patch' ] - ApiPlatform\Metadata\Post: ~ - ApiPlatform\Metadata\Delete: ~ + ApiPlatform\Metadata\Post: + security: 'is_granted("ROLE_SUPER_ADMIN") or is_granted("ROLE_ORGANIZATIONAL_UNIT_ADMIN")' + ApiPlatform\Metadata\Delete: + security: 'is_granted("ROLE_SUPER_ADMIN") or (is_granted("ROLE_ORGANIZATIONAL_UNIT_ADMIN") and object.getCreatedBy() == user.getUserIdentifier())' + securityMessage: 'You can only delete organizational units you created.' change_parent: class: ApiPlatform\Metadata\Post method: POST diff --git a/config/api_platform/Subnet.yaml b/config/api_platform/Subnet.yaml index dd3e49d..77bb4a8 100644 --- a/config/api_platform/Subnet.yaml +++ b/config/api_platform/Subnet.yaml @@ -17,11 +17,15 @@ resources: ApiPlatform\Metadata\Get: provider: App\State\Provider\SubnetProvider ApiPlatform\Metadata\Put: + security: 'is_granted("ROLE_SUPER_ADMIN")' provider: App\State\Provider\SubnetProvider ApiPlatform\Metadata\Patch: + security: 'is_granted("ROLE_SUPER_ADMIN")' provider: App\State\Provider\SubnetProvider - ApiPlatform\Metadata\Post: ~ - ApiPlatform\Metadata\Delete: ~ + ApiPlatform\Metadata\Post: + security: 'is_granted("ROLE_SUPER_ADMIN")' + ApiPlatform\Metadata\Delete: + security: 'is_granted("ROLE_SUPER_ADMIN")' get_subnet: @@ -39,6 +43,7 @@ resources: class: ApiPlatform\Metadata\Post method: POST input: false + security: 'is_granted("ROLE_SUPER_ADMIN")' uriTemplate: /og-dhcp/server/{uuid}/post controller: App\Controller\OgDhcp\Subnet\PostAction @@ -48,6 +53,7 @@ resources: class: ApiPlatform\Metadata\Put method: PUT input: false + security: 'is_granted("ROLE_SUPER_ADMIN")' uriTemplate: /og-dhcp/server/{uuid}/put controller: App\Controller\OgDhcp\Subnet\PutAction @@ -57,6 +63,7 @@ resources: class: ApiPlatform\Metadata\Delete method: DELETE input: false + security: 'is_granted("ROLE_SUPER_ADMIN")' uriTemplate: /og-dhcp/server/{uuid}/delete controller: App\Controller\OgDhcp\Subnet\DeleteAction @@ -66,6 +73,7 @@ resources: class: ApiPlatform\Metadata\Post method: POST input: App\Dto\Input\SubnetAddHostInput + security: 'is_granted("ROLE_SUPER_ADMIN")' uriTemplate: /og-dhcp/server/{uuid}/post-host controller: App\Controller\OgDhcp\Subnet\PostHostAction @@ -84,6 +92,7 @@ resources: class: ApiPlatform\Metadata\Put method: PUT input: false + security: 'is_granted("ROLE_SUPER_ADMIN")' uriTemplate: /og-dhcp/server/{uuid}/put-host controller: App\Controller\OgDhcp\Subnet\PutHostAction @@ -94,6 +103,7 @@ resources: method: DELETE input: false read: false + security: 'is_granted("ROLE_SUPER_ADMIN")' uriTemplate: /og-dhcp/server/{uuid}/delete-host/{clientUuid} controller: App\Controller\OgDhcp\Subnet\DeleteHostAction @@ -103,6 +113,7 @@ resources: class: ApiPlatform\Metadata\Delete method: DELETE input: false + security: 'is_granted("ROLE_SUPER_ADMIN")' uriTemplate: /og-dhcp/server/{uuid}/delete-leases controller: App\Controller\OgDhcp\Subnet\DeleteSubnetLeasesAction @@ -113,6 +124,7 @@ resources: method: DELETE input: false read: false + security: 'is_granted("ROLE_SUPER_ADMIN")' uriTemplate: /og-dhcp/server/{uuid}/delete-lease/{clientUuid} controller: App\Controller\OgDhcp\Subnet\DeleteClientLeaseAction diff --git a/config/packages/security.yaml b/config/packages/security.yaml index a4ce57f..c0f8945 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -39,6 +39,11 @@ security: - { path: ^/validate, roles: PUBLIC_ACCESS } - { path: ^/menu-browser, roles: PUBLIC_ACCESS } - { path: ^/menu/, roles: PUBLIC_ACCESS } + # Creación de clientes y OUs: solo super-admin y ou-admin + - { path: ^/clients$, methods: [POST], roles: [ROLE_SUPER_ADMIN, ROLE_ORGANIZATIONAL_UNIT_ADMIN] } + - { path: ^/organizational-units$, methods: [POST], roles: [ROLE_SUPER_ADMIN, ROLE_ORGANIZATIONAL_UNIT_ADMIN] } + # ogLive puede consultar clientes por IP con su API key + - { path: ^/clients, methods: [GET], roles: [ROLE_OGCLIENT_API, ROLE_USER] } - { path: ^/, roles: ROLE_USER } when@test: diff --git a/migrations/Version20260615092704.php b/migrations/Version20260615092704.php new file mode 100644 index 0000000..5d60c4b --- /dev/null +++ b/migrations/Version20260615092704.php @@ -0,0 +1,33 @@ +addSql('ALTER TABLE hardware_profile DROP FOREIGN KEY FK_2D9A246019EB6921'); + $this->addSql('ALTER TABLE hardware_profile ADD CONSTRAINT FK_2D9A246019EB6921 FOREIGN KEY (client_id) REFERENCES client (id) ON DELETE CASCADE'); + } + + public function down(Schema $schema): void + { + // this down() migration is auto-generated, please modify it to your needs + $this->addSql('ALTER TABLE hardware_profile DROP FOREIGN KEY FK_2D9A246019EB6921'); + $this->addSql('ALTER TABLE hardware_profile ADD CONSTRAINT FK_2D9A246019EB6921 FOREIGN KEY (client_id) REFERENCES client (id)'); + } +} diff --git a/src/Controller/OgAgent/OrganizationalUnitStatusAction.php b/src/Controller/OgAgent/OrganizationalUnitStatusAction.php index d884117..77c4a84 100644 --- a/src/Controller/OgAgent/OrganizationalUnitStatusAction.php +++ b/src/Controller/OgAgent/OrganizationalUnitStatusAction.php @@ -47,6 +47,8 @@ class OrganizationalUnitStatusAction extends AbstractOgAgentController } $options = $this->buildRequestOptions(['json' => ['full-config' => false]]); + $options['timeout'] = 5.0; + $options['max_duration'] = 5.0; $skippedStatuses = [ ClientStatus::DISCONNECTED, diff --git a/src/Controller/OgBoot/PxeBootFile/DeleteAction.php b/src/Controller/OgBoot/PxeBootFile/DeleteAction.php index 0a957a8..201f29d 100644 --- a/src/Controller/OgBoot/PxeBootFile/DeleteAction.php +++ b/src/Controller/OgBoot/PxeBootFile/DeleteAction.php @@ -25,7 +25,7 @@ class DeleteAction extends AbstractOgBootController { $response = $this->createRequest('DELETE', '/ogboot/v1/pxes/'.$mac); - if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) { + if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) { return new JsonResponse( data: 'An error occurred', status: Response::HTTP_INTERNAL_SERVER_ERROR); } diff --git a/src/Dto/Input/CommandTaskScheduleInput.php b/src/Dto/Input/CommandTaskScheduleInput.php index 6f6d272..d592a22 100644 --- a/src/Dto/Input/CommandTaskScheduleInput.php +++ b/src/Dto/Input/CommandTaskScheduleInput.php @@ -74,20 +74,18 @@ final class CommandTaskScheduleInput $commandTaskSchedule = new CommandTaskSchedule(); } - $utc = new \DateTimeZone('UTC'); - if ($this->commandTask) { $commandTaskSchedule->setCommandTask($this->commandTask->getEntity()); } $commandTaskSchedule->setRecurrenceType($this->recurrenceType); $commandTaskSchedule->setExecutionTime( $this->executionTime - ? \DateTime::createFromInterface($this->executionTime)->setTimezone($utc) + ? \DateTime::createFromInterface($this->executionTime)->setTimezone(new \DateTimeZone('UTC')) : null ); $commandTaskSchedule->setExecutionDate( $this->executionDate - ? \DateTime::createFromInterface($this->executionDate)->setTimezone($utc) + ? \DateTime::createFromInterface($this->executionDate) : null ); $commandTaskSchedule->setRecurrenceDetails($this->recurrenceDetails); diff --git a/src/Dto/Output/CommandTaskOutput.php b/src/Dto/Output/CommandTaskOutput.php index eb04d38..f4439e5 100644 --- a/src/Dto/Output/CommandTaskOutput.php +++ b/src/Dto/Output/CommandTaskOutput.php @@ -92,8 +92,15 @@ final class CommandTaskOutput extends AbstractOutput } $this->notes = $commandTask->getNotes(); $this->scope = $commandTask->getScope(); - $this->lastExecution = $commandTask->getLastExecution(); - $this->nextExecution = $commandTask->getNextExecution(); + $rawLast = $commandTask->getLastExecution(); + $this->lastExecution = $rawLast + ? new \DateTime($rawLast->format('Y-m-d H:i:s'), new \DateTimeZone('UTC')) + : null; + + $rawNext = $commandTask->getNextExecution(); + $this->nextExecution = $rawNext + ? new \DateTime($rawNext->format('Y-m-d H:i:s'), new \DateTimeZone('UTC')) + : null; $this->createdAt = $commandTask->getCreatedAt(); $this->createdBy = $commandTask->getCreatedBy(); } diff --git a/src/Dto/Output/CommandTaskScheduleOutput.php b/src/Dto/Output/CommandTaskScheduleOutput.php index 6860aee..13921fa 100644 --- a/src/Dto/Output/CommandTaskScheduleOutput.php +++ b/src/Dto/Output/CommandTaskScheduleOutput.php @@ -54,7 +54,12 @@ class CommandTaskScheduleOutput extends AbstractOutput } $this->recurrenceType = $commandTaskSchedule->getRecurrenceType(); - $this->executionTime = $commandTaskSchedule->getExecutionTime(); + + $rawTime = $commandTaskSchedule->getExecutionTime(); + $this->executionTime = $rawTime + ? new \DateTime('1970-01-01 ' . $rawTime->format('H:i:s'), new \DateTimeZone('UTC')) + : null; + $this->executionDate = $commandTaskSchedule->getExecutionDate(); $this->recurrenceDetails = $commandTaskSchedule->getRecurrenceDetails(); $this->enabled = $commandTaskSchedule->isEnabled(); diff --git a/src/Entity/HardwareProfile.php b/src/Entity/HardwareProfile.php index 448be48..533ff9b 100644 --- a/src/Entity/HardwareProfile.php +++ b/src/Entity/HardwareProfile.php @@ -17,7 +17,7 @@ class HardwareProfile extends AbstractEntity private ?string $comments = null; #[ORM\ManyToOne(targetEntity: Client::class, inversedBy: 'hardwareProfile')] - #[ORM\JoinColumn(nullable: false)] + #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')] private ?Client $client = null; /** diff --git a/src/Security/Voter/OrganizationalUnitVoter.php b/src/Security/Voter/OrganizationalUnitVoter.php index 2fd3112..8755e2d 100644 --- a/src/Security/Voter/OrganizationalUnitVoter.php +++ b/src/Security/Voter/OrganizationalUnitVoter.php @@ -34,11 +34,33 @@ class OrganizationalUnitVoter extends Voter return true; } - if ($attribute === 'ORGANIZATIONAL_UNIT_VIEW' ) { - foreach ($user->getAllowedOrganizationalUnits() as $allowedOrganizationalUnit) { - if ($allowedOrganizationalUnit->getId() === $subject->getEntity()->getId()) { - return true; - } + if ($attribute === 'ORGANIZATIONAL_UNIT_VIEW') { + return $this->isAllowed($subject->getEntity(), $user); + } + + return false; + } + + private function isAllowed(OrganizationalUnit $target, User $user): bool + { + foreach ($user->getAllowedOrganizationalUnits() as $allowedOU) { + if ($this->isDescendantOrSelf($target, $allowedOU)) { + return true; + } + } + + return false; + } + + private function isDescendantOrSelf(OrganizationalUnit $target, OrganizationalUnit $root): bool + { + if ($root->getId() === $target->getId()) { + return true; + } + + foreach ($root->getOrganizationalUnits() as $child) { + if ($this->isDescendantOrSelf($target, $child)) { + return true; } } diff --git a/src/State/Processor/ClientProcessor.php b/src/State/Processor/ClientProcessor.php index a1879e3..9a5bb2a 100644 --- a/src/State/Processor/ClientProcessor.php +++ b/src/State/Processor/ClientProcessor.php @@ -13,16 +13,21 @@ use App\Controller\OgBoot\PxeBootFile\DeleteAction; use App\Controller\OgDhcp\Subnet\DeleteHostAction; use App\Dto\Input\ClientInput; use App\Dto\Output\ClientOutput; +use App\Entity\User; +use App\Model\UserGroupPermissions; use App\Repository\ClientRepository; use App\Repository\BootServerRepository; use App\Repository\MenuRepository; use App\Repository\OgLiveRepository; use App\Repository\PxeTemplateRepository; +use Symfony\Bundle\SecurityBundle\Security; use Symfony\Component\HttpKernel\KernelInterface; +use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface; use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface; use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; +use Symfony\Component\HttpKernel\Exception\HttpException; readonly class ClientProcessor implements ProcessorInterface { @@ -36,6 +41,7 @@ readonly class ClientProcessor implements ProcessorInterface private DeleteHostAction $deleteHostAction, private DeleteAction $deletePxeAction, private KernelInterface $kernel, + private Security $security, ) { } @@ -60,6 +66,16 @@ readonly class ClientProcessor implements ProcessorInterface */ private function processCreateOrUpdate($data, Operation $operation, array $uriVariables = [], array $context = []): ClientOutput { + if ($operation instanceof Post) { + $currentUser = $this->security->getUser(); + if ($currentUser instanceof User + && !in_array(UserGroupPermissions::ROLE_SUPER_ADMIN, $currentUser->getRoles()) + && !in_array(UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN, $currentUser->getRoles()) + ) { + throw new AccessDeniedException('You are not allowed to create clients.'); + } + } + if (!($data instanceof ClientInput)) { throw new \Exception(sprintf('data is not instance of %s', ClientInput::class)); } @@ -117,9 +133,27 @@ readonly class ClientProcessor implements ProcessorInterface if ($this->kernel->getEnvironment() !== 'test') { if ($client->getSubnet()) { - $this->deleteHostAction->__invoke($client->getSubnet(), $client->getUuid()); + try { + $this->deleteHostAction->__invoke($client->getSubnet(), $client->getUuid()); + } catch (HttpException $e) { + if ($e->getStatusCode() !== 404) { + throw $e; + } + } catch (\Exception $e) { + // Ignore missing DHCP server or other non-HTTP exceptions during deletion + } + } + if ($client->getMac() && $client->getTemplate()) { + try { + $this->deletePxeAction->__invoke($client->getMac()); + } catch (HttpException $e) { + if ($e->getStatusCode() !== 404) { + throw $e; + } + } catch (\Exception $e) { + // Ignore missing DHCP server or other non-HTTP exceptions during deletion + } } - $this->deletePxeAction->__invoke($client->getMac()); } $this->clientRepository->delete($client); diff --git a/src/State/Processor/OrganizationalUnitProcessor.php b/src/State/Processor/OrganizationalUnitProcessor.php index 3a733e2..c984b4f 100644 --- a/src/State/Processor/OrganizationalUnitProcessor.php +++ b/src/State/Processor/OrganizationalUnitProcessor.php @@ -11,9 +11,14 @@ use ApiPlatform\State\ProcessorInterface; use ApiPlatform\Validator\ValidatorInterface; use App\Dto\Input\OrganizationalUnitInput; use App\Dto\Output\OrganizationalUnitOutput; +use App\Entity\User; +use App\Model\UserGroupPermissions; use App\Repository\OrganizationalUnitRepository; use App\Repository\BootServerRepository; +use App\Repository\UserRepository; use App\Service\ChangeClientNetworkSettingsService; +use Symfony\Bundle\SecurityBundle\Security; +use Symfony\Component\Security\Core\Exception\AccessDeniedException; readonly class OrganizationalUnitProcessor implements ProcessorInterface { @@ -22,6 +27,8 @@ readonly class OrganizationalUnitProcessor implements ProcessorInterface private BootServerRepository $bootServerRepository, private ValidatorInterface $validator, private ChangeClientNetworkSettingsService $changeClientNetworkSettingsService, + private Security $security, + private UserRepository $userRepository, ) { } @@ -46,6 +53,17 @@ readonly class OrganizationalUnitProcessor implements ProcessorInterface */ private function processCreateOrUpdate($data, Operation $operation, array $uriVariables = [], array $context = []): OrganizationalUnitOutput { + if ($operation instanceof Post) { + $user = $this->security->getUser(); + if ($user instanceof User) { + if (!in_array(UserGroupPermissions::ROLE_SUPER_ADMIN, $user->getRoles()) + && !in_array(UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN, $user->getRoles()) + ) { + throw new AccessDeniedException('You are not allowed to create organizational units.'); + } + } + } + if (!($data instanceof OrganizationalUnitInput)) { throw new \Exception(sprintf('data is not instance of %s', OrganizationalUnitInput::class)); } @@ -69,6 +87,15 @@ readonly class OrganizationalUnitProcessor implements ProcessorInterface $this->validator->validate($organizationalUnit, ['groups' => ['organizational-unit:write']]); $this->organizationalUnitRepository->save($organizationalUnit); + if ($operation instanceof Post) { + $user = $this->security->getUser(); + if ($user instanceof User && !in_array(UserGroupPermissions::ROLE_SUPER_ADMIN, $user->getRoles())) { + // Añadir la OU a la lista de permitidas para el ou-admin que la creó + $user->addAllowedOrganizationalUnit($organizationalUnit); + $this->userRepository->save($user); + } + } + //$this->changeClientNetworkSettingsService->__invoke($organizationalUnit); return new OrganizationalUnitOutput($organizationalUnit); @@ -76,8 +103,19 @@ readonly class OrganizationalUnitProcessor implements ProcessorInterface private function processDelete($data, Operation $operation, array $uriVariables = [], array $context = []): null { - $user = $this->organizationalUnitRepository->findOneByUuid($uriVariables['uuid']); - $this->organizationalUnitRepository->delete($user); + $organizationalUnit = $this->organizationalUnitRepository->findOneByUuid($uriVariables['uuid']); + + $currentUser = $this->security->getUser(); + + if ($currentUser instanceof User && !in_array(UserGroupPermissions::ROLE_SUPER_ADMIN, $currentUser->getRoles())) { + if ($organizationalUnit->getCreatedBy() === null + || $organizationalUnit->getCreatedBy() !== $currentUser->getUserIdentifier() + ) { + throw new AccessDeniedException('You are not allowed to delete this organizational unit.'); + } + } + + $this->organizationalUnitRepository->delete($organizationalUnit); return null; } diff --git a/tests/Functional/OrganizationalUnitTest.php b/tests/Functional/OrganizationalUnitTest.php index bcb4a97..c965947 100644 --- a/tests/Functional/OrganizationalUnitTest.php +++ b/tests/Functional/OrganizationalUnitTest.php @@ -104,6 +104,61 @@ class OrganizationalUnitTest extends AbstractTest ]); } + /** + * Verifica que un ou-admin puede editar (PUT/GET) un aula que él mismo creó. + * Antes del fix, el POST no añadía la OU a allowedOrganizationalUnits y + * el GET/PUT devolvía 403/404. + */ + public function testOuAdminCanEditOrganizationalUnitTheyCreated(): void + { + $username = 'ou-admin-test'; + UserFactory::createOne([ + 'username' => $username, + 'roles' => [UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN], + ]); + + $token = $this->getToken(['username' => $username, 'password' => UserFactory::PLAIN_PASSWORD]); + $client = $this->createClientWithCredentials($token); + + $response = $client->request('POST', '/organizational-units', ['json' => [ + 'name' => 'aula-creada-por-ou-admin', + 'type' => OrganizationalUnitTypes::CLASSROOM, + ]]); + $this->assertResponseStatusCodeSame(201); + $iri = $response->toArray()['@id']; + + $client->request('GET', $iri); + $this->assertResponseStatusCodeSame(200); + + $client->request('PUT', $iri, ['json' => [ + 'name' => 'aula-creada-por-ou-admin-editada', + ]]); + $this->assertResponseIsSuccessful(); + $this->assertJsonContains(['name' => 'aula-creada-por-ou-admin-editada']); + } + + /** + * Verifica que un ou-operator NO puede crear OUs (POST → 403). + * Antes del fix de permisos, los operadores podían crear OUs. + * Con la restricción actual, deben recibir 403. + */ + public function testOuOperatorCannotCreateOrganizationalUnit(): void + { + $username = 'ou-operator-test'; + UserFactory::createOne([ + 'username' => $username, + 'roles' => [UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR], + ]); + + $token = $this->getToken(['username' => $username, 'password' => UserFactory::PLAIN_PASSWORD]); + + $this->createClientWithCredentials($token)->request('POST', '/organizational-units', ['json' => [ + 'name' => 'aula-operador-no-puede-crear', + 'type' => OrganizationalUnitTypes::CLASSROOM, + ]]); + $this->assertResponseStatusCodeSame(403); + } + /** * @throws TransportExceptionInterface * @throws ServerExceptionInterface diff --git a/tests/Functional/PermissionsTest.php b/tests/Functional/PermissionsTest.php new file mode 100644 index 0000000..d49a5d7 --- /dev/null +++ b/tests/Functional/PermissionsTest.php @@ -0,0 +1,523 @@ + $username, 'roles' => [$role]]); + return $this->getToken([ + 'username' => $username, + 'password' => UserFactory::PLAIN_PASSWORD, + ]); + } + + /** Cliente HTTP autenticado con el token dado. */ + private function as(string $token): \ApiPlatform\Symfony\Bundle\Test\Client + { + return $this->createClientWithCredentials($token); + } + + /** Crea un DhcpServer directamente en BD y devuelve su IRI. */ + private function createDhcpServerIri(string $ip = '192.0.2.10', string $name = 'dhcp-test'): string + { + $em = static::getContainer()->get('doctrine')->getManager(); + $server = new DhcpServer(); + $server->setIp($ip); + $server->setName($name); + $em->persist($server); + $em->flush(); + return '/dhcp-servers/' . $server->getUuid(); + } + + /** Crea un BootServer directamente en BD y devuelve su IRI. */ + private function createBootServerIri(string $name = 'boot-test', string $ip = '192.0.2.11'): string + { + $em = static::getContainer()->get('doctrine')->getManager(); + $server = new BootServer(); + $server->setName($name); + $server->setIp($ip); + $em->persist($server); + $em->flush(); + return '/boot-servers/' . $server->getUuid(); + } + + /** + * Crea una OU directamente en BD con un createdBy específico + * y opcionalmente la asigna al usuario indicado (para que el filtro + * de OUs no devuelva 404 cuando intenten borrarla). + */ + private function createOuOwnedBy( + string $createdByUsername, + string $ouName = 'test-ou', + ?\App\Entity\User $assignToUser = null + ): string { + $em = static::getContainer()->get('doctrine')->getManager(); + + $ou = new OrganizationalUnit(); + $ou->setName($ouName); + $ou->setType(OrganizationalUnitTypes::CLASSROOM); + $ou->setCreatedBy($createdByUsername); + $em->persist($ou); + + if ($assignToUser !== null) { + $assignToUser->addAllowedOrganizationalUnit($ou); + $em->persist($assignToUser); + } + + $em->flush(); + return '/organizational-units/' . $ou->getUuid(); + } + + // ═════════════════════════════════════════════════════════════════════════ + // SECCIÓN 1 — CLIENTES: creación + // ═════════════════════════════════════════════════════════════════════════ + + /** Super-admin puede crear un cliente (POST → 201). */ + public function testSuperAdminCanCreateClient(): void + { + $token = $this->tokenFor(self::SA_USER, UserGroupPermissions::ROLE_SUPER_ADMIN); + $ouFactory = OrganizationalUnitFactory::createOne(['type' => OrganizationalUnitTypes::CLASSROOM]); + $ouIri = $this->findIriBy(OrganizationalUnit::class, ['name' => $ouFactory->getName()]); + + $this->as($token)->request('POST', '/clients', ['json' => [ + 'name' => 'client-by-super-admin', + 'organizationalUnit' => $ouIri, + ]]); + $this->assertResponseStatusCodeSame(Response::HTTP_CREATED); + } + + /** OU-admin puede crear un cliente (POST → 201). */ + public function testOuAdminCanCreateClient(): void + { + $token = $this->tokenFor(self::OA_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN); + + // Crear la OU como super-admin y asignarla al ou-admin + $saToken = $this->tokenFor(self::SA_USER, UserGroupPermissions::ROLE_SUPER_ADMIN); + $this->as($saToken)->request('POST', '/organizational-units', ['json' => [ + 'name' => 'aula-for-client-test', + 'type' => OrganizationalUnitTypes::CLASSROOM, + ]]); + $this->assertResponseStatusCodeSame(201); + $ouIri = $this->findIriBy(OrganizationalUnit::class, ['name' => 'aula-for-client-test']); + + // Asignar la OU al ou-admin directamente en BD + $em = static::getContainer()->get('doctrine')->getManager(); + $user = $em->getRepository(\App\Entity\User::class)->findOneBy(['username' => self::OA_USER]); + $ou = $em->getRepository(OrganizationalUnit::class)->findOneBy(['name' => 'aula-for-client-test']); + $user->addAllowedOrganizationalUnit($ou); + $em->flush(); + + $this->as($token)->request('POST', '/clients', ['json' => [ + 'name' => 'client-by-ou-admin', + 'organizationalUnit' => $ouIri, + ]]); + $this->assertResponseStatusCodeSame(Response::HTTP_CREATED); + } + + /** OU-operator NO puede crear un cliente (POST → 403). */ + public function testOuOperatorCannotCreateClient(): void + { + $token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR); + + $this->as($token)->request('POST', '/clients', ['json' => [ + 'name' => 'forbidden-client', + ]]); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + /** OU-minimal NO puede crear un cliente (POST → 403). */ + public function testOuMinimalCannotCreateClient(): void + { + $token = $this->tokenFor(self::OM_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_MINIMAL); + + $this->as($token)->request('POST', '/clients', ['json' => [ + 'name' => 'forbidden-client-minimal', + ]]); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + // ═════════════════════════════════════════════════════════════════════════ + // SECCIÓN 2 — OUs: creación + // ═════════════════════════════════════════════════════════════════════════ + + /** Super-admin puede crear una OU (POST → 201). */ + public function testSuperAdminCanCreateOrganizationalUnit(): void + { + $token = $this->tokenFor(self::SA_USER, UserGroupPermissions::ROLE_SUPER_ADMIN); + $this->as($token)->request('POST', '/organizational-units', ['json' => [ + 'name' => 'ou-by-super-admin', + 'type' => OrganizationalUnitTypes::CLASSROOM, + ]]); + $this->assertResponseStatusCodeSame(Response::HTTP_CREATED); + } + + /** OU-admin puede crear una OU (POST → 201). */ + public function testOuAdminCanCreateOrganizationalUnit(): void + { + $token = $this->tokenFor(self::OA_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN); + $this->as($token)->request('POST', '/organizational-units', ['json' => [ + 'name' => 'ou-by-ou-admin', + 'type' => OrganizationalUnitTypes::CLASSROOM, + ]]); + $this->assertResponseStatusCodeSame(Response::HTTP_CREATED); + } + + /** OU-operator NO puede crear una OU (POST → 403). */ + public function testOuOperatorCannotCreateOrganizationalUnit(): void + { + $token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR); + $this->as($token)->request('POST', '/organizational-units', ['json' => [ + 'name' => 'forbidden-ou', + 'type' => OrganizationalUnitTypes::CLASSROOM, + ]]); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + /** OU-minimal NO puede crear una OU (POST → 403). */ + public function testOuMinimalCannotCreateOrganizationalUnit(): void + { + $token = $this->tokenFor(self::OM_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_MINIMAL); + $this->as($token)->request('POST', '/organizational-units', ['json' => [ + 'name' => 'forbidden-ou-minimal', + 'type' => OrganizationalUnitTypes::CLASSROOM, + ]]); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + // ═════════════════════════════════════════════════════════════════════════ + // SECCIÓN 3 — OUs: borrado con control de autoría + // ═════════════════════════════════════════════════════════════════════════ + + /** + * OU-admin puede borrar una OU que él mismo creó. + * Flujo: POST (crea la OU con createdBy=username) → DELETE → 204. + */ + public function testOuAdminCanDeleteOwnOrganizationalUnit(): void + { + $token = $this->tokenFor(self::OA_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN); + $client = $this->as($token); + + // Crear la OU como ou-admin (Gedmo establece createdBy automáticamente) + $response = $client->request('POST', '/organizational-units', ['json' => [ + 'name' => 'ou-to-delete-by-owner', + 'type' => OrganizationalUnitTypes::CLASSROOM, + ]]); + $this->assertResponseStatusCodeSame(201); + $iri = $response->toArray()['@id']; + + // Borrarla → 204 + $client->request('DELETE', $iri); + $this->assertResponseStatusCodeSame(Response::HTTP_NO_CONTENT); + } + + /** + * OU-admin NO puede borrar una OU creada por otro usuario. + * Se crea la OU directamente en BD con createdBy='otro-usuario' y se asigna + * al ou-admin en allowedOrganizationalUnits para que el filtro no devuelva 404. + */ + public function testOuAdminCannotDeleteOtherUsersOrganizationalUnit(): void + { + // Crear el ou-admin + UserFactory::createOne([ + 'username' => self::OA_USER, + 'roles' => [UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN], + ]); + $token = $this->getToken(['username' => self::OA_USER, 'password' => UserFactory::PLAIN_PASSWORD]); + + // Recuperar la entidad User recién creada para poder asignarle la OU + $em = static::getContainer()->get('doctrine')->getManager(); + $user = $em->getRepository(\App\Entity\User::class)->findOneBy(['username' => self::OA_USER]); + + // Crear una OU con createdBy='otro-admin' y asignarla al ou-admin + $iri = $this->createOuOwnedBy('otro-admin', 'ou-owned-by-other', $user); + + // Intento de borrado → 403 + $this->as($token)->request('DELETE', $iri); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + /** + * Super-admin puede borrar cualquier OU, independientemente de quién la creó. + */ + public function testSuperAdminCanDeleteAnyOrganizationalUnit(): void + { + $token = $this->tokenFor(self::SA_USER, UserGroupPermissions::ROLE_SUPER_ADMIN); + + // OU creada por 'otro-usuario', no el super-admin + $iri = $this->createOuOwnedBy('otro-usuario', 'ou-to-delete-by-sa'); + + $this->as($token)->request('DELETE', $iri); + $this->assertResponseStatusCodeSame(Response::HTTP_NO_CONTENT); + } + + /** + * OU-operator NO puede borrar ninguna OU (no las crea → createdBy nunca coincide). + */ + public function testOuOperatorCannotDeleteOrganizationalUnit(): void + { + UserFactory::createOne([ + 'username' => self::OP_USER, + 'roles' => [UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR], + ]); + $token = $this->getToken(['username' => self::OP_USER, 'password' => UserFactory::PLAIN_PASSWORD]); + + $em = static::getContainer()->get('doctrine')->getManager(); + $user = $em->getRepository(\App\Entity\User::class)->findOneBy(['username' => self::OP_USER]); + + // OU creada por 'otro-admin' y visible para el operador + $iri = $this->createOuOwnedBy('otro-admin', 'ou-op-cannot-delete', $user); + + $this->as($token)->request('DELETE', $iri); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + // ═════════════════════════════════════════════════════════════════════════ + // SECCIÓN 4 — DHCP SERVERS + // ═════════════════════════════════════════════════════════════════════════ + + /** Super-admin puede hacer PATCH en un DhcpServer (→ 200). */ + public function testSuperAdminCanPatchDhcpServer(): void + { + $token = $this->tokenFor(self::SA_USER, UserGroupPermissions::ROLE_SUPER_ADMIN); + $iri = $this->createDhcpServerIri('192.0.2.20', 'dhcp-sa-test'); + + $this->as($token)->request('PATCH', $iri, ['json' => ['name' => 'dhcp-updated']]); + $this->assertResponseIsSuccessful(); + } + + /** OU-admin NO puede hacer PATCH en un DhcpServer (→ 403). */ + public function testOuAdminCannotPatchDhcpServer(): void + { + $token = $this->tokenFor(self::OA_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN); + $iri = $this->createDhcpServerIri('192.0.2.21', 'dhcp-oa-test'); + + $this->as($token)->request('PATCH', $iri, ['json' => ['name' => 'dhcp-forbidden']]); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + /** OU-operator NO puede hacer PATCH en un DhcpServer (→ 403). */ + public function testOuOperatorCannotPatchDhcpServer(): void + { + $token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR); + $iri = $this->createDhcpServerIri('192.0.2.22', 'dhcp-op-test'); + + $this->as($token)->request('PATCH', $iri, ['json' => ['name' => 'dhcp-forbidden']]); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + /** OU-admin NO puede borrar un DhcpServer (→ 403). */ + public function testOuAdminCannotDeleteDhcpServer(): void + { + $token = $this->tokenFor(self::OA_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN); + $iri = $this->createDhcpServerIri('192.0.2.23', 'dhcp-oa-del-test'); + + $this->as($token)->request('DELETE', $iri); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + /** OU-operator NO puede borrar un DhcpServer (→ 403). */ + public function testOuOperatorCannotDeleteDhcpServer(): void + { + $token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR); + $iri = $this->createDhcpServerIri('192.0.2.24', 'dhcp-op-del-test'); + + $this->as($token)->request('DELETE', $iri); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + // ═════════════════════════════════════════════════════════════════════════ + // SECCIÓN 5 — BOOT SERVERS + // ═════════════════════════════════════════════════════════════════════════ + + /** Super-admin puede hacer PATCH en un BootServer (→ 200). */ + public function testSuperAdminCanPatchBootServer(): void + { + $token = $this->tokenFor(self::SA_USER, UserGroupPermissions::ROLE_SUPER_ADMIN); + $iri = $this->createBootServerIri('boot-sa-test', '192.0.2.30'); + + $this->as($token)->request('PATCH', $iri, ['json' => ['name' => 'boot-updated']]); + $this->assertResponseIsSuccessful(); + } + + /** OU-admin NO puede hacer PATCH en un BootServer (→ 403). */ + public function testOuAdminCannotPatchBootServer(): void + { + $token = $this->tokenFor(self::OA_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN); + $iri = $this->createBootServerIri('boot-oa-test', '192.0.2.31'); + + $this->as($token)->request('PATCH', $iri, ['json' => ['name' => 'boot-forbidden']]); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + /** OU-operator NO puede hacer PATCH en un BootServer (→ 403). */ + public function testOuOperatorCannotPatchBootServer(): void + { + $token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR); + $iri = $this->createBootServerIri('boot-op-test', '192.0.2.32'); + + $this->as($token)->request('PATCH', $iri, ['json' => ['name' => 'boot-forbidden']]); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + /** OU-admin NO puede borrar un BootServer (→ 403). */ + public function testOuAdminCannotDeleteBootServer(): void + { + $token = $this->tokenFor(self::OA_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN); + $iri = $this->createBootServerIri('boot-oa-del', '192.0.2.33'); + + $this->as($token)->request('DELETE', $iri); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + /** OU-operator NO puede borrar un BootServer (→ 403). */ + public function testOuOperatorCannotDeleteBootServer(): void + { + $token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR); + $iri = $this->createBootServerIri('boot-op-del', '192.0.2.34'); + + $this->as($token)->request('DELETE', $iri); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + // ═════════════════════════════════════════════════════════════════════════ + // SECCIÓN 6 — IMAGE REPOSITORIES + // ═════════════════════════════════════════════════════════════════════════ + + /** Super-admin puede crear un Image Repository (POST → 201). */ + public function testSuperAdminCanCreateImageRepository(): void + { + $token = $this->tokenFor(self::SA_USER, UserGroupPermissions::ROLE_SUPER_ADMIN); + $this->as($token)->request('POST', '/image-repositories', ['json' => [ + 'name' => 'repo-by-super-admin', + 'ip' => '192.0.2.40', + ]]); + $this->assertResponseStatusCodeSame(Response::HTTP_CREATED); + } + + /** OU-admin NO puede crear un Image Repository (POST → 403). */ + public function testOuAdminCannotCreateImageRepository(): void + { + $token = $this->tokenFor(self::OA_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN); + $this->as($token)->request('POST', '/image-repositories', ['json' => [ + 'name' => 'repo-forbidden', + 'ip' => '192.0.2.41', + ]]); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + /** OU-operator NO puede crear un Image Repository (POST → 403). */ + public function testOuOperatorCannotCreateImageRepository(): void + { + $token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR); + $this->as($token)->request('POST', '/image-repositories', ['json' => [ + 'name' => 'repo-forbidden-op', + 'ip' => '192.0.2.42', + ]]); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + /** OU-admin NO puede borrar un Image Repository (DELETE → 403). */ + public function testOuAdminCannotDeleteImageRepository(): void + { + $token = $this->tokenFor(self::OA_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN); + $repo = ImageRepositoryFactory::createOne(); + $iri = $this->findIriBy(\App\Entity\ImageRepository::class, ['name' => $repo->getName()]); + + $this->as($token)->request('DELETE', $iri); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + // ═════════════════════════════════════════════════════════════════════════ + // SECCIÓN 7 — COMMANDS + // ═════════════════════════════════════════════════════════════════════════ + + /** Super-admin puede crear un Command (POST → 201). */ + public function testSuperAdminCanCreateCommand(): void + { + $token = $this->tokenFor(self::SA_USER, UserGroupPermissions::ROLE_SUPER_ADMIN); + $this->as($token)->request('POST', '/commands', ['json' => [ + 'name' => 'cmd-by-super-admin', + 'script' => 'echo test', + ]]); + $this->assertResponseStatusCodeSame(Response::HTTP_CREATED); + } + + /** OU-admin NO puede crear un Command (POST → 403). */ + public function testOuAdminCannotCreateCommand(): void + { + $token = $this->tokenFor(self::OA_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN); + $this->as($token)->request('POST', '/commands', ['json' => [ + 'name' => 'cmd-forbidden', + 'script' => 'echo test', + ]]); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + /** OU-operator NO puede crear un Command (POST → 403). */ + public function testOuOperatorCannotCreateCommand(): void + { + $token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR); + $this->as($token)->request('POST', '/commands', ['json' => [ + 'name' => 'cmd-forbidden-op', + 'script' => 'echo test', + ]]); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + /** OU-admin NO puede borrar un Command (DELETE → 403). */ + public function testOuAdminCannotDeleteCommand(): void + { + $token = $this->tokenFor(self::OA_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN); + $command = CommandFactory::createOne(); + $iri = $this->findIriBy(\App\Entity\Command::class, ['name' => $command->getName()]); + + $this->as($token)->request('DELETE', $iri); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } + + /** OU-admin NO puede editar un Command (PUT → 403). */ + public function testOuAdminCannotEditCommand(): void + { + $token = $this->tokenFor(self::OA_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN); + $command = CommandFactory::createOne(); + $iri = $this->findIriBy(\App\Entity\Command::class, ['name' => $command->getName()]); + + $this->as($token)->request('PUT', $iri, ['json' => ['name' => 'forbidden-edit']]); + $this->assertResponseStatusCodeSame(Response::HTTP_FORBIDDEN); + } +}