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/CloudUserInstanceSettingsBe...

213 lines
7.4 KiB
PHTML

<?php
namespace App\Services\Cloud {
use App\Models\CloudInstance;
use App\Models\CloudJob;
final class UserSettingsJobCapture
{
public static array $calls = [];
}
final class CloudJobService
{
public static function enqueue(CloudInstance $instance, array $actor,
string $kind, string $method, string $suffix, array $body = [],
?array $credential = null): CloudJob
{
UserSettingsJobCapture::$calls[] = compact(
'kind', 'method', 'suffix', 'body', 'credential'
);
$job = new CloudJob();
$job->id = 92;
return $job;
}
}
final class UserSettingsAgentClient
{
public function request(string $method, string $path, array $actor,
array $body): array
{
return [
'ticket' => str_repeat('a', 32),
'expires_at' => time() + 30,
];
}
}
final class CloudAgentSettingsService
{
public static function clientForHost(int $hostId,
float $timeoutSeconds = 20.0): UserSettingsAgentClient
{
return new UserSettingsAgentClient();
}
}
final class CloudConsoleTicketService
{
public static function issue(CloudInstance $instance, array $actor,
array $agentTicket): array
{
return [
'ticket' => 'browser-ticket',
'expires_in' => 30,
'websocket_path' => '/engine-console',
];
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Controllers\CloudApiController;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\UserSettingsJobCapture;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
use Slim\Http\Environment;
use Slim\Http\Request;
use Slim\Http\Response;
$assert = static function (bool $condition, string $message): void {
if (!$condition) { throw new RuntimeException($message); }
};
$rejects = static function (callable $callback, string $message): void {
try { $callback(); } catch (CloudError $error) {
if ($error->httpStatus === 409) { return; }
throw new RuntimeException($message . ': unexpected status '
. $error->httpStatus);
}
throw new RuntimeException($message);
};
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite', 'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$capsule->schema('default')->create('cloud_instances', static function (
Blueprint $t
): void {
$t->increments('id'); $t->integer('host_id');
$t->integer('user_id'); $t->string('uuid');
$t->string('status'); $t->string('service_status');
$t->integer('expires_at')->nullable(); $t->text('spec_json');
$t->text('sealed_credential')->nullable();
});
$network = [
'contract' => 1, 'network_selector' => 'bridge:br0',
'ipv4' => [
'pool_key' => str_repeat('a', 32),
'pool_cidr' => '8.8.8.0/24',
'address_cidr' => '8.8.8.10/24',
'gateway' => '8.8.8.1', 'gateway_on_link' => false,
],
'ipv6' => [
'pool_key' => str_repeat('b', 32),
'pool_cidr' => '2404:c140:156:3a::/64',
'address_cidr' => '2404:c140:156:3a::10/64',
'gateway' => '2404:c140:156::1', 'gateway_on_link' => true,
],
'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'],
];
$canonicalSpec = [
'managed' => true, 'os_source' => 'cloud_template',
'public_network' => $network,
];
$specs = [
1 => $canonicalSpec,
2 => [
'managed' => true, 'os_source' => 'cloud_template',
'public_ip_cidr' => '8.8.8.20/24',
],
3 => ['managed' => true, 'os_source' => 'cloud_template'],
4 => [
'managed' => true, 'os_source' => 'cloud_template',
'public_network' => ['contract' => 1],
],
5 => [
'managed' => false, 'os_source' => 'cloud_template',
'public_network' => $network,
],
6 => [
'managed' => true, 'os_source' => 'custom_iso',
'public_network' => $network,
],
7 => $canonicalSpec,
];
$now = time();
foreach ($specs as $id => $spec) {
Capsule::table('cloud_instances')->insert([
'id' => $id, 'host_id' => 1, 'user_id' => 7,
'uuid' => sprintf('00000000-0000-4000-8000-%012d', $id),
'status' => 'active',
'service_status' => $id === 7 ? 'expired' : 'active',
'expires_at' => $id === 7 ? $now - 1 : $now + 3600,
'spec_json' => json_encode(
$spec,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
),
'sealed_credential' => null,
]);
}
$actor = [
'user_id' => 7, 'is_admin' => false,
'is_super_admin' => false, 'can_manage' => false,
'session_id' => str_repeat('c', 64),
];
$settingsRequest = static function (int $id) use ($actor): Request {
return Request::createFromEnvironment(Environment::mock([
'REQUEST_METHOD' => 'POST',
'REQUEST_URI' => '/api/v1/instances/' . $id . '/settings',
]))->withAttribute('cloud_actor', $actor)->withParsedBody([
'hostname' => 'canonical-host', 'confirm_restart' => true,
]);
};
$controller = new CloudApiController();
$response = $controller->settings(
$settingsRequest(1), new Response(), ['id' => '1']
);
$payload = json_decode((string) $response->getBody(), true);
$assert($response->getStatusCode() === 202
&& ($payload['task_id'] ?? null) === '92'
&& (UserSettingsJobCapture::$calls[0]['kind'] ?? null)
=== 'instance_settings',
'Canonical tenant settings request was not admitted.');
$before = count(UserSettingsJobCapture::$calls);
foreach ([2, 3, 4, 5, 6, 7] as $id) {
$rejects(
static fn () => $controller->settings(
$settingsRequest($id), new Response(), ['id' => (string) $id]
),
'Unsupported tenant instance ' . $id . ' admitted settings.'
);
}
$assert(count(UserSettingsJobCapture::$calls) === $before,
'Rejected tenant settings request queued a job.');
// Console admission is intentionally independent from cloud-template and
// canonical-network eligibility; a legacy instance must not regress here.
$consoleRequest = Request::createFromEnvironment(Environment::mock([
'REQUEST_METHOD' => 'POST',
'REQUEST_URI' => '/api/v1/instances/2/console-ticket',
]))->withAttribute('cloud_actor', $actor);
$consoleResponse = $controller->consoleTicket(
$consoleRequest,
new Response(),
['id' => '2']
);
$consolePayload = json_decode((string) $consoleResponse->getBody(), true);
$assert($consoleResponse->getStatusCode() === 200
&& ($consolePayload['ticket'] ?? null) === 'browser-ticket',
'Canonical settings guard leaked into the console endpoint.');
echo "Canonical tenant settings behavior passed.\n";
}