60 || !is_string($nonce) || preg_match('/^[A-Za-z0-9_-]{16,128}$/D', $nonce) !== 1 || !is_string($digest) || preg_match('/^[a-f0-9]{64}$/D', $digest) !== 1 || !hash_equals(hash('sha256', $body), $digest) || !is_string($signature) || preg_match('/^[a-f0-9]{64}$/D', $signature) !== 1 || !is_string($actor) || strlen($actor) > 4096 || !self::validRelayActor($actor)) { return false; } $expected = hash_hmac('sha256', CloudAgentClient::canonical( $method, $path, $digest, $time, $nonce, $actor ), $key); return hash_equals($expected, $signature); } public function introspection($request, $response) { try { $body = (string) $request->getBody(); $secret = (string) Config::get('cloud_console_relay_secret', ''); $headers = [ 'timestamp' => $request->getHeaderLine('X-Virt-Timestamp'), 'nonce' => $request->getHeaderLine('X-Virt-Nonce'), 'digest' => $request->getHeaderLine('X-Virt-Content-SHA256'), 'actor' => $request->getHeaderLine('X-Virt-Actor'), 'signature' => $request->getHeaderLine('X-Virt-Signature'), ]; if ($request->getMethod() !== 'POST' || $request->getUri()->getPath() !== '/api/internal/cloud/session-introspection' || $request->getUri()->getQuery() !== '' || strlen($body) > 4096 || !self::validSignature( $request->getMethod(), $request->getRequestTarget(), $body, $headers, $secret, time() )) { return $response->withJson(['active' => false], 403) ->withHeader('Cache-Control', 'no-store'); } $redis = (new RedisClient())->getClient(); if ((string) $redis->set( 'virt-console-introspection-nonce:' . $headers['nonce'], '1', 'EX', 120, 'NX' ) !== 'OK') { return $response->withJson(['active' => false], 403) ->withHeader('Cache-Control', 'no-store'); } try { $value = json_decode($body, true, 8, JSON_THROW_ON_ERROR); } catch (\Throwable $error) { throw new CloudError('控制台校验请求无效', 400); } if (!is_array($value) || array_is_list($value)) { throw new CloudError('控制台校验请求无效', 400); } return $response->withJson( CloudConsoleTicketService::introspect($value) )->withHeader('Cache-Control', 'no-store'); } catch (CloudError $error) { return $response->withJson( ['active' => false], $error->httpStatus )->withHeader('Cache-Control', 'no-store'); } catch (\Throwable $error) { error_log('Cloud console introspection unavailable: ' . get_class($error)); return $response->withJson(['active' => false], 503) ->withHeader('Cache-Control', 'no-store'); } } private static function validRelayActor(string $encoded): bool { if (preg_match('/^[A-Za-z0-9_-]+$/D', $encoded) !== 1) { return false; } $padding = (4 - strlen($encoded) % 4) % 4; $raw = base64_decode( strtr($encoded, '-_', '+/') . str_repeat('=', $padding), true ); if ($raw === false) { return false; } try { $actor = json_decode($raw, true, 4, JSON_THROW_ON_ERROR); } catch (\Throwable $error) { return false; } return is_array($actor) && !array_is_list($actor) && count($actor) === 1 && ($actor['service'] ?? null) === 'console-relay'; } }