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.
211 lines
11 KiB
PHP
211 lines
11 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Cloud {
|
|
final class CloudEngineClient
|
|
{
|
|
public function __construct()
|
|
{
|
|
throw new \RuntimeException('History reads must never contact the engine.');
|
|
}
|
|
}
|
|
}
|
|
|
|
namespace {
|
|
require dirname(__DIR__) . '/vendor/autoload.php';
|
|
require __DIR__ . '/CloudHostInventoryDiagnosticsFixture.php';
|
|
|
|
use App\Models\CloudHostInventoryAttempt;
|
|
use App\Services\Cloud\CloudError;
|
|
use App\Services\Cloud\CloudHostInventoryDiagnostics as Diagnostics;
|
|
use Illuminate\Database\Capsule\Manager as Capsule;
|
|
use Illuminate\Database\Schema\Blueprint;
|
|
|
|
$assert = static function ($condition, string $message): void {
|
|
if (!$condition) {
|
|
throw new \RuntimeException($message);
|
|
}
|
|
};
|
|
$reject = static function (callable $call, int $status) use ($assert): void {
|
|
try {
|
|
$call();
|
|
} catch (CloudError $error) {
|
|
$assert($error->httpStatus === $status, 'Unexpected error status.');
|
|
return;
|
|
}
|
|
throw new \RuntimeException('Expected request rejection.');
|
|
};
|
|
$capsule = new Capsule();
|
|
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
|
|
$capsule->setAsGlobal();
|
|
$capsule->bootEloquent();
|
|
$schema = $capsule->schema();
|
|
$schema->create('cloud_hosts', static function (Blueprint $table): void {
|
|
$table->increments('id');
|
|
$table->string('name');
|
|
$table->string('credential_cipher')->default('never-read-this-secret');
|
|
});
|
|
createCloudHostInventoryAttemptTable($schema);
|
|
Capsule::table('cloud_hosts')->insert([
|
|
['id' => 1, 'name' => 'Host One'], ['id' => 2, 'name' => 'Host Two'],
|
|
]);
|
|
$actor = ['is_admin' => true];
|
|
$now = time();
|
|
|
|
$success = Diagnostics::start(1, 'auto', $now, 8.0);
|
|
$assert(preg_match('/^[a-f0-9]{32}$/D', $success->id()) === 1, 'Attempt IDs must be stable opaque identifiers.');
|
|
$success->generation(10);
|
|
$success->stage('capacity_request');
|
|
$success->stage('capacity_validate');
|
|
$success->stage('network_request');
|
|
$success->stage('network_validate');
|
|
$success->stage('database_apply');
|
|
$success->finish('succeeded', '', null, true);
|
|
$beforeLateFinish = CloudHostInventoryAttempt::find($success->id())->toArray();
|
|
$success->finish('failed', 'unexpected_error');
|
|
$success->stage('capacity_request');
|
|
$success->generation(500);
|
|
$assert(CloudHostInventoryAttempt::find($success->id())->toArray() === $beforeLateFinish,
|
|
'Terminal outcomes must not change on a second finish or a late phase.');
|
|
$dto = Diagnostics::detail($actor, $success->id())['attempt'];
|
|
$assert($dto['outcome'] === 'succeeded' && $dto['applied'] && $dto['generation'] === 10,
|
|
'Successful commit metadata was lost.');
|
|
$assert($dto['timeout_ms'] === 8000 && $dto['finished_at'] >= $dto['started_at']
|
|
&& $dto['duration_ms'] >= 0 && count($dto['stages']) === 6,
|
|
'Timeout and monotonic phase durations must be recorded.');
|
|
$assert($dto['panel_version'] === 'inventory-diagnostics-v1', 'Never pretend runtime version is current disk Git HEAD.');
|
|
|
|
$timeout = Diagnostics::start(1, 'manual', $now, 8.0);
|
|
$timeout->generation(11);
|
|
$timeout->stage('capacity_request');
|
|
$timeout->finish('timeout', 'engine_http_timeout', null, false);
|
|
$failed = Diagnostics::start(1, 'auto', $now, 8.0);
|
|
$failed->generation(12);
|
|
$failed->stage('network_request');
|
|
$failed->finish('failed', 'engine_resource_missing', 404, false);
|
|
$unrelated = Diagnostics::start(2, 'auto', $now, 8.0);
|
|
$unrelated->finish('succeeded', '', null, true);
|
|
$summary = Diagnostics::page($actor, ['host_id' => '1'])['summary'];
|
|
$assert($summary['consecutive_failures'] === 2,
|
|
'Same-second failures must not disappear behind the earlier success timestamp.');
|
|
$assert($summary['last_success_at'] !== null && $summary['last_failure_at'] !== null,
|
|
'The last success/failure times must survive subsequent attempts.');
|
|
$assert(Diagnostics::page($actor)['summary']['consecutive_failures'] === null,
|
|
'A global failure streak across unrelated hosts is misleading.');
|
|
|
|
$superseded = Diagnostics::start(1, 'manual', $now, 8.0);
|
|
$superseded->finish('superseded');
|
|
$assert(Diagnostics::page($actor, ['host_id' => 1])['summary']['consecutive_failures'] === 2,
|
|
'Superseded/skipped attempts cannot be counted as confirmed failures.');
|
|
$running = Diagnostics::start(1, 'auto', $now, 8.0);
|
|
$running->stage('capacity_request');
|
|
$assert(Diagnostics::page($actor, ['host_id' => 1])['summary']['in_progress'] === 1,
|
|
'Recent running attempt should be visible.');
|
|
CloudHostInventoryAttempt::where('attempt_id', $running->id())->update(['updated_at' => $now - 301]);
|
|
$interrupted = Diagnostics::detail($actor, $running->id())['attempt'];
|
|
$assert($interrupted['outcome'] === 'interrupted' && $interrupted['finished_at'] === null
|
|
&& $interrupted['last_confirmed_stage'] === 'capacity_request',
|
|
'Abandoned attempts must display unknown without inventing a completion or failure cause.');
|
|
$assert(CloudHostInventoryAttempt::find($running->id())->outcome === 'running',
|
|
'Read-side interpretation must not mutate diagnostic history.');
|
|
$assert(Diagnostics::page($actor, ['host_id' => 1, 'outcome' => 'attention'])['pagination']['total'] === 3,
|
|
'Attention filter should include failed, timed-out, and interrupted records.');
|
|
$assert(Diagnostics::page($actor, ['outcome' => 'running'])['pagination']['total'] === 0,
|
|
'Interrupted records must not appear as actively running.');
|
|
$assert(Diagnostics::page($actor, ['outcome' => 'interrupted'])['pagination']['total'] === 1,
|
|
'Interrupted filter must match stale ongoing records.');
|
|
|
|
$malicious = Diagnostics::start(1, 'Bearer never-store-source-secret', $now, 8.0);
|
|
$malicious->stage('password=never-store-stage-secret');
|
|
$malicious->finish('failed', 'token=never-store-error-secret', 999, true);
|
|
$maliciousDto = Diagnostics::detail($actor, $malicious->id())['attempt'];
|
|
$assert($maliciousDto['error_code'] === 'unexpected_error' && $maliciousDto['stage'] === 'admission'
|
|
&& $maliciousDto['source'] === 'auto' && $maliciousDto['http_status'] === null && !$maliciousDto['applied'],
|
|
'Unknown raw diagnostics must be reduced to fixed safe values.');
|
|
CloudHostInventoryAttempt::where('attempt_id', $malicious->id())->update([
|
|
'stages_json' => '[{"stage":"password=never-display-stage-secret","duration_ms":4},'
|
|
. '{"stage":"capacity_request","duration_ms":5,"password":"never-display-extra-secret"}]',
|
|
'error_code' => 'token=never-display-error-secret',
|
|
]);
|
|
$clean = json_encode(Diagnostics::detail($actor, $malicious->id()), JSON_THROW_ON_ERROR);
|
|
$assert(!str_contains($clean, 'never-') && !str_contains($clean, 'credential'),
|
|
'Only allowlisted diagnostic keys may be exposed by the DTO.');
|
|
$assert(count(Diagnostics::detail($actor, $malicious->id())['attempt']['stages']) === 1,
|
|
'Unsafe stage entries must be discarded, extra keys stripped.');
|
|
|
|
$reject(static fn () => Diagnostics::page(['is_admin' => false]), 403);
|
|
$reject(static fn () => Diagnostics::detail([], $success->id()), 403);
|
|
$reject(static fn () => Diagnostics::detail($actor, '../secret'), 400);
|
|
$reject(static fn () => Diagnostics::detail($actor, str_repeat('0', 32)), 404);
|
|
foreach ([['host_id' => '-1'], ['outcome' => 'injected'], ['page' => '0'],
|
|
['per_page' => '10000'], ['host_id' => []], ['q' => 'not-supported']] as $input) {
|
|
$reject(static fn () => Diagnostics::page($actor, $input), 400);
|
|
}
|
|
$lastPage = Diagnostics::page($actor, ['page' => '900']);
|
|
$assert($lastPage['pagination']['page'] === $lastPage['pagination']['total_pages'],
|
|
'Out-of-range pages should clamp to the last page.');
|
|
|
|
// Capture only page/detail queries: they must never write or load host secrets.
|
|
$connection = $capsule->getConnection('default');
|
|
$connection->enableQueryLog();
|
|
Diagnostics::page($actor, ['host_id' => '1']);
|
|
Diagnostics::detail($actor, $timeout->id());
|
|
foreach ($connection->getQueryLog() as $query) {
|
|
$assert(str_starts_with(strtolower(ltrim($query['query'])), 'select'),
|
|
'Viewing diagnostic records must be database-read-only.');
|
|
$assert(!str_contains($query['query'], 'credential_cipher'), 'History must not select host credentials.');
|
|
}
|
|
$connection->disableQueryLog();
|
|
|
|
// Old history is removed in a bounded batch on a new attempt, not on a read.
|
|
$seed = CloudHostInventoryAttempt::find($timeout->id())->getAttributes();
|
|
unset($seed['sequence_id']);
|
|
for ($i = 1; $i <= 300; $i++) {
|
|
$row = $seed;
|
|
$row['attempt_id'] = sprintf('%032x', $i);
|
|
$row['started_at'] = $now - 8 * 86400;
|
|
$row['updated_at'] = $row['started_at'];
|
|
$row['finished_at'] = $row['started_at'];
|
|
CloudHostInventoryAttempt::query()->insert($row);
|
|
}
|
|
Diagnostics::start(3, 'auto', $now, 8.0)->finish('skipped');
|
|
$assert(CloudHostInventoryAttempt::where('started_at', '<', $now - 7 * 86400)->count() === 44,
|
|
'Retention cleanup must be bounded rather than deleting unbounded history per sync.');
|
|
|
|
// The per-host cap is independent of the age cutoff, including a burst of
|
|
// same-second attempts. Bulk fixtures avoid one query per synthetic row.
|
|
$rows = [];
|
|
for ($i = 10000; $i < 35020; $i++) {
|
|
$row = $seed;
|
|
$row['attempt_id'] = sprintf('%032x', $i);
|
|
$row['host_id'] = 4;
|
|
$row['started_at'] = $now - 1;
|
|
$row['updated_at'] = $now - 1;
|
|
$row['finished_at'] = $now - 1;
|
|
$rows[] = $row;
|
|
if (count($rows) === 100) {
|
|
CloudHostInventoryAttempt::query()->insert($rows);
|
|
$rows = [];
|
|
}
|
|
}
|
|
if ($rows !== []) {
|
|
CloudHostInventoryAttempt::query()->insert($rows);
|
|
}
|
|
$capAttempt = Diagnostics::start(4, 'auto', $now, 8.0);
|
|
$capAttempt->finish('skipped');
|
|
$assert(CloudHostInventoryAttempt::where('host_id', 4)->count() === 25000
|
|
&& CloudHostInventoryAttempt::find($capAttempt->id()) !== null,
|
|
'The per-host cap must prune older rows while preserving the current attempt.');
|
|
|
|
// Diagnostic storage failure is fail-open and cannot abort the actual inventory.
|
|
$schema->drop('cloud_host_inventory_attempts');
|
|
$fallback = Diagnostics::start(1, 'manual', $now, 8.0);
|
|
$fallback->stage('capacity_request');
|
|
$fallback->generation(20);
|
|
$fallback->finish('timeout', 'engine_http_timeout');
|
|
$assert(strlen($fallback->id()) === 32, 'An ID is still needed for engine correlation when DB logging fails.');
|
|
$reject(static fn () => Diagnostics::page($actor), 503);
|
|
$reject(static fn () => Diagnostics::detail($actor, $fallback->id()), 503);
|
|
|
|
echo "Cloud inventory diagnostic history tests passed.\n";
|
|
}
|