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

211 lines
8.1 KiB
PHTML

<?php
namespace App\Services\Cloud;
final class CloudInput
{
private const INSTANCE_NAME_CODE_LENGTH = 6;
private const INSTANCE_NAME_CODE_ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789';
public const ROOT_PASSWORD_LENGTH = 32;
public const ROOT_PASSWORD_MIN_LENGTH = 12;
public const ROOT_PASSWORD_MAX_LENGTH = 128;
public const ROOT_PASSWORD_UPPERCASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
public const ROOT_PASSWORD_LOWERCASE = 'abcdefghijklmnopqrstuvwxyz';
public const ROOT_PASSWORD_DIGITS = '0123456789';
public const ROOT_PASSWORD_SYMBOLS = '!@#$%*-_=+?';
public const ROOT_PASSWORD_ALPHABET = self::ROOT_PASSWORD_UPPERCASE
. self::ROOT_PASSWORD_LOWERCASE . self::ROOT_PASSWORD_DIGITS
. self::ROOT_PASSWORD_SYMBOLS;
public static function object($request, int $maximum = 32768): array
{
$length = $request->getBody()->getSize();
if (($length !== null && $length > $maximum)
|| (int) $request->getHeaderLine('Content-Length') > $maximum) {
throw new CloudError('请求过大', 413);
}
$value = $request->getParsedBody();
if (!is_array($value)) {
$raw = (string) $request->getBody();
if (strlen($raw) > $maximum) {
throw new CloudError('请求过大', 413);
}
$value = json_decode($raw, true);
}
if (!is_array($value) || ($value !== [] && array_is_list($value))) {
throw new CloudError('请求应为 JSON 对象');
}
return $value;
}
public static function only(array $input, array $allowed): void
{
if (array_diff(array_keys($input), $allowed) !== []) {
throw new CloudError('请求包含不允许设置的字段');
}
}
public static function name($value): string
{
if (!is_string($value) || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/D', $value) !== 1) {
throw new CloudError('名称只能包含英文、数字、点、下划线和连字符,最多 63 字符');
}
return $value;
}
/**
* Validate a guest hostname without accepting shell/control characters.
* Linux accepts a dotted hostname, but each label remains bounded so the
* value is safe to place in cloud-init metadata and administrator DTOs.
*/
public static function hostname($value): string
{
if (!is_string($value)) {
throw new CloudError('主机名格式无效');
}
$value = trim($value);
if ($value === '' || strlen($value) > 253 || str_ends_with($value, '.')) {
throw new CloudError('主机名最多 253 个字符,且不能以点结尾');
}
$labels = explode('.', $value);
foreach ($labels 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) {
throw new CloudError('主机名只能包含英文、数字、连字符和点');
}
}
return strtolower($value);
}
public static function optionalName($value): ?string
{
if ($value === null || $value === '') {
return null;
}
return self::name($value);
}
/** User-visible label only; it is never used as a host path or volume name. */
public static function snapshotName($value): string
{
if (!is_string($value)) {
throw new CloudError('快照名称需为 1 至 64 个字符');
}
$value = trim($value);
if ($value === '' || mb_strlen($value, 'UTF-8') > 64
|| preg_match('//u', $value) !== 1
|| preg_match('/[\x00-\x1F\x7F\/\\\\]/u', $value) === 1) {
throw new CloudError('快照名称需为 1 至 64 个字符,且不能包含控制字符或路径分隔符');
}
return $value;
}
public static function snapshotConsistency($value): string
{
if (!is_string($value)
|| !in_array($value, ['filesystem', 'crash'], true)) {
throw new CloudError('请选择文件系统一致或崩溃一致的在线快照模式');
}
return $value;
}
/** Generate a short, user-facing label; libvirt resources use their UUID. */
public static function generateInstanceName(): string
{
$code = '';
$maximum = strlen(self::INSTANCE_NAME_CODE_ALPHABET) - 1;
for ($index = 0; $index < self::INSTANCE_NAME_CODE_LENGTH; $index++) {
$code .= self::INSTANCE_NAME_CODE_ALPHABET[random_int(0, $maximum)];
}
return 'vm-' . $code;
}
public static function password($value): string
{
if ($value === null || $value === '') {
return self::generateRootPassword();
}
$length = is_string($value) ? strlen($value) : 0;
if (!is_string($value) || $length < self::ROOT_PASSWORD_MIN_LENGTH
|| $length > self::ROOT_PASSWORD_MAX_LENGTH
|| preg_match('/^[\x21-\x7e]+$/D', $value) !== 1
|| !preg_match('/[A-Z]/', $value)
|| !preg_match('/[a-z]/', $value) || !preg_match('/[0-9]/', $value)
|| !preg_match('/[^A-Za-z0-9]/', $value)) {
throw new CloudError('虚拟机密码需为 12 至 128 位可打印 ASCII 字符,不能包含空格,并包含大写、小写、数字和符号');
}
return $value;
}
private static function generateRootPassword(): string
{
do {
$password = '';
$maximum = strlen(self::ROOT_PASSWORD_ALPHABET) - 1;
for ($index = 0; $index < self::ROOT_PASSWORD_LENGTH; $index++) {
$password .= self::ROOT_PASSWORD_ALPHABET[random_int(0, $maximum)];
}
} while (!self::hasRequiredPasswordClasses($password));
return $password;
}
private static function hasRequiredPasswordClasses(string $password): bool
{
return strpbrk($password, self::ROOT_PASSWORD_UPPERCASE) !== false
&& strpbrk($password, self::ROOT_PASSWORD_LOWERCASE) !== false
&& strpbrk($password, self::ROOT_PASSWORD_DIGITS) !== false
&& strpbrk($password, self::ROOT_PASSWORD_SYMBOLS) !== false;
}
public static function template($value): string
{
if (!is_string($value) || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', $value) !== 1) {
throw new CloudError('请选择有效的云镜像模板');
}
return $value;
}
/**
* Validate the public IPv4 address/prefix accepted by a network-change
* task. The engine remains authoritative for the host's configured pool;
* this boundary only rejects malformed or non-IPv4 input before a job is
* persisted.
*/
public static function publicIpCidr($value): string
{
if (!is_string($value)) {
throw new CloudError('公网 IPv4 地址必须使用 CIDR 格式');
}
$value = trim($value);
$parts = explode('/', $value, 2);
if (count($parts) !== 2
|| filter_var($parts[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false
|| preg_match('/^(?:[1-9]|[12][0-9]|3[0-2])$/D', $parts[1]) !== 1) {
throw new CloudError('公网 IPv4 地址必须使用有效的 CIDR 格式,例如 203.0.113.10/24');
}
return $parts[0] . '/' . (int) $parts[1];
}
/** Validate the stable, non-secret identifier of one native public pool. */
public static function publicPoolKey($value): string
{
if (!is_string($value)
|| preg_match('/^[a-f0-9]{32}$/D', $value) !== 1) {
throw new CloudError('请选择有效的公网地址池');
}
return $value;
}
public static function safeResult(array $value): array
{
foreach ($value as $key => $item) {
if (preg_match('/password|secret|(?:public|private).?key|ssh.?key|passphrase|token|credential/i', (string) $key)) {
unset($value[$key]);
} elseif (is_array($item)) {
$value[$key] = self::safeResult($item);
}
}
return $value;
}
}