394 lines
13 KiB
JavaScript
394 lines
13 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 { 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: Extended Backend Endpoints (new-endpoints.test.js)', () => {
|
|
const testTmpDir = path.resolve(process.cwd(), '.tmp/test-new-endpoints');
|
|
const testUserDataPath = path.join(testTmpDir, 'users.json');
|
|
|
|
let server;
|
|
let baseUrl;
|
|
let adminCookie;
|
|
let operatorCookie;
|
|
let mockDriver;
|
|
|
|
before(async () => {
|
|
if (fs.existsSync(testTmpDir)) {
|
|
fs.rmSync(testTmpDir, { recursive: true, force: true });
|
|
}
|
|
fs.mkdirSync(testTmpDir, { recursive: true });
|
|
|
|
mockDriver = new MockApacheDriver(testTmpDir);
|
|
DriverFactory.setDriver(mockDriver);
|
|
|
|
defaultUserStore.filePath = testUserDataPath;
|
|
await defaultUserStore.init({ seedAdmin: true });
|
|
|
|
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();
|
|
});
|
|
});
|
|
|
|
// Login Admin
|
|
const adminLoginRes = await fetch(`${baseUrl}/api/auth/login`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username: 'admin', password: config.adminPass })
|
|
});
|
|
adminCookie = adminLoginRes.headers.get('set-cookie')?.split(';')[0];
|
|
|
|
// Crear operador para validar permisos
|
|
await fetch(`${baseUrl}/api/users`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({
|
|
username: 'operator1',
|
|
password: 'OperatorPass123!',
|
|
fullName: 'Operador de Pruebas',
|
|
role: 'operator'
|
|
})
|
|
});
|
|
|
|
// Login Operator
|
|
const operatorLoginRes = await fetch(`${baseUrl}/api/auth/login`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username: 'operator1', password: 'OperatorPass123!' })
|
|
});
|
|
operatorCookie = operatorLoginRes.headers.get('set-cookie')?.split(';')[0];
|
|
});
|
|
|
|
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. Subdomain Risk & Update API', () => {
|
|
it('POST /api/subdomains/:name/validate - Debe evaluar riesgos y retornar riskReport (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/subdomains/git/validate`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ type: 'static' })
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const data = await res.json();
|
|
assert.equal(data.success, true);
|
|
assert.equal(data.subdomain, 'git');
|
|
assert.equal(data.isGitea, true);
|
|
assert.equal(data.hasRisk, true);
|
|
assert.equal(data.requiresConfirmation, true);
|
|
assert.ok(data.risks.some((r) => r.code === 'GITEA_STATIC'));
|
|
});
|
|
|
|
it('PUT /api/subdomains/:name - Debe rechazar con 428 si hay riesgos y no se confirma', async () => {
|
|
const res = await fetch(`${baseUrl}/api/subdomains/git`, {
|
|
method: 'PUT',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ type: 'static' })
|
|
});
|
|
|
|
assert.equal(res.status, 428);
|
|
const data = await res.json();
|
|
assert.equal(data.code, 'PRECONDITION_REQUIRED');
|
|
assert.ok(data.riskReport);
|
|
assert.equal(data.riskReport.requiresConfirmation, true);
|
|
});
|
|
|
|
it('PUT /api/subdomains/:name - Debe permitir actualizar con forceConfirmed: true (200)', async () => {
|
|
// Crear un subdominio de prueba
|
|
await fetch(`${baseUrl}/api/subdomains`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ name: 'my-service', type: 'static' })
|
|
});
|
|
|
|
// Modificarlo a proxy confirmando explícitamente
|
|
const res = await fetch(`${baseUrl}/api/subdomains/my-service`, {
|
|
method: 'PUT',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({
|
|
type: 'proxy',
|
|
port: 8888,
|
|
forceConfirmed: true
|
|
})
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const data = await res.json();
|
|
assert.equal(data.success, true);
|
|
assert.equal(data.subdomain.type, 'proxy');
|
|
assert.equal(data.subdomain.port, 8888);
|
|
});
|
|
});
|
|
|
|
describe('2. File Manager API (/api/folders)', () => {
|
|
const folder = 'site-files';
|
|
|
|
before(async () => {
|
|
await fetch(`${baseUrl}/api/subdomains`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ name: folder, type: 'static' })
|
|
});
|
|
});
|
|
|
|
it('POST /api/folders/:name/item - Debe crear un nuevo archivo o subdirectorio (201)', async () => {
|
|
const dirRes = await fetch(`${baseUrl}/api/folders/${folder}/item`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ path: '', name: 'src', type: 'dir' })
|
|
});
|
|
assert.equal(dirRes.status, 201);
|
|
|
|
const fileRes = await fetch(`${baseUrl}/api/folders/${folder}/item`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ path: 'src', name: 'app.js', type: 'file' })
|
|
});
|
|
assert.equal(fileRes.status, 201);
|
|
});
|
|
|
|
it('PUT /api/folders/:name/file - Debe guardar contenido de archivo (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/folders/${folder}/file`, {
|
|
method: 'PUT',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({
|
|
path: 'src/app.js',
|
|
content: 'console.log("Servidor iniciado");'
|
|
})
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const data = await res.json();
|
|
assert.equal(data.success, true);
|
|
assert.equal(data.name, 'app.js');
|
|
});
|
|
|
|
it('GET /api/folders/:name/file - Debe leer el contenido del archivo (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/folders/${folder}/file?path=src/app.js`, {
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const data = await res.json();
|
|
assert.equal(data.success, true);
|
|
assert.equal(data.content, 'console.log("Servidor iniciado");');
|
|
});
|
|
|
|
it('POST /api/folders/:name/upload - Debe subir un archivo codificado en base64 (201)', async () => {
|
|
const content = 'Contenido subido por base64';
|
|
const base64 = Buffer.from(content, 'utf-8').toString('base64');
|
|
|
|
const res = await fetch(`${baseUrl}/api/folders/${folder}/upload`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({
|
|
path: '',
|
|
fileName: 'uploaded-test.txt',
|
|
base64Content: base64
|
|
})
|
|
});
|
|
|
|
assert.equal(res.status, 201);
|
|
const data = await res.json();
|
|
assert.equal(data.success, true);
|
|
assert.equal(data.name, 'uploaded-test.txt');
|
|
});
|
|
|
|
it('GET /api/folders/:name/files - Debe listar archivos con soporte para query ?path= (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/folders/${folder}/files?path=src`, {
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const data = await res.json();
|
|
assert.equal(data.folder, folder);
|
|
assert.equal(data.path, 'src');
|
|
assert.ok(data.files.some((f) => f.name === 'app.js'));
|
|
});
|
|
|
|
it('DELETE /api/folders/:name/item - Debe eliminar archivo de forma segura (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/folders/${folder}/item`, {
|
|
method: 'DELETE',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ path: 'uploaded-test.txt' })
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const data = await res.json();
|
|
assert.equal(data.success, true);
|
|
assert.equal(data.deleted, true);
|
|
});
|
|
});
|
|
|
|
describe('3. Remote Web Terminal API (/api/terminal)', () => {
|
|
let terminalToken = null;
|
|
|
|
it('POST /api/terminal/login - Rechaza al usuario ggc con 403 Forbidden', async () => {
|
|
const res = await fetch(`${baseUrl}/api/terminal/login`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ vpsUser: 'ggc', vpsPassword: 'any' })
|
|
});
|
|
|
|
assert.equal(res.status, 403);
|
|
});
|
|
|
|
it('POST /api/terminal/login - Administrador autentica con usuario root del VPS (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/terminal/login`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie
|
|
},
|
|
body: JSON.stringify({ vpsUser: 'root', vpsPassword: 'valid_password' })
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const data = await res.json();
|
|
assert.equal(data.success, true);
|
|
assert.equal(data.vpsUser, 'root');
|
|
assert.ok(data.terminalToken);
|
|
terminalToken = data.terminalToken;
|
|
});
|
|
|
|
it('POST /api/terminal/execute - Operador debe ser rechazado con 403 Forbidden', async () => {
|
|
const res = await fetch(`${baseUrl}/api/terminal/execute`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: operatorCookie,
|
|
'x-terminal-token': terminalToken
|
|
},
|
|
body: JSON.stringify({ command: 'whoami' })
|
|
});
|
|
|
|
assert.equal(res.status, 403);
|
|
});
|
|
|
|
it('POST /api/terminal/execute - Administrador puede ejecutar comandos con token de usuario VPS (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/terminal/execute`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Cookie: adminCookie,
|
|
'x-terminal-token': terminalToken
|
|
},
|
|
body: JSON.stringify({ command: 'echo "a2host terminal execution test"' })
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const data = await res.json();
|
|
assert.equal(data.success, true);
|
|
assert.equal(data.exitCode, 0);
|
|
assert.ok(data.stdout.includes('a2host terminal execution test'));
|
|
assert.equal(typeof data.executionTimeMs, 'number');
|
|
});
|
|
|
|
it('GET /api/terminal/info - Debe retornar información del entorno de shell (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/terminal/info`, {
|
|
headers: {
|
|
Cookie: adminCookie,
|
|
'x-terminal-token': terminalToken
|
|
}
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const data = await res.json();
|
|
assert.equal(data.authenticated, true);
|
|
assert.equal(data.user, 'root');
|
|
assert.ok(data.cwd);
|
|
assert.ok(data.hostname);
|
|
assert.ok(data.shell);
|
|
});
|
|
});
|
|
|
|
describe('4. Extended System & Processes API (/api/system)', () => {
|
|
it('GET /api/system/stats - Debe retornar estadísticas extendidas de CPU, Swap y Disco (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.cpu);
|
|
assert.ok(stats.swap);
|
|
assert.ok(stats.disk);
|
|
assert.ok(stats.memory.hostTotalBytes > 0);
|
|
});
|
|
|
|
it('GET /api/system/processes - Debe retornar top procesos por memoria (200)', async () => {
|
|
const res = await fetch(`${baseUrl}/api/system/processes`, {
|
|
headers: { Cookie: adminCookie }
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
const procs = await res.json();
|
|
assert.ok(Array.isArray(procs));
|
|
assert.ok(procs.length > 0);
|
|
assert.ok(procs[0].pid !== undefined);
|
|
assert.ok(procs[0].user);
|
|
assert.ok(procs[0].rssBytes !== undefined);
|
|
});
|
|
});
|
|
});
|