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

118 lines
5.9 KiB
PHP

<?php
namespace App\Services\Cloud {
final class CloudEngineClient
{
public static array $requests = [];
public static array $result = [];
public function request(string $method, string $path, array $actor, ?array $body = null): array
{
self::$requests[] = compact('method', 'path', 'actor', 'body');
return self::$result;
}
}
}
namespace {
use App\Controllers\CloudAdminController;
use App\Services\Cloud\CloudEngineClient;
use App\Services\Cloud\CloudError;
require dirname(__DIR__) . '/app/Services/Cloud/CloudError.php';
require dirname(__DIR__) . '/app/Services/Cloud/CloudAccess.php';
require dirname(__DIR__) . '/app/Services/Cloud/CloudInput.php';
require dirname(__DIR__) . '/app/Controllers/CloudAdminController.php';
final class RequestBody
{
public function __construct(private string $body) {}
public function getSize(): int { return strlen($this->body); }
public function __toString(): string { return $this->body; }
}
final class Request
{
private RequestBody $body;
public function __construct(private string $method, private array $actor, array $body = [])
{
$this->body = new RequestBody(json_encode($body, JSON_THROW_ON_ERROR));
}
public function getMethod(): string { return $this->method; }
public function getAttribute(string $name): array { return $this->actor; }
public function getBody(): RequestBody { return $this->body; }
public function getHeaderLine(string $name): string { return ''; }
public function getParsedBody() { return null; }
}
final class Response
{
public array $payload = [];
public array $headers = [];
public function withJson(array $payload): self { $this->payload = $payload; return $this; }
public function withHeader(string $name, string $value): self { $this->headers[$name] = $value; return $this; }
}
$assert = static function (bool $condition, string $message): void {
if (!$condition) throw new \RuntimeException($message);
};
$controller = new CloudAdminController();
$owner = ['user_id' => 1, 'is_admin' => true, 'is_super_admin' => true, 'can_manage' => true];
$viewer = array_replace($owner, ['is_super_admin' => false, 'can_manage' => false]);
$tenant = array_replace($viewer, ['is_admin' => false]);
$args = ['id' => '1234567890abcdef'];
$valid = ['script' => "#!/bin/bash\necho test\n", 'expected_revision' => 0, 'created_at' => 1234];
CloudEngineClient::$result = ['startup_script' => $valid['script'], 'revision' => 2, 'created_at' => 1234];
foreach ([$owner, $viewer] as $reader) {
$result = $controller->templateStartupScript(new Request('GET', $reader), new Response(), $args);
$request = CloudEngineClient::$requests[array_key_last(CloudEngineClient::$requests)];
$assert($request['method'] === 'GET' && $request['body'] === null
&& $request['path'] === '/internal/v1/vm-templates/1234567890abcdef/startup-script',
'Read must use the dedicated private route without a write payload.');
$assert($result->payload === CloudEngineClient::$result && $result->headers['Cache-Control'] === 'no-store',
'Script response must retain the authoritative version and avoid shared caching.');
}
foreach ([['GET', $tenant], ['PATCH', $tenant], ['PATCH', $viewer]] as [$method, $actor]) {
$before = count(CloudEngineClient::$requests);
try {
$controller->templateStartupScript(new Request($method, $actor, $valid), new Response(), $args);
throw new \RuntimeException('Unauthorized script access was accepted.');
} catch (CloudError $error) {
$assert($error->httpStatus === 403 && count(CloudEngineClient::$requests) === $before,
'Unauthorized requests must fail before forwarding to the Engine.');
}
}
$body = array_replace($valid, ['script' => "#!/bin/bash\r\necho \"中文\"\r\n"]);
$controller->templateStartupScript(new Request('PATCH', $owner, $body), new Response(), $args);
$request = CloudEngineClient::$requests[array_key_last(CloudEngineClient::$requests)];
$assert($request['method'] === 'PATCH' && $request['actor'] === $owner
&& $request['body'] === array_replace($body, ['script' => "#!/bin/bash\necho \"中文\"\n"]),
'Saving must preserve the script and CAS identity, normalizing only CRLF.');
// JSON escaping may expand a valid script well beyond the standard 32 KiB body limit.
foreach (['', str_repeat("\t", 32768), str_repeat('中', 10922)] as $script) {
$controller->templateStartupScript(new Request('PATCH', $owner,
array_replace($valid, ['script' => $script])), new Response(), $args);
$assert(CloudEngineClient::$requests[array_key_last(CloudEngineClient::$requests)]['body']['script'] === $script,
'Valid or blank scripts must round-trip without trimming content.');
}
foreach ([
['script' => "echo\0oops"], ['script' => str_repeat('中', 10923)], ['script' => []],
['expected_revision' => -1], ['expected_revision' => '1'], ['expected_revision' => true],
['created_at' => 0], ['created_at' => '1234'], ['unexpected' => 'field'],
] as $invalid) {
$before = count(CloudEngineClient::$requests);
try {
$controller->templateStartupScript(new Request('PATCH', $owner,
array_replace($valid, $invalid)), new Response(), $args);
throw new \RuntimeException('Invalid startup-script request was accepted.');
} catch (CloudError $error) {
$assert($error->httpStatus === 422 && count(CloudEngineClient::$requests) === $before,
'Invalid script or version data must never reach the Engine.');
}
}
echo "Cloud-template startup script authorization, validation and forwarding passed.\n";
}