447 lines
15 KiB
JavaScript
447 lines
15 KiB
JavaScript
import { describe, it, before, after } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { createApp } from '../../src/app.js';
|
|
import { UserStore } from '../../src/infrastructure/storage/user.store.js';
|
|
import { MockApacheDriver } from '../../src/infrastructure/apache/mock.apache.driver.js';
|
|
import DriverFactory from '../../src/infrastructure/apache/driver.factory.js';
|
|
import defaultUserStore from '../../src/infrastructure/storage/user.store.js';
|
|
import config from '../../src/config/env.js';
|
|
|
|
describe('Integration Tests: Complete REST API Endpoints (api.test.js)', () => {
|
|
const testTmpDir = path.resolve(process.cwd(), '.tmp/test-api');
|
|
const testUserDataPath = path.join(testTmpDir, 'users.json');
|
|
|
|
let server;
|
|
let baseUrl;
|
|
let adminCookie;
|
|
let operatorCookie;
|
|
let mockDriver;
|
|
|
|
before(async () => {
|
|
// 1. Limpiar directorio temporal de pruebas
|
|
if (fs.existsSync(testTmpDir)) {
|
|
fs.rmSync(testTmpDir, { recursive: true, force: true });
|
|
}
|
|
fs.mkdirSync(testTmpDir, { recursive: true });
|
|
|
|
// 2. Configurar mock driver aislado
|
|
mockDriver = new MockApacheDriver(testTmpDir);
|
|
DriverFactory.setDriver(mockDriver);
|
|
|
|
// 3. Inicializar userStore de pruebas en data path temporal
|
|
defaultUserStore.filePath = testUserDataPath;
|
|
await defaultUserStore.init({ seedAdmin: true });
|
|
|
|
// 4. Crear servidor Express en puerto efímero (0)
|
|
const app = createApp();
|
|
await new Promise((resolve) => {
|
|
server = app.listen(0, '127.0.0.1', () => {
|
|
const addr = server.address();
|
|
baseUrl = `http://127.0.0.1:${addr.port}`;
|
|
resolve();
|
|
});
|
|
});
|
|
});
|
|
|
|
after(async () => {
|
|
await new Promise((resolve) => {
|
|
if (server) {
|
|
server.close(resolve);
|
|
} else {
|
|
resolve();
|
|
}
|
|
});
|
|
|
|
DriverFactory.resetDriver();
|
|
|
|
if (fs.existsSync(testTmpDir)) {
|
|
fs.rmSync(testTmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
describe('1. Módulo de Autenticación (/api/auth)', () => {
|
|
it('POST /api/auth/login - Debe rechazar credenciales incorrectas (401)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/auth/login`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username: 'admin', password: 'WrongPassword!' })
|
|
});
|
|
|
|
assert.equal(res.status, 401);
|
|
const data = await res.json();
|
|
assert.equal(data.code, 'UNAUTHORIZED');
|
|
assert.ok(data.detail);
|
|
});
|
|
|
|
it('POST /api/auth/login - Debe autenticar al superadmin y emitir cookie Set-Cookie (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/auth/login`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username: 'admin', password: config.adminPass })
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const rawCookie = res.headers.get('set-cookie');
|
|
assert.ok(rawCookie, 'Debe emitir cabecera set-cookie');
|
|
assert.ok(rawCookie.includes('a2host_session=s%3A'));
|
|
assert.ok(rawCookie.includes('HttpOnly'));
|
|
|
|
// Guardar cookie para pruebas subsiguientes
|
|
adminCookie = rawCookie.split(';')[0];
|
|
|
|
const body = await res.json();
|
|
assert.equal(body.success, true);
|
|
assert.equal(body.user.username, 'admin');
|
|
assert.equal(body.user.role, 'admin');
|
|
});
|
|
|
|
it('GET /api/auth/me - Debe rechazar peticiones sin sesión (401)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/auth/me`);
|
|
assert.equal(res.status, 401);
|
|
});
|
|
|
|
it('GET /api/auth/me - Debe retornar perfil con sesión válida (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/auth/me`, {
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const body = await res.json();
|
|
assert.equal(body.username, 'admin');
|
|
assert.equal(body.role, 'admin');
|
|
assert.ok(Array.isArray(body.permissions));
|
|
assert.ok(body.permissions.includes('subdomains:write'));
|
|
});
|
|
});
|
|
|
|
describe('2. Módulo de Usuarios (/api/users)', () => {
|
|
let createdUserId;
|
|
|
|
it('GET /api/users - Debe listar usuarios para rol admin (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/users`, {
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const users = await res.json();
|
|
assert.ok(Array.isArray(users));
|
|
assert.equal(users.length, 1);
|
|
assert.equal(users[0].username, 'admin');
|
|
});
|
|
|
|
it('POST /api/users - Debe crear un nuevo operador (201)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/users`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({
|
|
username: 'operator_jose',
|
|
password: 'PasswordSegura2026!',
|
|
fullName: 'José Operador',
|
|
role: 'operator'
|
|
})
|
|
});
|
|
|
|
assert.equal(res.status, 201);
|
|
const body = await res.json();
|
|
assert.equal(body.success, true);
|
|
assert.equal(body.user.username, 'operator_jose');
|
|
assert.equal(body.user.role, 'operator');
|
|
createdUserId = body.user.id;
|
|
});
|
|
|
|
it('POST /api/auth/login - Debe permitir login del operador recién creado', async () => {
|
|
const res = await fetch(`${baseUrl}/api/auth/login`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
username: 'operator_jose',
|
|
password: 'PasswordSegura2026!'
|
|
})
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const rawCookie = res.headers.get('set-cookie');
|
|
operatorCookie = rawCookie.split(';')[0];
|
|
});
|
|
|
|
it('POST /api/users - Operador no debe poder acceder a gestión de usuarios (403 Forbidden)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/users`, {
|
|
headers: { Cookie: operatorCookie }
|
|
});
|
|
assert.equal(res.status, 403);
|
|
});
|
|
|
|
it('PUT /api/users/:id - Admin puede actualizar nombre de usuario (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/users/${createdUserId}`, {
|
|
method: 'PUT',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ fullName: 'José Operador Senior' })
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const body = await res.json();
|
|
assert.equal(body.user.fullName, 'José Operador Senior');
|
|
});
|
|
|
|
it('DELETE /api/users/:id - Debe impedir que un admin se elimine a sí mismo (400)', async () => {
|
|
const meRes = await fetch(`${baseUrl}/api/auth/me`, {
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
const me = await meRes.json();
|
|
|
|
const res = await fetch(`${baseUrl}/api/users/${me.id}`, {
|
|
method: 'DELETE',
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
assert.equal(res.status, 400);
|
|
const body = await res.json();
|
|
assert.equal(body.code, 'CANNOT_DELETE_SELF');
|
|
});
|
|
|
|
it('DELETE /api/users/:id - Admin puede eliminar cuenta de operador (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/users/${createdUserId}`, {
|
|
method: 'DELETE',
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const body = await res.json();
|
|
assert.equal(body.success, true);
|
|
});
|
|
});
|
|
|
|
describe('3. Módulo de Subdominios (/api/subdomains)', () => {
|
|
it('GET /api/subdomains - Debe listar subdominios y marcar protegidos (git.conf)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/subdomains`, {
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const list = await res.json();
|
|
assert.ok(Array.isArray(list));
|
|
|
|
const gitSite = list.find((s) => s.name === 'git');
|
|
assert.ok(gitSite, 'git.conf debe figurar en la lista');
|
|
assert.equal(gitSite.protected, true, 'git debe estar protegido');
|
|
});
|
|
|
|
it('POST /api/subdomains - Debe rechazar subdominios con inyección o formato inválido (400)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/subdomains`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ name: 'attack;rm -rf /', type: 'static' })
|
|
});
|
|
|
|
assert.equal(res.status, 400);
|
|
const body = await res.json();
|
|
assert.equal(body.code, 'VALIDATION_FAILED');
|
|
});
|
|
|
|
it('POST /api/subdomains - Debe rechazar puertos reservados en Modo B (400)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/subdomains`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ name: 'my-service', type: 'proxy', port: 3000 })
|
|
});
|
|
|
|
assert.equal(res.status, 400);
|
|
const body = await res.json();
|
|
assert.equal(body.code, 'PORT_RESERVED');
|
|
});
|
|
|
|
it('POST /api/subdomains - Debe crear subdominio Modo A (Estático) exitosamente (201)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/subdomains`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ name: 'portfolio', type: 'static' })
|
|
});
|
|
|
|
assert.equal(res.status, 201);
|
|
const body = await res.json();
|
|
assert.equal(body.success, true);
|
|
assert.equal(body.subdomain.name, 'portfolio');
|
|
assert.equal(body.subdomain.type, 'static');
|
|
assert.equal(body.subdomain.enabled, true);
|
|
});
|
|
|
|
it('POST /api/subdomains - Debe crear subdominio Modo B (Proxy) exitosamente (201)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/subdomains`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ name: 'fastapi-app', type: 'proxy', port: 8080 })
|
|
});
|
|
|
|
assert.equal(res.status, 201);
|
|
const body = await res.json();
|
|
assert.equal(body.success, true);
|
|
assert.equal(body.subdomain.name, 'fastapi-app');
|
|
assert.equal(body.subdomain.port, 8080);
|
|
});
|
|
|
|
it('POST /api/subdomains - Debe rechazar nombres duplicados (409 Conflict)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/subdomains`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ name: 'portfolio', type: 'static' })
|
|
});
|
|
|
|
assert.equal(res.status, 409);
|
|
const body = await res.json();
|
|
assert.equal(body.code, 'SUBDOMAIN_ALREADY_EXISTS');
|
|
});
|
|
|
|
it('GET /api/subdomains/:name - Debe retornar la información de un subdominio (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/subdomains/portfolio`, {
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const body = await res.json();
|
|
assert.equal(body.name, 'portfolio');
|
|
assert.ok(body.rawConfig.includes('portfolio'));
|
|
});
|
|
|
|
it('POST /api/subdomains/:name/toggle - Debe pausar/deshabilitar subdominio (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/subdomains/portfolio/toggle`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ enabled: false })
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const body = await res.json();
|
|
assert.equal(body.subdomain.enabled, false);
|
|
});
|
|
|
|
it('POST /api/subdomains/:name/toggle - Debe rechazar toggle sobre sitios protegidos (403)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/subdomains/git/toggle`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ enabled: false })
|
|
});
|
|
|
|
assert.equal(res.status, 403);
|
|
const body = await res.json();
|
|
assert.equal(body.code, 'SITE_PROTECTED');
|
|
});
|
|
|
|
it('DELETE /api/subdomains/:name - Debe rechazar borrado de sitios protegidos (403)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/subdomains/git`, {
|
|
method: 'DELETE',
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
assert.equal(res.status, 403);
|
|
const body = await res.json();
|
|
assert.equal(body.code, 'SITE_PROTECTED');
|
|
});
|
|
|
|
it('DELETE /api/subdomains/:name - Debe eliminar subdominio y purgar archivos (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/subdomains/portfolio?deleteFiles=true`, {
|
|
method: 'DELETE',
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const body = await res.json();
|
|
assert.equal(body.success, true);
|
|
assert.equal(body.deletedFiles, true);
|
|
});
|
|
});
|
|
|
|
describe('4. Módulo de Carpetas Web (/api/folders)', () => {
|
|
it('GET /api/folders - Debe listar las carpetas dentro de la raíz web (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/folders`, {
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const folders = await res.json();
|
|
assert.ok(Array.isArray(folders));
|
|
});
|
|
|
|
it('GET /api/folders/:name/files - Debe proteger contra Path Traversal (400)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/folders/..%2Fetc/files`, {
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
// El nombre no pasará la regex de subdominio
|
|
assert.equal(res.status, 400);
|
|
});
|
|
});
|
|
|
|
describe('5. Módulo de Telemetría y Salud (/api/system/stats)', () => {
|
|
it('GET /api/system/stats - Debe retornar instantánea de memoria y Apache (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/system/stats`, {
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const stats = await res.json();
|
|
|
|
assert.ok(stats.server);
|
|
assert.ok(stats.server.hostname);
|
|
assert.ok(stats.memory);
|
|
assert.ok(stats.memory.processRssFormatted);
|
|
assert.equal(stats.memory.pm2LimitFormatted, '120 MB');
|
|
assert.ok(stats.apache);
|
|
assert.equal(stats.apache.mockMode, true);
|
|
});
|
|
});
|
|
|
|
describe('6. Módulo de Documentación (/api/docs)', () => {
|
|
it('GET /api/docs - Debe retornar el catálogo de documentos técnicos (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/docs`, {
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const docs = await res.json();
|
|
assert.ok(Array.isArray(docs));
|
|
assert.ok(docs.length > 0);
|
|
});
|
|
|
|
it('GET /api/docs/:id - Debe retornar el contenido Markdown de un documento (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/docs/01-requirements/srs-ieee-29148.md`, {
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const doc = await res.json();
|
|
assert.ok(doc.title);
|
|
assert.ok(doc.content);
|
|
assert.ok(doc.content.includes('SRS') || doc.content.includes('ISO/IEC/IEEE'));
|
|
});
|
|
});
|
|
});
|