Files
vHost/deploy/panel-runtime-suite-verify.mjs
T

147 lines
7.7 KiB
JavaScript

import crypto from 'node:crypto';
import http from 'node:http';
import https from 'node:https';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const panelURL = process.env.SEA_PANEL_URL?.trim();
const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim();
const consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !consoleURL) process.exit(2);
const panelBase = new URL(panelURL);
const panelClient = panelBase.protocol === 'https:' ? https : http;
const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined;
const md5 = (value) => crypto.createHash('md5').update(value).digest('hex');
const q = (value) => `'${value.replaceAll("'", "'\\''")}'`;
const suffix = crypto.randomBytes(6).toString('hex');
const email = `runtime-${suffix}@seavhost.test`;
const password = `Sv-${crypto.randomBytes(18).toString('base64url')}4r`;
const scriptDirectory = path.dirname(fileURLToPath(import.meta.url));
const workspace = path.dirname(scriptDirectory);
function authFields() {
const requestTime = Math.floor(Date.now() / 1000).toString();
return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) };
}
function panelForm(pathname, values) {
const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString());
return new Promise((resolve, reject) => {
const request = panelClient.request(new URL(pathname, panelBase), {
method: 'POST', agent: panelAgent, timeout: 30_000,
headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length },
}, (response) => {
let data = '';
response.setEncoding('utf8');
response.on('data', (chunk) => { data += chunk; });
response.on('end', () => {
if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`));
try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); }
});
});
request.on('timeout', () => request.destroy(new Error('panel request timed out')));
request.on('error', reject);
request.end(body);
});
}
async function runShell(name, shell, marker) {
const task = await panelForm('/crontab', {
action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0',
sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost runtime suite account', save: '0', backupTo: 'localhost',
});
if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary task');
const taskID = Number(task.id);
try {
await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
let log = '';
for (let attempt = 0; attempt < 90; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) });
log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log;
if (log.includes(marker)) return;
}
throw new Error(`temporary task failed: ${log.trim()}`);
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
const dbParts = [
'mapfile -t control_db < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')',
'control_user="${control_db[0]}"; control_password="${control_db[1]}"; control_host="${control_db[2]}"; control_port="${control_db[3]}"; control_name="${control_db[4]}"',
'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi',
].join('\n');
const seedMarker = `runtime-seeded-${suffix}`;
const seedShell = [
'set -euo pipefail', `email=${q(email)}`, `password=${q(password)}`,
'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"',
dbParts,
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$email\',\'$email\',\'Runtime verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"',
`printf '%s\n' ${q(seedMarker)}`,
].join('\n');
const cleanupMarker = `runtime-cleaned-${suffix}`;
const cleanupShell = [
'set -euo pipefail', `email=${q(email)}`, dbParts,
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\';"',
`printf '%s\n' ${q(cleanupMarker)}`,
].join('\n');
const artifacts = {
Go: path.join(workspace, 'build', 'smoke', 'sea-vhost-go-smoke'),
Java: path.join(workspace, 'build', 'smoke', 'sea-vhost-java-smoke.jar'),
};
const requestedRuntimes = process.env.SEA_RUNTIMES?.split(',').map((value) => value.trim()).filter(Boolean) ?? ['Node.js', 'Python', 'Go', 'Java'];
if (requestedRuntimes.length === 0 || requestedRuntimes.some((runtime) => !['Node.js', 'Python', 'Go', 'Java'].includes(runtime))) {
throw new Error('SEA_RUNTIMES contains an unsupported runtime');
}
let seeded = false;
try {
await runShell(`Sea vHost runtime seed ${suffix}`, seedShell, seedMarker);
seeded = true;
const results = [];
for (const runtime of requestedRuntimes) {
const child = spawnSync(process.execPath, [path.join(scriptDirectory, 'runtime-smoke.mjs')], {
cwd: workspace,
env: {
...process.env,
SEA_PANEL_URL: panelURL,
SEA_PANEL_API_KEY: panelAPIKey,
SEA_PANEL_TLS_INSECURE: String(insecureTLS),
SEA_CONSOLE_URL: consoleURL,
SEA_TENANT_LOGIN: email,
SEA_TENANT_PASSWORD: password,
SEA_RUNTIME: runtime,
...(artifacts[runtime] ? { SEA_RUNTIME_ARTIFACT: artifacts[runtime] } : {}),
},
encoding: 'utf8', timeout: 10 * 60_000, maxBuffer: 4 * 1024 * 1024,
});
if (child.status !== 0) {
const diagnostic = (child.stderr || child.stdout).trim().replaceAll(password, '[redacted]').slice(0, 1000);
results.push({ runtime, status: 'failed', diagnostic });
console.log(`${runtime}=failed`);
continue;
}
results.push({ ...JSON.parse(child.stdout), status: 'passed' });
console.log(`${runtime}=passed`);
}
const allPassed = results.every((result) => result.status === 'passed');
console.log(JSON.stringify({ status: allPassed ? 'passed' : 'failed', runtimes: results, checks: {
dynamicVersionCatalog: results.every((result) => result.version || result.status === 'failed'),
createUploadPreflightDeploy: allPassed,
nginxReverseProxy: allPassed,
isolatedLinuxIdentity: allPassed,
zeroProcessCapabilities: allPassed,
controlConfigAndSocketDenied: allPassed,
stopRestartDeleteCleanup: allPassed,
} }, null, 2));
if (!allPassed) process.exitCode = 1;
} finally {
if (seeded) {
try { await runShell(`Sea vHost runtime cleanup ${suffix}`, cleanupShell, cleanupMarker); } catch { process.exitCode = 1; }
}
}