Files
vHost/deploy/runtime-smoke.mjs
T

209 lines
14 KiB
JavaScript

import crypto from 'node:crypto';
import fs from 'node:fs';
import http from 'node:http';
import https from 'node:https';
const consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const panelURL = process.env.SEA_PANEL_URL?.trim();
const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim();
const tenantLogin = process.env.SEA_TENANT_LOGIN?.trim();
const tenantPassword = process.env.SEA_TENANT_PASSWORD?.trim();
const runtime = process.env.SEA_RUNTIME?.trim() || 'Node.js';
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!consoleURL || !panelURL || !panelAPIKey || !tenantLogin || !tenantPassword) {
console.error('SEA_CONSOLE_URL, SEA_PANEL_URL, SEA_PANEL_API_KEY, SEA_TENANT_LOGIN and SEA_TENANT_PASSWORD are required.');
process.exit(2);
}
if (!['Node.js', 'Python', 'Go', 'Java'].includes(runtime)) {
console.error('SEA_RUNTIME must be Node.js, Python, Go or Java.');
process.exit(2);
}
async function uploadFile(pathname, cookie, directory, localPath, filename) {
const content = fs.readFileSync(localPath);
if (content.length === 0 || content.length > 20 * 1024 * 1024) throw new Error('runtime artifact must be between 1 byte and 20 MB');
const body = new FormData();
body.set('path', directory);
body.set('overwrite', 'false');
body.set('file', new Blob([content]), filename);
const response = await fetch(new URL(pathname, consoleBase), { method: 'POST', headers: { Accept: 'application/json', Cookie: cookie }, body, redirect: 'manual' });
const text = await response.text();
let payload;
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
if (response.status !== 201) throw new Error(payload?.error?.message || `artifact upload returned HTTP ${response.status}`);
}
const consoleBase = new URL(consoleURL);
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');
function panelForm(pathname, values, timeoutMs = 30_000) {
const requestTime = Math.floor(Date.now() / 1000).toString();
const requestToken = md5(requestTime + md5(panelAPIKey));
const body = Buffer.from(new URLSearchParams({ ...values, request_time: requestTime, request_token: requestToken }).toString());
const url = new URL(pathname, panelBase);
return new Promise((resolve, reject) => {
const request = panelClient.request(url, {
method: 'POST', agent: panelAgent, timeout: timeoutMs,
headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length },
}, (response) => {
let data = '';
response.setEncoding('utf8');
response.on('data', (chunk) => {
data += chunk;
if (data.length > 2 * 1024 * 1024) request.destroy(new Error('panel response exceeded 2 MB'));
});
response.on('end', () => {
if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel 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 api(pathname, { method = 'GET', body, cookie, expected } = {}) {
const response = await fetch(new URL(pathname, consoleBase), {
method,
headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) },
body: body === undefined ? undefined : JSON.stringify(body),
redirect: 'manual',
});
const text = await response.text();
let payload;
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
const accepted = expected ? expected.includes(response.status) : response.status >= 200 && response.status < 300;
if (!accepted) throw new Error(payload?.error?.message || `${method} ${pathname} returned HTTP ${response.status}`);
return { response, payload };
}
function sessionCookie(response) {
const setCookie = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie');
const cookie = setCookie?.split(';', 1)[0];
if (!cookie?.startsWith('sea_session=')) throw new Error('tenant login did not return a session cookie');
return cookie;
}
async function localShellCheck(name, command, marker) {
if (!/^[A-Za-z0-9 ._-]{1,80}$/.test(name) || !/^[A-Za-z0-9._:-]{1,160}$/.test(marker)) throw new Error('unsafe smoke-check metadata');
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: `set -Eeo pipefail\nstage=initial\ntrap 'printf "runtime_check_failed_line=%s stage=%s\\n" "$LINENO" "$stage"' ERR\n${command}\nprintf '%s\\n' '${marker}'`,
sName: 'Temporary Sea vHost runtime lifecycle check', save: '0', backupTo: 'localhost',
});
const taskID = Number(task?.id);
if ((task?.status !== true && task?.status !== 'true') || !Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('aaPanel rejected runtime check task');
try {
await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
let lastLog = '';
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) });
const log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : '';
lastLog = log;
if (log.includes(marker)) return;
if (log.includes('runtime_check_failed_line=')) throw new Error(`runtime check assertion failed: ${log.trim()}`);
if (log.includes('Failed') || log.includes('ERROR')) throw new Error('runtime check task failed');
}
throw new Error(`runtime check task timed out: ${lastLog.trim().slice(-1200)}`);
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
const suffix = Date.now().toString(36).slice(-6);
const runtimeSlug = { 'Node.js': 'node', Python: 'python', Go: 'go', Java: 'java' }[runtime];
const runPath = `/${runtimeSlug}-${suffix}`;
let cookie;
let project;
let site;
try {
const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: tenantLogin, password: tenantPassword } });
cookie = sessionCookie(login.response);
const dashboard = await api('/api/v1/dashboard', { cookie });
project = dashboard.payload?.projects?.[0];
if (!project?.id) throw new Error('tenant has no virtual host for the runtime smoke test');
const catalog = await api('/api/v1/runtime-catalog', { cookie });
const runtimeVersion = catalog.payload?.versions?.[runtime]?.[0];
if (!runtimeVersion) throw new Error(`${runtime} is not installed`);
const created = await api(`/api/v1/projects/${project.id}/sites`, {
method: 'POST', cookie, expected: [201],
body: { name: `${runtimeSlug}-${suffix}`, runtime, version: runtimeVersion, runPath, customDomain: '', autoSSL: false },
});
site = created.payload?.site;
if (!site?.id || site.status !== 'awaiting_upload' || !Number.isInteger(site.backendPort)) throw new Error(`${runtime} site creation returned an incomplete record`);
const marker = ['Go', 'Java'].includes(runtime) ? `sea-vhost-${runtimeSlug}-artifact` : `sea-vhost-${runtimeSlug}-${suffix}`;
let entryFile;
if (runtime === 'Node.js') {
entryFile = 'package.json';
await api(`/api/v1/projects/${project.id}/files`, {
method: 'PUT', cookie, expected: [204],
body: { path: `${runPath.slice(1)}/package.json`, content: JSON.stringify({ name: `sea-vhost-${suffix}`, private: true, scripts: { start: 'node server.js' } }, null, 2), overwrite: false },
});
await api(`/api/v1/projects/${project.id}/files`, {
method: 'PUT', cookie, expected: [204],
body: { path: `${runPath.slice(1)}/server.js`, content: `require('node:http').createServer((_, res) => { res.end('${marker}'); }).listen(Number(process.env.PORT), '127.0.0.1');\n`, overwrite: false },
});
} else if (runtime === 'Python') {
entryFile = 'app.py';
const pythonSource = `import os\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nclass Handler(BaseHTTPRequestHandler):\n def do_GET(self):\n body = b'${marker}'\n self.send_response(200)\n self.send_header('Content-Length', str(len(body)))\n self.end_headers()\n self.wfile.write(body)\n def log_message(self, *_):\n pass\nHTTPServer(('127.0.0.1', int(os.environ['PORT'])), Handler).serve_forever()\n`;
await api(`/api/v1/projects/${project.id}/files`, {
method: 'PUT', cookie, expected: [204],
body: { path: `${runPath.slice(1)}/app.py`, content: pythonSource, overwrite: false },
});
} else {
entryFile = runtime === 'Go' ? 'app' : 'app.jar';
const artifact = process.env.SEA_RUNTIME_ARTIFACT?.trim();
if (!artifact || !fs.statSync(artifact).isFile()) throw new Error(`SEA_RUNTIME_ARTIFACT is required for ${runtime}`);
await uploadFile(`/api/v1/projects/${project.id}/files`, cookie, runPath.slice(1), artifact, entryFile);
}
const checked = await api(`/api/v1/projects/${project.id}/sites/${site.id}/deployment/check`, { method: 'POST', cookie, body: { entryFile } });
if (!checked.payload?.check?.ready || !checked.payload?.check?.adapterReady) throw new Error(`${runtime} deployment preflight did not become ready`);
const deployed = await api(`/api/v1/projects/${project.id}/sites/${site.id}/deployment`, { method: 'POST', cookie, body: { entryFile } });
site = deployed.payload?.site;
if (site?.status !== 'running') throw new Error(`${runtime} deployment was not committed as running`);
if (!/^[a-z0-9.-]+$/.test(site.domain)) throw new Error('runtime site returned an unsafe domain');
if (!/^\/www\/wwwroot\/seavHost\/vHost\/sv[0-9a-f]{10}$/.test(project.path) || !/^sv[0-9a-f]{10}$/.test(project.hostName)) {
throw new Error('runtime project returned an unsafe host identity or path');
}
await localShellCheck(`Sea vHost ${runtimeSlug} live ${suffix}`, `curl --silent --show-error --fail --max-time 10 --header 'Host: ${site.domain}' http://127.0.0.1/ | grep -Fq '${marker}'`, `live-${suffix}`);
const runtimeRoot = `${project.path}${runPath}`;
await localShellCheck(`Sea vHost ${runtimeSlug} identity ${suffix}`, [
`runtime_root='${runtimeRoot}'`, `host_name='${project.hostName}'`, `runtime_port='${site.backendPort}'`,
'stage=listener; pid="$(fuser -n tcp "$runtime_port" 2>/dev/null | tr -s \' \' \'\\n\' | grep -E \'^[0-9]+$\' | head -n1)"; test -n "$pid"',
'stage=process_owner; test "$(stat -c %U "/proc/$pid")" = "$host_name"',
'stage=directory_owner; test "$(stat -c %U:%G "$runtime_root")" = "sea-vhost:$host_name"',
'stage=capabilities; test "$(grep -Ec \'^Cap(Prm|Eff|Amb):[[:space:]]+0+$\' "/proc/$pid/status")" -eq 3',
'stage=config_privacy; if runuser -u "$host_name" -- test -r /var/lib/sea-vhost/config.json; then exit 1; fi',
'stage=socket_privacy; if timeout 3 runuser -u "$host_name" -- curl --silent --unix-socket /run/sea-vhost/agent.sock http://localhost/v1/health >/dev/null 2>&1; then exit 1; fi',
].join('\n'), `identity-${suffix}`);
await api(`/api/v1/projects/${project.id}/sites/${site.id}/state`, { method: 'POST', cookie, body: { enabled: false } });
await localShellCheck(`Sea vHost ${runtimeSlug} stopped ${suffix}`, `if curl --silent --fail --max-time 3 http://127.0.0.1:${site.backendPort}/ >/dev/null 2>&1; then stage=still_listening; false; fi`, `stopped-${suffix}`);
const restarted = await api(`/api/v1/projects/${project.id}/sites/${site.id}/state`, { method: 'POST', cookie, body: { enabled: true } });
if (restarted.payload?.site?.status !== 'running') throw new Error(`${runtime} site restart did not return running`);
await localShellCheck(`Sea vHost ${runtimeSlug} restarted ${suffix}`, `curl --silent --show-error --fail --max-time 10 --header 'Host: ${site.domain}' http://127.0.0.1/ | grep -Fq '${marker}'`, `restarted-${suffix}`);
await api(`/api/v1/projects/${project.id}/sites/${site.id}`, { method: 'DELETE', cookie, expected: [204] });
await localShellCheck(`Sea vHost ${runtimeSlug} removed ${suffix}`, `if curl --silent --fail --max-time 3 http://127.0.0.1:${site.backendPort}/ >/dev/null 2>&1; then exit 1; fi`, `removed-${suffix}`);
site = undefined;
await api(`/api/v1/projects/${project.id}/files?path=${encodeURIComponent(runPath.slice(1))}`, { method: 'DELETE', cookie, expected: [204] });
await api(`/api/v1/projects/${project.id}/files?emptyTrash=1`, { method: 'DELETE', cookie, expected: [204] });
console.log(JSON.stringify({ runtime, version: runtimeVersion, lifecycle: ['create', 'upload', 'check', 'deploy', 'proxy', 'stop', 'start', 'delete'], cleanup: 'complete' }, null, 2));
} finally {
if (cookie && project?.id && site?.id) {
try { await api(`/api/v1/projects/${project.id}/sites/${site.id}`, { method: 'DELETE', cookie, expected: [204] }); } catch { /* best effort */ }
}
if (cookie && project?.id) {
try { await api(`/api/v1/projects/${project.id}/files?path=${encodeURIComponent(runPath.slice(1))}`, { method: 'DELETE', cookie, expected: [204] }); } catch { /* best effort */ }
try { await api(`/api/v1/projects/${project.id}/files?emptyTrash=1`, { method: 'DELETE', cookie, expected: [204] }); } catch { /* best effort */ }
}
}