From c1090936ab99c58a880c8e2e5f8ebae75e309067 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Fri, 27 Feb 2026 09:53:40 +0100 Subject: [PATCH 01/11] =?UTF-8?q?Nuevo=20men=C3=BA=20por=20defecto=20en=20?= =?UTF-8?q?el=20cliente,=20organizando=20la=20informaci=C3=B3n=20por=20dis?= =?UTF-8?q?cos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 5 + src/Controller/MenuBrowserController.php | 39 ++++- templates/browser/main.html.twig | 173 +++++++++++++++++------ 3 files changed, 169 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e3d49e7..db719f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,9 @@ # Changelog +## [1.2.2] - 2026-02-27 +### Improved +- Nuevo menú por defecto en el cliente, organizando la información por discos + +--- ## [1.2.1] - 2025-10-22 ### Fixed - Se ha corregido un error en el commando que se encarga de ejecutar tareas pendientes. diff --git a/src/Controller/MenuBrowserController.php b/src/Controller/MenuBrowserController.php index 2ca78be..0553a91 100644 --- a/src/Controller/MenuBrowserController.php +++ b/src/Controller/MenuBrowserController.php @@ -29,9 +29,42 @@ class MenuBrowserController extends AbstractController $partitions = []; $client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $host]); + + $disks = []; // Array nuevo estructurado if ($client) { - $partitions = $client->getPartitions(); + $rawPartitions = $client->getPartitions()->toArray(); + + foreach ($rawPartitions as $part) { + $diskNum = $part->getDiskNumber(); + $partNum = $part->getPartitionNumber(); + + // Inicializamos el array del disco si no existe + if (!isset($disks[$diskNum])) { + $disks[$diskNum] = [ + 'info' => null, // Aquí guardaremos la partición 0 (tamaño total) + 'parts' => [] // Aquí las particiones reales + ]; + } + + if ($partNum == 0) { + // Es la info del disco completo + $disks[$diskNum]['info'] = $part; + } else { + // Es una partición normal + $disks[$diskNum]['parts'][] = $part; + } + } + + // Ordenamos los discos (1, 2, 3...) + ksort($disks); + + // Ordenamos las particiones dentro de cada disco (1, 2, 3...) + foreach ($disks as &$diskData) { + usort($diskData['parts'], function($a, $b) { + return $a->getPartitionNumber() <=> $b->getPartitionNumber(); + }); + } } $menuName = $client->getMenu()->getPublicUrl(); @@ -39,7 +72,7 @@ class MenuBrowserController extends AbstractController return $this->render('browser/' . $menuName . '.html.twig', [ 'ip' => $host, 'mac' => $client ? $client->getMac() : null, - 'partitions' => $partitions, + 'disks' => $disks, ]); } @@ -54,7 +87,7 @@ class MenuBrowserController extends AbstractController return $this->render($templatePath, [ 'ip' => 'invitado', - 'partitions' => [], + 'disks' => [], ]); } } diff --git a/templates/browser/main.html.twig b/templates/browser/main.html.twig index ed786ed..69ac50f 100644 --- a/templates/browser/main.html.twig +++ b/templates/browser/main.html.twig @@ -34,7 +34,7 @@ background-color: var(--background-color); color: var(--text-color); line-height: 1.5; - background-image: + background-image: radial-gradient(at 0% 0%, rgba(37, 99, 235, 0.1) 0px, transparent 50%), radial-gradient(at 100% 100%, rgba(5, 150, 105, 0.1) 0px, transparent 50%); min-height: 100vh; @@ -210,15 +210,15 @@ .linux i { color: var(--success-color); } .apagar i { color: var(--danger-color); } - .windows a:hover { + .windows a:hover { background-color: rgba(37, 99, 235, 0.1); color: var(--primary-color); } - .linux a:hover { + .linux a:hover { background-color: rgba(5, 150, 105, 0.1); color: var(--success-color); } - .apagar a:hover { + .apagar a:hover { background-color: rgba(220, 38, 38, 0.1); color: var(--danger-color); } @@ -393,7 +393,6 @@ border: 2px dashed #cbd5e1; } - /* Estados especiales para diferentes tipos de particiones */ .partition-os { font-weight: 600; color: var(--success-color); @@ -444,6 +443,57 @@ font-size: 0.8rem; } } + + /* --- NUEVOS ESTILOS PARA LA AGRUPACIÓN POR DISCOS --- */ + .disk-container { + margin-bottom: 2.5rem; + border: 1px solid #e2e8f0; + border-radius: var(--border-radius); + overflow: hidden; + background: white; + box-shadow: 0 4px 6px rgba(0, 0, 0, 0.02); + } + + .disk-header { + background: #f8fafc; + padding: 1rem 1.5rem; + border-bottom: 1px solid #e2e8f0; + display: flex; + justify-content: space-between; + align-items: center; + } + + .disk-header h3 { + margin: 0; + font-size: 1.1rem; + color: var(--text-color); + display: flex; + align-items: center; + gap: 0.5rem; + } + + .disk-total-badge { + background: linear-gradient(135deg, var(--primary-color), var(--primary-light)); + color: white; + padding: 0.35rem 0.85rem; + border-radius: 20px; + font-size: 0.85rem; + font-weight: 600; + box-shadow: 0 2px 4px rgba(37, 99, 235, 0.2); + } + + .empty-disk { + text-align: center; + padding: 2rem; + color: #64748b; + font-style: italic; + } + + .partition-number { + font-weight: bold; + font-size: 1.1rem; + color: var(--text-color); + } @@ -475,48 +525,81 @@
-

