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/CloudInstanceMetadata.php

480 lines
18 KiB
PHTML

<?php
namespace App\Services\Cloud;
use App\Models\CloudInstance;
/**
* Validate and persist the non-secret, slow-changing part of an engine VM.
*
* The engine response also contains mutable power/console/rescue fields and
* storage source names. Those values must never become an authoritative
* business record or be embedded into an SSR bootstrap. This class is the
* single allowlist used by provisioning and by an actor-scoped backfill.
*/
final class CloudInstanceMetadata
{
private const VERSION = 1;
private const STATIC_KEYS = [
'vcpu', 'memory_mib', 'disk_gib', 'disks', 'autostart', 'managed',
'public_ip_cidr', 'os_source', 'os_name', 'install_iso', 'login_name',
'engine_metadata_version',
];
private const FORBIDDEN_ENGINE_KEYS = [
'state', 'hostname', 'console_port', 'credential_generation', 'rescue_mode',
'rescue_staged', 'rescue_volume_name', 'auth_mode',
'password_available', 'generated_password',
];
/**
* Keys that may be copied from the durable instance specification into a
* user-facing page payload. sanitizeSpec() deliberately preserves
* business snapshot fields for billing and reconciliation, so it is not
* itself a presentation allowlist.
*/
private const PUBLIC_SPEC_KEYS = [
'region', 'location', 'country_code', 'plan_name', 'os_source',
'os_name', 'install_iso', 'guest_hostname', 'public_ip', 'public_ip_cidr', 'login_name',
'vcpu', 'cpu_cores', 'memory_mib',
'ram_mib', 'disks', 'disk_gib', 'bandwidth_mbps', 'autostart',
'managed', 'engine_metadata_version',
];
/**
* Normalize the small set of libvirt power states that the panel renders.
* Unknown engine text is deliberately collapsed to `unknown` so a host
* implementation cannot use the status field as an arbitrary message
* channel.
*/
public static function state($value): string
{
if (!is_string($value)) {
return 'unknown';
}
$value = strtolower(trim($value));
$value = preg_replace('/[\s-]+/', '_', $value) ?? '';
return in_array($value, [
'running', 'shutoff', 'shut_off', 'stopped', 'paused', 'crashed',
'pmsuspended', 'nostate', 'blocked', 'shutdown', 'unknown',
], true) ? $value : 'unknown';
}
/**
* Canonicalize cached engine fields without touching order/billing keys.
* Safe to call while building an SSR payload from an older database row.
*/
public static function sanitizeSpec(array $spec): array
{
$spec = CloudInput::safeResult($spec);
$existing = self::metadata($spec);
$version = self::integer($spec['engine_metadata_version'] ?? null,
1, self::VERSION);
foreach (array_merge(self::STATIC_KEYS, self::FORBIDDEN_ENGINE_KEYS) as $key) {
unset($spec[$key]);
}
$spec = array_merge($spec, $existing);
if ($version !== null) {
$spec['engine_metadata_version'] = $version;
}
return $spec;
}
/**
* Return only fields intended for ordinary user page/bootstrap payloads.
* Keep this separate from sanitizeSpec(): historical specs can contain
* private engine keys that are harmless for server-side reconciliation but
* must never be copied into HTML or a public API response.
*/
public static function publicSpec(array $spec): array
{
$safe = self::sanitizeSpec($spec);
$public = [];
foreach (['region', 'location'] as $key) {
$value = self::text($safe[$key] ?? null, 64);
if ($value !== null) {
$public[$key] = $value;
}
}
$country = self::text($safe['country_code'] ?? null, 16);
if ($country !== null && preg_match('/^[A-Za-z]{2,16}$/D', $country) === 1) {
$public['country_code'] = strtoupper($country);
}
$plan = self::text($safe['plan_name'] ?? null, 120);
if ($plan !== null) {
$public['plan_name'] = $plan;
}
$source = $safe['os_source'] ?? null;
if (is_string($source) && in_array($source,
['cloud_template', 'iso', 'unknown'], true)) {
$public['os_source'] = $source;
}
$osName = self::text($safe['os_name'] ?? null, 64);
if ($osName !== null && ($public['os_source'] ?? null) === 'cloud_template') {
$public['os_name'] = $osName;
}
$installIso = self::text($safe['install_iso'] ?? null, 255);
if ($installIso !== null && ($public['os_source'] ?? null) === 'iso'
&& basename($installIso) === $installIso
&& !str_contains($installIso, '\\') && !str_contains($installIso, ':')) {
$public['install_iso'] = $installIso;
}
$login = $safe['login_name'] ?? null;
if (($public['os_source'] ?? null) === 'cloud_template'
&& is_string($login)
&& preg_match('/^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/D', $login) === 1) {
$public['login_name'] = $login;
}
$hostname = self::hostname($safe['guest_hostname'] ?? null);
if ($hostname !== null && ($public['os_source'] ?? null) === 'cloud_template') {
$public['guest_hostname'] = $hostname;
}
$ip = self::ip($safe['public_ip'] ?? null);
if ($ip !== null) {
$public['public_ip'] = $ip;
}
$cidr = self::cidr($safe['public_ip_cidr'] ?? null);
if ($cidr !== null) {
$public['public_ip_cidr'] = $cidr;
}
foreach (['vcpu' => [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);
}
}