fix(ogcore): sistema de permisos por rol + fixes de borrado y timezone #123

Merged
narenas merged 14 commits from devel into main 2026-06-16 17:51:45 +02:00
21 changed files with 790 additions and 32 deletions

View File

@ -54,7 +54,8 @@
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
"App\\Tests\\": "tests/",
"Functional\\": "tests/Functional/"
}
},
"replace": {

View File

@ -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

View File

@ -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:

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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:

View File

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20260615092704 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() 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) 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)');
}
}

View File

@ -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,

View File

@ -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);
}

View File

@ -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);

View File

@ -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();
}

View File

@ -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();

View File

@ -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;
/**

View File

@ -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;
}
}

View File

@ -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);

View File

@ -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;
}

View File

@ -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

View File

@ -0,0 +1,523 @@
<?php
namespace Functional;
use App\Entity\BootServer;
use App\Entity\DhcpServer;
use App\Entity\OrganizationalUnit;
use App\Factory\ClientFactory;
use App\Factory\CommandFactory;
use App\Factory\ImageRepositoryFactory;
use App\Factory\OrganizationalUnitFactory;
use App\Factory\UserFactory;
use App\Model\OrganizationalUnitTypes;
use App\Model\UserGroupPermissions;
use Symfony\Component\HttpFoundation\Response;
/**
* Verifica que cada rol sólo puede realizar las operaciones permitidas.
*
* Cubre la matriz de permisos definida en permisos_opengnsys.xlsx:
* - Clientes : solo super-admin / ou-admin pueden crear
* - OUs : solo super-admin / ou-admin pueden crear;
* ou-admin solo puede borrar sus propias OUs
* - DHCP Servers : solo super-admin puede escribir
* - Boot Servers : solo super-admin puede escribir
* - Image Repos : solo super-admin puede escribir
* - Commands : solo super-admin puede crear/editar/borrar
*/
class PermissionsTest extends AbstractTest
{
// Nombres de usuario de prueba (únicos por test, se resetea la BD entre tests)
private const SA_USER = 'perm-super-admin';
private const OA_USER = 'perm-ou-admin';
private const OP_USER = 'perm-ou-operator';
private const OM_USER = 'perm-ou-minimal';
// ── Helpers ───────────────────────────────────────────────────────────────
/** Crea un usuario con el rol indicado y devuelve su JWT. */
private function tokenFor(string $username, string $role): string
{
UserFactory::createOne(['username' => $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);
}
}