Particiones del sistema

- - {% if partitions|length > 0 %} -
- - - - - - - - - - - - - {% for partition in partitions %} - - - - - - - - - {% endfor %} - -
DiscoParticiónTamañoTipoSOAcciones
{{ partition.diskNumber }}{{ partition.partitionNumber }}{{ (partition.size / 1024)|number_format(2) }} MB{{ partition.filesystem }}{{ partition.operativeSystem ? partition.operativeSystem.name : '-' }} - {% if partition.operativeSystem %} - - - Arrancar {{ partition.operativeSystem.name }} - - {% endif %} -
-
+

Almacenamiento del sistema

+ + {% if disks is defined and disks|length > 0 %} + + {% for diskNum, data in disks %} +
+ +
+

+ Disco {{ diskNum }} +

+ {% if data.info %} + + Total: {{ (data.info.size / 1024 / 1024)|number_format(2) }} GB + + {% endif %} +
+ +
+ + + + + + + + + + + + {% for partition in data.parts %} + + + + + + + + + + + + {% else %} + + + + {% endfor %} + +
ParticiónTamañoTipoSistema OperativoAcciones
+ {{ partition.partitionNumber }} + + {{ (partition.size / 1024)|number_format(0) }} MB + + {{ partition.filesystem|default('-') }} + + {{ partition.operativeSystem ? partition.operativeSystem.name : '-' }} + + {% if partition.operativeSystem %} + + Arrancar {{ partition.operativeSystem.name }} + + {% endif %} +
+ No hay particiones utilizables en este disco. +
+
+
+ {% endfor %} + {% else %} -

No hay particiones disponibles.

+

No hay discos detectados en el sistema.

{% endif %}
- + \ No newline at end of file -- 2.40.1 From 621b8f81ba72023b05ddecac3f64681dad117645 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Wed, 11 Mar 2026 12:31:36 +0100 Subject: [PATCH 02/11] process base64 payload in menu to create twig templates on server --- CHANGELOG.md | 7 + src/Controller/MenuBrowserController.php | 2 +- src/Dto/Input/MenuInput.php | 4 + src/State/Processor/MenuProcessor.php | 176 ++++++++++++++++++++++- 4 files changed, 185 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index db719f5..2fc644e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,11 @@ # Changelog +## [1.2.3] - 2026-03-11 +### Added +- Se ha añadido una nueva funcionalidad en el DTO `MenuInput` (campo `menuHtmlContent`) para recibir la plantilla HTML íntegra del menú codificada en Base64. + +### Improved +- Se ha refactorizado y asegurado la lógica de creación de menús dentro de `MenuProcessor`, para decodificar estrictamente el payload en Base64 y sobreescribir físicamente la plantilla `.twig` descartando la plantilla por defecto. + ## [1.2.2] - 2026-02-27 ### Improved - Nuevo menú por defecto en el cliente, organizando la información por discos diff --git a/src/Controller/MenuBrowserController.php b/src/Controller/MenuBrowserController.php index 0553a91..4d661f1 100644 --- a/src/Controller/MenuBrowserController.php +++ b/src/Controller/MenuBrowserController.php @@ -76,7 +76,7 @@ class MenuBrowserController extends AbstractController ]); } - #[Route('/menu/{templateName}', name: 'render_menu_template')] + #[Route('/menu/{templateName}', name: 'render_menu_template', requirements: ['templateName' => '.+'])] public function renderMenu(string $templateName, Request $request): Response { $templatePath = 'browser/' . $templateName . '.html.twig'; diff --git a/src/Dto/Input/MenuInput.php b/src/Dto/Input/MenuInput.php index 5a8c1c1..9835a73 100644 --- a/src/Dto/Input/MenuInput.php +++ b/src/Dto/Input/MenuInput.php @@ -37,6 +37,10 @@ final class MenuInput #[ApiProperty(description: 'The default menu', example: "false")] public ?bool $isDefault = false; + #[Groups(['menu:write'])] + #[ApiProperty(description: 'HTML Content of the menu in Base64', example: "PGh0bWw+PC9odG1sPg==")] + public ?string $menuHtmlContent = null; + public function __construct(?Menu $menu = null) { if (!$menu) { diff --git a/src/State/Processor/MenuProcessor.php b/src/State/Processor/MenuProcessor.php index a0722c2..ff9576c 100644 --- a/src/State/Processor/MenuProcessor.php +++ b/src/State/Processor/MenuProcessor.php @@ -12,12 +12,19 @@ use ApiPlatform\Validator\ValidatorInterface; use App\Dto\Input\MenuInput; use App\Dto\Output\MenuOutput; use App\Repository\MenuRepository; +use App\Entity\Menu; +use Symfony\Component\Filesystem\Exception\IOExceptionInterface; +use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; +use Symfony\Component\Filesystem\Filesystem; + readonly class MenuProcessor implements ProcessorInterface { public function __construct( private MenuRepository $menuRepository, - private ValidatorInterface $validator + private ValidatorInterface $validator, + private ParameterBagInterface $params, + private Filesystem $filesystem ) { } @@ -47,12 +54,24 @@ readonly class MenuProcessor implements ProcessorInterface } $entity = null; + $oldPublicUrl = null; + if (isset($uriVariables['uuid'])) { $entity = $this->menuRepository->findOneByUuid($uriVariables['uuid']); + if ($entity) { + $oldPublicUrl = $entity->getPublicUrl(); + } } $menu = $data->createOrUpdateEntity($entity); $this->validator->validate($menu); + + // Extraemos el contenido base64 (asumiendo que $data es tu MenuInput) + $base64HtmlContent = property_exists($data, 'menuHtmlContent') ? $data->menuHtmlContent : null; + + // Sincronización de ficheros físicos y caché + $this->syncMenuTemplateFile($menu, $operation, $oldPublicUrl, $base64HtmlContent); + $this->menuRepository->save($menu); return new MenuOutput($menu); @@ -60,9 +79,160 @@ readonly class MenuProcessor implements ProcessorInterface private function processDelete($data, Operation $operation, array $uriVariables = [], array $context = []): null { - $user = $this->menuRepository->findOneByUuid($uriVariables['uuid']); - $this->menuRepository->delete($user); + $entity = null; + + if (isset($uriVariables['uuid'])) { + $entity = $this->menuRepository->findOneByUuid($uriVariables['uuid']); + + if ($entity) { + // 1. Borrar el fichero físico y la caché antes de eliminar de BD + $this->removeMenuTemplateFile($entity); + + // 2. Eliminar de la base de datos + $this->menuRepository->delete($entity); + } + } return null; } + + /** + * Creates, renames, and updates the Twig file associated with the menu. + * Throws \RuntimeException if any file system operation fails. + */ + private function syncMenuTemplateFile(Menu $menu, Operation $operation, ?string $oldPublicUrl, ?string $base64HtmlContent = null): void + { + $newPublicUrl = $menu->getPublicUrl(); + + if ($newPublicUrl) { + $projectDir = $this->params->get('kernel.project_dir'); + $templatesDir = rtrim($projectDir, '/') . '/templates/browser/'; + $newTemplateName = preg_replace('#^/menu/#', '', parse_url($newPublicUrl, PHP_URL_PATH)); + + if (!empty($newTemplateName)) { + $targetFile = $templatesDir . $newTemplateName . '.html.twig'; + $filesChanged = false; + + try { + // 1. RENAME OPERATION (Only for PUT/PATCH if URL changed) + if (($operation instanceof Put || $operation instanceof Patch) && $newPublicUrl !== $oldPublicUrl && $oldPublicUrl) { + $oldTemplateName = preg_replace('#^/menu/#', '', parse_url($oldPublicUrl, PHP_URL_PATH)); + $sourceFile = $templatesDir . $oldTemplateName . '.html.twig'; + + if ($this->filesystem->exists($sourceFile)) { + $this->filesystem->mkdir(dirname($targetFile), 0755); + $this->filesystem->rename($sourceFile, $targetFile, true); + $this->cleanupEmptyDirectories(dirname($sourceFile), $templatesDir); + $filesChanged = true; + } + } + + // 2. DETERMINE CONTENT + $contentToWrite = "{# Template for menu: {$menu->getName()} #}\n{% extends 'base.html.twig' %}\n{% block body %}\n

