Updated Trace role view
parent
09eadaaad5
commit
e5d6f468e3
|
|
@ -28,6 +28,8 @@ use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
|
|||
|
||||
class DeployImageAction extends AbstractController
|
||||
{
|
||||
private const NO_REPOSITORY = '__no_repository__';
|
||||
|
||||
public function __construct(
|
||||
protected readonly EntityManagerInterface $entityManager,
|
||||
protected readonly HttpClientInterface $httpClient,
|
||||
|
|
@ -118,28 +120,29 @@ class DeployImageAction extends AbstractController
|
|||
private function handleMulticastDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array
|
||||
{
|
||||
$clientJobs = [];
|
||||
$repositoryErrors = $this->prepareRepositoryTransmissions($input, $image, 'multicast');
|
||||
|
||||
foreach ($input->clients as $client) {
|
||||
try {
|
||||
$inputData = $this->createMulticastInputData($input, $image, $client->getEntity());
|
||||
|
||||
try {
|
||||
$this->deployImageOgRepositoryAction->__invoke($input, $image, $client->getEntity());
|
||||
} catch (\Exception $e) {
|
||||
|
||||
$repositoryError = $repositoryErrors[$this->getRepositoryKey($client->getEntity())] ?? null;
|
||||
|
||||
if ($repositoryError !== null) {
|
||||
$this->logger->warning('Error with OgRepository for client (multicast)', [
|
||||
'client_uuid' => $client->getEntity()->getUuid(),
|
||||
'error' => $e->getMessage()
|
||||
'error' => $repositoryError
|
||||
]);
|
||||
|
||||
|
||||
if ($input->queue) {
|
||||
$this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
|
||||
}
|
||||
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$jobId = $this->processDeployment($client->getEntity(), $input, $image, $inputData, DeployMethodTypes::MULTICAST, $trace);
|
||||
|
||||
|
||||
if ($jobId) {
|
||||
$clientJobs[(string) '/clients/' . $client->getEntity()->getUuid()] = $jobId;
|
||||
}
|
||||
|
|
@ -164,32 +167,29 @@ class DeployImageAction extends AbstractController
|
|||
private function handleTorrentDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array
|
||||
{
|
||||
$clientJobs = [];
|
||||
$repositoryErrors = $this->prepareRepositoryTransmissions($input, $image, 'torrent');
|
||||
|
||||
foreach ($input->clients as $client) {
|
||||
try {
|
||||
$inputData = $this->createTorrentInputData($input, $image, $client->getEntity());
|
||||
|
||||
try {
|
||||
$response = $this->deployImageOgRepositoryAction->__invoke($input, $image, $client->getEntity(), $this->httpClient);
|
||||
|
||||
if (is_array($response) && isset($response['code']) && $response['code'] === 500) {
|
||||
throw new \Exception('Error del servidor OgRepository: ' . ($response['error'] ?? 'Error desconocido') . ' - ' . ($response['details'] ?? ''));
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
|
||||
$repositoryError = $repositoryErrors[$this->getRepositoryKey($client->getEntity())] ?? null;
|
||||
|
||||
if ($repositoryError !== null) {
|
||||
$this->logger->warning('Error with OgRepository for client (torrent)', [
|
||||
'client_uuid' => $client->getEntity()->getUuid(),
|
||||
'error' => $e->getMessage()
|
||||
'error' => $repositoryError
|
||||
]);
|
||||
|
||||
|
||||
if ($input->queue) {
|
||||
$this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
|
||||
}
|
||||
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$jobId = $this->processDeployment($client->getEntity(), $input, $image, $inputData, DeployMethodTypes::TORRENT, $trace);
|
||||
|
||||
|
||||
if ($jobId) {
|
||||
$clientJobs[(string) '/clients/' . $client->getEntity()->getUuid()] = $jobId;
|
||||
}
|
||||
|
|
@ -211,6 +211,53 @@ class DeployImageAction extends AbstractController
|
|||
return $clientJobs;
|
||||
}
|
||||
|
||||
/**
|
||||
* La transmisión (multicast/torrent) se levanta en el ogRepository una sola vez, no por cliente.
|
||||
* Como cada cliente puede resolver a un repositorio distinto, se agrupan por repositorio y se
|
||||
* lanza una única petición por repositorio implicado.
|
||||
*
|
||||
* @return array<string, string> error por clave de repositorio; sin entrada = transmisión creada
|
||||
*/
|
||||
private function prepareRepositoryTransmissions(DeployImageInput $input, ImageImageRepository $image, string $methodLabel): array
|
||||
{
|
||||
$clientsByRepository = [];
|
||||
|
||||
foreach ($input->clients as $client) {
|
||||
$clientsByRepository[$this->getRepositoryKey($client->getEntity())][] = $client;
|
||||
}
|
||||
|
||||
$errors = [];
|
||||
|
||||
foreach ($clientsByRepository as $repositoryKey => $clients) {
|
||||
if ($repositoryKey === self::NO_REPOSITORY) {
|
||||
$errors[$repositoryKey] = 'Client has no repository assigned';
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->deployImageOgRepositoryAction->__invoke($input, $image, $clients[0]->getEntity());
|
||||
} catch (\Exception $e) {
|
||||
$errors[$repositoryKey] = $e->getMessage();
|
||||
|
||||
$this->logger->warning('Error creating transmission in OgRepository', [
|
||||
'method' => $methodLabel,
|
||||
'repository' => $repositoryKey,
|
||||
'affected_clients' => count($clients),
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
private function getRepositoryKey($client): string
|
||||
{
|
||||
$repository = $client->getRepository();
|
||||
|
||||
return $repository ? (string) $repository->getUuid() : self::NO_REPOSITORY;
|
||||
}
|
||||
|
||||
private function processDeployment($client, DeployImageInput $input, ImageImageRepository $image, array $inputData, string $deployType, ?Trace $trace = null): ?string
|
||||
{
|
||||
$agentJobId = $this->deployImageOgAgentAction->__invoke($image, $input, $client, $deployType);
|
||||
|
|
|
|||
|
|
@ -7,7 +7,9 @@ use ApiPlatform\Doctrine\Orm\Extension\QueryItemExtensionInterface;
|
|||
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
|
||||
use ApiPlatform\Metadata\Operation;
|
||||
use App\Entity\OrganizationalUnit;
|
||||
use App\Entity\Trace;
|
||||
use App\Entity\User;
|
||||
use App\Model\UserGroupPermissions;
|
||||
use Doctrine\ORM\QueryBuilder;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
|
||||
|
|
@ -20,31 +22,74 @@ readonly class UserAllowedOrganizationalUnitExtension implements QueryCollection
|
|||
}
|
||||
public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, Operation $operation = null, array $context = []): void
|
||||
{
|
||||
$this->addWhere($queryBuilder, $resourceClass);
|
||||
$this->addWhere($queryBuilder, $queryNameGenerator, $resourceClass);
|
||||
}
|
||||
|
||||
public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, Operation $operation = null, array $context = []): void
|
||||
{
|
||||
$this->addWhere($queryBuilder, $resourceClass);
|
||||
$this->addWhere($queryBuilder, $queryNameGenerator, $resourceClass);
|
||||
}
|
||||
|
||||
private function addWhere(QueryBuilder $queryBuilder, string $resourceClass): void
|
||||
private function addWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass): void
|
||||
{
|
||||
/** @var User $user */
|
||||
$user = $this->security->getUser();
|
||||
|
||||
if (OrganizationalUnit::class !== $resourceClass || null === $user || in_array('ROLE_SUPER_ADMIN', $user->getRoles())) {
|
||||
if (null === $user || in_array(UserGroupPermissions::ROLE_SUPER_ADMIN, $user->getRoles())) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch ($resourceClass) {
|
||||
case OrganizationalUnit::class:
|
||||
$this->addOrganizationalUnitWhere($queryBuilder, $user);
|
||||
break;
|
||||
case Trace::class:
|
||||
$this->addTraceWhere($queryBuilder, $queryNameGenerator, $user);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private function addOrganizationalUnitWhere(QueryBuilder $queryBuilder, User $user): void
|
||||
{
|
||||
$rootAlias = $queryBuilder->getRootAliases()[0];
|
||||
$queryBuilder->andWhere(sprintf('%s.id in (:ou)', $rootAlias));
|
||||
$queryBuilder->setParameter('ou', $this->getAllowedOrganizationalUnitIds($user));
|
||||
}
|
||||
|
||||
/**
|
||||
* Una traza pertenece a un cliente, y el cliente a una unidad organizativa: el usuario solo puede
|
||||
* ver las trazas de los equipos de las unidades organizativas que tiene asignadas (y sus hijas).
|
||||
*/
|
||||
private function addTraceWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, User $user): void
|
||||
{
|
||||
$rootAlias = $queryBuilder->getRootAliases()[0];
|
||||
$organizationalUnitIds = $this->getAllowedOrganizationalUnitIds($user);
|
||||
|
||||
if (empty($organizationalUnitIds)) {
|
||||
$queryBuilder->andWhere('1 = 0');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$clientAlias = $queryNameGenerator->generateJoinAlias('client');
|
||||
|
||||
$queryBuilder->innerJoin(sprintf('%s.client', $rootAlias), $clientAlias);
|
||||
$queryBuilder->andWhere(sprintf('%s.organizationalUnit in (:trace_ou)', $clientAlias));
|
||||
$queryBuilder->setParameter('trace_ou', $organizationalUnitIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int[]
|
||||
*/
|
||||
private function getAllowedOrganizationalUnitIds(User $user): array
|
||||
{
|
||||
$organizationalUnitIds = [];
|
||||
|
||||
foreach ($user->getAllowedOrganizationalUnits() as $allowedOrganizationalUnit) {
|
||||
$this->addOrganizationalUnitAndChildrenIds($allowedOrganizationalUnit, $organizationalUnitIds);
|
||||
}
|
||||
|
||||
$rootAlias = $queryBuilder->getRootAliases()[0];
|
||||
$queryBuilder->andWhere(sprintf('%s.id in (:ou)', $rootAlias));
|
||||
$queryBuilder->setParameter('ou', $organizationalUnitIds);
|
||||
return $organizationalUnitIds;
|
||||
}
|
||||
|
||||
private function addOrganizationalUnitAndChildrenIds(OrganizationalUnit $organizationalUnit, array &$organizationalUnitIds): void
|
||||
|
|
@ -58,4 +103,4 @@ readonly class UserAllowedOrganizationalUnitExtension implements QueryCollection
|
|||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,197 @@
|
|||
<?php
|
||||
|
||||
namespace Functional;
|
||||
|
||||
use ApiPlatform\Symfony\Bundle\Test\Client as ApiClient;
|
||||
use App\Entity\Client;
|
||||
use App\Entity\OrganizationalUnit;
|
||||
use App\Entity\Trace;
|
||||
use App\Entity\User;
|
||||
use App\Factory\UserFactory;
|
||||
use App\Model\OrganizationalUnitTypes;
|
||||
use App\Model\TraceStatus;
|
||||
use App\Model\UserGroupPermissions;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Una traza pertenece a un cliente y el cliente a una unidad organizativa, así que un usuario
|
||||
* que no sea super-admin solo debe ver las trazas de los equipos de las OUs que tiene asignadas
|
||||
* (y las de sus OUs hijas).
|
||||
*
|
||||
* @see \App\Doctrine\UserAllowedOrganizationalUnitExtension
|
||||
*/
|
||||
class TraceVisibilityTest extends AbstractTest
|
||||
{
|
||||
private const SA_USER = 'trace-super-admin';
|
||||
private const OP_USER = 'trace-ou-operator';
|
||||
|
||||
/** 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,
|
||||
]);
|
||||
}
|
||||
|
||||
private function as(string $token): ApiClient
|
||||
{
|
||||
return $this->createClientWithCredentials($token);
|
||||
}
|
||||
|
||||
private function getEntityManager(): EntityManagerInterface
|
||||
{
|
||||
return static::getContainer()->get('doctrine')->getManager();
|
||||
}
|
||||
|
||||
private function createOrganizationalUnit(string $name, ?OrganizationalUnit $parent = null): OrganizationalUnit
|
||||
{
|
||||
$organizationalUnit = new OrganizationalUnit();
|
||||
$organizationalUnit->setName($name);
|
||||
$organizationalUnit->setType(OrganizationalUnitTypes::CLASSROOM);
|
||||
$organizationalUnit->setParent($parent);
|
||||
|
||||
$this->getEntityManager()->persist($organizationalUnit);
|
||||
|
||||
return $organizationalUnit;
|
||||
}
|
||||
|
||||
/** Crea una traza asociada a un cliente de la OU indicada y devuelve su uuid. */
|
||||
private function createTrace(?OrganizationalUnit $organizationalUnit, string $command): string
|
||||
{
|
||||
$entityManager = $this->getEntityManager();
|
||||
|
||||
$trace = new Trace();
|
||||
$trace->setCommand($command);
|
||||
$trace->setStatus(TraceStatus::SUCCESS);
|
||||
$trace->setExecutedAt(new \DateTime());
|
||||
|
||||
if ($organizationalUnit !== null) {
|
||||
$client = new Client();
|
||||
$client->setName('client-'.$command);
|
||||
$client->setMaintenance(false);
|
||||
$client->setOrganizationalUnit($organizationalUnit);
|
||||
$entityManager->persist($client);
|
||||
|
||||
$trace->setClient($client);
|
||||
}
|
||||
|
||||
$entityManager->persist($trace);
|
||||
|
||||
return (string) $trace->getUuid();
|
||||
}
|
||||
|
||||
/**
|
||||
* Escenario común: una OU permitida con una OU hija, y otra OU ajena al usuario.
|
||||
*
|
||||
* @return array{allowed: string, child: string, foreign: string, orphan: string}
|
||||
*/
|
||||
private function createScenario(string $username): array
|
||||
{
|
||||
$entityManager = $this->getEntityManager();
|
||||
|
||||
$allowedOrganizationalUnit = $this->createOrganizationalUnit('trace-allowed-ou');
|
||||
$childOrganizationalUnit = $this->createOrganizationalUnit('trace-child-ou', $allowedOrganizationalUnit);
|
||||
$foreignOrganizationalUnit = $this->createOrganizationalUnit('trace-foreign-ou');
|
||||
|
||||
$traces = [
|
||||
'allowed' => $this->createTrace($allowedOrganizationalUnit, 'allowed'),
|
||||
'child' => $this->createTrace($childOrganizationalUnit, 'child'),
|
||||
'foreign' => $this->createTrace($foreignOrganizationalUnit, 'foreign'),
|
||||
'orphan' => $this->createTrace(null, 'orphan'),
|
||||
];
|
||||
|
||||
/** @var User $user */
|
||||
$user = $entityManager->getRepository(User::class)->findOneBy(['username' => $username]);
|
||||
$user->addAllowedOrganizationalUnit($allowedOrganizationalUnit);
|
||||
$entityManager->persist($user);
|
||||
|
||||
$entityManager->flush();
|
||||
|
||||
return $traces;
|
||||
}
|
||||
|
||||
/** @return string[] uuids devueltos por GET /traces */
|
||||
private function getTraceUuids(string $token): array
|
||||
{
|
||||
$response = $this->as($token)->request('GET', '/traces');
|
||||
$this->assertResponseIsSuccessful();
|
||||
|
||||
return array_map(
|
||||
static fn (array $trace): string => $trace['uuid'],
|
||||
$response->toArray()['hydra:member']
|
||||
);
|
||||
}
|
||||
|
||||
/** El super-admin sigue viendo todas las trazas, incluidas las que no tienen cliente. */
|
||||
public function testSuperAdminSeesEveryTrace(): void
|
||||
{
|
||||
$token = $this->tokenFor(self::SA_USER, UserGroupPermissions::ROLE_SUPER_ADMIN);
|
||||
$traces = $this->createScenario(self::SA_USER);
|
||||
|
||||
$uuids = $this->getTraceUuids($token);
|
||||
|
||||
$this->assertContains($traces['allowed'], $uuids);
|
||||
$this->assertContains($traces['child'], $uuids);
|
||||
$this->assertContains($traces['foreign'], $uuids);
|
||||
$this->assertContains($traces['orphan'], $uuids);
|
||||
}
|
||||
|
||||
/** El resto de roles solo ven las trazas de sus OUs permitidas y de las hijas de éstas. */
|
||||
public function testOperatorOnlySeesTracesOfAllowedOrganizationalUnits(): void
|
||||
{
|
||||
$token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR);
|
||||
$traces = $this->createScenario(self::OP_USER);
|
||||
|
||||
$uuids = $this->getTraceUuids($token);
|
||||
|
||||
$this->assertContains($traces['allowed'], $uuids, 'Debe ver las trazas de su OU');
|
||||
$this->assertContains($traces['child'], $uuids, 'Debe ver las trazas de las OUs hijas');
|
||||
$this->assertNotContains($traces['foreign'], $uuids, 'No debe ver las trazas de otras OUs');
|
||||
$this->assertNotContains($traces['orphan'], $uuids, 'No debe ver trazas sin cliente');
|
||||
}
|
||||
|
||||
/** El filtro también se aplica al item: una traza ajena no es accesible por uuid. */
|
||||
public function testOperatorCannotFetchForeignTraceItem(): void
|
||||
{
|
||||
$token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR);
|
||||
$traces = $this->createScenario(self::OP_USER);
|
||||
|
||||
$this->as($token)->request('GET', '/traces/'.$traces['allowed']);
|
||||
$this->assertResponseIsSuccessful();
|
||||
|
||||
$this->as($token)->request('GET', '/traces/'.$traces['foreign']);
|
||||
$this->assertResponseStatusCodeSame(Response::HTTP_NOT_FOUND);
|
||||
}
|
||||
|
||||
/** Filtrar por un cliente ajeno no permite saltarse la restricción. */
|
||||
public function testOperatorCannotBypassFilterWithClientFilter(): void
|
||||
{
|
||||
$token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR);
|
||||
$traces = $this->createScenario(self::OP_USER);
|
||||
|
||||
$foreignTrace = $this->getEntityManager()->getRepository(Trace::class)
|
||||
->findOneBy(['uuid' => $traces['foreign']]);
|
||||
|
||||
$response = $this->as($token)->request('GET', '/traces', [
|
||||
'query' => ['client.id' => $foreignTrace->getClient()->getId()],
|
||||
]);
|
||||
$this->assertResponseIsSuccessful();
|
||||
|
||||
$this->assertSame([], $response->toArray()['hydra:member']);
|
||||
}
|
||||
|
||||
/** Un usuario sin ninguna OU asignada no ve ninguna traza. */
|
||||
public function testUserWithoutOrganizationalUnitsSeesNoTraces(): void
|
||||
{
|
||||
$token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR);
|
||||
|
||||
$this->createTrace($this->createOrganizationalUnit('trace-unassigned-ou'), 'unassigned');
|
||||
$this->getEntityManager()->flush();
|
||||
|
||||
$this->assertSame([], $this->getTraceUuids($token));
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue