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

272 lines
11 KiB
PHTML

<?php
namespace App\Services {
final class AdminPermission
{
public static function isSuperAdmin(): bool
{
return true;
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudJob;
use App\Services\Cloud\CloudAdminOperationsService as Operations;
use App\Services\Cloud\CloudError;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$reject = static function (callable $callback, int $status,
string $message) use ($assert): void {
try {
$callback();
} catch (CloudError $error) {
$assert($error->httpStatus === $status,
$message . ': HTTP ' . $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');
});
$schema->create('cloud_hosts', static function (Blueprint $table): void {
$table->increments('id');
$table->string('name');
$table->string('region');
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->string('uuid');
$table->string('name');
$table->integer('host_id');
$table->integer('user_id');
$table->string('status');
});
$schema->create('cloud_orders', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
$table->integer('user_id');
$table->integer('instance_id')->nullable();
});
$schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->increments('id');
$table->string('operation_id');
$table->integer('parent_job_id')->nullable();
$table->integer('order_id')->nullable();
$table->integer('invoice_id')->nullable();
$table->integer('instance_id')->nullable();
$table->integer('user_id');
$table->integer('host_id');
$table->string('kind');
$table->string('execution_mode')->default('agent');
$table->string('phase');
$table->string('outcome')->nullable();
$table->string('status');
$table->integer('attempts')->default(0);
$table->integer('dispatch_attempts')->default(0);
$table->integer('dispatch_deadline_at');
$table->integer('receipt_deadline_at')->nullable();
$table->integer('dispatched_at')->nullable();
$table->integer('terminal_at')->nullable();
$table->boolean('effect_may_have_applied')->nullable();
$table->boolean('safe_to_resubmit')->nullable();
$table->string('effect_resolution')->default('not_applicable');
$table->integer('effect_resolved_at')->nullable();
$table->integer('effect_resolved_by')->nullable();
$table->string('effect_resolution_reason')->default('');
$table->string('lease_token')->nullable();
$table->integer('lease_until')->default(0);
$table->integer('available_at')->default(0);
$table->string('error_code')->nullable();
$table->boolean('finalization_incident')->default(0);
$table->string('finalization_error_code')->nullable();
$table->text('result_json')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
Capsule::table('user')->insert([
['id' => 1, 'user_name' => 'Instance Owner',
'email' => 'owner@example.test'],
['id' => 99, 'user_name' => 'Root Operator',
'email' => 'root@example.test'],
]);
Capsule::table('cloud_hosts')->insert([
'id' => 7, 'name' => 'Host Seven', 'region' => 'HongKong',
]);
Capsule::table('cloud_instances')->insert([
'id' => 10,
'uuid' => '11111111-1111-4111-8111-111111111110',
'name' => "tenant's 100%_vm", 'host_id' => 7, 'user_id' => 1,
'status' => 'active',
]);
Capsule::table('cloud_orders')->insert([
'id' => 100, 'host_id' => 7, 'user_id' => 1, 'instance_id' => 10,
]);
$now = time();
$insert = static function (int $id, array $values = []) use ($now): void {
Capsule::table('cloud_jobs')->insert(array_replace([
'id' => $id, 'operation_id' => sprintf('%032x', $id),
'order_id' => 100, 'instance_id' => 10,
'user_id' => 99, 'host_id' => 7, 'kind' => 'action',
'phase' => 'terminal', 'outcome' => 'succeeded',
'status' => 'succeeded', 'attempts' => 1,
'dispatch_attempts' => 1,
'dispatch_deadline_at' => $now - 100,
'receipt_deadline_at' => $now - 50,
'dispatched_at' => $now - 90,
'terminal_at' => $now - 40,
'effect_may_have_applied' => false,
'safe_to_resubmit' => false,
'effect_resolution' => 'not_applicable',
'lease_until' => 0, 'available_at' => 0,
'result_json' => json_encode(['cause_code' => ''],
JSON_THROW_ON_ERROR),
'created_at' => $now - 120, 'updated_at' => $now - 40,
], $values));
};
$insert(1, [
'phase' => 'accepted', 'outcome' => null, 'status' => 'queued',
'attempts' => 0, 'dispatch_attempts' => 0,
'dispatch_deadline_at' => $now + 100,
'dispatched_at' => null, 'receipt_deadline_at' => null,
'terminal_at' => null, 'effect_may_have_applied' => null,
'safe_to_resubmit' => null,
]);
$insert(2);
$insert(3, [
'outcome' => 'failed', 'status' => 'failed',
'effect_may_have_applied' => true, 'safe_to_resubmit' => false,
'effect_resolution' => 'unknown', 'error_code' => 'transport_lost',
'result_json' => json_encode(['cause_code' => 'transport_lost'],
JSON_THROW_ON_ERROR),
]);
$insert(4, [
'outcome' => 'failed', 'status' => 'failed',
'error_code' => 'operation_failed',
]);
$insert(5, [
'outcome' => 'failed', 'status' => 'failed',
'effect_may_have_applied' => false, 'safe_to_resubmit' => false,
'error_code' => 'validation_failed',
]);
$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 = Operations::page($admin, ['status' => 'all']);
$assert($ids($all['items']) === [5, 4, 3, 2, 1]
&& $all['summary'] === [
'total' => 5, 'active' => 1, 'succeeded' => 1,
'failed' => 3, 'unresolved_effect' => 1,
], 'Operations inventory did not expose active and terminal states exactly.');
foreach ([
'active' => [1], 'succeeded' => [2],
'failed' => [5, 4, 3], 'attention' => [5, 4, 3],
] as $status => $expected) {
$page = Operations::page($admin, ['status' => $status]);
$assert($ids($page['items']) === $expected,
'Status filter diverged from task receipt state: ' . $status);
}
foreach (["tenant's", '100%_vm',
'11111111-1111-4111-8111-111111111110'] as $search) {
$assert(Operations::page($admin,
['status' => 'all', 'q' => $search])['summary']['total'] === 5,
'Bound task search failed for ' . $search);
}
$assert(Operations::page($admin,
['status' => 'all', 'q' => "' OR 1=1 --"])['items'] === [],
'Task search accepted SQL injection text as a predicate.');
$detail = Operations::detail($admin, '3')['job'];
$assert($detail['completed'] === true && $detail['status'] === 'failed'
&& $detail['dispatch_attempts'] === 1
&& $detail['effect_may_have_applied'] === true
&& $detail['safe_to_resubmit'] === false
&& $detail['effect_resolution'] === 'unknown'
&& $detail['can_inspect'] === true
&& $detail['can_resolve_effect'] === false
&& str_contains($detail['resolve_effect_reason'],
'尚无可原子收敛业务账本'),
'Unknown-effect terminal failure lost its immutable outcome or safety fence.');
$active = Operations::detail($admin, '1')['job'];
$assert($active['completed'] === false && $active['status'] === 'active',
'Accepted task was exposed as a fabricated terminal result.');
$assert(Operations::detail($readonly, '3')['job']['can_resolve_effect']
=== false, 'Read-only administrator received effect-resolution authority.');
$reason = '已在宿主机只读核对虚拟机与磁盘,确认原操作效果已经发生。';
$operationId = sprintf('%032x', 3);
$freshInspection = [
'operation_id' => $operationId, 'checked_at' => $now,
'status' => 'failed',
];
// A generic host action has no business-ledger finalizer. Even a valid
// historical Agent fence receipt must not clear its safety fence.
$persistedFenceReceipt = [
'operation_id' => $operationId,
'resolution_id' => str_repeat('a', 32),
'resolution' => 'applied',
'inspection_checked_at' => $now - 60,
'reason_sha256' => hash('sha256', $reason),
'resolved_at' => $now - 50,
'resolved_by' => 7,
'replayed' => false,
];
$reject(static fn () => Operations::resolveEffect($admin, '3', [
'resolution' => 'applied', 'reason' => $reason,
], $freshInspection, $persistedFenceReceipt), 409,
'Unsupported action effect resolution cleared a safety fence');
$row = CloudJob::find(3);
$assert($row !== null && (string) $row->phase === 'terminal'
&& (string) $row->outcome === 'failed'
&& (string) $row->effect_resolution === 'unknown'
&& $row->effect_resolved_by === null,
'Rejected generic effect resolution changed the immutable task receipt.');
$reject(static fn () => Operations::resolveEffect($readonly, '5', [
'resolution' => 'not_applied', 'reason' => $reason,
], $freshInspection, $persistedFenceReceipt), 403,
'Read-only administrator resolved a fence');
foreach ([
['status' => 'invented'], ['page' => '0'], ['per_page' => '30'],
['q' => str_repeat('x', 81)], ['unknown' => 'value'],
] as $invalid) {
$reject(static fn () => Operations::page($admin, $invalid), 400,
'Malformed task filter was accepted');
}
$reject(static fn () => Operations::page($customer), 403,
'Customer accessed administrator operations');
$reject(static fn () => Operations::detail($admin, '999'), 404,
'Missing task detail was fabricated');
echo "Administrator task inventory, terminal receipt, and audited fence-resolution tests passed.\n";
}