From 203675e7ad010436f02608ec3e40474b2893ae29 Mon Sep 17 00:00:00 2001 From: Nicolas Arenas Date: Tue, 26 May 2026 14:34:26 +0200 Subject: [PATCH 01/12] =?UTF-8?q?fix(ogcore):=20corregir=20permisos=20de?= =?UTF-8?q?=20edici=C3=B3n=20de=20aulas=20para=20ou-admin=20y=20ou-operato?= =?UTF-8?q?r?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - OrganizationalUnitProcessor: tras crear una OU (POST), añade automáticamente la nueva OU a allowedOrganizationalUnits del usuario creador (si no es SUPER_ADMIN), para que pueda verla y editarla de inmediato. - OrganizationalUnitVoter: amplía la comprobación de ORGANIZATIONAL_UNIT_VIEW para incluir descendientes de las OUs permitidas, alineando el voter con la lógica de UserAllowedOrganizationalUnitExtension. --- .../Voter/OrganizationalUnitVoter.php | 32 ++++++++++++++++--- .../Processor/OrganizationalUnitProcessor.php | 14 ++++++++ 2 files changed, 41 insertions(+), 5 deletions(-) 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/OrganizationalUnitProcessor.php b/src/State/Processor/OrganizationalUnitProcessor.php index 3a733e2..c7d6d90 100644 --- a/src/State/Processor/OrganizationalUnitProcessor.php +++ b/src/State/Processor/OrganizationalUnitProcessor.php @@ -11,9 +11,13 @@ 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; readonly class OrganizationalUnitProcessor implements ProcessorInterface { @@ -22,6 +26,8 @@ readonly class OrganizationalUnitProcessor implements ProcessorInterface private BootServerRepository $bootServerRepository, private ValidatorInterface $validator, private ChangeClientNetworkSettingsService $changeClientNetworkSettingsService, + private Security $security, + private UserRepository $userRepository, ) { } @@ -69,6 +75,14 @@ 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())) { + $user->addAllowedOrganizationalUnit($organizationalUnit); + $this->userRepository->save($user); + } + } + //$this->changeClientNetworkSettingsService->__invoke($organizationalUnit); return new OrganizationalUnitOutput($organizationalUnit); -- 2.40.1 From 6d35163b3f32bd8050ca21224347efbf41718d03 Mon Sep 17 00:00:00 2001 From: Nicolas Arenas Date: Tue, 26 May 2026 15:21:02 +0200 Subject: [PATCH 02/12] fix(ogcore): restringir escritura de infraestructura a ROLE_SUPER_ADMIN Las operaciones de creacion, edicion y eliminacion de servidores DHCP, Boot, Subredes, Comandos y Repositorios de imagenes quedan restringidas a ROLE_SUPER_ADMIN. Las operaciones de lectura siguen accesibles a cualquier usuario autenticado. --- config/api_platform/BootServer.yaml | 10 ++++++++-- config/api_platform/Command.yaml | 8 ++++++-- config/api_platform/DhcpServer.yaml | 9 +++++++-- config/api_platform/ImageRepository.yaml | 8 ++++++-- config/api_platform/Subnet.yaml | 16 ++++++++++++++-- 5 files changed, 41 insertions(+), 10 deletions(-) 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/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/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 -- 2.40.1 From b1903ea321037b58bad9ec6afc6ca61e7eb445dc Mon Sep 17 00:00:00 2001 From: Nicolas Arenas Date: Wed, 27 May 2026 12:03:43 +0200 Subject: [PATCH 03/12] fix(ogcore): restringir creacion de OUs y clientes a ou-admin y superior El POST de OrganizationalUnit y Client queda restringido a ROLE_SUPER_ADMIN o ROLE_ORGANIZATIONAL_UNIT_ADMIN. Los operadores (ROLE_ORGANIZATIONAL_UNIT_OPERATOR) ya no pueden crear aulas ni clientes via API. --- config/api_platform/Client.yaml | 3 ++- config/api_platform/OrganizationalUnit.yaml | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) 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/OrganizationalUnit.yaml b/config/api_platform/OrganizationalUnit.yaml index b383a20..00697fa 100644 --- a/config/api_platform/OrganizationalUnit.yaml +++ b/config/api_platform/OrganizationalUnit.yaml @@ -26,7 +26,8 @@ resources: provider: App\State\Provider\OrganizationalUnitProvider validationContext: groups: ['organizational-unit:patch' ] - ApiPlatform\Metadata\Post: ~ + ApiPlatform\Metadata\Post: + security: 'is_granted("ROLE_SUPER_ADMIN") or is_granted("ROLE_ORGANIZATIONAL_UNIT_ADMIN")' ApiPlatform\Metadata\Delete: ~ change_parent: class: ApiPlatform\Metadata\Post -- 2.40.1 From ab1a7c2d1104980e0d9de175155f587a586147b2 Mon Sep 17 00:00:00 2001 From: Nicolas Arenas Date: Wed, 27 May 2026 14:20:02 +0200 Subject: [PATCH 04/12] =?UTF-8?q?fix(ogcore):=20mover=20seguridad=20de=20c?= =?UTF-8?q?reaci=C3=B3n/borrado=20a=20los=20processors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ClientProcessor: añade comprobación inline en processCreateOrUpdate para bloquear (403) creación de clientes a ROLE_ORGANIZATIONAL_UNIT_OPERATOR y roles inferiores. Añade Security al constructor. - OrganizationalUnitProcessor: mueve el bloqueo de creación al inicio de processCreateOrUpdate (antes de validate/save) para que el 403 se devuelva sin persistir datos. Separa la lógica de añadir la OU a la lista del usuario. - OrganizationalUnitProcessor.processDelete: corrige bug de nombre de variable ($user apuntaba a una OU); añade comprobación de autoría via createdBy para que solo el creador o super-admin pueda borrar la OU (403 en caso contrario). Motivo del cambio: la expresión security: de API Platform YAML no se evaluaba antes de la validación del DTO en AP 3.4 para operaciones POST sin provider explícito, resultando en 422 en lugar del esperado 403. Co-Authored-By: Claude Sonnet 4.6 --- src/State/Processor/ClientProcessor.php | 15 ++++++++++ .../Processor/OrganizationalUnitProcessor.php | 28 +++++++++++++++++-- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/src/State/Processor/ClientProcessor.php b/src/State/Processor/ClientProcessor.php index a1879e3..5ad7ffa 100644 --- a/src/State/Processor/ClientProcessor.php +++ b/src/State/Processor/ClientProcessor.php @@ -13,12 +13,16 @@ 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; @@ -36,6 +40,7 @@ readonly class ClientProcessor implements ProcessorInterface private DeleteHostAction $deleteHostAction, private DeleteAction $deletePxeAction, private KernelInterface $kernel, + private Security $security, ) { } @@ -60,6 +65,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)); } diff --git a/src/State/Processor/OrganizationalUnitProcessor.php b/src/State/Processor/OrganizationalUnitProcessor.php index c7d6d90..c984b4f 100644 --- a/src/State/Processor/OrganizationalUnitProcessor.php +++ b/src/State/Processor/OrganizationalUnitProcessor.php @@ -18,6 +18,7 @@ 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 { @@ -52,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)); } @@ -78,6 +90,7 @@ readonly class OrganizationalUnitProcessor implements ProcessorInterface 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); } @@ -90,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; } -- 2.40.1 From 06bca9395eceb10749af0601eafa4d3f040d3517 Mon Sep 17 00:00:00 2001 From: Nicolas Arenas Date: Wed, 27 May 2026 14:45:55 +0200 Subject: [PATCH 05/12] =?UTF-8?q?fix(ogcore):=20bloquear=20creaci=C3=B3n?= =?UTF-8?q?=20de=20clientes=20y=20OUs=20a=20nivel=20de=20firewall?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Añade reglas access_control al firewall de Symfony para los endpoints POST /api/clients y POST /api/organizational-units, restringiendo el acceso a ROLE_SUPER_ADMIN y ROLE_ORGANIZATIONAL_UNIT_ADMIN. La comprobación a nivel de firewall se ejecuta antes de que API Platform procese la petición (antes de deserialización y validación del DTO), lo que garantiza un HTTP 403 inmediato sin necesidad de que el cuerpo de la petición sea válido. Las reglas usan el ancla $ para que no afecten a sub-rutas como /api/clients/server/reboot, /api/clients/server/boot-client, etc. --- config/packages/security.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/config/packages/security.yaml b/config/packages/security.yaml index a4ce57f..c7edad6 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -39,6 +39,9 @@ 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: ^/api/clients$, methods: [POST], roles: [ROLE_SUPER_ADMIN, ROLE_ORGANIZATIONAL_UNIT_ADMIN] } + - { path: ^/api/organizational-units$, methods: [POST], roles: [ROLE_SUPER_ADMIN, ROLE_ORGANIZATIONAL_UNIT_ADMIN] } - { path: ^/, roles: ROLE_USER } when@test: -- 2.40.1 From 5ce29848f128a337eb06372649c8df3e1d0553ad Mon Sep 17 00:00:00 2001 From: Nicolas Arenas Date: Wed, 27 May 2026 15:37:12 +0200 Subject: [PATCH 06/12] =?UTF-8?q?test(ogcore):=20a=C3=B1adir=20suite=20de?= =?UTF-8?q?=20tests=20de=20permisos=20por=20rol?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PermissionsTest.php cubre la matriz completa de permisos: Sección 1 — Clientes (POST): - super-admin / ou-admin pueden crear (201) - ou-operator / ou-minimal no pueden (403) Sección 2 — OUs (POST): - super-admin / ou-admin pueden crear (201) - ou-operator / ou-minimal no pueden (403) Sección 3 — OUs (DELETE con autoría): - ou-admin borra la suya propia (204) - ou-admin no borra la de otro usuario (403) - super-admin borra cualquiera (204) - ou-operator no borra ninguna (403) Sección 4 — DHCP Servers: - super-admin puede PATCH (200) - ou-admin / ou-operator no pueden PATCH ni DELETE (403) Sección 5 — Boot Servers: - super-admin puede PATCH (200) - ou-admin / ou-operator no pueden PATCH ni DELETE (403) Sección 6 — Image Repositories: - super-admin puede crear (201) - ou-admin / ou-operator no pueden crear ni borrar (403) Sección 7 — Commands: - super-admin puede crear (201) - ou-admin / ou-operator no pueden crear, editar ni borrar (403) OrganizationalUnitTest: reemplaza testOuOperatorCanEditOrganizationalUnitTheyCreated (que asumía que operadores podían crear OUs) por testOuOperatorCannotCreateOrganizationalUnit (que verifica el comportamiento correcto). Co-Authored-By: Claude Sonnet 4.6 --- tests/Functional/OrganizationalUnitTest.php | 55 ++ tests/Functional/PermissionsTest.php | 523 ++++++++++++++++++++ 2 files changed, 578 insertions(+) create mode 100644 tests/Functional/PermissionsTest.php 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); + } +} -- 2.40.1 From 0284654f3e740d28caeda161204ae6c107926957 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Fri, 12 Jun 2026 10:27:04 +0200 Subject: [PATCH 07/12] =?UTF-8?q?A=C3=B1adido=20un=20timeout=20de=205=20se?= =?UTF-8?q?gundos=20para=20detectar=20el=20estado=20de=20cada=20equipo=20e?= =?UTF-8?q?n=20el=20sondeo=20del=20aula=20completa?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/OgAgent/OrganizationalUnitStatusAction.php | 2 ++ 1 file changed, 2 insertions(+) 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, -- 2.40.1 From 7f56b6291ab09ed82dac4d9a91d64ff40258b7ac Mon Sep 17 00:00:00 2001 From: Nicolas Arenas Date: Mon, 15 Jun 2026 11:52:44 +0200 Subject: [PATCH 08/12] fix(ogcore): permisos DELETE de OUs y borrado de clientes sin plantilla --- composer.json | 3 ++- config/api_platform/OrganizationalUnit.yaml | 5 ++++- src/Controller/OgBoot/PxeBootFile/DeleteAction.php | 2 +- src/State/Processor/ClientProcessor.php | 4 +++- 4 files changed, 10 insertions(+), 4 deletions(-) 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/OrganizationalUnit.yaml b/config/api_platform/OrganizationalUnit.yaml index 00697fa..71063e4 100644 --- a/config/api_platform/OrganizationalUnit.yaml +++ b/config/api_platform/OrganizationalUnit.yaml @@ -28,7 +28,10 @@ resources: groups: ['organizational-unit:patch' ] ApiPlatform\Metadata\Post: security: 'is_granted("ROLE_SUPER_ADMIN") or is_granted("ROLE_ORGANIZATIONAL_UNIT_ADMIN")' - ApiPlatform\Metadata\Delete: ~ + ApiPlatform\Metadata\Delete: + provider: App\State\Provider\OrganizationalUnitProvider + 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/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/State/Processor/ClientProcessor.php b/src/State/Processor/ClientProcessor.php index 5ad7ffa..9a0945d 100644 --- a/src/State/Processor/ClientProcessor.php +++ b/src/State/Processor/ClientProcessor.php @@ -134,7 +134,9 @@ readonly class ClientProcessor implements ProcessorInterface if ($client->getSubnet()) { $this->deleteHostAction->__invoke($client->getSubnet(), $client->getUuid()); } - $this->deletePxeAction->__invoke($client->getMac()); + if ($client->getMac() && $client->getTemplate()) { + $this->deletePxeAction->__invoke($client->getMac()); + } } $this->clientRepository->delete($client); -- 2.40.1 From 9baa1120a643781146d3802e140d343938d74fe6 Mon Sep 17 00:00:00 2001 From: Nicolas Arenas Date: Mon, 15 Jun 2026 11:52:44 +0200 Subject: [PATCH 09/12] fix(ogcore): normalizar timezone UTC en CommandTask DTOs --- src/Dto/Input/CommandTaskScheduleInput.php | 6 ++---- src/Dto/Output/CommandTaskOutput.php | 11 +++++++++-- src/Dto/Output/CommandTaskScheduleOutput.php | 7 ++++++- 3 files changed, 17 insertions(+), 7 deletions(-) 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(); -- 2.40.1 From cb3a8aa58a4d86de0a622f2345299598726c054e Mon Sep 17 00:00:00 2001 From: Nicolas Arenas Date: Mon, 15 Jun 2026 11:57:15 +0200 Subject: [PATCH 10/12] =?UTF-8?q?fix(ogcore):=20permitir=20a=20ogLive=20co?= =?UTF-8?q?nsultar=20clientes=20v=C3=ADa=20API=20key?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Añade regla access_control para que ROLE_OGCLIENT_API pueda hacer GET en /clients. Sin esta regla, ogLive no puede consultar la configuración del equipo por IP al arrancar (el catch-all ROLE_USER bloquearía la petición porque ogclient_api_user no tiene ese rol). Ya existía la misma excepción para /commands. Co-Authored-By: Claude Sonnet 4.6 --- config/packages/security.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/config/packages/security.yaml b/config/packages/security.yaml index c7edad6..a973345 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -42,6 +42,8 @@ security: # Creación de clientes y OUs: solo super-admin y ou-admin - { path: ^/api/clients$, methods: [POST], roles: [ROLE_SUPER_ADMIN, ROLE_ORGANIZATIONAL_UNIT_ADMIN] } - { path: ^/api/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: -- 2.40.1 From 024f2ace6bd0682da530e4e60170f8817c946a14 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Tue, 16 Jun 2026 09:17:09 +0200 Subject: [PATCH 11/12] Corregida asociacion de perfil hardware con cliente, se usa delete cascade para que al borrar un cliente, se borre su perfil hardware asociado --- migrations/Version20260615092704.php | 33 +++++++++++++++++++++++++ src/Entity/HardwareProfile.php | 2 +- src/State/Processor/ClientProcessor.php | 21 ++++++++++++++-- 3 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 migrations/Version20260615092704.php 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/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/State/Processor/ClientProcessor.php b/src/State/Processor/ClientProcessor.php index 9a0945d..9a5bb2a 100644 --- a/src/State/Processor/ClientProcessor.php +++ b/src/State/Processor/ClientProcessor.php @@ -27,6 +27,7 @@ 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 { @@ -132,10 +133,26 @@ 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()) { - $this->deletePxeAction->__invoke($client->getMac()); + 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 + } } } -- 2.40.1 From 3d0883a0bd1461afaa1339238060c63a28d60191 Mon Sep 17 00:00:00 2001 From: Nicolas Arenas Date: Tue, 16 Jun 2026 11:20:43 +0200 Subject: [PATCH 12/12] fix(ogcore): corregir rutas de firewall y provider de DELETE en OUs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dos bugs introducidos en fix_permissions: 1. access_control paths incorrectos: nginx elimina el prefijo /api/ antes de llegar a ogcore, por lo que las rutas reales son /clients y /organizational-units (sin /api/). Las reglas anteriores con ^/api/clients$ y ^/api/organizational-units$ nunca coincidían. 2. OrganizationalUnitProvider no manejaba Delete: el switch del provider no tenía case para Delete, devolvía null implícitamente y API Platform respondía 404 a cualquier usuario que intentara borrar una OU. Quitando el provider del DELETE, el proveedor Doctrine por defecto carga la entidad correctamente y la expresión security: del YAML puede evaluarse. Co-Authored-By: Claude Sonnet 4.6 --- config/api_platform/OrganizationalUnit.yaml | 1 - config/packages/security.yaml | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/config/api_platform/OrganizationalUnit.yaml b/config/api_platform/OrganizationalUnit.yaml index 71063e4..17e304b 100644 --- a/config/api_platform/OrganizationalUnit.yaml +++ b/config/api_platform/OrganizationalUnit.yaml @@ -29,7 +29,6 @@ resources: ApiPlatform\Metadata\Post: security: 'is_granted("ROLE_SUPER_ADMIN") or is_granted("ROLE_ORGANIZATIONAL_UNIT_ADMIN")' ApiPlatform\Metadata\Delete: - provider: App\State\Provider\OrganizationalUnitProvider 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: diff --git a/config/packages/security.yaml b/config/packages/security.yaml index a973345..c0f8945 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -40,8 +40,8 @@ security: - { path: ^/menu-browser, roles: PUBLIC_ACCESS } - { path: ^/menu/, roles: PUBLIC_ACCESS } # Creación de clientes y OUs: solo super-admin y ou-admin - - { path: ^/api/clients$, methods: [POST], roles: [ROLE_SUPER_ADMIN, ROLE_ORGANIZATIONAL_UNIT_ADMIN] } - - { path: ^/api/organizational-units$, methods: [POST], roles: [ROLE_SUPER_ADMIN, ROLE_ORGANIZATIONAL_UNIT_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 } -- 2.40.1