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/tests/CloudTemplateErrorContractT...

156 lines
5.8 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 {
final class Config
{
public static function get($name, $default = null)
{
return $name === 'cloud_engine_url' ? 'http://127.0.0.1:8000' : $default;
}
}
}
namespace App\Services\Cloud {
final class CloudSecrets
{
public static function key(string $purpose): string
{
return str_repeat('k', 32);
}
}
}
namespace GuzzleHttp {
final class TestResponse
{
public function __construct(private int $status, private string $body)
{
}
public function getStatusCode(): int
{
return $this->status;
}
public function getBody(): string
{
return $this->body;
}
}
class Client
{
public function __construct(private array $responses = [])
{
}
public function request(string $method, string $url, array $options): TestResponse
{
$response = array_shift($this->responses);
if (!$response instanceof TestResponse) {
throw new \RuntimeException('No fake engine response was queued.');
}
return $response;
}
}
}
namespace {
use App\Services\Cloud\CloudEngineClient;
use App\Services\Cloud\CloudError;
use GuzzleHttp\Client;
use GuzzleHttp\TestResponse;
require dirname(__DIR__) . '/app/Services/Cloud/CloudError.php';
require dirname(__DIR__) . '/app/Services/Cloud/CloudEngineClient.php';
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$publicMessage = '仅支持 AlmaLinux、Debian、Ubuntu 和 CentOS Stream 官方 x86_64 云镜像直链';
$assert(CloudEngineClient::safeVmTemplateMessage($publicMessage) === $publicMessage,
'A reviewed cloud-template validation error was hidden.');
$assert(CloudEngineClient::safeVmTemplateMessage(" {$publicMessage} ") === $publicMessage,
'Reviewed cloud-template messages should be normalized before matching.');
$reviewedDownloadErrors = [
'仅支持 AlmaLinux 官方仓库的 9/10 x86_64 GenericCloud qcow2 镜像',
'官方云镜像地址无法解析',
'官方云镜像地址解析结果无效',
'官方云镜像地址解析到非公网地址',
'无法连接官方云镜像下载地址',
'官方云镜像重定向目标不安全',
'官方云镜像重定向次数过多',
'官方云镜像下载服务器返回异常状态',
'官方云镜像下载响应格式无效',
'云镜像下载内容不完整',
'面板未安装 qemu-img,无法验证云镜像',
'云镜像完整性检查失败',
];
foreach ($reviewedDownloadErrors as $reviewed) {
$assert(CloudEngineClient::safeVmTemplateMessage($reviewed) === $reviewed,
'A reviewed cloud-template download error was hidden.');
}
foreach ([
null,
422,
'',
'仅支持任意内网镜像',
'/root/cloud-templates/secret.qcow2',
] as $unsafe) {
$assert(CloudEngineClient::safeVmTemplateMessage($unsafe) === null,
'An unknown cloud-template error crossed the PHP trust boundary.');
}
$allowlisted = new ReflectionMethod(CloudEngineClient::class, 'safeAllowlistedError');
$assert($allowlisted->invoke(null, '/internal/v1/vm-templates/import', ['error' => $publicMessage])
=== $publicMessage, 'The fixed cloud-template import path did not pass its reviewed error.');
$assert($allowlisted->invoke(null,
'/internal/v1/vm-templates/import-jobs/12345678', ['detail' => '云镜像导入任务不存在'])
=== '云镜像导入任务不存在', 'The fixed import-job path did not pass its reviewed error.');
$uploadMessage = '上传文件不是有效的 qcow2 镜像';
$uploadPath = '/internal/v1/vm-templates/upload?name=Debian%2012&os_family=Debian&os_version=12';
$assert($allowlisted->invoke(null, $uploadPath, ['error' => $uploadMessage])
=== $uploadMessage, 'The fixed cloud-template upload path did not pass its reviewed error.');
foreach ([
['/internal/v1/vm-templates/import', ['error' => 'Traceback: /root/private/key']],
['/internal/v1/vm-templates/import?unexpected=true', ['error' => $publicMessage]],
['/internal/v1/vm-templates/import/extra', ['error' => $publicMessage]],
['/internal/v1/hosts/1/vm-templates/import', ['error' => $publicMessage]],
['/internal/v1/vm-templates/import', ['error' => str_repeat('x', 501)]],
] as [$path, $payload]) {
$assert($allowlisted->invoke(null, $path, $payload) === null,
'An unknown error, similar path or oversized value crossed the PHP trust boundary.');
}
$actor = ['user_id' => 1, 'is_admin' => true, 'can_manage' => true];
$knownClient = new CloudEngineClient(new Client([
new TestResponse(422, json_encode(['error' => $publicMessage], JSON_UNESCAPED_UNICODE)),
]));
try {
$knownClient->request('POST', '/internal/v1/vm-templates/import', $actor, []);
throw new RuntimeException('A failed cloud-template import did not raise CloudError.');
} catch (CloudError $error) {
$assert($error->getMessage() === $publicMessage && $error->httpStatus === 422,
'A reviewed cloud-template error was replaced by a generic engine status.');
}
$unknownClient = new CloudEngineClient(new Client([
new TestResponse(400, '{"error":"Traceback: host=/root/private key=secret"}'),
]));
try {
$unknownClient->request('POST', '/internal/v1/vm-templates/import', $actor, []);
throw new RuntimeException('An unknown engine failure did not raise CloudError.');
} catch (CloudError $error) {
$assert($error->getMessage() === '虚拟化操作未成功(引擎状态 400)'
&& $error->httpStatus === 502
&& !str_contains($error->getMessage(), 'private'),
'An arbitrary engine error escaped instead of the generic failure.');
}
echo "Cloud-template engine error allowlist contract passed.\n";
}