You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudOperationErrorCatalog.php

713 lines
31 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Services\Cloud;
/**
* The single trust boundary for operation failure text.
*
* Engine responses are authenticated, but their human-readable fields are
* still host-controlled data. They must never be copied into a tenant
* response verbatim. This catalog keeps the tenant message intentionally
* small while retaining a bounded, unconditionally redacted summary for
* administrator diagnostics.
*/
final class CloudOperationErrorCatalog
{
/**
* Exact engine messages reviewed as safe for a tenant to see. Keep this
* list deliberately small: adding a message is a review of the complete
* engine call path, not a convenience for a new error string.
*/
private const USER_SAFE_DETAILS = [
'虚拟机参数校验失败',
'虚拟机不存在',
'虚拟机已经在运行',
'虚拟机未运行',
'虚拟机强制停机失败',
'虚拟机停机状态未确认',
'虚拟机服务恢复后启动失败',
'虚拟机持久网络状态未确认',
'虚拟机实时网络状态未确认',
'虚拟机操作已完成,但数据库状态保存失败;请管理员检查救援记录',
'服务状态尚未确认,引擎将安全重试',
'任务执行器已不存在,不会自动重放;请核查虚拟机实际状态',
'引擎重启导致任务中断,请核查虚拟机状态后重试',
'重装系统失败,请查看面板日志',
'重装失败,已恢复原虚拟机定义及旧系统盘',
'重装已完成,但旧系统盘清理待核对',
'重装结果待核对',
'网络修改失败,已恢复原配置',
'实例设置失败,已恢复原配置',
'实例设置修改失败,已恢复原配置',
'虚拟机名称已存在',
'虚拟机 UUID 已存在',
'虚拟机配置已变化,请重新提交救援操作',
'虚拟机配置已变化,网络修改已停止',
'虚拟机配置已变化,重装已停止',
'正常关机超时,重装已停止;旧系统盘未改变',
'正常关机超时,网络未修改',
'确认名称与虚拟机名称不一致',
'虚拟机操作缺少持久幂等编号',
'实例服务已到期或正在执行策略,不能执行该操作',
'引擎中已无此任务记录,请核查虚拟机状态后重试',
'在线快照要求虚拟机处于运行状态',
'文件系统一致快照需要虚拟机内的 QEMU Guest Agent 正常运行',
'在线快照创建失败',
'快照恢复失败,原系统盘保持不变',
'快照删除失败',
'防火墙能力不可用',
'防火墙规则无效',
'防火墙应用失败',
'防火墙策略漂移',
];
private const MAX_ADMIN_LENGTH = 300;
/**
* A deliberately small set of progress labels that are safe to show to
* an instance owner. New engine phases fall back to a status label
* instead of becoming an accidental error-message channel.
*/
private const USER_SAFE_PHASES = [
'等待任务开始', '正在处理', '正在执行', '正在检查虚拟机', '等待核对结果',
'等待重装任务开始', '重装完成', '重装失败',
'重装完成,但旧系统盘清理待核对', '重装结果待核对',
'正在预挂载救援 ISO 并等待正常关机', '正在强制断电并从救援 ISO 冷启动',
'正在正常关机并恢复原系统启动配置', '救援 ISO 已预挂载,等待手动强制断电后开机',
'救援系统已启动', '已退出救援模式,原系统已启动', '救援操作失败',
'网络修改完成', '网络修改失败', '任务已中断',
'正在创建在线快照', '在线快照创建完成', '在线快照创建失败',
'正在恢复快照', '快照恢复完成', '快照恢复失败',
'正在删除快照', '快照删除完成', '快照删除失败',
'正在应用防火墙', '防火墙已生效', '防火墙应用失败',
// User ISO jobs use the same engine progress store but have their own
// reviewed phrases. Keep these here so the ISO endpoint does not
// become a second arbitrary phase-text channel.
'等待下载', '正在安全下载 ISO', '正在保存到面板 ISO 目录',
'ISO 已保存,可用于所有宿主机', '导入失败', '引擎重启,任务已中断',
];
private const USER_SAFE_STATUSES = [
'queued', 'pending', 'running', 'succeeded', 'completed', 'done',
'failed', 'uncertain', 'cancelled', 'canceled', 'blocked', 'active',
'inactive', 'deleted', 'deleting', 'expired', 'unknown',
];
/**
* Stable values persisted in cloud_jobs.error_code for unreviewed engine
* failures. The column predates this catalog and is still consumed by
* older workers, so keep the values ASCII and independent of HTTP status
* text, host names, or upstream wording.
*/
private const WORKER_CODES = [
'uncertain' => '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);
}
}