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/app/Services/Cloud/CloudConsoleTicketService.php

208 lines
8.1 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudConsoleTicket;
use App\Models\CloudHostAgent;
use App\Models\CloudInstance;
use App\Models\CloudSession;
/** Panel-owned, one-use browser ticket mapping for the local Agent gateway. */
final class CloudConsoleTicketService
{
private const BROWSER_TTL = 45;
private const MAX_CONNECTION_SECONDS = 28800;
public static function issue(
CloudInstance $instance,
array $actor,
array $agentTicket
): array {
$sessionId = $actor['session_id'] ?? null;
if (!is_string($sessionId)
|| preg_match('/^[a-f0-9]{64}$/D', $sessionId) !== 1) {
throw new CloudError('控制台需要有效的网页登录会话', 401);
}
$session = CloudSession::find($sessionId);
if ($session === null || (int) $session->user_id !== (int) $actor['user_id']
|| !CloudSessionService::active(
$sessionId,
(int) $instance->host_id,
(string) $instance->uuid
)) {
throw new CloudError('控制台会话已失效,请重新登录', 401);
}
[$ticket, $agentExpiry] = self::validateAgentTicket($agentTicket);
if (!self::agentReady((int) $instance->host_id)) {
throw new CloudError(
'宿主机 Agent 或面板网络尚未配置就绪,请重新配置并测试',
503
);
}
$now = time();
$ticketExpiry = min($agentExpiry, $now + self::BROWSER_TTL);
if ($ticketExpiry <= $now) {
throw new CloudError('宿主机 Agent 返回的控制台票据已经过期', 502);
}
$browserTicket = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
$record = new CloudConsoleTicket();
$record->ticket_hash = hash('sha256', $browserTicket);
$record->session_id = $sessionId;
$record->user_id = (int) $actor['user_id'];
$record->instance_id = (int) $instance->id;
$record->host_id = (int) $instance->host_id;
$record->vm_uuid = strtolower((string) $instance->uuid);
$record->sealed_agent_ticket = CloudSecrets::encrypt([
'ticket' => $ticket,
'host_id' => (int) $instance->host_id,
'vm_uuid' => strtolower((string) $instance->uuid),
], 'console-agent-ticket');
$record->agent_expires_at = $agentExpiry;
$record->ticket_expires_at = $ticketExpiry;
$record->connection_expires_at = min(
(int) $session->expires_at,
$now + self::MAX_CONNECTION_SECONDS
);
$record->consumed_at = null;
$record->connection_id = null;
$record->created_at = $now;
$record->save();
self::purgeExpired($now);
return [
'ticket' => $browserTicket,
'expires_in' => $ticketExpiry - $now,
'websocket_path' => '/engine-console',
];
}
public static function introspect(array $input): array
{
$allowed = ['ticket', 'connection_id', 'consume'];
foreach (array_keys($input) as $key) {
if (!is_string($key) || !in_array($key, $allowed, true)) {
throw new CloudError('控制台校验请求无效', 400);
}
}
$ticket = $input['ticket'] ?? null;
$consume = $input['consume'] ?? null;
$connectionId = $input['connection_id'] ?? null;
if (!is_string($ticket)
|| preg_match('/^[A-Za-z0-9_-]{32,256}$/D', $ticket) !== 1
|| !is_bool($consume)) {
throw new CloudError('控制台校验请求无效', 400);
}
if ($consume) {
if ($connectionId !== null) {
throw new CloudError('控制台首次校验不能包含连接编号', 400);
}
} elseif (!is_string($connectionId)
|| preg_match('/^[a-f0-9]{64}$/D', $connectionId) !== 1) {
throw new CloudError('控制台连接编号无效', 400);
}
$hash = hash('sha256', $ticket);
$connection = (new CloudConsoleTicket())->getConnection();
return $connection->transaction(static function () use (
$hash,
$consume,
$connectionId
): array {
$record = CloudConsoleTicket::query()
->where('ticket_hash', $hash)
->lockForUpdate()
->first();
$now = time();
if ($record === null
|| !CloudSessionService::active(
(string) $record->session_id,
(int) $record->host_id,
(string) $record->vm_uuid
)) {
return ['active' => false];
}
if (!self::agentReady((int) $record->host_id)) {
return ['active' => false];
}
if ($consume) {
if ($record->consumed_at !== null
|| (int) $record->ticket_expires_at <= $now
|| (int) $record->agent_expires_at <= $now) {
return ['active' => false];
}
$sealed = CloudSecrets::decrypt(
(string) $record->sealed_agent_ticket,
'console-agent-ticket'
);
if ((int) ($sealed['host_id'] ?? 0) !== (int) $record->host_id
|| !is_string($sealed['vm_uuid'] ?? null)
|| !hash_equals((string) $record->vm_uuid,
strtolower($sealed['vm_uuid']))
|| !is_string($sealed['ticket'] ?? null)
|| preg_match('/^[A-Za-z0-9_-]{32,256}$/D',
$sealed['ticket']) !== 1) {
return ['active' => false];
}
$newConnectionId = bin2hex(random_bytes(32));
$record->connection_id = $newConnectionId;
$record->consumed_at = $now;
$record->save();
return [
'active' => true,
'connection_id' => $newConnectionId,
'agent_id' => (string) $record->host_id,
'agent_ticket' => $sealed['ticket'],
'agent_expires_at' => gmdate(
'Y-m-d\\TH:i:s\\Z',
(int) $record->agent_expires_at
),
];
}
return [
'active' => $record->consumed_at !== null
&& (int) $record->connection_expires_at > $now
&& is_string($record->connection_id)
&& hash_equals($record->connection_id, $connectionId),
];
}, 3);
}
private static function agentReady(int $hostId): bool
{
$setting = CloudHostAgent::find($hostId);
return $setting !== null && $setting->isReady();
}
private static function validateAgentTicket(array $value): array
{
$ticket = $value['ticket'] ?? null;
$expiresAt = $value['expires_at'] ?? null;
if (array_is_list($value) || count($value) !== 2
|| !array_key_exists('ticket', $value)
|| !array_key_exists('expires_at', $value)
|| !is_string($ticket)
|| preg_match('/^[A-Za-z0-9_-]{32,256}$/D', $ticket) !== 1
|| !is_string($expiresAt)) {
throw new CloudError('宿主机 Agent 返回了无效控制台票据', 502);
}
try {
$expiry = (new \DateTimeImmutable($expiresAt))->getTimestamp();
} catch (\Throwable $error) {
throw new CloudError('宿主机 Agent 返回了无效票据期限', 502);
}
$now = time();
if ($expiry <= $now || $expiry > $now + 90) {
throw new CloudError('宿主机 Agent 返回了无效票据期限', 502);
}
return [$ticket, $expiry];
}
private static function purgeExpired(int $now): void
{
CloudConsoleTicket::query()
->where('connection_expires_at', '<=', $now - 3600)
->limit(100)
->delete();
}
}