{$menu->getName()}

\n{% endblock %}\n"; + $hasCustomContent = false; + + if (!empty($base64HtmlContent)) { + $decodedContent = base64_decode($base64HtmlContent, true); // true = strict mode + if ($decodedContent !== false) { + $contentToWrite = $decodedContent; + $hasCustomContent = true; + } + } + + // 3. WRITE OPERATION (If file doesn't exist, OR if we received explicit HTML content) + if (!$this->filesystem->exists($targetFile) || $hasCustomContent) { + $this->filesystem->mkdir(dirname($targetFile), 0755); + $this->filesystem->dumpFile($targetFile, $contentToWrite); + + $filesChanged = true; + } + + // 4. TWIG CACHE INVALIDATION + if ($filesChanged) { + $env = $this->params->get('kernel.environment'); + $twigCacheDir = $projectDir . '/var/cache/' . $env . '/twig'; + + if ($this->filesystem->exists($twigCacheDir)) { + $this->filesystem->remove($twigCacheDir); + } + } + } catch (IOExceptionInterface $exception) { + throw new \RuntimeException( + sprintf('Critical failure synchronizing menu template file. Reason: %s', $exception->getMessage()), + 0, + $exception + ); + } + } + } + } + + /** + * Removes the Twig file associated with the menu, cleans up empty parent directories, + * and clears the cache. Throws \RuntimeException if any file system operation fails. + */ + private function removeMenuTemplateFile(Menu $menu): void + { + $publicUrl = $menu->getPublicUrl(); + + if ($publicUrl) { + $projectDir = $this->params->get('kernel.project_dir'); + $templatesDir = $projectDir . '/templates/browser/'; + $templateName = preg_replace('#^/menu/#', '', parse_url($publicUrl, PHP_URL_PATH)); + + if (!empty($templateName)) { + $targetFile = $templatesDir . $templateName . '.html.twig'; + + try { + if ($this->filesystem->exists($targetFile)) { + // 1. Delete the actual file + $this->filesystem->remove($targetFile); + + $this->cleanupEmptyDirectories(dirname($targetFile), $templatesDir); + + // 3. TWIG CACHE INVALIDATION + $env = $this->params->get('kernel.environment'); + $twigCacheDir = $projectDir . '/var/cache/' . $env . '/twig'; + + if ($this->filesystem->exists($twigCacheDir)) { + $this->filesystem->remove($twigCacheDir); + } + } + } catch (IOExceptionInterface $exception) { + throw new \RuntimeException( + sprintf('Critical failure removing menu template file or directories. Reason: %s', $exception->getMessage()), 0, $exception); + } + } + } + } + + /** + * Traverses upwards from a starting directory to a base directory, removing empty folders. + */ + private function cleanupEmptyDirectories(string $startDir, string $baseDir): void + { + $currentDir = $startDir; + $baseDirExact = rtrim($baseDir, '/'); + $continueCleaning = true; + + // La condición del while tiene el control absoluto del flujo + while ($continueCleaning && $currentDir !== $baseDirExact && str_starts_with($currentDir, $baseDirExact)) { + // Asumimos que pararemos, a menos que encontremos una carpeta vacía + $continueCleaning = false; + + if (is_dir($currentDir)) { + $dirContents = array_diff(scandir($currentDir), ['.', '..']); + + if (empty($dirContents)) { + $this->filesystem->remove($currentDir); + $currentDir = dirname($currentDir); + + // Como hemos borrado esta, le decimos al bucle que siga mirando arriba + $continueCleaning = true; + } + } + } + } + + } -- 2.40.1 From c3a84ecbfc5759b20147a187d67ef667c0257349 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Mon, 16 Mar 2026 14:01:42 +0100 Subject: [PATCH 03/11] =?UTF-8?q?A=C3=B1adido=20ApiKeyAuthenticator=20para?= =?UTF-8?q?=20acceso=20seguro=20de=20clientes=20-=20Implementado=20ApiKeyA?= =?UTF-8?q?uthenticator=20para=20proteger=20el=20endpoint=20/commands=20us?= =?UTF-8?q?ando=20la=20cabecera=20X-API-KEY.=20-=20A=C3=B1adido=20soporte?= =?UTF-8?q?=20para=20OGCLIENT=5FAPI=5FKEY=20en=20env.json=20para=20central?= =?UTF-8?q?izar=20su=20gesti=C3=B3n=20desde=20el=20oggui.=20-=20Modificado?= =?UTF-8?q?=20PostAction=20(PxeBootFile)=20para=20inyectar=20la=20API=20Ke?= =?UTF-8?q?y=20en=20el=20JSON=20enviado=20a=20ogBoot.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 7 ++ config/packages/security.yaml | 3 + env.json | 3 +- .../OgBoot/PxeBootFile/PostAction.php | 3 +- src/Security/ApiKeyAuthenticator.php | 77 +++++++++++++++++++ 5 files changed, 91 insertions(+), 2 deletions(-) create mode 100644 src/Security/ApiKeyAuthenticator.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fc644e..82143f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,11 @@ # Changelog +## [1.2.4] - 2026-03-16 +### Added +- Se ha implementado un nuevo [ApiKeyAuthenticator] para dotar de acceso seguro al endpoint `/commands` mediante la cabecera `X-API-KEY`. +- Incorporación de la variable global de entorno `OGCLIENT_API_KEY` en env.json para gestionar el token de acceso de clientes desde la interfaz gráfica. +### Changed +- Se ha modificado el controlador PostAction de `PxeBootFile` para inyectar y propagar la clave `ogclient_api_key` al payload que se envía a `ogBoot` durante la creación del arranque. + ## [1.2.3] - 2026-03-11 ### Added - Se ha añadido una nueva funcionalidad en el DTO `MenuInput` (campo `menuHtmlContent`) para recibir la plantilla HTML íntegra del menú codificada en Base64. diff --git a/config/packages/security.yaml b/config/packages/security.yaml index 6466847..5a114f1 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -22,6 +22,8 @@ security: success_handler: lexik_jwt_authentication.handler.authentication_success failure_handler: lexik_jwt_authentication.handler.authentication_failure jwt: ~ + custom_authenticators: + - App\Security\ApiKeyAuthenticator refresh_jwt: check_path: refresh_token @@ -29,6 +31,7 @@ security: - { path: ^/$, roles: PUBLIC_ACCESS } # Allows accessing the Swagger UI - { path: ^/docs, roles: PUBLIC_ACCESS } # Allows accessing the Swagger UI docs - { path: ^/auth/login, roles: PUBLIC_ACCESS } + - { path: ^/commands, roles: [ROLE_OGCLIENT_API, ROLE_ADMIN] } - { path: ^/opengnsys/rest, roles: PUBLIC_ACCESS } - { path: ^/og-repository/webhook, roles: PUBLIC_ACCESS } - { path: ^/og-lives/install/webhook, roles: PUBLIC_ACCESS } diff --git a/env.json b/env.json index c40cd36..c62e201 100644 --- a/env.json +++ b/env.json @@ -10,6 +10,7 @@ "SSL_ENABLED": "false", "OG_BOOT_IP": "127.0.0.1", "OG_BOOT_API_PORT": "8082", - "OG_BOOT_PXE_PORT": "8082" + "OG_BOOT_PXE_PORT": "8082", + "OGCLIENT_API_KEY": "ogclient-super-secret-token" } } \ No newline at end of file diff --git a/src/Controller/OgBoot/PxeBootFile/PostAction.php b/src/Controller/OgBoot/PxeBootFile/PostAction.php index 725dad7..46d9a8b 100644 --- a/src/Controller/OgBoot/PxeBootFile/PostAction.php +++ b/src/Controller/OgBoot/PxeBootFile/PostAction.php @@ -58,7 +58,8 @@ class PostAction extends AbstractOgBootController 'ogntp' => $client->getOrganizationalUnit()->getNetworkSettings()?->getNtp(), 'ogdns' => $client->getOrganizationalUnit()->getNetworkSettings()?->getDns(), 'ogProxy' => $client->getOrganizationalUnit()->getNetworkSettings()?->getProxy(), - 'resolution' => $client->getResolution() ?? '791' + 'resolution' => $client->getResolution() ?? '791', + 'ogclient_api_key' => $_ENV['OGCLIENT_API_KEY'] ?? 'ogclient-super-secret-token' ] ]; diff --git a/src/Security/ApiKeyAuthenticator.php b/src/Security/ApiKeyAuthenticator.php new file mode 100644 index 0000000..c954021 --- /dev/null +++ b/src/Security/ApiKeyAuthenticator.php @@ -0,0 +1,77 @@ +projectDir = $kernel->getProjectDir(); + } + + /** + * Called on every request to decide if this authenticator should be used for the request. + * Returning `false` will cause this authenticator to be skipped. + */ + public function supports(Request $request): ?bool + { + return $request->headers->has('X-API-KEY'); + } + + public function authenticate(Request $request): Passport + { + $apiToken = $request->headers->get('X-API-KEY'); + + $envFile = $this->projectDir . DIRECTORY_SEPARATOR . 'env.json'; + if (!is_file($envFile)) { + throw new CustomUserMessageAuthenticationException('Configuration file not found.'); + } + + $config = json_decode(file_get_contents($envFile), true); + $expectedToken = $config['vars']['OGCLIENT_API_KEY'] ?? null; + + if (null === $expectedToken || $apiToken !== $expectedToken) { + throw new CustomUserMessageAuthenticationException('Invalid API Token.'); + } + + // Usamos tu propia entidad User para crear un usuario virtual "al vuelo" + return new SelfValidatingPassport(new UserBadge('ogclient_api_user', function() { + $apiUser = new User(); + $apiUser->setUsername('ogclient_api_user'); + $apiUser->setRoles(['ROLE_OGCLIENT_API']); + $apiUser->setPassword(''); // Evitamos nulos en propiedades requeridas si las hay + + return $apiUser; + })); + } + + public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response + { + // on success, let the request continue + return null; + } + + public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response + { + $data = [ + 'message' => strtr($exception->getMessageKey(), $exception->getMessageData()) + ]; + + return new JsonResponse($data, Response::HTTP_UNAUTHORIZED); + } +} -- 2.40.1 From 379218ef20c34a5cff34eb7f4788a15a2f612b51 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Mon, 16 Mar 2026 14:48:13 +0100 Subject: [PATCH 04/11] =?UTF-8?q?Modificacion=20en=20security=20para=20per?= =?UTF-8?q?mitir=20acceso=20a=20la=20api=20al=20ROLE=5FUSER=20en=20lugar?= =?UTF-8?q?=20de=20IS=5FAUTHENTICATED=5FFULLY,=20ya=20que=20en=20ese=20cas?= =?UTF-8?q?o=20un=20cliente=20con=20rol=20ROLE=5FOGCLIENT=5FAPI=20podr?= =?UTF-8?q?=C3=ADa=20acceder=20a=20toda=20la=20api=20y=20solo=20queremos?= =?UTF-8?q?=20dar=20acceso=20a=20commands?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/packages/security.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config/packages/security.yaml b/config/packages/security.yaml index 5a114f1..a4ce57f 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -31,7 +31,7 @@ security: - { path: ^/$, roles: PUBLIC_ACCESS } # Allows accessing the Swagger UI - { path: ^/docs, roles: PUBLIC_ACCESS } # Allows accessing the Swagger UI docs - { path: ^/auth/login, roles: PUBLIC_ACCESS } - - { path: ^/commands, roles: [ROLE_OGCLIENT_API, ROLE_ADMIN] } + - { path: ^/commands, roles: [ROLE_OGCLIENT_API, ROLE_USER] } - { path: ^/opengnsys/rest, roles: PUBLIC_ACCESS } - { path: ^/og-repository/webhook, roles: PUBLIC_ACCESS } - { path: ^/og-lives/install/webhook, roles: PUBLIC_ACCESS } @@ -39,7 +39,7 @@ security: - { path: ^/validate, roles: PUBLIC_ACCESS } - { path: ^/menu-browser, roles: PUBLIC_ACCESS } - { path: ^/menu/, roles: PUBLIC_ACCESS } - - { path: ^/, roles: IS_AUTHENTICATED_FULLY } + - { path: ^/, roles: ROLE_USER } when@test: security: -- 2.40.1 From ac31e09187f731ea82bad9949d8414e9697faa64 Mon Sep 17 00:00:00 2001 From: Nicolas Arenas Date: Mon, 16 Mar 2026 14:46:27 +0100 Subject: [PATCH 05/11] Add .venv and .vscode to .gitignore Co-Authored-By: Claude Sonnet 4.6 --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 293c8aa..90caa8f 100644 --- a/.gitignore +++ b/.gitignore @@ -37,4 +37,5 @@ debian/files ### Certificates certs/ - +.venv/ +.vscode/ -- 2.40.1 From 8d3f217032f4fecda6e4d463e15ab3888ce54ccd Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Mon, 16 Mar 2026 14:52:28 +0100 Subject: [PATCH 06/11] - Se ha modificado el fichero security.yml para que el acceso a la api lo tenga el ROLE_USER en lugar de IS_AUTHENTICATED_FULLY, ya que de lo contrario cualquier cliente con rol ROLE_OGCLIENT_API podia acceder a la api, de esta forma se asegura que solo los usuarios con rol ROLE_USER puedan acceder a la api y el cliente solo pueda acceder a la ruta commands. --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82143f2..4372ff9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,8 @@ # Changelog +## [1.2.5] - 2026-03-16 +### Fixed +- Se ha modificado el fichero security.yml para que el acceso a la api lo tenga el ROLE_USER en lugar de IS_AUTHENTICATED_FULLY, ya que de lo contrario cualquier cliente con rol ROLE_OGCLIENT_API podia acceder a la api, de esta forma se asegura que solo los usuarios con rol ROLE_USER puedan acceder a la api y el cliente solo pueda acceder a la ruta commands. + ## [1.2.4] - 2026-03-16 ### Added - Se ha implementado un nuevo [ApiKeyAuthenticator] para dotar de acceso seguro al endpoint `/commands` mediante la cabecera `X-API-KEY`. -- 2.40.1 From c77cc0d1bf232f5eb2f35010257637376dc0ae40 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Tue, 17 Mar 2026 13:10:57 +0100 Subject: [PATCH 07/11] =?UTF-8?q?A=C3=B1adido=20Controlador=20para=20CRUD?= =?UTF-8?q?=20de=20assets?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/AssetManagerController.php | 160 ++++++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 src/Controller/AssetManagerController.php diff --git a/src/Controller/AssetManagerController.php b/src/Controller/AssetManagerController.php new file mode 100644 index 0000000..1b6d194 --- /dev/null +++ b/src/Controller/AssetManagerController.php @@ -0,0 +1,160 @@ +query->get('path', ''); + $targetPath = $this->getSecureTargetPath($params->get('kernel.project_dir'), $requestedPath); + $response = null; + + if ($targetPath === null || !is_dir($targetPath)) { + $response = new JsonResponse(['message' => 'Directorio inválido o no encontrado.'], Response::HTTP_NOT_FOUND); + } else { + $items = []; + $iterator = new \DirectoryIterator($targetPath); + foreach ($iterator as $fileinfo) { + if ($fileinfo->isDot()) continue; + + $items[] = [ + 'name' => $fileinfo->getFilename(), + 'type' => $fileinfo->isDir() ? 'folder' : 'file', + 'size' => $fileinfo->isFile() ? $fileinfo->getSize() : null, + 'path' => ltrim($requestedPath . '/' . $fileinfo->getFilename(), '/') + ]; + } + + usort($items, function($a, $b) { + if ($a['type'] === $b['type']) { + return strcasecmp($a['name'], $b['name']); + } + return $a['type'] === 'folder' ? -1 : 1; + }); + + $response = new JsonResponse($items, Response::HTTP_OK); + } + + return $response; + } + + #[Route('/ogassets/upload', name: 'api_assets_upload', methods: ['POST'])] + public function uploadAsset(Request $request, ParameterBagInterface $params, Filesystem $filesystem): JsonResponse + { + $file = $request->files->get('file'); + $requestedPath = $request->request->get('path', ''); + $extractZip = $request->request->getBoolean('extractZip', false); + $response = null; + + if (!$file) { + $response = new JsonResponse(['message' => 'No file uploaded.'], Response::HTTP_BAD_REQUEST); + } else { + $targetDir = $this->getSecureTargetPath($params->get('kernel.project_dir'), $requestedPath); + + if ($targetDir === null) { + $response = new JsonResponse(['message' => 'Ruta destino inválida.'], Response::HTTP_FORBIDDEN); + } else { + if (!is_dir($targetDir)) { + mkdir($targetDir, 0755, true); + $targetDir = realpath($targetDir); + } + + $originalName = $file->getClientOriginalName(); + $extension = strtolower($file->getClientOriginalExtension()); + + if ($extractZip && $extension === 'zip') { + $safeName = preg_replace('/[^a-zA-Z0-9_\-]/', '_', pathinfo($originalName, PATHINFO_FILENAME)); + $extractDir = $targetDir . '/' . $safeName; + + if (!$filesystem->exists($extractDir)) { + $filesystem->mkdir($extractDir, 0755); + } + + $zip = new ZipArchive(); + if ($zip->open($file->getPathname()) === true) { + $zip->extractTo($extractDir); + $zip->close(); + $response = new JsonResponse(['message' => 'ZIP extraído correctamente.']); + } else { + $response = new JsonResponse(['message' => 'Error al extraer ZIP.'], Response::HTTP_INTERNAL_SERVER_ERROR); + } + } else { + try { + $file->move($targetDir, $originalName); + $response = new JsonResponse(['message' => 'Archivo subido correctamente.']); + } catch (\Exception $e) { + $response = new JsonResponse(['message' => 'Error al guardar el archivo.'], Response::HTTP_INTERNAL_SERVER_ERROR); + } + } + } + } + + return $response; + } + + #[Route('/ogassets/delete', name: 'api_assets_delete', methods: ['DELETE'])] + public function deleteAsset(Request $request, ParameterBagInterface $params, Filesystem $filesystem): JsonResponse + { + $data = json_decode($request->getContent(), true); + $requestedPath = $data['path'] ?? ''; + $response = null; + + if (empty($requestedPath)) { + $response = new JsonResponse(['message' => 'Ruta requerida.'], Response::HTTP_BAD_REQUEST); + } else { + $realBase = realpath($params->get('kernel.project_dir') . '/public/assets'); + $targetPath = $this->getSecureTargetPath($params->get('kernel.project_dir'), $requestedPath); + + if ($targetPath === null || !file_exists($targetPath) || $targetPath === $realBase) { + $response = new JsonResponse(['message' => 'Ruta inválida o prohibida.'], Response::HTTP_FORBIDDEN); + } else { + try { + $filesystem->remove($targetPath); + $response = new JsonResponse(['message' => 'Elemento eliminado correctamente.']); + } catch (\Exception $e) { + $response = new JsonResponse(['message' => 'Error al eliminar el elemento.'], Response::HTTP_INTERNAL_SERVER_ERROR); + } + } + } + + return $response; + } +} -- 2.40.1 From fe128dcbd9588ce1a7eb1c255cd66c3cb477cab8 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Tue, 17 Mar 2026 13:19:01 +0100 Subject: [PATCH 08/11] =?UTF-8?q?A=C3=B1adido=20Controlador=20para=20CRUD?= =?UTF-8?q?=20de=20assets?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4372ff9..72779f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,8 @@ # Changelog +## [1.2.6] - 2026-03-17 +### Added +- Se ha añadido AssetsManagerController para la gestion de assets. + ## [1.2.5] - 2026-03-16 ### Fixed - Se ha modificado el fichero security.yml para que el acceso a la api lo tenga el ROLE_USER en lugar de IS_AUTHENTICATED_FULLY, ya que de lo contrario cualquier cliente con rol ROLE_OGCLIENT_API podia acceder a la api, de esta forma se asegura que solo los usuarios con rol ROLE_USER puedan acceder a la api y el cliente solo pueda acceder a la ruta commands. -- 2.40.1 From 76e54647ba73289bc001da113cdb2b3f8b79f228 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Tue, 17 Mar 2026 14:23:29 +0100 Subject: [PATCH 09/11] Se ha corregido la lectura de la variable OGCLIENT_API_KEY desde env.json para inyectarla correctamente en la plantilla PXE generada por ogBoot. --- CHANGELOG.md | 4 ++++ src/Controller/OgBoot/AbstractOgBootController.php | 2 ++ src/Controller/OgBoot/PxeBootFile/PostAction.php | 2 +- 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 72779f6..6b2da4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,8 @@ # Changelog +## [1.2.7] - 2026-03-17 +### Fixed +- Se ha corregido la lectura de la variable `OGCLIENT_API_KEY` desde `env.json` para inyectarla correctamente en la plantilla PXE generada por `ogBoot`. + ## [1.2.6] - 2026-03-17 ### Added - Se ha añadido AssetsManagerController para la gestion de assets. diff --git a/src/Controller/OgBoot/AbstractOgBootController.php b/src/Controller/OgBoot/AbstractOgBootController.php index 18f6bea..2d3918e 100644 --- a/src/Controller/OgBoot/AbstractOgBootController.php +++ b/src/Controller/OgBoot/AbstractOgBootController.php @@ -41,6 +41,8 @@ abstract class AbstractOgBootController extends AbstractController protected readonly CreateService $createService, protected readonly SimplifyOgLiveFilenameService $simplifyOgLiveFilenameService, protected readonly ExtractOgLiveFilenameDateService $extractOgLiveFilenameDateService, + #[Autowire(env: 'OGCLIENT_API_KEY')] + protected string $ogClientApiKey, protected readonly LoggerInterface $logger, ) diff --git a/src/Controller/OgBoot/PxeBootFile/PostAction.php b/src/Controller/OgBoot/PxeBootFile/PostAction.php index 46d9a8b..4ca7410 100644 --- a/src/Controller/OgBoot/PxeBootFile/PostAction.php +++ b/src/Controller/OgBoot/PxeBootFile/PostAction.php @@ -59,7 +59,7 @@ class PostAction extends AbstractOgBootController 'ogdns' => $client->getOrganizationalUnit()->getNetworkSettings()?->getDns(), 'ogProxy' => $client->getOrganizationalUnit()->getNetworkSettings()?->getProxy(), 'resolution' => $client->getResolution() ?? '791', - 'ogclient_api_key' => $_ENV['OGCLIENT_API_KEY'] ?? 'ogclient-super-secret-token' + 'ogclient_api_key' => $this->ogClientApiKey ] ]; -- 2.40.1 From e702559d7680e267a125e84108d9bbc9fec24225 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Wed, 25 Mar 2026 15:00:55 +0100 Subject: [PATCH 10/11] =?UTF-8?q?Modificado=20MenuBrowserController=20para?= =?UTF-8?q?=20permitir=20la=20edici=C3=B3n=20de=20las=20plantillas=20de=20?= =?UTF-8?q?men=C3=BA=20en=20"raw",=20permitiendo=20modificar=20el=20c?= =?UTF-8?q?=C3=B3digo=20twig=20en=20lugar=20del=20html=20ya=20compilado=20?= =?UTF-8?q?por=20twig,=20de=20esta=20forma=20podemos=20editar=20el=20fiche?= =?UTF-8?q?ro=20twig=20=20y=20aplicar=20cambios=20para=20ver=20el=20result?= =?UTF-8?q?ado=20antes=20de=20guardar=20la=20plantilla.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 4 +++ src/Controller/MenuBrowserController.php | 43 ++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b2da4f..398e221 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,8 @@ # Changelog +## [1.2.8] - 2026-03-20 +### Added +- Modificado MenuBrowserController para permitir la edición de las plantillas de menú en "raw", permitiendo modificar el código twig en lugar del html ya compilado por twig, de esta forma podemos editar el fichero twig y aplicar cambios para ver el resultado antes de guardar la plantilla. + ## [1.2.7] - 2026-03-17 ### Fixed - Se ha corregido la lectura de la variable `OGCLIENT_API_KEY` desde `env.json` para inyectarla correctamente en la plantilla PXE generada por `ogBoot`. diff --git a/src/Controller/MenuBrowserController.php b/src/Controller/MenuBrowserController.php index 4d661f1..291dcff 100644 --- a/src/Controller/MenuBrowserController.php +++ b/src/Controller/MenuBrowserController.php @@ -9,6 +9,7 @@ use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Routing\Attribute\Route; use Twig\Environment; @@ -90,4 +91,46 @@ class MenuBrowserController extends AbstractController 'disks' => [], ]); } + + #[Route('/menu-raw/{templateName}', name: 'get_raw_menu_template', requirements: ['templateName' => '.+'], methods: ['GET'])] + public function getRawMenu(string $templateName, Request $request): Response + { + $templatePath = 'browser/' . $templateName . '.html.twig'; + + if (!$this->twig->getLoader()->exists($templatePath)) { + throw $this->createNotFoundException(sprintf('La plantilla "%s" no existe.', $templateName)); + } + + $content = $this->twig->getLoader()->getSourceContext($templatePath)->getCode(); + + return new Response($content, Response::HTTP_OK, ['Content-Type' => 'text/plain; charset=utf-8']); + } + + #[Route('/menu-preview', name: 'preview_menu_template', methods: ['POST'])] + public function previewMenu(Request $request): Response + { + $data = json_decode($request->getContent(), true); + $base64Template = $data['templateBase64'] ?? ''; + + if (empty($base64Template)) { + return new JsonResponse(['message' => 'Falta el contenido de la plantilla.'], Response::HTTP_BAD_REQUEST); + } + + $content = base64_decode($base64Template); + if ($content === false) { + return new JsonResponse(['message' => 'El contenido Base64 es inválido.'], Response::HTTP_BAD_REQUEST); + } + + try { + $template = $this->twig->createTemplate($content); + $rendered = $template->render([ + 'ip' => '127.0.0.1 (Previsualización)', + 'mac' => '00:00:00:00:00:00', + 'disks' => [], + ]); + return new Response($rendered, Response::HTTP_OK, ['Content-Type' => 'text/html; charset=utf-8']); + } catch (\Exception $e) { + return new JsonResponse(['message' => 'Error al compilar la plantilla Twig: ' . $e->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR); + } + } } -- 2.40.1 From 91478cacd55899ba53d778000f2a76ff76d662b9 Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Fri, 27 Mar 2026 10:16:53 +0100 Subject: [PATCH 11/11] refs #2883. Run as admin. Added backend logic --- src/Controller/OgAgent/RunScriptAction.php | 15 ++++----------- src/Dto/Input/CommandExecuteInput.php | 7 +++++++ 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Controller/OgAgent/RunScriptAction.php b/src/Controller/OgAgent/RunScriptAction.php index 6d0ae99..4812bf5 100644 --- a/src/Controller/OgAgent/RunScriptAction.php +++ b/src/Controller/OgAgent/RunScriptAction.php @@ -37,7 +37,7 @@ class RunScriptAction extends AbstractOgAgentController throw new BadRequestHttpException('IP is required'); } - $data = $this->buildRequestData($client, $input->script); + $data = $this->buildRequestData($client, $input->script, $input->runAsAdmin); $response = $this->executeScript($client, $data); if (isset($response['code']) && $response['code'] === 409) { @@ -58,21 +58,14 @@ class RunScriptAction extends AbstractOgAgentController return new JsonResponse(data: $clientJobs, status: Response::HTTP_OK); } - private function buildRequestData(Client $client, string $script): array + private function buildRequestData(Client $client, string $script, bool $runAsAdmin = false): array { $scriptBase64 = base64_encode($script); - if ($this->isLinuxOrWindows($client)) { + if ($this->isLinuxOrWindows($client) || $this->isLinuxOrWindowsSession($client)) { return [ 'script' => $scriptBase64, - 'client' => 'false' - ]; - } - - if ($this->isLinuxOrWindowsSession($client)) { - return [ - 'script' => $scriptBase64, - 'client' => 'true' + 'client' => $runAsAdmin ? 'false' : 'true' ]; } diff --git a/src/Dto/Input/CommandExecuteInput.php b/src/Dto/Input/CommandExecuteInput.php index 4f71b31..8d8b6f4 100644 --- a/src/Dto/Input/CommandExecuteInput.php +++ b/src/Dto/Input/CommandExecuteInput.php @@ -34,4 +34,11 @@ final class CommandExecuteInput example: false )] public bool $queue = false; + + #[Groups(['command:write'])] + #[ApiProperty( + description: 'Si ejecutar el script en modo administrador', + example: false + )] + public bool $runAsAdmin = false; } \ No newline at end of file -- 2.40.1