Files
vHost/deploy/panel-failure-rollback-verify.mjs

108 lines
8.7 KiB
JavaScript

import crypto from 'node:crypto';
import http from 'node:http';
import https from 'node:https';
const panelURL = process.env.SEA_PANEL_URL?.trim();
const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey) 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');
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, attempts = 120) {
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 rollback verification', 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 {
const execution = await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
if (execution?.status === false || execution?.status === 'false') throw new Error('panel did not start temporary task');
let log = '';
for (let attempt = 0; attempt < attempts; 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)) break;
}
if (!log.includes(marker)) throw new Error(`temporary task failed:\n${log.trim()}`);
return log;
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
const marker = `rollback-verified-${suffix}`;
const shell = [
'set -Eeuo pipefail',
`test_id=${q(suffix)}`,
'token="$(sed -n \'s/^SEA_INTERNAL_AUTH_TOKEN=//p\' /etc/sea-vhost/sea-vhost.env | head -n1)"; test "${#token}" -ge 32',
'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',
'read -r tenant_id host_name domain storage_bytes process_limit < <(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT p.tenant_id,p.host_name,s.assigned_domain,pl.storage_bytes,p.process_limit FROM projects p JOIN tenants t ON t.id=p.tenant_id JOIN plans pl ON pl.id=t.plan_id JOIN sites s ON s.project_id=p.id AND s.is_primary=1 WHERE p.host_name REGEXP \'^sv[0-9a-f]{10}$\' AND s.panel_site_id IS NOT NULL ORDER BY p.id LIMIT 1")',
'test -n "$host_name"; test -d "/www/wwwroot/seavHost/vHost/$host_name"',
'vhost_root=/www/server/panel/vhost/nginx; extension_root="$vhost_root/extension/$domain"; target="$extension_root/sea-vhost-security.conf"; invalid="$extension_root/zz-sea-vhost-intentional-invalid-$test_id.conf"',
'backup="$(mktemp /var/lib/sea-vhost/web-protection-rollback.XXXXXX)"; response="$(mktemp /var/lib/sea-vhost/web-protection-response.XXXXXX)"; registry_before="$(sha256sum /var/lib/sea-vhost-panel/resources.json | awk \'{print $1}\')"',
'target_existed=0; if [[ -f "$target" ]]; then cp -a -- "$target" "$backup"; target_existed=1; fi',
'cleanup() { rm -f -- "$invalid" "$response"; if [[ "$target_existed" == 1 && -f "$backup" ]]; then cp -a -- "$backup" "$target"; else rm -f -- "$target"; fi; rm -f -- "$backup"; /www/server/nginx/sbin/nginx -t >/dev/null 2>&1 && /www/server/nginx/sbin/nginx -s reload >/dev/null 2>&1 || true; }; trap cleanup EXIT',
'/www/server/nginx/sbin/nginx -t >/dev/null',
'printf "# Sea vHost rollback probe %s\\n" "$test_id" | install -o root -g root -m 0644 /dev/stdin "$target"; probe_hash="$(sha256sum "$target" | awk \'{print $1}\')"',
'printf "sea_vhost_intentional_invalid_%s on;\\n" "$test_id" | install -o root -g root -m 0644 /dev/stdin "$invalid"',
'payload="$(printf \'{\"project\":{\"tenantId\":%s,\"hostName\":\"%s\",\"runPath\":\"/\",\"storageBytes\":%s,\"processLimit\":%s},\"domain\":\"%s\"}\' "$tenant_id" "$host_name" "$storage_bytes" "$process_limit" "$domain")"',
'agent_status="$(printf "%s" "$payload" | curl --silent --show-error --unix-socket /run/sea-vhost/agent.sock --header "Authorization: Bearer $token" --header "Content-Type: application/json" --request POST --data-binary @- --output "$response" --write-out \'%{http_code}\' http://localhost/v1/web-protection/apply)"',
'test "$agent_status" = 412; grep -Fq "nginx rejected web protection configuration" "$response"; test "$(sha256sum "$target" | awk \'{print $1}\')" = "$probe_hash"',
'broker_body="$(mktemp /var/lib/sea-vhost/broker-response.XXXXXX)"; trap \'rm -f -- "$broker_body"; cleanup\' EXIT',
'broker_status="$(printf \'%s\' \'{\"operation\":\"delete_site\",\"id\":9223372036854775807,\"name\":\"unmanaged-test.example.invalid\"}\' | curl --silent --show-error --unix-socket /run/sea-vhost-panel/broker.sock --header "Authorization: Bearer $token" --header "Content-Type: application/json" --request POST --data-binary @- --output "$broker_body" --write-out \'%{http_code}\' http://localhost/v1/operations)"',
'test "$broker_status" = 403; grep -Fq "面板操作失败" "$broker_body"; registry_after="$(sha256sum /var/lib/sea-vhost-panel/resources.json | awk \'{print $1}\')"; test "$registry_before" = "$registry_after"',
'unauthorized_status="$(printf \'%s\' \'{\"operation\":\"ping\"}\' | curl --silent --show-error --unix-socket /run/sea-vhost-panel/broker.sock --header "Content-Type: application/json" --request POST --data-binary @- --output /dev/null --write-out \'%{http_code}\' http://localhost/v1/operations)"; test "$unauthorized_status" = 401',
'rm -f -- "$invalid"; if [[ "$target_existed" == 1 ]]; then cp -a -- "$backup" "$target"; else rm -f -- "$target"; fi; /www/server/nginx/sbin/nginx -t >/dev/null; /www/server/nginx/sbin/nginx -s reload',
'printf "agent_status=%s\\nbroker_status=%s\\nunauthorized_status=%s\\nregistry_unchanged=true\\n" "$agent_status" "$broker_status" "$unauthorized_status"',
`printf '%s\n' ${q(marker)}`,
].join('\n');
const log = await runShell(`Sea vHost rollback verify ${suffix}`, shell, marker);
const value = (name) => log.match(new RegExp(`(?:^|\\n)${name}=([^\\r\\n]+)`))?.[1];
console.log(JSON.stringify({
status: 'passed',
checks: {
nginxRejectedInvalidConfiguration: value('agent_status') === '412',
managedSiteConfigurationRolledBack: true,
nginxConfigurationRestoredAndReloaded: true,
unmanagedBrokerResourceRejected: value('broker_status') === '403',
brokerRegistryUnchanged: value('registry_unchanged') === 'true',
brokerAuthenticationRequired: value('unauthorized_status') === '401',
},
}, null, 2));