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
14 KiB
PHP
211 lines
14 KiB
PHP
<?php
|
|
namespace App\Services {
|
|
final class Config {
|
|
public static array $values = [
|
|
'authDriver' => 'cookie',
|
|
'super_admin' => '99',
|
|
'cloud_agent_gateway_secret' => 'kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk',
|
|
];
|
|
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; }
|
|
public static function forgetUser() {}
|
|
}
|
|
final class RedisClient {
|
|
public static array $values = [];
|
|
public static array $nonces = [];
|
|
public function getClient() { return $this; }
|
|
public function ttl($key) { return isset(self::$values[$key]) ? 60 : -2; }
|
|
public function get($key) { return self::$values[$key] ?? null; }
|
|
public function set($key, $value, ...$options) { if (isset(self::$nonces[$key])) { return null; } self::$nonces[$key] = true; return 'OK'; }
|
|
}
|
|
}
|
|
namespace App\Services\Cloud {
|
|
// Only a credential-reference double; this test does not assert production cryptography.
|
|
final class CloudSecrets {
|
|
private static array $memory = [];
|
|
public static function key(string $purpose): string { return str_repeat('k', 32); }
|
|
public static function encrypt(array $value): string { $id = bin2hex(random_bytes(16)); self::$memory[$id] = $value; return 'test-only:' . $id; }
|
|
public static function decrypt(string $value): array { return self::$memory[substr($value, 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\CloudSession;
|
|
use App\Services\Cloud\CloudSessionService;
|
|
use App\Services\Cloud\CloudAgentClient;
|
|
use App\Services\Cloud\CloudError;
|
|
use App\Services\LoginSessionRevocationService;
|
|
use App\Services\AdminCsrf;
|
|
use App\Services\Config;
|
|
use App\Services\RedisClient;
|
|
use App\Controllers\CloudInternalController;
|
|
use Slim\Http\Environment;
|
|
use Slim\Http\Request;
|
|
use Slim\Http\Response;
|
|
use Slim\Http\Body;
|
|
$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->integer('enable')->default(1); $t->integer('is_admin')->default(0); $t->integer('login_session_version')->default(0); });
|
|
$schema->create('cloud_sessions', function (Blueprint $t) { $t->string('id')->primary(); $t->integer('user_id'); $t->integer('version'); $t->string('fingerprint')->unique(); $t->string('auth_driver'); $t->text('auth_reference')->nullable(); $t->integer('active'); $t->integer('expires_at'); $t->integer('created_at'); });
|
|
$schema->create('cloud_instances', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('user_id'); $t->string('uuid'); $t->string('status'); $t->string('service_status')->default('active'); $t->integer('expires_at')->nullable(); });
|
|
$capsule->getConnection('default')->table('cloud_instances')->insert(['host_id' => 9, 'user_id' => 1, 'uuid' => '11111111-1111-4111-8111-111111111111', 'status' => 'active', 'expires_at' => time() + 3600]);
|
|
$capsule->getConnection('default')->table('cloud_instances')->insert(['host_id' => 9, 'user_id' => 2, 'uuid' => '22222222-2222-4222-8222-222222222222', 'status' => 'active', 'expires_at' => time() + 3600]);
|
|
$user = new User(); $user->id = 1; $user->enable = 1; $user->is_admin = false; $user->login_session_version = 0; $user->save(); $user->isLogin = true; \App\Services\Auth::$user = $user;
|
|
$_COOKIE = ['uid' => '1', 'key' => 'authenticated-cookie-reference', 'ip' => 'bound-cookie', 'expire_in' => (string) (time() + 300), 'login_session_version' => '0'];
|
|
$id = CloudSessionService::current($user);
|
|
$assert($id === CloudSessionService::current($user) && CloudSession::count() === 1, 'Concurrent-equivalent cookie duplicated session.');
|
|
$assert(CloudSessionService::active($id, 9, '11111111-1111-4111-8111-111111111111'), 'Active owner console rejected.');
|
|
$assert(!CloudSessionService::active($id, 9, '22222222-2222-4222-8222-222222222222')
|
|
&& !CloudSessionService::active($id, 8, '11111111-1111-4111-8111-111111111111'), 'Console crossed tenant or host boundary.');
|
|
$capsule->getConnection('default')->table('cloud_instances')->where('user_id', 1)->update(['service_status' => 'suspended_expired']);
|
|
$assert(!CloudSessionService::active($id, 9, '11111111-1111-4111-8111-111111111111'), 'Expired service retained console access.');
|
|
$capsule->getConnection('default')->table('cloud_instances')->where('user_id', 1)->update(['service_status' => 'active']);
|
|
User::where('id', 1)->update(['enable' => 0]); $assert(!CloudSessionService::active($id), 'Disabled user retained console.'); User::where('id', 1)->update(['enable' => 1]);
|
|
CloudSession::where('id', $id)->update(['expires_at' => time() - 1]); $assert(!CloudSessionService::active($id), 'Expired session retained console.'); CloudSession::where('id', $id)->update(['expires_at' => time() + 300]);
|
|
LoginSessionRevocationService::revokeUser($user); $assert(!CloudSessionService::active($id), 'Password/version change retained console.');
|
|
$_COOKIE['key'] = 'new-authenticated-cookie'; $_COOKIE['login_session_version'] = '1';
|
|
$new = CloudSessionService::current($user); CloudSessionService::revokeCurrent(); $assert(!CloudSessionService::active($new), 'Logout failed to revoke ticket session.');
|
|
try { CloudSessionService::current($user); throw new RuntimeException('Revoked fingerprint was reactivated.'); } catch (CloudError $expected) {}
|
|
Config::$values['authDriver'] = 'redis'; $_COOKIE = ['sid' => 'test-redis-session']; RedisClient::$values['test-redis-session'] = LoginSessionRevocationService::encodeRedisSession(1, 1);
|
|
$redisId = CloudSessionService::current($user); $assert(CloudSessionService::active($redisId), 'Live Redis session rejected.');
|
|
$assert(!str_contains((string) CloudSession::find($redisId)->auth_reference, 'test-redis-session'), 'Raw Redis bearer saved in reference.');
|
|
unset(RedisClient::$values['test-redis-session']); $assert(!CloudSessionService::active($redisId), 'Revoked Redis session retained console.');
|
|
RedisClient::$values['test-redis-session'] = LoginSessionRevocationService::encodeRedisSession(1, 0); $assert(!CloudSessionService::active($redisId), 'Redis snapshot version mismatch ignored.');
|
|
RedisClient::$values['test-redis-session'] = LoginSessionRevocationService::encodeRedisSession(1, 1);
|
|
User::where('id', 1)->update(['is_admin' => 1]); $assert(!CloudSessionService::active($redisId, 9, '22222222-2222-4222-8222-222222222222'), 'Readonly admin inherited other console.');
|
|
Config::$values['super_admin'] = '1'; $assert(CloudSessionService::active($redisId, 9, '22222222-2222-4222-8222-222222222222'), 'Superadmin console denied.'); Config::$values['super_admin'] = '99';
|
|
$body = json_encode(['ticket' => 'opaque-browser-ticket',
|
|
'connection_id' => '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef']);
|
|
$path = '/api/internal/cloud/session-introspection';
|
|
$timestamp = '1800000000';
|
|
$nonce = 'ConsoleRelayNonce_1234567890';
|
|
$relayActor = rtrim(strtr(base64_encode(json_encode([
|
|
'service' => 'agent-gateway',
|
|
], JSON_THROW_ON_ERROR)), '+/', '-_'), '=');
|
|
$digest = hash('sha256', $body);
|
|
$named = [
|
|
'timestamp' => $timestamp,
|
|
'nonce' => $nonce,
|
|
'digest' => $digest,
|
|
'actor' => $relayActor,
|
|
'signature' => hash_hmac('sha256', CloudAgentClient::canonical(
|
|
'POST', $path, $digest, $timestamp, $nonce, $relayActor
|
|
), str_repeat('k', 32)),
|
|
];
|
|
$assert(CloudInternalController::validSignature(
|
|
'POST', $path, $body, $named, str_repeat('k', 32), 1800000000
|
|
), 'Signed Agent-gateway introspection request was rejected.');
|
|
foreach ([
|
|
['POST', $path . '/extra', $body, 1800000000],
|
|
['GET', $path, $body, 1800000000],
|
|
['POST', $path, $body . ' ', 1800000000],
|
|
['POST', $path, $body, 1800000061],
|
|
] as [$method, $target, $raw, $now]) {
|
|
$assert(!CloudInternalController::validSignature(
|
|
$method, $target, $raw, $named, str_repeat('k', 32), $now
|
|
), 'Tampered or stale Agent-gateway signature was accepted.');
|
|
}
|
|
// Middleware uses the existing per-account CSRF session token and returns JSON instead of redirects.
|
|
Config::$values['authDriver'] = 'cookie'; $_COOKIE = ['uid' => '1', 'key' => 'third-auth-cookie', 'ip' => '', 'expire_in' => (string) (time() + 300), 'login_session_version' => '1'];
|
|
$request = Request::createFromEnvironment(Environment::mock(['REQUEST_METHOD' => 'POST', 'REQUEST_URI' => '/api/v1/vms/1/actions']));
|
|
$called = false; $next = function ($request, $response) use (&$called) { $called = true; return $response; };
|
|
$middleware = new \App\Middleware\CloudApi(); $reply = $middleware($request, new Response(), $next);
|
|
$assert($reply->getStatusCode() === 403 && !$called && !$reply->hasHeader('Location'), 'Missing CSRF did not fail with JSON403.');
|
|
$request = $request->withHeader('X-CSRF-Token', AdminCsrf::token()); $reply = $middleware($request, new Response(), $next); $assert($called && $reply->getStatusCode() === 200, 'Valid CSRF was rejected.');
|
|
$sessionCount = CloudSession::count();
|
|
$sshKeysWrite = Request::createFromEnvironment(Environment::mock([
|
|
'REQUEST_METHOD' => 'POST', 'REQUEST_URI' => '/api/v1/ssh-keys',
|
|
]));
|
|
$sshKeysWriteCalled = false;
|
|
$sshKeysWriteActor = null;
|
|
$sshKeysWriteNext = function ($request, $response) use (&$sshKeysWriteCalled,
|
|
&$sshKeysWriteActor) {
|
|
$sshKeysWriteCalled = true;
|
|
$sshKeysWriteActor = $request->getAttribute('cloud_actor');
|
|
return $response;
|
|
};
|
|
$reply = $middleware($sshKeysWrite, new Response(), $sshKeysWriteNext);
|
|
$assert($reply->getStatusCode() === 403 && !$sshKeysWriteCalled
|
|
&& CloudSession::count() === $sessionCount,
|
|
'SSH-key mutation without CSRF was accepted or created a cloud session.');
|
|
$sshKeysWrite = $sshKeysWrite->withHeader('X-CSRF-Token', AdminCsrf::token());
|
|
$reply = $middleware($sshKeysWrite, new Response(), $sshKeysWriteNext);
|
|
$assert($reply->getStatusCode() === 200 && $sshKeysWriteCalled
|
|
&& is_array($sshKeysWriteActor)
|
|
&& ($sshKeysWriteActor['session_id'] ?? null) === ''
|
|
&& CloudSession::count() === $sessionCount,
|
|
'Valid SSH-key mutation CSRF failed or created a console cloud session.');
|
|
$displayNameWrite = Request::createFromEnvironment(Environment::mock([
|
|
'REQUEST_METHOD' => 'PATCH', 'REQUEST_URI' => '/api/v1/vms/1/display-name',
|
|
]));
|
|
$displayNameCalled = false;
|
|
$displayNameActor = null;
|
|
$displayNameNext = function ($request, $response) use (&$displayNameCalled,
|
|
&$displayNameActor) {
|
|
$displayNameCalled = true;
|
|
$displayNameActor = $request->getAttribute('cloud_actor');
|
|
return $response;
|
|
};
|
|
$reply = $middleware($displayNameWrite, new Response(), $displayNameNext);
|
|
$assert($reply->getStatusCode() === 403 && !$displayNameCalled
|
|
&& CloudSession::count() === $sessionCount,
|
|
'Display-name mutation without CSRF was accepted or created a cloud session.');
|
|
$displayNameWrite = $displayNameWrite->withHeader(
|
|
'X-CSRF-Token', AdminCsrf::token()
|
|
);
|
|
$reply = $middleware($displayNameWrite, new Response(), $displayNameNext);
|
|
$assert($reply->getStatusCode() === 200 && $displayNameCalled
|
|
&& is_array($displayNameActor)
|
|
&& ($displayNameActor['session_id'] ?? null) === ''
|
|
&& CloudSession::count() === $sessionCount,
|
|
'Valid display-name CSRF failed or allocated a console cloud session.');
|
|
$billingRequest = Request::createFromEnvironment(Environment::mock([
|
|
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/api/v1/invoices/1/status',
|
|
]));
|
|
$billingActor = null;
|
|
$billingNext = function ($request, $response) use (&$billingActor) {
|
|
$billingActor = $request->getAttribute('cloud_actor');
|
|
return $response;
|
|
};
|
|
$reply = $middleware($billingRequest, new Response(), $billingNext);
|
|
$assert($reply->getStatusCode() === 200
|
|
&& is_array($billingActor) && ($billingActor['session_id'] ?? null) === ''
|
|
&& CloudSession::count() === $sessionCount,
|
|
'Invoice-only API authentication created or queried a console cloud session.');
|
|
$instancePageRequest = Request::createFromEnvironment(Environment::mock([
|
|
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/api/v1/vms/page?page=1',
|
|
]));
|
|
$instancePageActor = null;
|
|
$instancePageNext = function ($request, $response) use (&$instancePageActor) {
|
|
$instancePageActor = $request->getAttribute('cloud_actor');
|
|
return $response;
|
|
};
|
|
$reply = $middleware($instancePageRequest, new Response(), $instancePageNext);
|
|
$assert($reply->getStatusCode() === 200
|
|
&& is_array($instancePageActor) && ($instancePageActor['session_id'] ?? null) === ''
|
|
&& CloudSession::count() === $sessionCount,
|
|
'Database-only VM pagination created or queried a console cloud session.');
|
|
$sshKeysRequest = Request::createFromEnvironment(Environment::mock([
|
|
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/api/v1/ssh-keys',
|
|
]));
|
|
$sshKeysActor = null;
|
|
$sshKeysNext = function ($request, $response) use (&$sshKeysActor) {
|
|
$sshKeysActor = $request->getAttribute('cloud_actor');
|
|
return $response;
|
|
};
|
|
$reply = $middleware($sshKeysRequest, new Response(), $sshKeysNext);
|
|
$assert($reply->getStatusCode() === 200
|
|
&& is_array($sshKeysActor) && ($sshKeysActor['session_id'] ?? null) === ''
|
|
&& CloudSession::count() === $sessionCount,
|
|
'Database-only SSH-key API created or queried a console cloud session.');
|
|
$user->isLogin = false; $called = false; $reply = $middleware($request, new Response(), $next); $assert($reply->getStatusCode() === 401 && !$called && !$reply->hasHeader('Location'), 'Guest API redirected or passed through.');
|
|
echo "Cloud cookie/Redis revocation, signed introspection, admin console isolation and JSON CSRF checks passed (crypto reference double only).\n";
|
|
}
|