[1, 64], 'cpu_cores' => [1, 64], 'memory_mib' => [1, 262144], 'ram_mib' => [1, 262144], 'disk_gib' => [1, 1048576], 'bandwidth_mbps' => [1, 10000000]] as $key => $bounds) { $value = self::integer($safe[$key] ?? null, $bounds[0], $bounds[1]); if ($value !== null) { $public[$key] = $value; } } $disks = self::disks($safe['disks'] ?? null); if ($disks !== []) { $public['disks'] = $disks; } foreach (['autostart', 'managed'] as $key) { if (is_bool($safe[$key] ?? null)) { $public[$key] = $safe[$key]; } } $version = self::integer($safe['engine_metadata_version'] ?? null, 1, self::VERSION); if ($version !== null) { $public['engine_metadata_version'] = $version; } return array_intersect_key($public, array_flip(self::PUBLIC_SPEC_KEYS)); } /** Merge a trusted engine snapshot into an existing business spec. */ public static function merge(array $spec, array $live): array { // Re-validate an older cached copy as well. Early discovery releases // stored raw disk source paths in `disks`; canonicalizing before the // overlay removes them during the first successful backfill. $spec = self::sanitizeSpec($spec); $metadata = self::metadata($live); if ($metadata === []) { return $spec; } unset($spec['engine_metadata_version']); if (($metadata['os_source'] ?? null) === 'cloud_template') { unset($spec['install_iso']); } elseif (($metadata['os_source'] ?? null) === 'iso') { unset($spec['os_name'], $spec['login_name']); } elseif (($metadata['os_source'] ?? null) === 'unknown') { unset($spec['os_name'], $spec['install_iso'], $spec['login_name']); } return array_merge($spec, $metadata, [ 'engine_metadata_version' => self::VERSION, ]); } /** * Return only identity and public static fields after an exact UUID check. * * The snapshot is already actor-scoped by the caller. A mismatched live * record is ignored instead of allowing one libvirt row to decorate a * different tenant's database record. */ public static function publicView(array $snapshot, array $live): array { $view = self::identity($snapshot); $view = array_merge($view, self::metadata($snapshot)); if (self::sameUuid($snapshot['uuid'] ?? null, $live['uuid'] ?? null)) { $metadata = self::metadata($live); $view = array_merge($view, $metadata); if ($metadata !== []) { $view['engine_metadata_version'] = self::VERSION; } } return $view; } /** * Persist engine metadata for only the caller-provided, actor-visible rows. * * $liveByUuid is expected to be keyed by canonical UUID, although the UUID * inside every live row remains authoritative and must match as well. The * database rows are locked and re-read before merge so a concurrent worker * cannot lose an updated order/reinstall specification. */ public static function persistBatch(array $snapshots, array $liveByUuid): void { $allowed = []; foreach ($snapshots as $snapshot) { if (!is_array($snapshot)) { continue; } $id = filter_var($snapshot['id'] ?? $snapshot['api_id'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); $uuid = self::uuid($snapshot['uuid'] ?? null); if ($id !== false && $uuid !== null) { $allowed[(int) $id] = $uuid; } } if ($allowed === []) { return; } $live = []; foreach ($liveByUuid as $key => $value) { if (!is_array($value)) { continue; } $rowUuid = self::uuid($value['uuid'] ?? null); $keyUuid = self::uuid(is_string($key) ? $key : null); if ($rowUuid !== null && $keyUuid !== null && hash_equals($keyUuid, $rowUuid)) { $live[$rowUuid] = $value; } } if ($live === []) { return; } $connection = (new CloudInstance())->getConnection(); $connection->transaction(static function () use ($allowed, $live): void { $instances = CloudInstance::whereIn('id', array_keys($allowed)) ->where('status', '<>', 'deleted') ->lockForUpdate()->get(['id', 'uuid', 'spec_json', 'updated_at']); foreach ($instances as $instance) { $uuid = self::uuid($instance->uuid); if ($uuid === null || !isset($allowed[(int) $instance->id]) || !hash_equals($allowed[(int) $instance->id], $uuid) || !isset($live[$uuid])) { continue; } $decoded = json_decode((string) $instance->spec_json, true); if (!is_array($decoded) || array_is_list($decoded)) { // A damaged business snapshot may still contain the only // plan/template evidence. Never replace it with a partial // engine view; publicView can serve the live fields for // this response while an administrator repairs the row. continue; } $spec = $decoded; $merged = self::merge($spec, $live[$uuid]); if ($merged === $spec) { continue; } $instance->spec_json = json_encode($merged, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); $instance->updated_at = time(); $instance->save(); } }, 3); } private static function identity(array $snapshot): array { $id = filter_var($snapshot['id'] ?? $snapshot['api_id'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); $uuid = self::uuid($snapshot['uuid'] ?? null); return [ 'id' => $id === false ? '' : (string) $id, 'api_id' => $id === false ? '' : (string) $id, 'uuid' => $uuid ?? '', 'name' => self::name($snapshot['name'] ?? null) ?? '', ]; } /** Extract the strict public/static allowlist from one engine row. */ private static function metadata(array $value): array { $result = []; $integerBounds = [ 'vcpu' => [1, 64], 'memory_mib' => [1, 262144], 'disk_gib' => [1, 1048576], ]; foreach ($integerBounds as $key => [$minimum, $maximum]) { $integer = self::integer($value[$key] ?? null, $minimum, $maximum); if ($integer !== null) { $result[$key] = $integer; } } foreach (['autostart', 'managed'] as $key) { if (is_bool($value[$key] ?? null)) { $result[$key] = $value[$key]; } } $cidr = self::cidr($value['public_ip_cidr'] ?? null); if ($cidr !== null) { $result['public_ip_cidr'] = $cidr; } $source = $value['os_source'] ?? null; if (is_string($source) && in_array($source, ['cloud_template', 'iso', 'unknown'], true)) { $result['os_source'] = $source; } $osName = self::text($value['os_name'] ?? null, 64); if ($osName !== null && $source === 'cloud_template') { $result['os_name'] = $osName; } $installIso = self::text($value['install_iso'] ?? null, 255); if ($installIso !== null && $source === 'iso' && basename($installIso) === $installIso && !str_contains($installIso, '\\') && !str_contains($installIso, ':')) { $result['install_iso'] = $installIso; } $login = $value['login_name'] ?? null; if ($source === 'cloud_template' && is_string($login) && preg_match('/^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/D', $login) === 1) { $result['login_name'] = $login; } elseif (($result['managed'] ?? false) === true && ($result['os_source'] ?? null) === 'cloud_template') { // Discovery returns raw libvirt data rather than decorate_vm(). $result['login_name'] = 'root'; } $hostname = self::hostname($value['guest_hostname'] ?? $value['hostname'] ?? null); if ($hostname !== null && $source === 'cloud_template') { $result['guest_hostname'] = $hostname; } $disks = self::disks($value['disks'] ?? null); if ($disks !== []) { $result['disks'] = $disks; $capacity = array_sum(array_column($disks, 'capacity_gib')); if ($capacity > 0) { $result['disk_gib'] = round($capacity, 2); } } return $result; } private static function disks($value): array { if (!is_array($value) || !array_is_list($value)) { return []; } $result = []; foreach (array_slice($value, 0, 32) as $disk) { if (!is_array($disk)) { continue; } $capacity = $disk['capacity_gib'] ?? $disk['size_gib'] ?? null; if (is_int($capacity) || is_float($capacity) || (is_string($capacity) && is_numeric($capacity))) { $capacity = (float) $capacity; if (is_finite($capacity) && $capacity > 0 && $capacity <= 1048576) { // Capacity is all the UI needs. Never persist a host path, // pool/volume name, target name or disk format here. $result[] = ['capacity_gib' => round($capacity, 2)]; } } } return $result; } private static function integer($value, int $minimum, int $maximum): ?int { if (is_bool($value) || (!is_int($value) && !(is_string($value) && preg_match('/^[0-9]+$/D', $value) === 1))) { return null; } $value = (int) $value; return $value >= $minimum && $value <= $maximum ? $value : null; } private static function cidr($value): ?string { if (!is_string($value) || strlen($value) > 64 || trim($value) !== $value) { return null; } $parts = explode('/', $value, 2); if (count($parts) !== 2 || filter_var($parts[0], FILTER_VALIDATE_IP) === false || preg_match('/^[0-9]{1,3}$/D', $parts[1]) !== 1) { return null; } $maximum = filter_var($parts[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false ? 32 : 128; $prefix = (int) $parts[1]; return $prefix <= $maximum ? $parts[0] . '/' . $prefix : null; } private static function ip($value): ?string { if (!is_string($value) || trim($value) !== $value || filter_var($value, FILTER_VALIDATE_IP) === false) { return null; } return $value; } private static function hostname($value): ?string { if (!is_string($value)) { return null; } $value = trim($value); if ($value === '' || strlen($value) > 253 || str_ends_with($value, '.')) { return null; } foreach (explode('.', $value) as $label) { if ($label === '' || strlen($label) > 63 || preg_match('/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/D', $label) !== 1) { return null; } } return strtolower($value); } private static function text($value, int $maximum): ?string { if (!is_string($value) || $value === '' || trim($value) !== $value) { return null; } $controls = preg_match('/[\x00-\x1F\x7F]/u', $value); if ($controls !== 0 || mb_strlen($value) > $maximum) { return null; } return $value; } private static function name($value): ?string { return self::text($value, 63); } private static function uuid($value): ?string { if (!is_string($value)) { return null; } $value = strtolower(trim($value)); // libvirt also accepts operator-supplied UUIDs whose version/variant // nibbles do not follow RFC 4122. Match the existing ownership and // discovery boundary while still requiring the canonical shape. return preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/D', $value) === 1 ? $value : null; } private static function sameUuid($left, $right): bool { $left = self::uuid($left); $right = self::uuid($right); return $left !== null && $right !== null && hash_equals($left, $right); } }