'operation_uncertain', 'provision_failed' => 'provision_failed_refunded', 'failed' => 'operation_failed', ]; private const CODE_LABELS = [ 'operation_uncertain' => '操作结果待核对,请稍后刷新,切勿重复提交', 'reinstall_cleanup_pending' => '重装已完成,但旧系统盘清理待核对,请勿重复提交并联系管理员检查宿主机', 'reinstall_result_uncertain' => '重装结果待核对,请稍后刷新,切勿重复提交', 'provision_failed_refunded' => '开通失败,订单已退款', 'operation_failed' => '虚拟机操作失败,请稍后重试', 'snapshot_guest_agent_unavailable' => 'QEMU Guest Agent 不可用,无法创建文件系统一致快照;请修复 Guest Agent,或明确选择崩溃一致快照', // Compatibility for any job persisted by a short-lived preview build. 'snapshot_qga_unavailable' => 'QEMU Guest Agent 不可用,无法创建文件系统一致快照;请修复 Guest Agent,或明确选择崩溃一致快照', 'firewall_capability_missing' => '宿主机缺少防火墙能力,请联系管理员处理', 'firewall_rule_invalid' => '防火墙规则未通过引擎校验,请刷新后重新提交', 'firewall_apply_failed' => '防火墙应用失败;上一版已生效策略保持不变', 'firewall_result_uncertain' => '防火墙应用结果待核对,请勿重复提交', 'firewall_drift_detected' => '检测到防火墙策略漂移,请联系管理员核对', 'firewall_cleanup_pending' => '实例删除结果待核对,防火墙清理状态尚未确认', 'firewall_apply_superseded' => '防火墙请求已被更新的策略替代', 'admin_cancelled' => '管理员已中止后续重试;已派发的宿主机操作仍需核查', ]; /** * These fields are transport diagnostics rather than operation state. * Keep the list token based: engine versions have used snake_case, * camelCase, dotted and hyphenated names for the same values. */ private const DIAGNOSTIC_TOKENS = [ 'error', 'errors', 'detail', 'details', 'message', 'messages', 'exception', 'exceptions', 'trace', 'traces', 'traceback', 'tracebacks', 'stderr', 'stdout', 'diagnostic', 'diagnostics', 'reason', 'reasons', 'path', 'paths', 'command', 'commands', 'cmd', 'debug', 'debug_info', 'stack', 'stacktrace', 'url', 'uri', 'warning', 'warnings', 'diagnosis', 'diagnoses', 'error_code', 'status_code', 'http_status', 'engine_status', 'engine_http_status', 'safe_to_refund', ]; /** * Result fields that have a stable, user-facing meaning. Unknown engine * fields are intentionally dropped, even when they are scalar: a future * libvirt response must not become a new disclosure channel by merely * adding a key to its JSON envelope. */ private const SAFE_RESULT_KEYS = [ 'phase', 'status', 'state', 'uuid', 'name', 'hostname', 'job_id', 'public_ip', 'public_ip_cidr', 'network_changed', 'skipped', 'settings_changed', 'snapshot_key', 'consistency', 'size_bytes', 'revision', 'policy_digest', 'created', 'restored', 'deleted', 'service_was_running', 'service_was_running_hint', 'vm', 'reinstall_committed', 'cleanup_pending', 'vcpu', 'cpu_cores', 'memory_mib', 'ram_mib', 'disk_gib', 'os_source', 'os_name', 'install_iso', 'login_name', 'autostart', 'managed', ]; /** Keys that are safe only after the administrator summary redactor. */ private const ADMIN_RESULT_DIAGNOSTICS = ['error', 'detail', 'message']; /** Keys that should never survive in a persisted or presented result. */ private const FORBIDDEN_RESULT_KEYS = [ 'console_port', 'credential_generation', 'rescue_mode', 'rescue_staged', 'rescue_volume_name', 'volume_name', 'snapshot_volume_name', 'auth_mode', 'password_available', 'generated_password', 'safe_to_refund', ]; /** Keys that are diagnostic transport data, never tenant result data. */ public static function isDiagnosticKey(string $key): bool { $key = self::normalizeKey($key); if ($key === '') { return false; } foreach (explode('_', $key) as $token) { if (in_array($token, self::DIAGNOSTIC_TOKENS, true)) { return true; } } return in_array($key, self::DIAGNOSTIC_TOKENS, true); } /** * Sanitize a historical or engine operation result at the presentation * boundary. Ordinary users receive only the reviewed state fields; * administrators may also receive a bounded/redacted diagnostic string. */ public static function result(array $value, bool $administrator = false, ?string $kind = null, ?string $status = null, bool $hasOrder = false, ?string $action = null): array { return self::sanitizeResult($value, $administrator, $kind, $status, $hasOrder, $action, false); } /** * Return the only error text that may be sent to an ordinary user. * * A successful or still-running job has no error. For failed and * uncertain jobs the base text is selected from the persisted kind and * the optional reviewed detail is appended only when it is an exact * allow-list match. */ public static function userMessage(?string $kind, ?string $status, $raw, bool $hasOrder = false, ?string $action = null): ?string { $status = (string) $status; if (in_array($status, ['succeeded', 'completed', 'done', 'running', 'queued', 'pending'], true)) { return null; } $code = self::publicCode($raw); if ($code !== null) { return self::CODE_LABELS[$code]; } $base = self::baseMessage($kind, $status, $hasOrder, $action); $detail = self::reviewedDetail($raw); if ($detail === null || str_contains($base, $detail)) { return $base; } return $base . ':' . $detail; } /** * Return a bounded diagnostic summary for administrator-only views. * * This method intentionally does not consult AdminDataMasker::shouldMask: * even a super administrator should not receive credentials or arbitrary * host paths through an operation DTO. Exact reviewed messages are kept; * unknown engine text is redacted in-place and bounded. */ public static function adminSummary(?string $kind, ?string $status, $raw, bool $hasOrder = false, ?string $action = null): ?string { if ($raw === null || !is_scalar($raw)) { return null; } $value = trim((string) $raw); if ($value === '') { return null; } $reviewed = self::reviewedDetail($value); if ($reviewed !== null) { return $reviewed; } if (isset(self::CODE_LABELS[$value])) { return self::CODE_LABELS[$value]; } $value = self::redact($value); if ($value === '') { return self::baseMessage($kind, $status, $hasOrder, $action); } return mb_substr($value, 0, self::MAX_ADMIN_LENGTH, 'UTF-8'); } /** * Convert an engine operation envelope to a safe durable worker value. * Only reviewed details or stable internal codes are returned; the * operation envelope itself is never serialized into a tenant field. */ public static function workerSummary(?string $kind, ?string $status, array $operation, bool $hasOrder = false, ?string $action = null): ?string { $status = (string) $status; if (in_array($status, ['succeeded', 'completed', 'done', 'running', 'queued', 'pending'], true)) { return null; } $engineCode = is_string($operation['error_code'] ?? null) ? strtolower(trim($operation['error_code'])) : ''; if ((string) $kind === 'snapshot_create' && in_array($engineCode, ['qga_unavailable', 'snapshot_qga_unavailable', 'snapshot_guest_agent_unavailable'], true)) { return 'snapshot_guest_agent_unavailable'; } if ((string) $kind === 'reinstall' && in_array($engineCode, [ 'reinstall_cleanup_pending', 'reinstall_result_uncertain', ], true)) { return $engineCode; } if ((string) $kind === 'reinstall' && is_array($operation['result'] ?? null)) { // Older engines reported a post-commit cleanup warning inside a // nominally successful result. Once disposition() converts it // to uncertain, infer only a reviewed stable code; keep the raw // warning out of durable job fields. $result = $operation['result']; if (($result['cleanup_pending'] ?? false) === true || (is_string($result['warning'] ?? null) && str_starts_with(trim($result['warning']), '旧存储卷'))) { return 'reinstall_cleanup_pending'; } if (($result['reinstall_committed'] ?? false) === true || (is_string($result['warning'] ?? null) && trim($result['warning']) !== '')) { return 'reinstall_result_uncertain'; } } if ((string) $kind === 'firewall_apply') { if ($status === 'uncertain') { return 'firewall_result_uncertain'; } if (in_array($engineCode, [ 'firewall_capability_missing', 'firewall_rule_invalid', 'firewall_apply_failed', 'firewall_drift_detected', 'firewall_apply_superseded', ], true)) { return $engineCode; } return 'firewall_apply_failed'; } // A worker may persist only a reviewed detail or a stable generic // message. Never put an arbitrary engine/admin summary into the // legacy error_code column: old rows are displayed through // adminSummary(), but new rows must remain safe at rest as well. foreach (['error', 'detail', 'message'] as $field) { $reviewed = self::reviewedDetail($operation[$field] ?? null); if ($reviewed !== null) { return $reviewed; } } return self::workerCode($kind, $status, $hasOrder); } /** Stable code allow-list for browser branching; raw engine codes stay private. */ public static function publicCode($value): ?string { if (!is_string($value)) { return null; } $value = strtolower(trim($value)); return array_key_exists($value, self::CODE_LABELS) ? $value : null; } /** * Sanitize an operation result before it is persisted in result_json. * Error-like fields are represented by the durable error_code instead; * retaining them here would leave a second raw engine-error store that a * future DTO could accidentally expose. */ public static function workerResult(array $value): array { // Persistence is stricter than the administrator presentation view: // error/detail/message remain in error_code and never get a second // durable copy in result_json. return self::sanitizeResult($value, false, null, null, false, null, true); } /** * Return a status-only phase for a tenant. The engine may add arbitrary * progress text over time; exposing that text would recreate the same * host/libvirt disclosure problem as a raw error field. */ public static function userPhase($value, ?string $status, ?string $kind = null): ?string { // A post-commit reinstall may retain the last progress label while // its cleanup is being reconciled. Status wins over stale success // labels for reinstall only; other operation kinds may have their // own safe, useful uncertain phases. if ((string) $status === 'uncertain' && ($kind === null || (string) $kind === 'reinstall')) { if (is_string($value) && in_array(trim($value), [ '重装完成,但旧系统盘清理待核对', '重装结果待核对', ], true)) { return trim($value); } return '等待核对结果'; } if (is_string($value)) { $phase = self::normalize($value); if (in_array($phase, self::USER_SAFE_PHASES, true)) { return $phase; } } return match ((string) $status) { 'queued', 'pending' => '等待任务开始', 'running' => '正在处理', 'uncertain' => '等待核对结果', 'succeeded', 'completed', 'done' => '已完成', 'failed', 'cancelled', 'canceled', 'blocked' => '处理失败', default => null, }; } /** * Normalize a status emitted by a user-scoped engine job. * * Unknown values are rejected instead of being copied to the browser; * callers can then omit the record or show their own fixed fallback. */ public static function userStatus($value): ?string { if (!is_string($value)) { return null; } $status = strtolower(trim($value)); return in_array($status, self::USER_SAFE_STATUSES, true) ? $status : null; } /** Return a detail only when it exactly matches a reviewed message. */ public static function reviewedDetail($value): ?string { if (!is_string($value)) { return null; } $value = self::normalize($value); if (isset(self::CODE_LABELS[$value])) { return null; } return in_array($value, self::USER_SAFE_DETAILS, true) ? $value : null; } private static function workerCode(?string $kind, string $status, bool $hasOrder): string { if ($status === 'uncertain') { return self::WORKER_CODES['uncertain']; } if ((string) $kind === 'create' && $hasOrder) { return self::WORKER_CODES['provision_failed']; } return self::WORKER_CODES['failed']; } private static function baseMessage(?string $kind, string $status, bool $hasOrder, ?string $action): string { if ($status === 'uncertain') { return '操作结果待核对,请稍后刷新,切勿重复提交'; } if ((string) $kind === 'create' && $hasOrder) { return '开通失败,订单已退款'; } return match ((string) $kind) { 'action' => self::actionMessage($action), 'reinstall' => '重装系统失败,请核对实例状态后重试', 'rescue' => '救援操作失败,请核对实例状态后重试', 'delete', 'expiry_delete' => '删除实例失败,请核对实例状态后重试', 'network_change' => '更换公网 IP 失败,请核对实例状态后重试', 'instance_settings' => '实例设置失败,请核对实例状态后重试', 'snapshot_create' => '创建快照失败,请核对快照列表后重试', 'snapshot_restore' => '恢复快照失败,请核对实例和快照状态后重试', 'snapshot_delete' => '删除快照失败,请核对快照列表后重试', 'firewall_apply' => '防火墙应用失败,请核对当前策略后重试', 'service_suspend', 'service_resume', 'network_suspend', 'network_resume' => '实例策略执行失败,请稍后重试', default => '虚拟机操作失败,请稍后重试', }; } private static function actionMessage(?string $action): string { return match ((string) $action) { 'start' => '开机操作失败,请核对实例状态后重试', 'shutdown' => '关机操作失败,请核对实例状态后重试', 'reboot' => '重启操作失败,请核对实例状态后重试', 'poweroff' => '强制断电操作失败,请核对实例状态后重试', 'reset' => '强制重置操作失败,请核对实例状态后重试', default => '电源操作失败,请核对实例状态后重试', }; } private static function normalize(string $value): string { $value = trim($value); if ($value === '' || preg_match('//u', $value) !== 1) { return ''; } $value = preg_replace('/[\x00-\x1F\x7F]+/u', ' ', $value) ?? ''; return trim(preg_replace('/\s+/u', ' ', $value) ?? ''); } /** Normalize transport field spelling before applying the deny-list. */ private static function normalizeKey(string $key): string { $key = trim($key); if ($key === '') { return ''; } $key = preg_replace('/([a-z0-9])([A-Z])/', '$1_$2', $key) ?? ''; $key = preg_replace('/[^A-Za-z0-9]+/', '_', $key) ?? ''; return strtolower(trim($key, '_')); } private static function sanitizeResult(array $value, bool $administrator, ?string $kind, ?string $status, bool $hasOrder, ?string $action, bool $persist): array { $value = CloudInput::safeResult($value); if (array_is_list($value)) { return []; } $result = []; foreach ($value as $key => $item) { $name = self::normalizeKey((string) $key); if ($name === '' || in_array($name, self::FORBIDDEN_RESULT_KEYS, true)) { continue; } if (self::isDiagnosticKey($name)) { if ($persist || !$administrator) { continue; } $summary = self::adminSummary($kind, $status, $item, $hasOrder, $action); if ($summary !== null) { // Preserve the historical key for the three common // fields; normalize every camelCase/dotted variant to a // single generic administrator diagnostic slot. $diagnosticKey = in_array($name, self::ADMIN_RESULT_DIAGNOSTICS, true) ? $name : 'diagnostic'; if (!isset($result[$diagnosticKey])) { $result[$diagnosticKey] = $summary; } } continue; } if (!in_array($name, self::SAFE_RESULT_KEYS, true)) { continue; } if ($name === 'phase') { $phase = $administrator && !$persist ? self::adminSummary($kind, $status, $item, $hasOrder, $action) : self::userPhase($item, $status, $kind); if ($phase !== null) { $result[$name] = mb_substr($phase, 0, self::MAX_ADMIN_LENGTH, 'UTF-8'); } continue; } if ($name === 'vm') { if (is_array($item) && !array_is_list($item)) { $result[$name] = self::sanitizeResult($item, $administrator, $kind, $status, $hasOrder, $action, $persist); } continue; } $safe = self::safeResultScalar($name, $item); if ($safe !== null) { $result[$name] = $safe; } } return $result; } private static function safeResultScalar(string $key, $value) { if (is_bool($value)) { return in_array($key, ['network_changed', 'settings_changed', 'skipped', 'service_was_running', 'service_was_running_hint', 'autostart', 'managed', 'created', 'restored', 'deleted', 'reinstall_committed', 'cleanup_pending'], true) ? $value : null; } if (is_int($value) || is_float($value)) { if (!is_finite((float) $value)) { return null; } $maximums = [ 'vcpu' => 64, 'cpu_cores' => 64, 'memory_mib' => 262144, 'ram_mib' => 262144, 'disk_gib' => 1048576, 'size_bytes' => PHP_INT_MAX, 'revision' => PHP_INT_MAX, ]; $minimums = [ 'vcpu' => 1, 'cpu_cores' => 1, 'memory_mib' => 1, 'ram_mib' => 1, 'disk_gib' => 1, 'size_bytes' => 0, 'revision' => 1, ]; if (!array_key_exists($key, $maximums) || $value < $minimums[$key] || $value > $maximums[$key] || floor((float) $value) !== (float) $value) { return null; } return (int) $value; } if (!is_string($value)) { return null; } $value = self::normalize($value); if ($value === '' || mb_strlen($value) > 255) { return null; } if (in_array($key, ['vcpu', 'cpu_cores', 'memory_mib', 'ram_mib', 'disk_gib', 'size_bytes', 'revision'], true)) { if (preg_match('/^[0-9]+$/D', $value) !== 1) { return null; } $maximums = [ 'vcpu' => 64, 'cpu_cores' => 64, 'memory_mib' => 262144, 'ram_mib' => 262144, 'disk_gib' => 1048576, 'size_bytes' => PHP_INT_MAX, 'revision' => PHP_INT_MAX, ]; $number = (int) $value; $minimum = $key === 'size_bytes' ? 0 : 1; return $number >= $minimum && $number <= $maximums[$key] ? $number : null; } if (in_array($key, ['network_changed', 'settings_changed', 'skipped', 'service_was_running', 'service_was_running_hint', 'autostart', 'managed', 'created', 'restored', 'deleted'], true)) { return null; } if ($key === 'snapshot_key' && preg_match('/^[a-f0-9]{32}$/D', $value) !== 1) { return null; } if ($key === 'policy_digest' && preg_match('/^[a-f0-9]{64}$/D', $value) !== 1) { return null; } if ($key === 'consistency' && !in_array($value, ['filesystem', 'crash'], true)) { return null; } if (in_array($key, ['public_ip', 'public_ip_cidr'], true)) { if (($key === 'public_ip_cidr' && !str_contains($value, '/')) || ($key === 'public_ip' && str_contains($value, '/'))) { return null; } $address = explode('/', $value, 2)[0]; if (filter_var($address, FILTER_VALIDATE_IP) === false) { return null; } if (str_contains($value, '/')) { $parts = explode('/', $value, 2); $maximum = filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false ? 32 : 128; if (preg_match('/^[0-9]{1,3}$/D', $parts[1]) !== 1 || (int) $parts[1] > $maximum) { return null; } } } if ($key === 'state') { $state = CloudInstanceMetadata::state($value); return $state === 'unknown' && $value !== 'unknown' ? null : $state; } if ($key === 'status' && !in_array($value, [ 'queued', 'pending', 'running', 'succeeded', 'completed', 'done', 'failed', 'uncertain', 'cancelled', 'canceled', 'blocked', 'unknown', 'active', 'inactive', 'deleted', 'deleting', 'expired', ], true)) { return null; } if ($key === 'uuid' && preg_match( '/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iD', $value ) !== 1) { return null; } if ($key === 'job_id' && preg_match('/^[A-Za-z0-9_-]{8,128}$/D', $value) !== 1) { return null; } if ($key === 'hostname') { if (strlen($value) > 253 || str_ends_with($value, '.') || preg_match('/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/D', $value) !== 1) { return null; } } if ($key === 'os_source' && !in_array($value, ['cloud_template', 'iso', 'unknown'], true)) { return null; } if ($key === 'login_name' && preg_match('/^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/D', $value) !== 1) { return null; } if (in_array($key, ['name', 'os_name', 'install_iso'], true) && (str_contains($value, '/') || str_contains($value, '\\') || str_contains($value, ':'))) { return null; } return $value; } private static function redact(string $value): string { $value = self::normalize($value); if ($value === '') { return ''; } $value = preg_replace( '/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----.*?(?:-----END (?:[A-Z]+ )?PRIVATE KEY-----|$)/is', '[私密内容已隐藏]', $value ) ?? ''; $value = preg_replace('/\bBearer\s+\S+/i', 'Bearer [凭据已隐藏]', $value) ?? ''; $value = preg_replace( '/((?:password|passwd|password_hash|api[_ -]?key|api[_ -]?token|access[_ -]?token|refresh[_ -]?token|token|secret|client_secret|authorization|credential|private[_ -]?key)\s*[:=]\s*)(?:"[^"]*"|\'[^\']*\'|[^\s,;]+)/i', '$1[凭据已隐藏]', $value ) ?? ''; $value = preg_replace('#https?://[^\s]+#i', '[地址已隐藏]', $value) ?? ''; $value = preg_replace( '#(?:[A-Za-z]:[\\\\/]|/|\\\\)[^\s,;)]*#', '[路径已隐藏]', $value ) ?? ''; $value = preg_replace('/\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}(?::[0-9]{1,5})?\b/', '[地址已隐藏]', $value) ?? ''; $value = preg_replace('/\b(?:[0-9A-F]{1,4}:){2,}[0-9A-F:.]*\b/i', '[地址已隐藏]', $value) ?? ''; $value = preg_replace('/\s{2,}/u', ' ', trim($value)) ?? ''; return trim($value); } }