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.
843 lines
43 KiB
PHP
843 lines
43 KiB
PHP
<?php
|
|
|
|
namespace App\Services {
|
|
final class AdminPermission
|
|
{
|
|
public static bool $superAdmin = true;
|
|
|
|
public static function isSuperAdmin(): bool
|
|
{
|
|
return self::$superAdmin;
|
|
}
|
|
}
|
|
|
|
final class Auth
|
|
{
|
|
public static $user = null;
|
|
|
|
public static function getUser()
|
|
{
|
|
return self::$user;
|
|
}
|
|
}
|
|
|
|
final class Config
|
|
{
|
|
public static function get($name, $default = null)
|
|
{
|
|
return $default;
|
|
}
|
|
}
|
|
}
|
|
|
|
namespace App\Services\Cloud {
|
|
final class CloudSessionService
|
|
{
|
|
public static int $calls = 0;
|
|
|
|
public static function current($user): string
|
|
{
|
|
self::$calls++;
|
|
throw new \RuntimeException('Database-only instance reads created an engine session.');
|
|
}
|
|
}
|
|
|
|
final class CloudAgentSettingsService
|
|
{
|
|
public static int $calls = 0;
|
|
|
|
public function __construct()
|
|
{
|
|
self::$calls++;
|
|
throw new \RuntimeException('Database-only instance reads contacted a host Agent.');
|
|
}
|
|
}
|
|
}
|
|
|
|
namespace {
|
|
require dirname(__DIR__) . '/vendor/autoload.php';
|
|
|
|
use App\Controllers\CloudAdminInstanceController;
|
|
use App\Models\User;
|
|
use App\Services\AdminPermission;
|
|
use App\Services\Auth;
|
|
use App\Services\Cloud\CloudAdminInstanceService;
|
|
use App\Services\Cloud\CloudAdminOperationsService;
|
|
use App\Services\Cloud\CloudAgentSettingsService;
|
|
use App\Services\Cloud\CloudError;
|
|
use App\Services\Cloud\CloudJobRecoverySql;
|
|
use App\Services\Cloud\CloudSessionService;
|
|
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 ($condition, string $message): void {
|
|
if (!$condition) {
|
|
throw new RuntimeException($message);
|
|
}
|
|
};
|
|
$expectError = static function (callable $callback, int $status, string $message) use ($assert): void {
|
|
try {
|
|
$callback();
|
|
} catch (CloudError $error) {
|
|
$assert($error->httpStatus === $status, $message . ': unexpected HTTP status ' . $error->httpStatus);
|
|
return;
|
|
}
|
|
throw new RuntimeException($message . ': request was accepted.');
|
|
};
|
|
$ids = static fn (array $items): array => array_map('intval', array_column($items, 'id'));
|
|
|
|
$capsule = new Capsule();
|
|
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
|
|
$capsule->setAsGlobal();
|
|
$capsule->bootEloquent();
|
|
$schema = $capsule->schema('default');
|
|
$schema->create('user', static function (Blueprint $table): void {
|
|
$table->increments('id');
|
|
$table->string('user_name');
|
|
$table->string('email');
|
|
$table->boolean('is_admin')->default(false);
|
|
$table->boolean('enable')->default(true);
|
|
$table->string('pass')->default('must-not-expose-account-password');
|
|
});
|
|
$schema->create('cloud_hosts', static function (Blueprint $table): void {
|
|
$table->increments('id');
|
|
$table->string('name');
|
|
$table->string('region')->default('');
|
|
$table->string('country_code')->default('');
|
|
$table->boolean('enabled')->default(true);
|
|
});
|
|
$schema->create('shop', static function (Blueprint $table): void {
|
|
$table->increments('id');
|
|
$table->string('name');
|
|
});
|
|
$schema->create('cloud_instances', static function (Blueprint $table): void {
|
|
$table->increments('id');
|
|
$table->string('uuid');
|
|
$table->integer('host_id');
|
|
$table->integer('user_id');
|
|
$table->integer('order_id')->nullable();
|
|
$table->integer('plan_id')->nullable();
|
|
$table->integer('current_period_id')->nullable();
|
|
$table->string('name');
|
|
$table->string('status')->default('active');
|
|
$table->string('service_status')->default('active');
|
|
$table->string('network_status')->default('active');
|
|
$table->integer('expires_at')->nullable();
|
|
$table->string('renewal_price')->nullable();
|
|
$table->integer('renewal_days')->default(0);
|
|
$table->integer('renewal_traffic_bytes')->default(0);
|
|
$table->integer('traffic_quota_bytes')->default(0);
|
|
$table->integer('traffic_download_bytes')->default(0);
|
|
$table->integer('traffic_upload_bytes')->default(0);
|
|
$table->integer('lifetime_download_bytes')->default(0);
|
|
$table->integer('lifetime_upload_bytes')->default(0);
|
|
$table->integer('traffic_synced_at')->default(0);
|
|
$table->integer('suspended_at')->nullable();
|
|
$table->integer('network_suspended_at')->nullable();
|
|
$table->text('spec_json');
|
|
$table->text('sealed_credential')->nullable();
|
|
$table->integer('created_at');
|
|
$table->integer('updated_at');
|
|
});
|
|
$schema->create('cloud_public_ips', static function (Blueprint $table): void {
|
|
$table->increments('id');
|
|
$table->integer('instance_id')->nullable();
|
|
$table->integer('address_family');
|
|
$table->string('address', 45);
|
|
$table->string('state')->default('available');
|
|
});
|
|
$schema->create('cloud_service_periods', static function (Blueprint $table): void {
|
|
$table->increments('id');
|
|
$table->integer('instance_id');
|
|
$table->integer('user_id');
|
|
$table->integer('traffic_pool_group_id')->nullable();
|
|
$table->string('traffic_quota_mode')->default('finite');
|
|
$table->integer('starts_at');
|
|
$table->integer('ends_at');
|
|
$table->string('status');
|
|
});
|
|
$schema->create('cloud_orders', static function (Blueprint $table): void {
|
|
$table->increments('id');
|
|
$table->integer('instance_id')->nullable();
|
|
$table->integer('user_id');
|
|
$table->integer('plan_id')->nullable();
|
|
$table->integer('host_id')->default(7);
|
|
$table->string('amount')->default('10.00');
|
|
$table->string('status')->default('succeeded');
|
|
$table->text('spec_json')->default('{}');
|
|
$table->text('sealed_payload')->default('must-not-expose-order-payload');
|
|
$table->integer('created_at')->default(0);
|
|
$table->integer('updated_at')->default(0);
|
|
});
|
|
$schema->create('cloud_jobs', static function (Blueprint $table): void {
|
|
$table->increments('id');
|
|
$table->string('operation_id');
|
|
$table->string('request_idempotency_key');
|
|
$table->string('request_fingerprint');
|
|
$table->integer('parent_job_id')->nullable();
|
|
$table->integer('instance_id')->nullable();
|
|
$table->integer('order_id')->nullable();
|
|
$table->integer('invoice_id')->nullable();
|
|
$table->integer('snapshot_id')->nullable();
|
|
$table->integer('user_id');
|
|
$table->integer('host_id')->default(7);
|
|
$table->string('kind');
|
|
$table->string('execution_mode')->default('agent');
|
|
$table->string('phase')->default('terminal');
|
|
$table->string('outcome')->nullable();
|
|
$table->string('status');
|
|
$table->integer('attempts')->default(0);
|
|
$table->integer('dispatch_attempts')->nullable()->default(0);
|
|
$table->integer('dispatch_deadline_at')->default(0);
|
|
$table->integer('dispatch_started_at')->nullable();
|
|
$table->integer('agent_accepted_at')->nullable();
|
|
$table->integer('dispatched_at')->nullable();
|
|
$table->integer('receipt_deadline_at')->nullable();
|
|
$table->boolean('effect_may_have_applied')->nullable();
|
|
$table->boolean('safe_to_resubmit')->nullable();
|
|
$table->string('effect_resolution')->default('not_applicable');
|
|
$table->integer('terminal_at')->nullable();
|
|
$table->string('completion_event_id')->nullable();
|
|
$table->string('error_code')->nullable();
|
|
$table->boolean('finalization_incident')->default(0);
|
|
$table->string('finalization_error_code')->nullable();
|
|
$table->integer('available_at')->default(0);
|
|
$table->text('sealed_payload')->default('must-not-expose-job-payload');
|
|
$table->text('result_json')->nullable();
|
|
$table->integer('created_at');
|
|
$table->integer('updated_at');
|
|
});
|
|
$schema->create('cloud_invoices', static function (Blueprint $table): void {
|
|
$table->increments('id');
|
|
$table->string('invoice_no');
|
|
$table->string('purpose')->default('renewal');
|
|
$table->integer('instance_id')->nullable();
|
|
$table->integer('order_id')->nullable();
|
|
$table->integer('user_id');
|
|
$table->integer('plan_id')->nullable();
|
|
$table->integer('renewal_id')->nullable();
|
|
$table->integer('due_at');
|
|
$table->string('amount')->default('10.00');
|
|
$table->string('status')->default('open');
|
|
$table->string('paid_via')->nullable();
|
|
$table->string('payment_reference')->default('must-not-expose-payment-reference');
|
|
$table->integer('paid_at')->nullable();
|
|
$table->integer('created_at');
|
|
$table->integer('updated_at');
|
|
});
|
|
Capsule::table('user')->insert([
|
|
['id' => 1, 'user_name' => 'Alice Ops', 'email' => 'alice@example.test'],
|
|
['id' => 2, 'user_name' => 'Bob Client', 'email' => 'bob@example.test'],
|
|
['id' => 99, 'user_name' => 'Root Operator', 'email' => 'root@example.test'],
|
|
]);
|
|
Capsule::table('cloud_hosts')->insert([
|
|
['id' => 7, 'name' => 'Hong Kong 07', 'region' => 'HongKong', 'country_code' => 'HK'],
|
|
['id' => 8, 'name' => 'Tokyo 08', 'region' => 'Tokyo', 'country_code' => 'JP'],
|
|
]);
|
|
Capsule::table('shop')->insert(['id' => 3, 'name' => 'Small Cloud']);
|
|
$now = time();
|
|
$publicNetwork = [
|
|
'contract' => 1, 'network_selector' => 'bridge:br0',
|
|
'ipv4' => [
|
|
'pool_key' => str_repeat('1', 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('2', 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'],
|
|
];
|
|
$base = [
|
|
'host_id' => 7, 'user_id' => 1, 'plan_id' => 3,
|
|
'status' => 'active', 'service_status' => 'active', 'network_status' => 'active',
|
|
'expires_at' => $now + 30 * 86400, 'renewal_price' => '10.00',
|
|
'renewal_days' => 30, 'renewal_traffic_bytes' => 2000,
|
|
'traffic_quota_bytes' => 2000, 'traffic_download_bytes' => 300,
|
|
'traffic_upload_bytes' => 200, 'traffic_synced_at' => $now - 30,
|
|
'sealed_credential' => 'must-not-expose-instance-credential',
|
|
'spec_json' => json_encode([
|
|
'vcpu' => 2, 'memory_mib' => 2048, 'disk_gib' => 40,
|
|
'os_source' => 'cloud_template', 'os_name' => 'AlmaLinux 10',
|
|
'managed' => true,
|
|
'public_network' => $publicNetwork,
|
|
'state' => 'running', 'console_port' => 5900,
|
|
'password' => 'must-not-expose-spec-password',
|
|
'api_token' => 'must-not-expose-api-token',
|
|
'unreviewed_note' => 'must-not-expose-unknown-spec-field',
|
|
'disks' => [['capacity_gib' => 40, 'source' => 'must-not-expose-disk-path']],
|
|
]),
|
|
'created_at' => $now - 600, 'updated_at' => $now - 300,
|
|
];
|
|
$insertInstance = static function (int $id, array $overrides = []) use ($base): void {
|
|
Capsule::table('cloud_instances')->insert(array_replace($base, [
|
|
'id' => $id, 'uuid' => sprintf('11111111-1111-4111-8111-%012d', $id),
|
|
'name' => 'vm-' . $id,
|
|
], $overrides));
|
|
};
|
|
for ($id = 1; $id <= 205; $id++) {
|
|
$insertInstance($id);
|
|
}
|
|
$insertInstance(206, ['user_id' => 2, 'host_id' => 8, 'order_id' => 601,
|
|
'current_period_id' => 1, 'expires_at' => $now + 2 * 86400]);
|
|
$insertInstance(207, ['expires_at' => $now - 3600, 'service_status' => 'expired', 'order_id' => 602]);
|
|
$insertInstance(208, ['expires_at' => null, 'service_status' => 'exempt']);
|
|
$insertInstance(209, ['network_status' => 'blocked_traffic']);
|
|
$insertInstance(210, ['network_status' => 'restore_failed']);
|
|
$insertInstance(211, ['status' => 'deleted', 'expires_at' => $now + 3600]);
|
|
$insertInstance(212, ['user_id' => 404, 'host_id' => 404, 'plan_id' => 404, 'expires_at' => null]);
|
|
$insertInstance(213, ['name' => "tenant's 100%_ready"]);
|
|
$insertInstance(214, ['spec_json' => json_encode([
|
|
'public_ip_cidr' => '203.0.113.74/24', 'vcpu' => 4, 'memory_mib' => 4096,
|
|
])]);
|
|
$insertInstance(215, [
|
|
'status' => 'delete_failed', 'expires_at' => $now + 2 * 86400,
|
|
]);
|
|
Capsule::table('cloud_public_ips')->insert([
|
|
['id' => 1, 'instance_id' => 214, 'address_family' => 4,
|
|
'address' => '8.8.8.74', 'state' => 'assigned'],
|
|
['id' => 2, 'instance_id' => 214, 'address_family' => 6,
|
|
'address' => '2404:c140:156:3a::74', 'state' => 'assigned'],
|
|
['id' => 3, 'instance_id' => null, 'address_family' => 4,
|
|
'address' => '9.9.9.9', 'state' => 'available'],
|
|
['id' => 4, 'instance_id' => 206, 'address_family' => 4,
|
|
'address' => '8.8.4.20', 'state' => 'released'],
|
|
]);
|
|
Capsule::table('cloud_service_periods')->insert([
|
|
'id' => 1, 'instance_id' => 206, 'user_id' => 2,
|
|
'starts_at' => $now - 28 * 86400, 'ends_at' => $now + 2 * 86400, 'status' => 'active',
|
|
]);
|
|
Capsule::table('cloud_orders')->insert([
|
|
['id' => 601, 'instance_id' => 206, 'user_id' => 2],
|
|
['id' => 602, 'instance_id' => 207, 'user_id' => 2],
|
|
]);
|
|
$insertJob = static function (int $id, array $overrides = []) use ($now): void {
|
|
$values = array_replace([
|
|
'id' => $id, 'operation_id' => sprintf('%032d', $id),
|
|
'request_idempotency_key' => sprintf('%032d', $id),
|
|
'request_fingerprint' => hash('sha256', (string) $id),
|
|
'parent_job_id' => null,
|
|
'order_id' => null, 'invoice_id' => null, 'snapshot_id' => null,
|
|
'instance_id' => 206, 'user_id' => 99, 'kind' => 'action',
|
|
'execution_mode' => 'agent', 'dispatch_attempts' => 1,
|
|
'attempts' => 1,
|
|
'dispatch_deadline_at' => $now - 90,
|
|
'dispatch_started_at' => $now - 80,
|
|
'agent_accepted_at' => $now - 70,
|
|
'dispatched_at' => $now - 75,
|
|
'receipt_deadline_at' => $now - 60,
|
|
'completion_event_id' => null,
|
|
'phase' => 'terminal', 'outcome' => 'succeeded',
|
|
'created_at' => $now - 100, 'updated_at' => $now,
|
|
'result_json' => json_encode([
|
|
'phase' => 'finished', 'generated_password' => 'must-not-expose-job-password',
|
|
'unreviewed_note' => 'must-not-expose-unknown-job-result',
|
|
]),
|
|
], $overrides);
|
|
if (($values['execution_mode'] ?? '') === 'agent'
|
|
&& (int) ($values['dispatch_attempts'] ?? -1) === 0) {
|
|
foreach (['attempts' => 0, 'dispatch_started_at' => null,
|
|
'agent_accepted_at' => null, 'dispatched_at' => null,
|
|
'receipt_deadline_at' => null, 'completion_event_id' => null]
|
|
as $field => $value) {
|
|
if (!array_key_exists($field, $overrides)) {
|
|
$values[$field] = $value;
|
|
}
|
|
}
|
|
}
|
|
if ($values['phase'] === 'terminal') {
|
|
if (!in_array($values['outcome'], ['succeeded', 'failed'], true)) {
|
|
throw new RuntimeException('Terminal job fixtures require a supported outcome.');
|
|
}
|
|
$values['status'] = $values['outcome'];
|
|
} elseif ($values['phase'] === 'active' && $values['outcome'] === null) {
|
|
$values['status'] = 'active';
|
|
} else {
|
|
throw new RuntimeException('Active job fixtures cannot carry a terminal outcome.');
|
|
}
|
|
$values['terminal_at'] = $values['phase'] === 'terminal'
|
|
? ($values['terminal_at'] ?? $now) : null;
|
|
Capsule::table('cloud_jobs')->insert($values);
|
|
};
|
|
for ($id = 1; $id <= 26; $id++) {
|
|
$insertJob($id, $id === 26 ? ['phase' => 'active', 'outcome' => null] : []);
|
|
}
|
|
$insertJob(27, ['instance_id' => 209, 'outcome' => 'failed',
|
|
'error_code' => 'test_failure']);
|
|
$insertJob(28, ['instance_id' => 210, 'outcome' => 'failed',
|
|
'effect_may_have_applied' => true, 'safe_to_resubmit' => false,
|
|
'effect_resolution' => 'unknown', 'updated_at' => $now - 172800]);
|
|
$insertJob(29, ['instance_id' => 207, 'outcome' => 'failed',
|
|
'updated_at' => $now - 172800]);
|
|
$insertJob(30, ['instance_id' => 211, 'outcome' => 'failed']);
|
|
$insertInvoice = static function (int $id, array $overrides = []) use ($now): void {
|
|
Capsule::table('cloud_invoices')->insert(array_replace([
|
|
'id' => $id, 'invoice_no' => 'TEST-' . $id,
|
|
'instance_id' => 206, 'user_id' => 2,
|
|
'due_at' => $now + 3600, 'created_at' => $now - 100, 'updated_at' => $now,
|
|
], $overrides));
|
|
};
|
|
for ($id = 1; $id <= 25; $id++) {
|
|
$insertInvoice($id);
|
|
}
|
|
$insertInvoice(26, ['user_id' => 1]);
|
|
$insertInvoice(27, ['instance_id' => null, 'order_id' => 601]);
|
|
$insertInvoice(28, ['instance_id' => null, 'order_id' => 602, 'user_id' => 1]);
|
|
|
|
$admin = ['user_id' => 99, 'is_admin' => true, 'is_super_admin' => true, 'can_manage' => true];
|
|
$readOnly = ['user_id' => 99, 'is_admin' => true, 'is_super_admin' => false, 'can_manage' => false];
|
|
$customer = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false, 'can_manage' => false];
|
|
|
|
// All timestamps are deliberately identical: ordering must include the ID.
|
|
$page = CloudAdminInstanceService::page($admin);
|
|
$assert($page['pagination']['total'] === 214 && count($page['items']) === 20
|
|
&& $ids($page['items']) === array_values(array_diff(range(215, 195), [211])),
|
|
'Administrator first page lost records above 200, included deleted rows, or sorted ties unstably.');
|
|
$assert($page['summary']['total'] === 214 && $page['summary']['expiring'] === 1
|
|
&& $page['summary']['network_restricted'] === 3 && $page['summary']['attention'] === 2,
|
|
'Database statistics must cover the complete filtered population and preserve state meanings.');
|
|
$assert(!isset($page['summary']['running']) && !isset($page['summary']['stopped']),
|
|
'Database-only summary fabricated a live power-state count.');
|
|
$seen = [];
|
|
for ($number = 1; $number <= 3; $number++) {
|
|
$chunk = CloudAdminInstanceService::page($admin, ['page' => (string) $number, 'per_page' => '100']);
|
|
$seen = array_merge($seen, $ids($chunk['items']));
|
|
}
|
|
$assert(count($seen) === 214 && count(array_unique($seen)) === 214
|
|
&& $seen === array_values(array_diff(range(215, 1), [211])),
|
|
'Paging beyond 200 duplicated or silently truncated instances.');
|
|
$last = CloudAdminInstanceService::page($admin, ['page' => '9999', 'per_page' => '100']);
|
|
$assert($last['pagination']['page'] === 3 && count($last['items']) === 14,
|
|
'Out-of-range pages did not clamp to the last valid page.');
|
|
$oldest = CloudAdminInstanceService::page($admin, ['sort' => 'oldest']);
|
|
$assert($ids($oldest['items']) === range(1, 20), 'Oldest sorting needs a stable ascending ID order.');
|
|
$expiry = CloudAdminInstanceService::page($admin, ['sort' => 'expiry']);
|
|
$assert((int) $expiry['items'][0]['id'] === 207, 'Expiry sorting did not put the oldest expiry first.');
|
|
|
|
foreach ([['user_id' => '2'], ['host_id' => '8'], ['user_id' => '2', 'host_id' => '8']] as $filter) {
|
|
$filtered = CloudAdminInstanceService::page($admin, $filter);
|
|
$assert($ids($filtered['items']) === [206] && $filtered['summary']['total'] === 1
|
|
&& $filtered['summary']['expiring'] === 1,
|
|
'Exact owner/host filters or filtered summary crossed instance boundaries.');
|
|
}
|
|
$empty = CloudAdminInstanceService::page($admin, ['user_id' => '2', 'host_id' => '7']);
|
|
$assert($empty['items'] === [] && $empty['pagination']['total'] === 0
|
|
&& $empty['pagination']['total_pages'] === 1 && $empty['pagination']['page'] === 1
|
|
&& $empty['summary']['total'] === 0,
|
|
'Empty filtered collections returned stale rows or invalid pagination.');
|
|
foreach ([
|
|
"tenant's" => [213], '100%_ready' => [213], '%' => [213], '_ready' => [213],
|
|
'8.8.8.74' => [214], '2404:C140:156:3A::74' => [214],
|
|
'c140:156:3a' => [214], '9.9.9.9' => [], '8.8.4.20' => [],
|
|
"' OR 1=1 --" => [],
|
|
'11111111-1111-4111-8111-000000000214' => [214],
|
|
'bob@example.test' => [206],
|
|
] as $query => $expected) {
|
|
$searched = CloudAdminInstanceService::page($admin, ['q' => $query]);
|
|
$assert($ids($searched['items']) === $expected,
|
|
'Search must bind quotes, escape SQL wildcards, and correctly match IP/UUID/account: ' . $query);
|
|
}
|
|
$scopedIpSearch = CloudAdminInstanceService::page($admin, [
|
|
'q' => '8.8.8.74', 'user_id' => '2',
|
|
]);
|
|
$assert($scopedIpSearch['items'] === [],
|
|
'Public-address search escaped the exact owner filter through its ledger subquery.');
|
|
foreach (['soon' => [206], 'expired' => [207], 'exempt' => [208]] as $mode => $expected) {
|
|
$filtered = CloudAdminInstanceService::page($admin, ['expiry' => $mode]);
|
|
$assert($ids($filtered['items']) === $expected,
|
|
'Expiry filter confused paid periods, expired instances, or exempt instances: ' . $mode);
|
|
}
|
|
$exempt = CloudAdminInstanceService::page($admin, ['service_status' => 'exempt']);
|
|
$assert($ids($exempt['items']) === [208], 'Exact service-status filter was ignored.');
|
|
foreach (['network' => [214, 210, 209], 'jobs' => [210, 209]] as $mode => $expected) {
|
|
$attention = CloudAdminInstanceService::page($admin, ['attention' => $mode]);
|
|
$assert($ids($attention['items']) === $expected,
|
|
'Attention filter included deleted/old failed jobs or omitted unresolved jobs/network restrictions.');
|
|
foreach ($attention['items'] as $item) {
|
|
$assert($item['state'] === 'unknown', 'Business/network/job state was mistaken for live VM power state.');
|
|
}
|
|
}
|
|
$networkPagingFixture = range(180, 199);
|
|
Capsule::table('cloud_instances')->whereIn('id', $networkPagingFixture)
|
|
->update(['spec_json' => '{invalid-network-snapshot']);
|
|
$networkPageOne = CloudAdminInstanceService::page($admin, [
|
|
'attention' => 'network', 'per_page' => '20', 'page' => '1',
|
|
]);
|
|
$networkPageTwo = CloudAdminInstanceService::page($admin, [
|
|
'attention' => 'network', 'per_page' => '20', 'page' => '2',
|
|
]);
|
|
$assert($ids($networkPageOne['items'])
|
|
=== array_merge([214, 210, 209], range(199, 183))
|
|
&& $ids($networkPageTwo['items']) === [182, 181, 180]
|
|
&& $networkPageOne['pagination']['total'] === 23
|
|
&& $networkPageOne['summary']['network_restricted'] === 23
|
|
&& $networkPageTwo['pagination']['total'] === 23,
|
|
'Canonical network-attention classification drifted between summary, filter and pagination.');
|
|
Capsule::table('cloud_instances')->whereIn('id', $networkPagingFixture)
|
|
->update(['spec_json' => $base['spec_json']]);
|
|
foreach (['page', 'per_page', 'q', 'user_id', 'host_id', 'service_status', 'expiry', 'attention', 'sort'] as $key) {
|
|
$expectError(static fn () => CloudAdminInstanceService::page($admin, [$key => ['1']]), 400,
|
|
'Array-valued filter must be rejected: ' . $key);
|
|
}
|
|
foreach ([['page' => '0'], ['page' => '-1'], ['page' => '1.5'], ['user_id' => '0'],
|
|
['host_id' => '1 OR 1=1'], ['expiry' => 'running'], ['attention' => 'powered'],
|
|
['sort' => 'id; DROP TABLE user'], ['service_status' => 'invented'], ['q' => str_repeat('x', 81)]] as $filter) {
|
|
$expectError(static fn () => CloudAdminInstanceService::page($admin, $filter), 400,
|
|
'Malformed filters must return a controlled client error');
|
|
}
|
|
$expectError(static fn () => CloudAdminInstanceService::page($customer), 403,
|
|
'Ordinary customers must not access the administrator read model');
|
|
$expectError(static fn () => CloudAdminInstanceService::detail($customer, '206'), 403,
|
|
'Ordinary customers must not inspect another owner through admin detail');
|
|
foreach (['211', '999999'] as $id) {
|
|
$expectError(static fn () => CloudAdminInstanceService::detail($admin, $id), 404,
|
|
'Missing or deleted detail must not disclose an instance');
|
|
}
|
|
$orphan = CloudAdminInstanceService::detail($admin, '212');
|
|
$assert((int) $orphan['instance']['id'] === 212 && $orphan['instance']['state'] === 'unknown',
|
|
'Missing user, host or plan caused an instance to disappear.');
|
|
$assert($orphan['instance']['display']['service'] === '期限未记录',
|
|
'An active record with an unknown billing deadline must not be labelled service-available.');
|
|
|
|
$detail = CloudAdminInstanceService::detail($admin, '206');
|
|
$assert((string) $detail['instance']['host_id'] === '8'
|
|
&& $detail['instance']['host_name'] === 'Tokyo 08',
|
|
'Administrator detail lost the physical placement needed for operations.');
|
|
$assert(($detail['instance']['public_ipv4'] ?? null) === '8.8.8.10'
|
|
&& ($detail['instance']['public_ipv6'] ?? null)
|
|
=== '2404:c140:156:3a::10'
|
|
&& ($detail['instance']['public_network_valid'] ?? null) === true,
|
|
'Administrator detail did not project the canonical dual-stack identity.');
|
|
$assert((int) $detail['instance']['active_job']['id'] === 26
|
|
&& $detail['instance']['active_job']['completed'] === false
|
|
&& $detail['instance']['active_job']['status'] === 'active'
|
|
&& $detail['instance']['can_manage'] === true
|
|
&& $detail['instance']['network_change_supported'] === true
|
|
&& $detail['instance']['instance_settings_supported'] === true,
|
|
'An operation submitted by a super-admin was lost because the job actor differs from the instance owner.');
|
|
$insertJob(31, [
|
|
'instance_id' => 213, 'outcome' => 'failed',
|
|
'effect_may_have_applied' => true, 'safe_to_resubmit' => false,
|
|
'effect_resolution' => 'unknown',
|
|
'finalization_incident' => true,
|
|
'finalization_error_code' => 'recovery_state_invalid',
|
|
'available_at' => $now + 30,
|
|
'dispatched_at' => $now - 20,
|
|
]);
|
|
$insertJob(32, [
|
|
'instance_id' => 214, 'phase' => 'active', 'outcome' => null,
|
|
'dispatched_at' => $now - 10,
|
|
]);
|
|
// A newer terminal failure that carries no unresolved effect must not hide
|
|
// the older active task that still owns the resource mutation fence.
|
|
$insertJob(33, [
|
|
'instance_id' => 214, 'outcome' => 'failed',
|
|
'dispatch_attempts' => 0,
|
|
'effect_may_have_applied' => false, 'safe_to_resubmit' => false,
|
|
'effect_resolution' => 'not_applicable',
|
|
]);
|
|
$attentionDetail = CloudAdminInstanceService::detail($admin, '213');
|
|
$activeDetail = CloudAdminInstanceService::detail($admin, '214');
|
|
$assert((int) $attentionDetail['instance']['active_job']['id'] === 31
|
|
&& $attentionDetail['instance']['active_job']['completed'] === true
|
|
&& $attentionDetail['instance']['active_job']['status'] === 'failed'
|
|
&& $attentionDetail['instance']['active_job']['blocks_mutation'] === true
|
|
&& ($attentionDetail['instance']['active_job']['recovery']['pending']
|
|
?? null) === true
|
|
&& str_contains(
|
|
(string) ($attentionDetail['instance']['active_job']['recovery']['message']
|
|
?? ''),
|
|
'仍会继续自动核对'
|
|
)
|
|
&& (int) $activeDetail['instance']['active_job']['id'] === 32
|
|
&& $activeDetail['instance']['active_job']['completed'] === false
|
|
&& $activeDetail['instance']['active_job']['status'] === 'active',
|
|
'Administrator detail omitted an active task or terminal failed safety fence.');
|
|
$insertJob(34, [
|
|
'instance_id' => 204,
|
|
'dispatch_attempts' => 2,
|
|
'outcome' => 'succeeded',
|
|
'effect_may_have_applied' => false,
|
|
'safe_to_resubmit' => false,
|
|
'effect_resolution' => 'applied',
|
|
'finalization_incident' => false,
|
|
'finalization_error_code' => null,
|
|
]);
|
|
$invalidSucceededDetail = CloudAdminInstanceService::detail(
|
|
$admin,
|
|
'204'
|
|
);
|
|
$assert((int) $invalidSucceededDetail['instance']['active_job']['id'] === 34
|
|
&& $invalidSucceededDetail['instance']['active_job']['completed'] === true
|
|
&& $invalidSucceededDetail['instance']['active_job']['status'] === 'succeeded'
|
|
&& $invalidSucceededDetail['instance']['active_job']['blocks_mutation'] === true
|
|
&& ($invalidSucceededDetail['instance']['active_job']['recovery']['pending']
|
|
?? null) === true,
|
|
'A succeeded task with an invalid dispatch ledger did not retain the administrator mutation fence.');
|
|
$insertJob(35, [
|
|
'instance_id' => 203,
|
|
'outcome' => 'succeeded',
|
|
'dispatch_attempts' => 1,
|
|
'effect_may_have_applied' => false,
|
|
'safe_to_resubmit' => false,
|
|
'effect_resolution' => 'applied',
|
|
'finalization_incident' => true,
|
|
'finalization_error_code' => 'recovery_dispatch_ledger_conflict',
|
|
]);
|
|
$insertJob(36, [
|
|
'instance_id' => 202,
|
|
'outcome' => 'failed',
|
|
'dispatch_attempts' => 0,
|
|
'dispatched_at' => null,
|
|
'effect_may_have_applied' => false,
|
|
'safe_to_resubmit' => false,
|
|
'effect_resolution' => 'not_applied',
|
|
'finalization_incident' => true,
|
|
'finalization_error_code' => 'recovery_ledger_conflict',
|
|
]);
|
|
$insertJob(37, [
|
|
'instance_id' => 201,
|
|
'outcome' => 'succeeded',
|
|
'dispatch_attempts' => null,
|
|
'effect_may_have_applied' => false,
|
|
'safe_to_resubmit' => false,
|
|
'effect_resolution' => 'applied',
|
|
'finalization_incident' => false,
|
|
'finalization_error_code' => null,
|
|
]);
|
|
$insertJob(38, [
|
|
'instance_id' => 200,
|
|
'outcome' => 'succeeded',
|
|
'dispatch_attempts' => 1,
|
|
'effect_may_have_applied' => false,
|
|
'safe_to_resubmit' => false,
|
|
'effect_resolution' => 'not_applied',
|
|
'finalization_incident' => false,
|
|
'finalization_error_code' => null,
|
|
]);
|
|
$insertJob(39, [
|
|
'instance_id' => 199,
|
|
'outcome' => 'succeeded',
|
|
'dispatch_attempts' => 1,
|
|
'receipt_deadline_at' => null,
|
|
'effect_may_have_applied' => false,
|
|
'safe_to_resubmit' => false,
|
|
'effect_resolution' => 'applied',
|
|
'finalization_incident' => false,
|
|
'finalization_error_code' => null,
|
|
]);
|
|
$stickyDetail = CloudAdminInstanceService::detail($admin, '203');
|
|
$localFinalizerDetail = CloudAdminInstanceService::detail($admin, '202');
|
|
$nullLedgerDetail = CloudAdminInstanceService::detail($admin, '201');
|
|
$resolvedConflictDetail = CloudAdminInstanceService::detail($admin, '200');
|
|
$envelopeConflictDetail = CloudAdminInstanceService::detail($admin, '199');
|
|
$assert((int) $stickyDetail['instance']['active_job']['id'] === 35
|
|
&& $stickyDetail['instance']['active_job']['status'] === 'succeeded'
|
|
&& $stickyDetail['instance']['active_job']['blocks_mutation'] === true
|
|
&& ($stickyDetail['instance']['active_job']['recovery']['code'] ?? null)
|
|
=== 'recovery_dispatch_ledger_conflict',
|
|
'A repaired succeeded task was presented as unlocked before sticky validation.');
|
|
$assert((int) $localFinalizerDetail['instance']['active_job']['id'] === 36
|
|
&& $localFinalizerDetail['instance']['active_job']['status'] === 'failed'
|
|
&& $localFinalizerDetail['instance']['active_job']['blocks_mutation'] === true
|
|
&& str_contains(
|
|
(string) ($localFinalizerDetail['instance']['active_job']['recovery']['message']
|
|
?? ''),
|
|
'面板账本'
|
|
),
|
|
'A zero-dispatch PHP finalizer failure was omitted from the active safety fence.');
|
|
$assert((int) $nullLedgerDetail['instance']['active_job']['id'] === 37
|
|
&& $nullLedgerDetail['instance']['active_job']['status'] === 'succeeded'
|
|
&& $nullLedgerDetail['instance']['active_job']['blocks_mutation'] === true
|
|
&& ($nullLedgerDetail['instance']['active_job']['recovery']['code'] ?? null)
|
|
=== 'recovery_dispatch_ledger_conflict',
|
|
'A NULL dispatch counter was presented as an ordinary succeeded task.');
|
|
$assert((int) $resolvedConflictDetail['instance']['active_job']['id'] === 38
|
|
&& $resolvedConflictDetail['instance']['active_job']['status']
|
|
=== 'succeeded'
|
|
&& $resolvedConflictDetail['instance']['active_job']['blocks_mutation']
|
|
=== true
|
|
&& ($resolvedConflictDetail['instance']['active_job']['recovery']['code']
|
|
?? null) === 'recovery_instance_state_conflict',
|
|
'A succeeded/not_applied terminal contradiction escaped the instance safety fence.');
|
|
$assert((int) $envelopeConflictDetail['instance']['active_job']['id'] === 39
|
|
&& $envelopeConflictDetail['instance']['active_job']['status']
|
|
=== 'succeeded'
|
|
&& $envelopeConflictDetail['instance']['active_job']['blocks_mutation']
|
|
=== true
|
|
&& ($envelopeConflictDetail['instance']['active_job']['recovery']['code']
|
|
?? null) === 'recovery_instance_state_conflict',
|
|
'A resolved Agent envelope with no receipt deadline escaped the instance safety fence.');
|
|
$jobAttentionIds = $ids(CloudAdminInstanceService::page(
|
|
$admin,
|
|
['attention' => 'jobs']
|
|
)['items']);
|
|
foreach ([204, 203, 202, 201, 200, 199] as $expectedAttentionId) {
|
|
$assert(in_array($expectedAttentionId, $jobAttentionIds, true),
|
|
'Administrator job-attention filter omitted recovery-fenced instance '
|
|
. $expectedAttentionId . '.');
|
|
}
|
|
$sharedResourceLockedSql = CloudJobRecoverySql::resourceLockedSql('cloud_jobs');
|
|
$compatibilityResourceLockedSql = CloudAdminOperationsService::resourceLockedSql(
|
|
'cloud_jobs'
|
|
);
|
|
$assert($compatibilityResourceLockedSql === $sharedResourceLockedSql,
|
|
'The administrator operations compatibility seam changed the shared recovery predicate.');
|
|
$sharedLockedJobIds = Capsule::table('cloud_jobs')
|
|
->whereRaw($sharedResourceLockedSql)
|
|
->orderBy('id')->pluck('id')
|
|
->map(static fn ($id): int => (int) $id)->all();
|
|
$compatibilityLockedJobIds = Capsule::table('cloud_jobs')
|
|
->whereRaw($compatibilityResourceLockedSql)
|
|
->orderBy('id')->pluck('id')
|
|
->map(static fn ($id): int => (int) $id)->all();
|
|
$assert($compatibilityLockedJobIds === $sharedLockedJobIds,
|
|
'The administrator operations compatibility seam diverged from the shared recovery predicate.');
|
|
foreach ([31 => 213, 34 => 204, 35 => 203, 36 => 202,
|
|
37 => 201, 38 => 200, 39 => 199] as $jobId => $instanceId) {
|
|
$assert(in_array($jobId, $sharedLockedJobIds, true)
|
|
&& in_array($instanceId, $jobAttentionIds, true),
|
|
'Recovery-fenced task and instance inventories diverged for job '
|
|
. $jobId . '.');
|
|
}
|
|
$unsupported = CloudAdminInstanceService::detail($admin, '214');
|
|
$assert($unsupported['instance']['network_change_supported'] === false
|
|
&& $unsupported['instance']['instance_settings_supported'] === false
|
|
&& $unsupported['instance']['can_manage'] === false
|
|
&& $unsupported['instance']['public_network_valid'] === false
|
|
&& $unsupported['instance']['public_ipv4'] === ''
|
|
&& $unsupported['instance']['public_ipv6'] === ''
|
|
&& $unsupported['instance']['network_status']
|
|
=== 'configuration_invalid',
|
|
'Incomplete legacy metadata exposed administrator mutation controls.');
|
|
Capsule::table('cloud_instances')->where('id', 205)->update(['status' => 'deleting']);
|
|
$inactive = CloudAdminInstanceService::detail($admin, '205');
|
|
$assert($inactive['instance']['network_change_supported'] === false
|
|
&& $inactive['instance']['instance_settings_supported'] === false,
|
|
'A non-active instance exposed controls that both mutation endpoints reject.');
|
|
Capsule::table('cloud_instances')->where('id', 205)->update(['status' => 'active']);
|
|
$assert(count($detail['jobs']) === 20 && $detail['jobs_truncated'] === true
|
|
&& $ids($detail['jobs']) === range(26, 7),
|
|
'Instance tasks must be newest-first, bounded to 20, and explicitly marked truncated.');
|
|
$expectedInvoiceIds = array_merge([27], range(25, 7));
|
|
$assert(count($detail['invoices']) === 20 && $detail['invoices_truncated'] === true
|
|
&& $ids($detail['invoices']) === $expectedInvoiceIds,
|
|
'Invoice detail included a foreign owner, missed the valid order link, or silently truncated history.');
|
|
$crossOwner = CloudAdminInstanceService::detail($admin, '207');
|
|
$assert($crossOwner['invoices'] === [],
|
|
'A same-owner invoice joined through another owner\'s order crossed the billing boundary.');
|
|
foreach ($detail['invoices'] as $invoice) {
|
|
$assert(str_starts_with($invoice['detail_url'], '/admin/billing?detail='),
|
|
'Invoice links must target the administrator ledger, not the customer route.');
|
|
}
|
|
$encoded = json_encode([$page, $detail, $crossOwner, $orphan], JSON_THROW_ON_ERROR);
|
|
$assert(!str_contains($encoded, 'must-not-expose')
|
|
&& !str_contains($encoded, 'sealed_credential')
|
|
&& !str_contains($encoded, 'sealed_payload')
|
|
&& !str_contains($encoded, 'result_json')
|
|
&& !str_contains($encoded, 'console_port')
|
|
&& !str_contains($encoded, 'unreviewed_note'),
|
|
'The administrator DTO allowlist leaked credentials, paths, or an unreviewed metadata/result field.');
|
|
|
|
AdminPermission::$superAdmin = false;
|
|
$masked = CloudAdminInstanceService::page($readOnly, ['user_id' => '2']);
|
|
$assert($masked['items'][0]['can_manage'] === false
|
|
&& $masked['items'][0]['user_email'] !== 'bob@example.test'
|
|
&& $masked['items'][0]['user_name'] !== 'Bob Client',
|
|
'Read-only administrators gained global operation controls or unmasked account data.');
|
|
$hiddenSearch = CloudAdminInstanceService::page($readOnly, ['q' => 'bob@example.test']);
|
|
$assert($hiddenSearch['items'] === [], 'Read-only account search became an oracle for masked email addresses.');
|
|
AdminPermission::$superAdmin = true;
|
|
|
|
$queryCounts = [];
|
|
foreach ([20, 100] as $size) {
|
|
$connection = Capsule::connection('default');
|
|
$connection->flushQueryLog();
|
|
$connection->enableQueryLog();
|
|
CloudAdminInstanceService::page($admin, ['per_page' => (string) $size]);
|
|
$queries = $connection->getQueryLog();
|
|
$connection->disableQueryLog();
|
|
$queryCounts[] = count($queries);
|
|
foreach ($queries as $query) {
|
|
$assert(preg_match('/^\s*(select|with)\b/i', $query['query']) === 1,
|
|
'Instance reads unexpectedly wrote business or session data.');
|
|
$assert(!str_contains(strtolower($query['query']), 'cloud_sessions'),
|
|
'Database-only instance reads touched the private engine session table.');
|
|
}
|
|
}
|
|
$assert($queryCounts[0] <= 8 && $queryCounts[1] <= $queryCounts[0],
|
|
'Increasing page size introduced per-instance SQL queries: ' . implode(', ', $queryCounts));
|
|
$login = static function (bool $isAdmin, bool $isSuper = false, bool $enabled = true): void {
|
|
$user = new User();
|
|
$user->id = $isAdmin ? 99 : 1;
|
|
$user->enable = $enabled ? 1 : 0;
|
|
$user->is_admin = $isAdmin;
|
|
$user->isLogin = true;
|
|
Auth::$user = $user;
|
|
AdminPermission::$superAdmin = $isSuper;
|
|
};
|
|
$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
|
|
require dirname(__DIR__) . '/config/routes_cloud.php';
|
|
$requestApi = static function (string $path, array $query = []) use ($app): array {
|
|
$request = Request::createFromEnvironment(Environment::mock([
|
|
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => $path,
|
|
]))->withQueryParams($query);
|
|
$response = $app->process($request, new Response());
|
|
return [$response, json_decode((string) $response->getBody(), true)];
|
|
};
|
|
$login(true, true);
|
|
[$response, $payload] = $requestApi('/api/v1/admin/instances', ['user_id' => '2']);
|
|
$assert($response->getStatusCode() === 200 && $ids($payload['items']) === [206]
|
|
&& $response->getHeaderLine('Cache-Control') === 'private, no-store',
|
|
'The registered administrator list route did not provide a private scoped database response.');
|
|
[$response, $payload] = $requestApi('/api/v1/admin/instances/206');
|
|
$assert($response->getStatusCode() === 200 && (int) $payload['instance']['id'] === 206,
|
|
'The registered administrator detail route did not dispatch the database read model.');
|
|
foreach ([['q' => ['bad']], ['page' => '0'], ['host_id' => ['8']]] as $query) {
|
|
[$response, $payload] = $requestApi('/api/v1/admin/instances', $query);
|
|
$assert($response->getStatusCode() === 400 && isset($payload['error']),
|
|
'Malformed query parameters escaped CloudApi as a server error.');
|
|
}
|
|
foreach (['211', '999999'] as $id) {
|
|
[$response] = $requestApi('/api/v1/admin/instances/' . $id);
|
|
$assert($response->getStatusCode() === 404, 'Registered detail disclosed a missing/deleted instance.');
|
|
}
|
|
$login(true);
|
|
[$response, $payload] = $requestApi('/api/v1/admin/instances/206');
|
|
$assert($response->getStatusCode() === 200 && $payload['instance']['can_manage'] === false,
|
|
'Read-only administrators must retain global read access without mutation capability.');
|
|
$login(false);
|
|
foreach (['/api/v1/admin/instances', '/api/v1/admin/instances/206'] as $path) {
|
|
[$response] = $requestApi($path);
|
|
$assert($response->getStatusCode() === 403, 'A customer reached a registered administrator route.');
|
|
}
|
|
$login(true, true, false);
|
|
[$response] = $requestApi('/api/v1/admin/instances');
|
|
$assert($response->getStatusCode() === 401, 'Disabled accounts bypassed CloudAccess authentication.');
|
|
Auth::$user = null;
|
|
[$response] = $requestApi('/api/v1/admin/instances');
|
|
$assert($response->getStatusCode() === 401, 'Anonymous requests bypassed CloudAccess authentication.');
|
|
|
|
// The controller also works without middleware attributes and must request
|
|
// actor(false), preserving the no-engine-session guarantee in this path.
|
|
$login(true, true);
|
|
$direct = (new CloudAdminInstanceController())->index(
|
|
Request::createFromEnvironment(Environment::mock([
|
|
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/api/v1/admin/instances',
|
|
])), new Response()
|
|
);
|
|
$assert($direct->getStatusCode() === 200, 'Controller fallback authentication broke database-only reads.');
|
|
$assert(CloudAgentSettingsService::$calls === 0 && CloudSessionService::$calls === 0,
|
|
'The service, middleware, or controller read path contacted a host Agent/console session service.');
|
|
|
|
echo 'Administrator instance SQL filtering, pagination, ownership, DTO safety and bounded queries passed ('
|
|
. implode('/', $queryCounts) . " queries for 20/100 rows).\n";
|
|
echo "Administrator instance registered API routes, authorization, validation and session isolation passed.\n";
|
|
}
|