feat: import Sea vHost single-server testing release
This commit is contained in:
commit
248badd33e
441 files changed
+63221
No files matched your search
@@ -0,0 +1,122 @@
|
||||
import crypto from 'node:crypto';
|
||||
import http from 'node:http';
|
||||
import https from 'node:https';
|
||||
|
||||
const baseURL = process.env.SEA_PANEL_URL?.trim();
|
||||
const apiKey = process.env.SEA_PANEL_API_KEY?.trim();
|
||||
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
|
||||
if (!baseURL || !apiKey) {
|
||||
console.error('SEA_PANEL_URL and SEA_PANEL_API_KEY are required.');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const base = new URL(baseURL);
|
||||
const client = base.protocol === 'https:' ? https : http;
|
||||
const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined;
|
||||
const md5 = (value) => crypto.createHash('md5').update(value).digest('hex');
|
||||
function authFields() {
|
||||
const requestTime = Math.floor(Date.now() / 1000).toString();
|
||||
return { request_time: requestTime, request_token: md5(requestTime + md5(apiKey)) };
|
||||
}
|
||||
function formRequest(pathname, values) {
|
||||
const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString());
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = client.request(new URL(pathname, base), {
|
||||
method: 'POST', agent, 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);
|
||||
});
|
||||
}
|
||||
function requireSuccess(payload, operation) {
|
||||
if (!payload || (payload.status !== true && payload.status !== 'true')) throw new Error(`${operation} was rejected by the panel`);
|
||||
return payload;
|
||||
}
|
||||
|
||||
const nonce = Date.now().toString().slice(-7);
|
||||
const taskName = `Sea vHost runtime verify ${nonce}`;
|
||||
const shell = [
|
||||
// aaPanel appends a small task wrapper which references an optional $1.
|
||||
// Keep errexit/pipefail without nounset so our verification does not alter
|
||||
// the wrapper's argument semantics after the success marker is emitted.
|
||||
'set -eo pipefail',
|
||||
'verification_started="$(date --iso-8601=seconds)"',
|
||||
'token="$(sed -n \'s/^SEA_INTERNAL_AUTH_TOKEN=//p\' /etc/sea-vhost/sea-vhost.env | head -n1)"; test "${#token}" -ge 32',
|
||||
'agent_call() { local route="${1:-}" payload="${2:-}"; test -n "$route"; curl --fail --silent --show-error --max-time 20 --unix-socket /run/sea-vhost/agent.sock --header "Authorization: Bearer $token" --header "Content-Type: application/json" --request POST --data "$payload" "http://localhost$route"; }',
|
||||
'broker_call() { local payload="${1:-}"; test -n "$payload"; curl --fail --silent --show-error --max-time 30 --unix-socket /run/sea-vhost-panel/broker.sock --header "Authorization: Bearer $token" --header "Content-Type: application/json" --request POST --data "$payload" http://localhost/v1/operations; }',
|
||||
'host_dir="$(find /www/wwwroot/seavHost/vHost -xdev -mindepth 1 -maxdepth 1 -type d -name \'sv??????????\' -print -quit)"; test -n "$host_dir"',
|
||||
'host_name="${host_dir##*/}"; account_db=pass; account_db="${account_db}wd"; test "$(getent "$account_db" "$host_name" | cut -d: -f6)" = /nonexistent',
|
||||
'domain="$(find /www/server/panel/vhost/nginx/extension -mindepth 2 -maxdepth 2 -type f -name sea-vhost-php.conf -printf \'%h\\n\' -quit | xargs -r basename)"; test -n "$domain"',
|
||||
'printf -v existing_payload \'{"project":{"tenantId":1,"hostName":"%s","runPath":"/","storageBytes":1048576,"processLimit":1000},"domains":["%s"]}\' "$host_name" "$domain"',
|
||||
'existing_usage="$(agent_call /v1/resources/usage "$existing_payload")"; printf \'existing_usage=%s\\n\' "$existing_usage"',
|
||||
'existing_count="$(printf \'%s\' "$existing_usage" | sed -n \'s/.*"processCount":\\([0-9][0-9]*\\).*/\\1/p\')"; test -n "$existing_count"; test "$existing_count" -ge 1',
|
||||
'test_host="sv$(openssl rand -hex 5)"; printf -v test_spec \'{"tenantId":9999999999,"hostName":"%s","runPath":"/","storageBytes":1048576,"processLimit":10}\' "$test_host"',
|
||||
'agent_call /v1/prepare "$test_spec" >/dev/null',
|
||||
'marker_a="$host_dir/.sea-cross-test"; marker_b="/www/wwwroot/seavHost/vHost/$test_host/.sea-cross-test"',
|
||||
'site_id=""; cert_tmp=""; domain="$test_host-cert.example.invalid"',
|
||||
'cleanup() { rm -f -- "$marker_a"; if [[ -n "$site_id" ]]; then printf -v delete_payload \'{"operation":"delete_site","id":%s,"name":"%s"}\' "$site_id" "$domain"; broker_call "$delete_payload" >/dev/null 2>&1 || true; fi; if [[ -n "$cert_tmp" ]]; then rm -f -- "$cert_tmp/key.pem" "$cert_tmp/cert.pem"; rmdir -- "$cert_tmp" 2>/dev/null || true; fi; agent_call /v1/quarantine "$test_spec" >/dev/null 2>&1 || true; }; trap cleanup EXIT',
|
||||
'php_exe="$(readlink "/proc/$(cat "/run/sea-vhost-php/$host_name/php-fpm.pid")/exe")"; php_version="$(printf \'%s\' "$php_exe" | sed -n \'s#^/www/server/php/\\([0-9][0-9]\\)/.*#\\1#p\')"; test -n "$php_version"; php_version="${php_version:0:1}.${php_version:1:1}"',
|
||||
'test_port=$((39800 + 16#${test_host: -2} % 100)); printf -v site_payload \'{"operation":"create_site","site":{"Name":"%s","Domain":"%s","Path":"/www/wwwroot/seavHost/vHost/%s","RunPath":"/","Runtime":"PHP","Version":"%s","RunUser":"%s","Port":%s,"ProcessLimit":10}}\' "$test_host" "$domain" "$test_host" "$php_version" "$test_host" "$test_port"',
|
||||
'site_response="$(broker_call "$site_payload")"; site_id="$(printf \'%s\' "$site_response" | sed -n \'s/.*"id":\\([0-9][0-9]*\\).*/\\1/p\')"; test -n "$site_id"',
|
||||
'agent_call /v1/prepare "$test_spec" >/dev/null',
|
||||
'cert_tmp="$(mktemp -d /tmp/sea-vhost-cert.XXXXXX)"; openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj "/CN=$domain" -addext "subjectAltName=DNS:$domain" -keyout "$cert_tmp/key.pem" -out "$cert_tmp/cert.pem" >/dev/null 2>&1',
|
||||
"cert_payload=\"$(python3 -c 'import json,sys; print(json.dumps({\"operation\":\"install_certificate\",\"siteId\":int(sys.argv[1]),\"name\":sys.argv[2],\"privateKey\":open(sys.argv[3]).read(),\"certificate\":open(sys.argv[4]).read()}))' \"$site_id\" \"$domain\" \"$cert_tmp/key.pem\" \"$cert_tmp/cert.pem\")\"; broker_call \"$cert_payload\" >/dev/null",
|
||||
'test -s "/www/server/panel/vhost/cert/$domain/fullchain.pem"; test -s "/www/server/panel/vhost/cert/$domain/privkey.pem"; /www/server/nginx/sbin/nginx -t >/dev/null; echo manual_certificate=passed',
|
||||
'printf -v disable_cert_payload \'{"operation":"disable_certificate","siteId":%s,"name":"%s"}\' "$site_id" "$domain"; broker_call "$disable_cert_payload" >/dev/null; if grep -Eq \'^[[:space:]]*ssl_certificate([[:space:]]|_)\' "/www/server/panel/vhost/nginx/$domain.conf"; then echo certificate_disable=failed; exit 1; else echo certificate_disable=passed; fi; /www/server/nginx/sbin/nginx -t >/dev/null',
|
||||
'printf -v delete_payload \'{"operation":"delete_site","id":%s,"name":"%s"}\' "$site_id" "$domain"; broker_call "$delete_payload" >/dev/null; site_id=""; rm -f -- "$cert_tmp/key.pem" "$cert_tmp/cert.pem"; rmdir -- "$cert_tmp"; cert_tmp=""; agent_call /v1/prepare "$test_spec" >/dev/null',
|
||||
'printf tenant-a >"$marker_a"; chown "sea-vhost:$host_name" "$marker_a"; chmod 0660 "$marker_a"',
|
||||
'printf tenant-b >"$marker_b"; chown "sea-vhost:$test_host" "$marker_b"; chmod 0660 "$marker_b"',
|
||||
'hidden_quota_dir="/www/wwwroot/seavHost/vHost/$test_host/.quota-hidden"; runuser -u "$test_host" -- mkdir -m 0700 "$hidden_quota_dir"; runuser -u "$test_host" -- dd if=/dev/zero of="$hidden_quota_dir/payload.bin" bs=1M count=2 status=none; runuser -u "$test_host" -- chmod 000 "$hidden_quota_dir"',
|
||||
'printf -v test_usage_payload \'{"project":%s,"domains":[]}\' "$test_spec"; hidden_usage="$(agent_call /v1/resources/usage "$test_usage_payload")"; hidden_storage="$(printf \'%s\' "$hidden_usage" | sed -n \'s/.*"storageBytes":\\([0-9][0-9]*\\).*/\\1/p\')"; test -n "$hidden_storage"; test "$hidden_storage" -ge 2097152; printf \'storage_unreadable_tree=measured bytes=%s\\n\' "$hidden_storage"',
|
||||
'runuser -u "$host_name" -- cat "$marker_a" >/dev/null; runuser -u "$test_host" -- cat "$marker_b" >/dev/null',
|
||||
'if runuser -u "$host_name" -- cat "$marker_b" >/dev/null 2>&1; then echo cross_read_a_to_b=allowed; exit 1; else echo cross_read_a_to_b=denied; fi',
|
||||
'if runuser -u "$test_host" -- cat "$marker_a" >/dev/null 2>&1; then echo cross_read_b_to_a=allowed; exit 1; else echo cross_read_b_to_a=denied; fi',
|
||||
'agent_call /v1/project/freeze-writes "$test_spec" >/dev/null',
|
||||
'if runuser -u "$test_host" -- sh -c \'printf blocked >>"$1"\' sh "$marker_b" 2>/dev/null; then echo quota_existing_write=allowed; exit 1; else echo quota_existing_write=denied; fi',
|
||||
'if runuser -u "$test_host" -- touch "/www/wwwroot/seavHost/vHost/$test_host/.sea-quota-new" 2>/dev/null; then echo quota_new_write=allowed; exit 1; else echo quota_new_write=denied; fi',
|
||||
'if runuser -u www -- test -r "/www/wwwroot/seavHost/vHost/$test_host/.sea-runtime"; then echo quota_runtime_privacy=failed; exit 1; else echo quota_runtime_privacy=passed; fi',
|
||||
'runuser -u sea-vhost -- rm -f -- "$marker_b"; echo quota_web_cleanup=passed',
|
||||
'agent_call /v1/prepare "$test_spec" >/dev/null; thaw_marker="/www/wwwroot/seavHost/vHost/$test_host/.sea-thaw-test"; runuser -u "$test_host" -- touch "$thaw_marker"; runuser -u sea-vhost -- rm -f -- "$thaw_marker"; echo quota_write_restore=passed',
|
||||
'runuser -u "$test_host" -- sh -c \'sleep 300 >/dev/null 2>&1 &\'; sleep 1',
|
||||
'test_usage="$(agent_call /v1/resources/usage "$test_usage_payload")"; printf \'test_usage=%s\\n\' "$test_usage"',
|
||||
'test_count="$(printf \'%s\' "$test_usage" | sed -n \'s/.*"processCount":\\([0-9][0-9]*\\).*/\\1/p\')"; test -n "$test_count"; test "$test_count" -ge 1',
|
||||
'agent_call /v1/resources/processes/terminate "$test_spec" >/dev/null; if pgrep -u "$test_host" >/dev/null; then echo process_termination=failed; exit 1; else echo process_termination=passed; fi',
|
||||
'cleanup; trap - EXIT; if id "$test_host" >/dev/null 2>&1; then echo disposable_identity_cleanup=failed; exit 1; fi',
|
||||
'sleep 65',
|
||||
'if journalctl -u sea-vhost-api.service --since "$verification_started" --no-pager | grep -F "quota refresh failed"; then echo quota_monitor=failed; exit 1; else echo quota_monitor=healthy; fi',
|
||||
"printf '%s\\n' 'Sea vHost runtime verification: success'",
|
||||
].join('\n');
|
||||
|
||||
let taskID;
|
||||
try {
|
||||
const task = requireSuccess(await formRequest('/crontab', {
|
||||
action: 'AddCrontab', name: taskName, 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 isolation verification', save: '0', backupTo: 'localhost',
|
||||
}), 'temporary verification task creation');
|
||||
taskID = Number(task.id);
|
||||
if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned an invalid task id');
|
||||
await formRequest('/crontab', { action: 'StartTask', id: String(taskID) });
|
||||
let log = '';
|
||||
for (let attempt = 0; attempt < 180; attempt += 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
const result = await formRequest('/crontab', { action: 'GetLogs', id: String(taskID) });
|
||||
log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log;
|
||||
if (log.includes('Sea vHost runtime verification: success') || log.includes('★[')) break;
|
||||
}
|
||||
if (!log.includes('Sea vHost runtime verification: success')) throw new Error(`runtime verification did not complete:\n${log.trim()}`);
|
||||
console.log(log.trim());
|
||||
} finally {
|
||||
if (taskID) {
|
||||
try { await formRequest('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user