20, 'cloud_engine_url' => 'http://127.0.0.1:8000', 'super_admin' => '99']; public static function get($name, $default = null) { return self::$values[$name] ?? $default; } } final class Auth { public static $user; public static function getUser() { return self::$user; } } } namespace App\Services\Cloud { final class CloudSecrets { private static array $memory = []; public static function key(string $purpose): string { return str_repeat('k', 32); } public static function encrypt(array $payload): string { $id = bin2hex(random_bytes(16)); self::$memory[$id] = $payload; return 'test-only:' . $id; } public static function decrypt(string $cipher): array { return self::$memory[substr($cipher, 10)]; } } } namespace { require dirname(__DIR__) . '/vendor/autoload.php'; use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Schema\Blueprint; use App\Models\User; use App\Models\Shop; use App\Models\CloudHost; use App\Models\CloudInstance; use App\Models\CloudOrder; use App\Models\CloudJob; use App\Services\Cloud\CloudOrderService; use App\Services\Cloud\CloudWorkerService; use App\Services\Cloud\CloudEngineClient; use App\Services\Cloud\CloudAccess; use App\Services\Cloud\CloudJobService; use App\Services\Cloud\CloudError; use GuzzleHttp\Client; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Exception\ConnectException; $assert = function ($condition, $message) { if (!$condition) { throw new RuntimeException($message); } }; $capsule = new Capsule(); $capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default'); $capsule->setAsGlobal(); $capsule->bootEloquent(); $schema = $capsule->schema('default'); $schema->create('user', function (Blueprint $t) { $t->increments('id'); $t->string('money'); $t->integer('enable')->default(1); $t->integer('is_admin')->default(0); $t->integer('restrict_balance_purchase')->default(0); }); $schema->create('shop', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->string('name'); $t->string('price'); foreach (['cpu_cores', 'memory_mib', 'bandwidth_mbps', 'disk_gib', 'status', 'stock', 'sort'] as $v) { $t->integer($v)->default(0); } }); $schema->create('cloud_hosts', function (Blueprint $t) { $t->increments('id'); $t->string('name'); $t->string('region')->default(''); $t->integer('enabled'); $t->string('default_network'); }); $schema->create('cloud_orders', function (Blueprint $t) { $t->increments('id'); foreach (['user_id', 'plan_id', 'host_id'] as $v) { $t->integer($v); } $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->string('status'); $t->text('spec_json'); $t->integer('instance_id')->nullable(); $t->integer('refunded_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); }); $schema->create('cloud_jobs', function (Blueprint $t) { $t->increments('id'); $t->string('operation_id')->unique(); foreach (['order_id', 'instance_id'] as $v) { $t->integer($v)->nullable(); } foreach (['user_id', 'host_id'] as $v) { $t->integer($v); } $t->string('kind'); $t->string('status'); $t->text('payload_cipher'); $t->integer('attempts')->default(0); $t->integer('dispatched_at')->nullable(); $t->string('lease_token')->nullable(); $t->integer('lease_until')->default(0); $t->integer('available_at'); $t->string('error_code')->nullable(); $t->text('result_json')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); }); $schema->create('cloud_instances', function (Blueprint $t) { $t->increments('id'); foreach (['host_id', 'user_id', 'order_id'] as $v) { $t->integer($v); } $t->string('uuid'); $t->string('name'); $t->string('status'); $t->text('spec_json'); $t->text('credential_cipher')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); $t->unique(['host_id', 'uuid']); }); $schema->create('cloud_ssh_keys', function (Blueprint $t) { $t->increments('id'); $t->integer('user_id'); $t->string('name'); $t->text('public_key'); $t->string('fingerprint'); $t->integer('created_at'); }); $user = new User(); $user->id = 1; $user->money = '100.00'; $user->enable = 1; $user->is_admin = false; $user->save(); $user->isLogin = true; \App\Services\Auth::$user = $user; $host = new CloudHost(); $host->name = 'host'; $host->enabled = true; $host->default_network = 'bridge:br0'; $host->save(); $plan = new Shop(); $plan->host_id = $host->id; $plan->name = 'plan'; $plan->price = '9.99'; $plan->cpu_cores = 2; $plan->memory_mib = 2048; $plan->bandwidth_mbps = 100; $plan->disk_gib = 20; $plan->status = 1; $plan->stock = 10; $plan->save(); $actor = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false, 'can_manage' => false, 'session_id' => '']; $input = ['plan_id' => 1, 'source' => 'cloud', 'name' => 'vm-one', 'template_id' => 'alma10-1234abcd-0123456789abcdef', 'idempotency_key' => 'test-request-key-0001']; $first = CloudOrderService::purchase($input, $actor); $same = CloudOrderService::purchase($input, $actor); $assert($first->id === $same->id && User::find(1)->money === '90.01' && CloudJob::count() === 1 && Shop::find(1)->stock === 9, 'Idempotent purchase charged twice or stock incorrect.'); try { CloudOrderService::purchase($input + ['vcpu' => 64], $actor); throw new RuntimeException('Resource bypass accepted.'); } catch (CloudError $e) {} try { CloudOrderService::purchase(array_replace($input, ['name' => 'changed']), $actor); throw new RuntimeException('Idempotency conflict accepted.'); } catch (CloudError $e) { $assert($e->httpStatus === 409, 'Wrong idempotency response.'); } $history = []; $mock = new MockHandler([new Response(200, [], json_encode(['status' => 'succeeded', 'uuid' => '11111111-1111-4111-8111-111111111111', 'generated_password' => 'must-not-persist']))]); $stack = HandlerStack::create($mock); $stack->push(Middleware::history($history)); $worker = new CloudWorkerService(new CloudEngineClient(new Client(['handler' => $stack]))); $worker->tick(); $assert(CloudOrder::find($first->id)->status === 'succeeded' && CloudInstance::count() === 1, 'Successful provision not associated.'); $posted = json_decode((string) $history[0]['request']->getBody(), true); $signedActor = json_decode(base64_decode(strtr($history[0]['request']->getHeaderLine('X-Cloud-Actor'), '-_', '+/')), true); $assert($posted['vcpu'] === 2 && $posted['bandwidth_mbps'] === 100 && $posted['network'] === 'bridge:br0' && $signedActor['can_provision'] === true && $signedActor['can_manage'] === true, 'Plan or provisioning authority lost.'); $assert(!str_contains(CloudJob::first()->result_json, 'must-not-persist'), 'Plain password saved in result.'); $instance = CloudInstance::first(); $assert(CloudAccess::instance((string) $instance->id, $actor)->id === $instance->id, 'Owner denied own VM.'); $other = array_replace($actor, ['user_id' => 2]); try { CloudAccess::instance((string) $instance->id, $other); throw new RuntimeException('Tenant isolation failed.'); } catch (CloudError $e) { $assert($e->httpStatus === 404, 'Nonowner information leaked.'); } $admin = array_replace($other, ['is_admin' => true]); $assert(CloudAccess::instance((string) $instance->id, $admin)->id === $instance->id, 'Admin readonly denied.'); try { CloudAccess::instance((string) $instance->id, $admin, true); throw new RuntimeException('Regular admin wrote other owner.'); } catch (CloudError $e) {} try { CloudJobService::enqueue($instance, array_replace($admin, ['can_manage' => true]), 'action', 'POST', '/actions', ['action' => 'reboot']); throw new RuntimeException('Scoped can_manage bypassed cross-owner queue authorization.'); } catch (CloudError $e) {} try { CloudAccess::manage($actor + ['can_provision' => true]); throw new RuntimeException('Provision actor globally privileged.'); } catch (CloudError $e) {} $failed = CloudOrderService::purchase(array_replace($input, ['name' => 'vm-two', 'idempotency_key' => 'test-request-key-0002']), $actor); $mock->append(new Response(200, [], '{"status":"failed","safe_to_refund":true}')); $worker->tick(); $worker->tick(); $assert(User::find(1)->money === '90.01' && CloudOrder::find($failed->id)->refunded_at !== null && Shop::find(1)->stock === 9, 'Failure refund not exact or duplicated.'); $uncertain = CloudOrderService::purchase(array_replace($input, ['name' => 'vm-three', 'idempotency_key' => 'test-request-key-0003']), $actor); $mock->append(new ConnectException('simulated timeout', new Request('POST', 'http://127.0.0.1:8000'))); $worker->tick(); $uncertainJob = CloudJob::where('order_id', $uncertain->id)->first(); $assert($uncertainJob->status === 'uncertain' && CloudOrder::find($uncertain->id)->refunded_at === null && User::find(1)->money === '80.02', 'Timeout incorrectly refunded.'); $uncertainJob->available_at = 0; $uncertainJob->save(); $mock->append(new Response(404, [], '{}')); $worker->tick(); $last = end($history)['request']; $assert($last->getMethod() === 'GET' && str_contains($last->getUri()->getPath(), '/operations/') && User::find(1)->money === '80.02', 'Ambiguous timeout recreated or refunded on unknown operation.'); $uncertainJob->refresh(); $uncertainJob->available_at = 0; $uncertainJob->save(); $mock->append(new Response(200, [], '{"status":"succeeded","result":{"uuid":"33333333-3333-4333-8333-333333333333"}}')); $worker->tick(); $assert(CloudInstance::count() === 2 && CloudOrder::find($uncertain->id)->status === 'succeeded' && User::find(1)->money === '80.02', 'Reconciliation did not recover exactly once.'); \App\Services\Config::$values['cloud_max_instances_per_user'] = 2; try { CloudOrderService::purchase(array_replace($input, ['name' => 'vm-four', 'idempotency_key' => 'test-request-key-0004']), $actor); throw new RuntimeException('Quota bypass.'); } catch (CloudError $e) { $assert($e->httpStatus === 409, 'Quota response incorrect.'); } $assert(User::find(1)->money === '80.02' && CloudOrder::count() === 3, 'Rejected order altered finance.'); $actionJob = CloudJobService::enqueue($instance, $actor, 'action', 'POST', '/actions', ['action' => 'reboot']); $mock->append(new Response(200, [], '{"status":"succeeded","uuid":"11111111-1111-4111-8111-111111111111","state":"running"}')); $worker->tick(); $last = end($history)['request']; $signedActor = json_decode(base64_decode(strtr($last->getHeaderLine('X-Cloud-Actor'), '-_', '+/')), true); $assert(CloudJob::find($actionJob->id)->status === 'succeeded' && $signedActor['can_manage'] === true && !isset($signedActor['can_provision']), 'Power task delegated provision authority or did not complete.'); $reinstall = CloudJobService::enqueue($instance, $actor, 'reinstall', 'POST', '/reinstall', ['template_id' => $input['template_id'], 'confirmation_name' => $instance->name, 'root_password' => 'NewStrongPassword!123'], ['password' => 'NewStrongPassword!123', 'login_name' => 'root']); $oldCredential = $instance->credential_cipher; $mock->append(new Response(202, [], '{"status":"pending","job_id":"remote-reinstall-id"}')); $worker->tick(); $assert(CloudJob::find($reinstall->id)->status === 'running' && $instance->fresh()->credential_cipher === $oldCredential, 'Pending reinstall replaced password prematurely.'); CloudJob::where('id', $reinstall->id)->update(['available_at' => 0]); $mock->append(new Response(200, [], '{"status":"succeeded","result":{"job_id":"remote-reinstall-id","generated_password":"never-public"}}')); $worker->tick(); $assert(CloudJob::find($reinstall->id)->status === 'succeeded' && $instance->fresh()->credential_cipher !== $oldCredential && !str_contains(CloudJob::find($reinstall->id)->result_json, 'never-public'), 'Completed reinstall password or sanitization failed.'); $delete = CloudJobService::enqueue($instance, $actor, 'delete', 'DELETE', '?delete_disks=true', []); $mock->append(new Response(200, [], '{"status":"succeeded","uuid":"11111111-1111-4111-8111-111111111111"}')); $worker->tick(); $last = end($history)['request']; $assert((string) $last->getBody() === '{}' && $last->getUri()->getQuery() === 'delete_disks=true' && $instance->fresh()->status === 'deleted' && $instance->fresh()->credential_cipher === null, 'Delete payload/query or credential removal failed.'); echo "Cloud SQLite purchase, provisioning, refund, ambiguity, quota and tenant checks passed (crypto double only).\n"; }