feat: improve admin virtual machine inventory and details
parent
5919dff9a9
commit
5905699742
@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Services\Cloud\CloudAccess;
|
||||
use App\Services\Cloud\CloudAdminInstanceService;
|
||||
|
||||
/** Read-only database snapshots; live power state uses the existing VM API. */
|
||||
final class CloudAdminInstanceController
|
||||
{
|
||||
public function index($request, $response)
|
||||
{
|
||||
return $response->withJson(CloudAdminInstanceService::page(
|
||||
$request->getAttribute('cloud_actor') ?? CloudAccess::actor(false),
|
||||
$request->getQueryParams()
|
||||
))->withHeader('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function detail($request, $response, $args)
|
||||
{
|
||||
return $response->withJson(CloudAdminInstanceService::detail(
|
||||
$request->getAttribute('cloud_actor') ?? CloudAccess::actor(false),
|
||||
(string) ($args['id'] ?? '')
|
||||
))->withHeader('Cache-Control', 'private, no-store');
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,473 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudHost;
|
||||
use App\Models\CloudInstance;
|
||||
use App\Models\CloudInvoice;
|
||||
use App\Models\CloudJob;
|
||||
use App\Models\CloudOrder;
|
||||
use App\Models\CloudServicePeriod;
|
||||
use App\Services\AdminDataMasker;
|
||||
|
||||
/** Database-only administrator inventory. Never hydrate engine/session state. */
|
||||
final class CloudAdminInstanceService
|
||||
{
|
||||
private const DETAIL_LIMIT = 20;
|
||||
private const SERVICE_LABELS = [
|
||||
'active' => '服务正常', 'exempt' => '免计费', 'expired' => '已到期',
|
||||
'expired_grace' => '到期宽限期',
|
||||
'suspending_expired' => '到期停用中', 'suspended_expired' => '到期已停用',
|
||||
'suspend_failed' => '停用失败', 'resume_pending' => '等待恢复',
|
||||
'resuming' => '恢复中', 'resume_failed' => '恢复失败',
|
||||
'purge_stopping' => '清理前关机中', 'purge_stop_failed' => '清理前关机失败',
|
||||
'purge_deleting' => '到期清理中', 'purge_failed' => '到期清理失败',
|
||||
];
|
||||
private const NETWORK_LABELS = [
|
||||
'active' => '正常', 'blocked_traffic' => '流量耗尽已断网',
|
||||
'blocking' => '正在限制网络', 'block_failed' => '限制网络失败',
|
||||
'blocking_expired' => '到期断网中', 'blocked_expired' => '到期已断网',
|
||||
'restore_pending' => '等待恢复网络', 'restoring' => '网络恢复中',
|
||||
'restore_failed' => '网络恢复失败',
|
||||
];
|
||||
|
||||
public static function page(array $actor, array $input = []): array
|
||||
{
|
||||
self::authorize($actor);
|
||||
$filters = self::filters($input);
|
||||
$now = time();
|
||||
$query = self::baseQuery();
|
||||
self::applyFilters($query, $filters, $now);
|
||||
$summary = (clone $query)->selectRaw(
|
||||
'COUNT(*) AS total, '
|
||||
. "COALESCE(SUM(CASE WHEN cloud_instances.service_status <> 'exempt' "
|
||||
. 'AND cloud_instances.expires_at > ? AND cloud_instances.expires_at <= ? '
|
||||
. 'THEN 1 ELSE 0 END), 0) AS expiring, '
|
||||
. "COALESCE(SUM(CASE WHEN cloud_instances.network_status <> 'active' "
|
||||
. 'THEN 1 ELSE 0 END), 0) AS network_restricted, '
|
||||
. 'COALESCE(SUM(CASE WHEN ' . self::attentionSql()
|
||||
. ' THEN 1 ELSE 0 END), 0) AS attention',
|
||||
[$now, $now + 7 * 86400, $now - 86400]
|
||||
)->first();
|
||||
$counts = [];
|
||||
foreach (['total', 'expiring', 'network_restricted', 'attention'] as $key) {
|
||||
$counts[$key] = max(0, (int) ($summary?->$key ?? 0));
|
||||
}
|
||||
$pages = max(1, (int) ceil($counts['total'] / $filters['per_page']));
|
||||
$filters['page'] = min($filters['page'], $pages);
|
||||
if ($filters['sort'] === 'expiry') {
|
||||
$query->orderByRaw('CASE WHEN cloud_instances.expires_at IS NULL THEN 1 ELSE 0 END')
|
||||
->orderBy('cloud_instances.expires_at')->orderBy('cloud_instances.id');
|
||||
} else {
|
||||
$direction = $filters['sort'] === 'oldest' ? 'asc' : 'desc';
|
||||
$query->orderBy('cloud_instances.created_at', $direction)
|
||||
->orderBy('cloud_instances.id', $direction);
|
||||
}
|
||||
$records = $query->select(self::columns())->selectRaw(
|
||||
'(SELECT MAX(j.id) FROM cloud_jobs j WHERE '
|
||||
. self::jobRelationSql('j')
|
||||
. " AND j.status IN ('queued','running','uncertain')) AS active_job_id"
|
||||
)->offset(($filters['page'] - 1) * $filters['per_page'])
|
||||
->limit($filters['per_page'])->get();
|
||||
$jobs = self::activeJobs($records);
|
||||
$items = [];
|
||||
foreach ($records as $instance) {
|
||||
$items[] = self::row($instance, $actor,
|
||||
$jobs[(string) $instance->active_job_id] ?? null, $now);
|
||||
}
|
||||
$hosts = [];
|
||||
foreach (CloudHost::orderBy('name')->orderBy('id')->get(['id', 'name', 'region']) as $host) {
|
||||
$hosts[] = ['id' => (string) $host->id, 'name' => (string) $host->name,
|
||||
'region' => (string) $host->region];
|
||||
}
|
||||
$from = $counts['total'] === 0 ? 0
|
||||
: ($filters['page'] - 1) * $filters['per_page'] + 1;
|
||||
return [
|
||||
'items' => $items,
|
||||
'pagination' => ['page' => $filters['page'], 'per_page' => $filters['per_page'],
|
||||
'total' => $counts['total'], 'total_pages' => $pages,
|
||||
'from' => $from, 'to' => $from === 0 ? 0 : $from + count($items) - 1],
|
||||
'summary' => $counts, 'filters' => $filters, 'hosts' => $hosts,
|
||||
'generated_at' => $now,
|
||||
];
|
||||
}
|
||||
|
||||
public static function detail(array $actor, string $id): array
|
||||
{
|
||||
self::authorize($actor);
|
||||
$id = self::positiveInteger($id, '实例编号');
|
||||
$instance = self::baseQuery()->where('cloud_instances.id', $id)
|
||||
->first(self::columns());
|
||||
if ($instance === null) {
|
||||
throw new CloudError('虚拟机不存在', 404);
|
||||
}
|
||||
// A creation task can predate the instance row. Only a verified order
|
||||
// may supply that fallback; an explicit, different instance_id wins.
|
||||
$orderId = null;
|
||||
if ($instance->order_id !== null) {
|
||||
$order = CloudOrder::where('id', $instance->order_id)
|
||||
->where('user_id', $instance->user_id)
|
||||
->where(static function ($query) use ($instance): void {
|
||||
$query->whereNull('instance_id')->orWhere('instance_id', $instance->id);
|
||||
})->first(['id']);
|
||||
$orderId = $order?->id;
|
||||
}
|
||||
$relation = static function ($query) use ($instance, $orderId): void {
|
||||
$query->where('instance_id', $instance->id);
|
||||
if ($orderId !== null) {
|
||||
$query->orWhere(static function ($fallback) use ($orderId): void {
|
||||
$fallback->whereNull('instance_id')->where('order_id', $orderId);
|
||||
});
|
||||
}
|
||||
};
|
||||
// job.user_id is the action's actor, not necessarily the instance owner.
|
||||
$jobRecords = CloudJob::where($relation)->orderByDesc('id')
|
||||
->limit(self::DETAIL_LIMIT + 1)->get(self::jobColumns())->all();
|
||||
$jobsTruncated = count($jobRecords) > self::DETAIL_LIMIT;
|
||||
$jobs = array_map([self::class, 'jobRow'], array_slice($jobRecords, 0, self::DETAIL_LIMIT));
|
||||
$active = CloudJob::where($relation)->whereIn('status', ['queued', 'running', 'uncertain'])
|
||||
->orderByDesc('id')->first(self::jobColumns());
|
||||
$invoiceRecords = CloudInvoice::where('user_id', $instance->user_id)
|
||||
->where($relation)->orderByDesc('id')->limit(self::DETAIL_LIMIT + 1)
|
||||
->get(['id', 'purpose', 'status', 'amount', 'created_at', 'due_at'])->all();
|
||||
$invoicesTruncated = count($invoiceRecords) > self::DETAIL_LIMIT;
|
||||
$now = time();
|
||||
$invoices = [];
|
||||
foreach (array_slice($invoiceRecords, 0, self::DETAIL_LIMIT) as $invoice) {
|
||||
$status = (string) $invoice->status;
|
||||
if ($status === 'open' && (int) $invoice->due_at <= $now) {
|
||||
$status = 'overdue';
|
||||
}
|
||||
$invoices[] = ['id' => (string) $invoice->id,
|
||||
'purpose' => (string) $invoice->purpose, 'status' => $status,
|
||||
'amount' => self::money($invoice->amount),
|
||||
'created_at' => max(0, (int) $invoice->created_at),
|
||||
'detail_url' => '/admin/billing?detail=' . $invoice->id];
|
||||
}
|
||||
$row = self::row($instance, $actor, $active === null ? null : self::jobRow($active), $now);
|
||||
$spec = self::spec($instance->spec_json);
|
||||
$period = $instance->current_period_id === null ? null
|
||||
: CloudServicePeriod::where('id', $instance->current_period_id)
|
||||
->where('instance_id', $instance->id)->first(['starts_at', 'ends_at']);
|
||||
$dns = is_array($spec['dns_servers'] ?? null) ? $spec['dns_servers'] : [];
|
||||
$dns = array_values(array_filter(array_slice($dns, 0, 8),
|
||||
static fn ($value): bool => is_string($value)
|
||||
&& filter_var($value, FILTER_VALIDATE_IP) !== false));
|
||||
$row += [
|
||||
'public_ip_cidr' => self::text($spec['public_ip_cidr'] ?? null, 64),
|
||||
'gateway' => self::ip($spec['gateway'] ?? null), 'dns_servers' => $dns,
|
||||
'bandwidth_mbps' => self::positiveOrNull($spec['bandwidth_mbps'] ?? null),
|
||||
'os_source' => self::text($spec['os_source'] ?? null, 32),
|
||||
'login_name' => self::text($spec['login_name'] ?? null, 32),
|
||||
// The engine can extend its UUID-derived name on collisions. Do
|
||||
// not invent that name from a UUID when it was never persisted.
|
||||
'engine_name' => self::resourceName($spec['engine_name'] ?? null),
|
||||
'current_period_started_at' => $period === null ? null : (int) $period->starts_at,
|
||||
'current_period_ends_at' => $period === null ? null : (int) $period->ends_at,
|
||||
'renewal_price' => $instance->renewal_price === null ? null : self::money($instance->renewal_price),
|
||||
'renewal_days' => max(0, (int) $instance->renewal_days),
|
||||
'renewal_traffic_bytes' => max(0, (int) $instance->renewal_traffic_bytes),
|
||||
'traffic_download_bytes' => max(0, (int) $instance->traffic_download_bytes),
|
||||
'traffic_upload_bytes' => max(0, (int) $instance->traffic_upload_bytes),
|
||||
'updated_at' => max(0, (int) $instance->updated_at),
|
||||
];
|
||||
return ['instance' => $row, 'jobs' => $jobs, 'jobs_truncated' => $jobsTruncated,
|
||||
'invoices' => $invoices, 'invoices_truncated' => $invoicesTruncated];
|
||||
}
|
||||
|
||||
public static function filters(array $input): array
|
||||
{
|
||||
$allowed = ['q', 'user_id', 'host_id', 'service_status', 'expiry', 'attention',
|
||||
'sort', 'page', 'per_page'];
|
||||
foreach ($input as $key => $value) {
|
||||
if (!in_array($key, $allowed, true) || (!is_string($value) && !is_int($value))) {
|
||||
throw new CloudError('筛选参数无效', 400);
|
||||
}
|
||||
}
|
||||
$q = trim((string) ($input['q'] ?? ''));
|
||||
if (mb_strlen($q, 'UTF-8') > 80 || preg_match('/[\x00-\x1f\x7f]/u', $q) !== 0) {
|
||||
throw new CloudError('搜索关键词最多 80 个字符,且不能包含控制字符', 400);
|
||||
}
|
||||
$filters = ['q' => $q];
|
||||
foreach (['user_id', 'host_id'] as $key) {
|
||||
$value = (string) ($input[$key] ?? '');
|
||||
$filters[$key] = $value === '' ? null : self::positiveInteger($value, $key);
|
||||
}
|
||||
foreach ([
|
||||
'service_status' => array_merge([''], array_keys(self::SERVICE_LABELS)),
|
||||
'expiry' => ['all', 'soon', 'expired', 'exempt'],
|
||||
'attention' => ['all', 'network', 'jobs'],
|
||||
'sort' => ['newest', 'oldest', 'expiry'],
|
||||
] as $key => $values) {
|
||||
$value = (string) ($input[$key] ?? $values[0]);
|
||||
if (!in_array($value, $values, true)) {
|
||||
throw new CloudError('筛选参数 ' . $key . ' 无效', 400);
|
||||
}
|
||||
$filters[$key] = $value;
|
||||
}
|
||||
$filters['page'] = self::positiveInteger((string) ($input['page'] ?? '1'), '页码');
|
||||
$filters['per_page'] = self::positiveInteger((string) ($input['per_page'] ?? '20'), '每页条数');
|
||||
if (!in_array($filters['per_page'], [20, 50, 100], true)) {
|
||||
throw new CloudError('每页条数只能为 20、50 或 100', 400);
|
||||
}
|
||||
return $filters;
|
||||
}
|
||||
|
||||
private static function authorize(array $actor): void
|
||||
{
|
||||
if (!($actor['is_admin'] ?? false)) {
|
||||
throw new CloudError('需要管理员权限', 403);
|
||||
}
|
||||
}
|
||||
|
||||
private static function baseQuery()
|
||||
{
|
||||
return CloudInstance::where('cloud_instances.status', '<>', 'deleted')
|
||||
->leftJoin('user as instance_user', 'instance_user.id', '=', 'cloud_instances.user_id')
|
||||
->leftJoin('cloud_hosts as instance_host', 'instance_host.id', '=', 'cloud_instances.host_id')
|
||||
->leftJoin('shop as instance_plan', 'instance_plan.id', '=', 'cloud_instances.plan_id');
|
||||
}
|
||||
|
||||
private static function columns(): array
|
||||
{
|
||||
$columns = ['id', 'uuid', 'host_id', 'user_id', 'order_id', 'current_period_id',
|
||||
'name', 'status', 'service_status', 'network_status', 'expires_at',
|
||||
'renewal_price', 'renewal_days', 'renewal_traffic_bytes', 'traffic_quota_bytes',
|
||||
'traffic_download_bytes', 'traffic_upload_bytes', 'traffic_synced_at',
|
||||
'spec_json', 'created_at', 'updated_at'];
|
||||
return array_merge(array_map(static fn ($key): string => 'cloud_instances.' . $key, $columns), [
|
||||
'instance_user.user_name as owner_name', 'instance_user.email as owner_email',
|
||||
'instance_host.name as host_name', 'instance_host.region as host_region',
|
||||
'instance_plan.name as plan_name',
|
||||
]);
|
||||
}
|
||||
|
||||
private static function applyFilters($query, array $filters, int $now): void
|
||||
{
|
||||
foreach (['user_id', 'host_id'] as $key) {
|
||||
if ($filters[$key] !== null) {
|
||||
$query->where('cloud_instances.' . $key, $filters[$key]);
|
||||
}
|
||||
}
|
||||
if ($filters['service_status'] !== '') {
|
||||
$query->where('cloud_instances.service_status', $filters['service_status']);
|
||||
}
|
||||
if ($filters['expiry'] === 'exempt') {
|
||||
$query->where('cloud_instances.service_status', 'exempt');
|
||||
} elseif ($filters['expiry'] === 'soon') {
|
||||
$query->where('cloud_instances.service_status', '<>', 'exempt')
|
||||
->where('cloud_instances.expires_at', '>', $now)
|
||||
->where('cloud_instances.expires_at', '<=', $now + 7 * 86400);
|
||||
} elseif ($filters['expiry'] === 'expired') {
|
||||
$query->where('cloud_instances.service_status', '<>', 'exempt')
|
||||
->whereNotNull('cloud_instances.expires_at')->where('cloud_instances.expires_at', '<=', $now);
|
||||
}
|
||||
if ($filters['attention'] === 'network') {
|
||||
$query->where('cloud_instances.network_status', '<>', 'active');
|
||||
} elseif ($filters['attention'] === 'jobs') {
|
||||
$query->whereRaw(self::attentionSql(), [$now - 86400]);
|
||||
}
|
||||
if ($filters['q'] === '') {
|
||||
return;
|
||||
}
|
||||
$like = '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $filters['q']) . '%';
|
||||
$query->where(static function ($search) use ($filters, $like): void {
|
||||
$search->whereRaw("cloud_instances.name LIKE ? ESCAPE '!'", [$like])
|
||||
->orWhereRaw("cloud_instances.uuid LIKE ? ESCAPE '!'", [$like]);
|
||||
foreach (['public_ip_cidr', 'public_ip'] as $key) {
|
||||
// CASE also permits searching databases containing a damaged
|
||||
// old specification without calling JSON_EXTRACT on it.
|
||||
$search->orWhereRaw("(CASE WHEN JSON_VALID(cloud_instances.spec_json) "
|
||||
. "THEN JSON_EXTRACT(cloud_instances.spec_json, '$." . $key . "') "
|
||||
. "ELSE '' END) LIKE ? ESCAPE '!'", [$like]);
|
||||
}
|
||||
if (preg_match('/^[1-9][0-9]*$/D', $filters['q']) === 1
|
||||
&& strlen($filters['q']) < 19) {
|
||||
$search->orWhere('cloud_instances.id', (int) $filters['q'])
|
||||
->orWhere('cloud_instances.user_id', (int) $filters['q']);
|
||||
}
|
||||
// Match the billing search privacy boundary: readonly operators
|
||||
// must not infer a masked account via repeated keyword searches.
|
||||
if (!AdminDataMasker::shouldMask()) {
|
||||
$search->orWhereRaw("instance_user.user_name LIKE ? ESCAPE '!'", [$like])
|
||||
->orWhereRaw("instance_user.email LIKE ? ESCAPE '!'", [$like]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static function jobRelationSql(string $alias): string
|
||||
{
|
||||
return '(' . $alias . '.instance_id = cloud_instances.id OR (' . $alias
|
||||
. '.instance_id IS NULL AND ' . $alias . '.order_id = cloud_instances.order_id '
|
||||
. 'AND EXISTS (SELECT 1 FROM cloud_orders job_order WHERE '
|
||||
. 'job_order.id = cloud_instances.order_id '
|
||||
. 'AND job_order.user_id = cloud_instances.user_id '
|
||||
. 'AND (job_order.instance_id IS NULL OR job_order.instance_id = cloud_instances.id))))';
|
||||
}
|
||||
|
||||
private static function attentionSql(): string
|
||||
{
|
||||
return 'EXISTS (SELECT 1 FROM cloud_jobs attention_job WHERE '
|
||||
. self::jobRelationSql('attention_job')
|
||||
. " AND (attention_job.status = 'uncertain' OR (attention_job.status = 'failed' "
|
||||
. 'AND attention_job.updated_at >= ?)))';
|
||||
}
|
||||
|
||||
private static function activeJobs($records): array
|
||||
{
|
||||
$ids = $records->pluck('active_job_id')->filter()->unique()->values()->all();
|
||||
$result = [];
|
||||
if ($ids !== []) {
|
||||
foreach (CloudJob::whereIn('id', $ids)->get(self::jobColumns()) as $job) {
|
||||
$result[(string) $job->id] = self::jobRow($job);
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function jobColumns(): array
|
||||
{
|
||||
return ['id', 'kind', 'status', 'attempts', 'error_code', 'result_json', 'created_at', 'updated_at'];
|
||||
}
|
||||
|
||||
private static function jobRow($job): array
|
||||
{
|
||||
$result = json_decode((string) $job->result_json, true);
|
||||
return ['id' => (string) $job->id, 'kind' => (string) $job->kind,
|
||||
'status' => (string) $job->status, 'attempts' => max(0, (int) $job->attempts),
|
||||
'error' => self::jobText($job->error_code),
|
||||
'phase' => self::jobText(is_array($result) ? ($result['phase'] ?? null) : null),
|
||||
'created_at' => max(0, (int) $job->created_at),
|
||||
'updated_at' => max(0, (int) $job->updated_at)];
|
||||
}
|
||||
|
||||
private static function row($instance, array $actor, ?array $job, int $now): array
|
||||
{
|
||||
$spec = self::spec($instance->spec_json);
|
||||
$cidr = self::text($spec['public_ip_cidr'] ?? null, 64);
|
||||
$publicIp = self::ip($cidr === null ? ($spec['public_ip'] ?? null) : explode('/', $cidr, 2)[0]);
|
||||
$service = (string) $instance->service_status;
|
||||
$expires = $instance->expires_at === null ? null : (int) $instance->expires_at;
|
||||
$used = max(0, (int) $instance->traffic_download_bytes) + max(0, (int) $instance->traffic_upload_bytes);
|
||||
$quota = max(0, (int) $instance->traffic_quota_bytes);
|
||||
$row = [
|
||||
'id' => (string) $instance->id, 'name' => (string) $instance->name,
|
||||
'uuid' => (string) $instance->uuid, 'user_id' => (string) $instance->user_id,
|
||||
'user_name' => AdminDataMasker::account($instance->owner_name ?? ''),
|
||||
'user_email' => AdminDataMasker::email($instance->owner_email ?? ''),
|
||||
'user_url' => ($actor['is_super_admin'] ?? false) && ($actor['can_manage'] ?? false)
|
||||
? '/admin/user/' . $instance->user_id . '/edit' : '',
|
||||
'host_id' => (string) $instance->host_id, 'host_name' => (string) ($instance->host_name ?? ''),
|
||||
'region' => self::text($instance->host_region, 64)
|
||||
?? self::text($spec['region'] ?? $spec['location'] ?? null, 64) ?? '',
|
||||
'plan_name' => self::text($spec['plan_name'] ?? null, 120)
|
||||
?? self::text($instance->plan_name, 120) ?? '',
|
||||
'os_name' => self::text($spec['os_name'] ?? $spec['install_iso'] ?? null, 255) ?? '',
|
||||
'public_ip' => $publicIp ?? '',
|
||||
'vcpu' => self::positiveOrNull($spec['vcpu'] ?? null),
|
||||
'memory_mib' => self::positiveOrNull($spec['memory_mib'] ?? null),
|
||||
'disk_gib' => self::positiveOrNull($spec['disk_gib'] ?? null),
|
||||
'instance_status' => (string) $instance->status, 'service_status' => $service,
|
||||
'network_status' => (string) $instance->network_status, 'service_expires_at' => $expires,
|
||||
'traffic_used_bytes' => $used, 'traffic_quota_bytes' => $quota,
|
||||
'traffic_synced_at' => max(0, (int) $instance->traffic_synced_at),
|
||||
'created_at' => max(0, (int) $instance->created_at), 'active_job' => $job,
|
||||
'state' => 'unknown',
|
||||
'can_manage' => ($actor['is_admin'] ?? false) && ($actor['is_super_admin'] ?? false)
|
||||
&& ($actor['can_manage'] ?? false),
|
||||
'detail_url' => '/user/cloud/instances/' . $instance->id,
|
||||
];
|
||||
$row['display'] = [
|
||||
'configuration' => ($row['vcpu'] === null ? '—' : $row['vcpu'] . ' 核') . ' · '
|
||||
. ($row['memory_mib'] === null ? '—' : self::number($row['memory_mib'] / 1024) . ' GiB') . ' · '
|
||||
. ($row['disk_gib'] === null ? '—' : self::number($row['disk_gib']) . ' GiB'),
|
||||
'traffic' => $row['traffic_synced_at'] === 0 ? '未获取'
|
||||
: self::bytes($used) . ($service === 'exempt' ? ' · 免计费' : ' / ' . self::bytes($quota)),
|
||||
'expiry' => $service === 'exempt' ? '免计费' : ($expires === null ? '—'
|
||||
: ($expires <= $now ? '已到期' : '剩余 ' . (int) ceil(($expires - $now) / 86400) . ' 天')),
|
||||
'service' => $service === 'active' && $expires === null ? '期限未记录'
|
||||
: ($service === 'active' && $expires <= $now
|
||||
? '已到期' : (self::SERVICE_LABELS[$service] ?? '未知')),
|
||||
'network' => self::NETWORK_LABELS[(string) $instance->network_status] ?? '未知',
|
||||
'lifecycle' => ['active' => '在管', 'deleting' => '删除中', 'delete_failed' => '删除失败']
|
||||
[(string) $instance->status] ?? '未知',
|
||||
];
|
||||
return $row;
|
||||
}
|
||||
|
||||
private static function spec($json): array
|
||||
{
|
||||
$value = json_decode((string) $json, true);
|
||||
return CloudInstanceMetadata::sanitizeSpec(is_array($value) && !array_is_list($value) ? $value : []);
|
||||
}
|
||||
|
||||
private static function positiveInteger(string $value, string $label): int
|
||||
{
|
||||
if (preg_match('/^[1-9][0-9]*$/D', $value) !== 1
|
||||
|| filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) === false) {
|
||||
throw new CloudError($label . ' 无效', 400);
|
||||
}
|
||||
return (int) $value;
|
||||
}
|
||||
|
||||
private static function positiveOrNull($value): ?float
|
||||
{
|
||||
if ((!is_int($value) && !is_float($value) && !is_string($value)) || !is_numeric($value)) {
|
||||
return null;
|
||||
}
|
||||
$number = (float) $value;
|
||||
return is_finite($number) && $number > 0 && $number <= 1048576 ? $number : null;
|
||||
}
|
||||
|
||||
private static function text($value, int $limit): ?string
|
||||
{
|
||||
if (!is_string($value) || trim($value) === '' || preg_match('/[\x00-\x1f\x7f]/u', $value) !== 0) {
|
||||
return null;
|
||||
}
|
||||
return mb_substr(trim($value), 0, $limit, 'UTF-8');
|
||||
}
|
||||
|
||||
private static function ip($value): ?string
|
||||
{
|
||||
return is_string($value) && filter_var($value, FILTER_VALIDATE_IP) !== false ? $value : null;
|
||||
}
|
||||
|
||||
private static function resourceName($value): ?string
|
||||
{
|
||||
return is_string($value) && preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/D', $value) === 1
|
||||
? $value : null;
|
||||
}
|
||||
|
||||
private static function jobText($value): ?string
|
||||
{
|
||||
$text = self::text($value, 300);
|
||||
if ($text === null) {
|
||||
return null;
|
||||
}
|
||||
// Progress text is not a credential viewer, even for superadmins.
|
||||
$text = preg_replace('/\bBearer\s+\S+/i', 'Bearer [已移除]', $text);
|
||||
$text = preg_replace('#(https?://[^:/\s]+:)[^@\s/]+@#i', '$1[已移除]@', $text);
|
||||
$text = preg_replace('/((?:"|\x27)?(?:password|passwd|api[_ -]?key|access[_ -]?token|refresh[_ -]?token|token|secret|credential|private[_ -]?key)(?:"|\x27)?\s*[:=]\s*)(?:"[^"]*"|\x27[^\x27]*\x27|[^\s,;]+)/i', '$1[已移除]', $text);
|
||||
return AdminDataMasker::sensitiveText($text);
|
||||
}
|
||||
|
||||
private static function bytes(int $bytes): string
|
||||
{
|
||||
foreach (['TiB' => 1099511627776, 'GiB' => 1073741824, 'MiB' => 1048576, 'KiB' => 1024] as $unit => $factor) {
|
||||
if ($bytes >= $factor) {
|
||||
return self::number($bytes / $factor) . ' ' . $unit;
|
||||
}
|
||||
}
|
||||
return $bytes . ' B';
|
||||
}
|
||||
|
||||
private static function number(float $value): string
|
||||
{
|
||||
return rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.');
|
||||
}
|
||||
|
||||
private static function money($value): string
|
||||
{
|
||||
return CloudMoney::decimal(CloudMoney::cents($value));
|
||||
}
|
||||
}
|
||||
@ -1,41 +1,62 @@
|
||||
{assign var=admin_title value='虚拟机实例'}
|
||||
{assign var=admin_title value='虚拟机管理'}
|
||||
{assign var=admin_active value='cloud-instances'}
|
||||
{include file='admin/static_header.tpl'}
|
||||
{if !$instance_page}
|
||||
{assign var=instance_page value=['items'=>[], 'hosts'=>[], 'filters'=>['q'=>'', 'user_id'=>'', 'host_id'=>'', 'service_status'=>'', 'expiry'=>'all', 'attention'=>'all', 'sort'=>'newest'], 'pagination'=>['page'=>1, 'per_page'=>20, 'total'=>'—', 'total_pages'=>1], 'summary'=>['total'=>'—', 'expiring'=>'—', 'network_restricted'=>'—', 'attention'=>'—']]}
|
||||
{/if}
|
||||
|
||||
<link rel="stylesheet" href="/cloud/admin.css?v={$venix_asset_version}">
|
||||
<section class="cloud-admin" data-cloud-admin="instances">
|
||||
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column cloud-admin-page-head">
|
||||
<div class="flex-grow-1">
|
||||
<p class="admin-eyebrow mb-1">Compute</p>
|
||||
<h4 class="fs-20 fw-semibold mb-1">虚拟机实例</h4>
|
||||
<p class="text-muted mb-0">跨宿主机查看已关联的实例、所属用户与资源配置。</p>
|
||||
</div>
|
||||
<div class="text-sm-end mt-3 mt-sm-0 cloud-admin-actions">
|
||||
<p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status" aria-live="polite">正在加载…</p>
|
||||
<button id="admin-records-refresh" class="btn btn-light" type="button">
|
||||
<i class="mdi mdi-refresh me-1"></i>刷新
|
||||
</button>
|
||||
</div>
|
||||
<main data-admin-instances>
|
||||
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column gap-3">
|
||||
<div class="flex-grow-1"><h1 class="fs-20 fw-semibold mb-1">虚拟机管理</h1><p class="text-muted mb-0">集中查看实例、服务期限和运行异常;电源状态异步更新,不影响列表加载。</p></div>
|
||||
<div class="admin-checkout-actions text-sm-end"><span class="admin-config-status {if $instance_error}is-error{else}is-success{/if}" id="instances-notice" role="status" aria-live="polite">{if $instance_error}{$instance_error|escape}{else}已读取 {$instance_page.pagination.total|escape} 台实例{/if}</span><button class="btn btn-light" id="instances-refresh" type="button"><i class="mdi mdi-refresh me-1" aria-hidden="true"></i>刷新</button></div>
|
||||
</div>
|
||||
|
||||
<div class="card cloud-admin-table-card">
|
||||
<div class="card-body">
|
||||
<div class="cloud-admin-card-head">
|
||||
<div>
|
||||
<p class="admin-eyebrow mb-1">Instances</p>
|
||||
<h5 class="mb-1">实例目录</h5>
|
||||
<p class="text-muted mb-0">客户资源与操作权限仍由后台校验,此页面仅用于集中查看。</p>
|
||||
</div>
|
||||
<span class="cloud-admin-card-icon"><i class="mdi mdi-server-network"></i></span>
|
||||
</div>
|
||||
<div class="table-responsive cloud-admin-table-wrap">
|
||||
<table class="table table-hover align-middle mb-0 cloud-admin-table">
|
||||
<thead><tr><th>实例</th><th>用户</th><th>宿主机</th><th>状态</th><th>公网 IP</th><th>配置</th></tr></thead>
|
||||
<tbody id="admin-records"><tr class="cloud-admin-placeholder"><td colspan="6">实例数据加载中</td></tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<section class="row g-3 mb-3 admin-billing-summary" aria-label="当前筛选实例摘要">
|
||||
<div class="col-6 col-xl-3"><article class="card admin-stat-card"><div class="card-body d-flex align-items-center justify-content-between gap-2"><div><h2 class="text-muted fs-14 fw-normal mb-1">在管实例</h2><strong class="admin-stat-value" id="instances-total">{$instance_page.summary.total|escape}</strong></div><span class="admin-stat-icon text-primary"><i class="mdi mdi-server-network" aria-hidden="true"></i></span></div></article></div>
|
||||
<div class="col-6 col-xl-3"><article class="card admin-stat-card"><div class="card-body d-flex align-items-center justify-content-between gap-2"><div><h2 class="text-muted fs-14 fw-normal mb-1">7 天内到期</h2><strong class="admin-stat-value" id="instances-expiring">{$instance_page.summary.expiring|escape}</strong></div><span class="admin-stat-icon text-warning"><i class="mdi mdi-calendar-clock" aria-hidden="true"></i></span></div></article></div>
|
||||
<div class="col-6 col-xl-3"><article class="card admin-stat-card"><div class="card-body d-flex align-items-center justify-content-between gap-2"><div><h2 class="text-muted fs-14 fw-normal mb-1">网络受限</h2><strong class="admin-stat-value" id="instances-network-restricted">{$instance_page.summary.network_restricted|escape}</strong></div><span class="admin-stat-icon text-danger"><i class="mdi mdi-lan-disconnect" aria-hidden="true"></i></span></div></article></div>
|
||||
<div class="col-6 col-xl-3"><article class="card admin-stat-card"><div class="card-body d-flex align-items-center justify-content-between gap-2"><div><h2 class="text-muted fs-14 fw-normal mb-1">异常任务实例</h2><strong class="admin-stat-value" id="instances-attention">{$instance_page.summary.attention|escape}</strong></div><span class="admin-stat-icon text-warning"><i class="mdi mdi-alert-circle-outline" aria-hidden="true"></i></span></div></article></div>
|
||||
</section>
|
||||
<section class="card mb-3 admin-billing-filter" aria-labelledby="instances-filter-title">
|
||||
<div class="card-header"><h2 class="h5 card-title mb-1" id="instances-filter-title">查找实例</h2><span class="text-muted fs-13">摘要和列表均按当前条件统计。异常任务包含待核对及近 24 小时失败任务。</span></div>
|
||||
<div class="card-body"><form id="instances-filter" class="row g-2 align-items-end" method="get" action="/admin/cloud/instances">
|
||||
<label class="col-xl-4 col-lg-6" for="instances-query"><span class="form-label d-block">关键词</span><input class="form-control" id="instances-query" name="q" type="search" maxlength="80" value="{$instance_page.filters.q|escape}" placeholder="名称 / IP / UUID / 用户"></label>
|
||||
<label class="col-xl-2 col-lg-3 col-6" for="instances-user"><span class="form-label d-block">用户 ID</span><input class="form-control" id="instances-user" name="user_id" type="text" inputmode="numeric" pattern="[1-9][0-9]*" maxlength="20" value="{$instance_page.filters.user_id|escape}" placeholder="全部用户"></label>
|
||||
<label class="col-xl-3 col-lg-3 col-6" for="instances-host"><span class="form-label d-block">宿主机</span><select class="form-select" id="instances-host" name="host_id"><option value="">全部宿主机</option>{foreach $instance_page.hosts as $host}<option value="{$host.id|escape}" {if $instance_page.filters.host_id == $host.id}selected{/if}>{$host.name|escape}{if $host.region} · {$host.region|escape}{/if}</option>{/foreach}</select></label>
|
||||
<label class="col-xl-3 col-lg-4 col-6" for="instances-service"><span class="form-label d-block">服务状态</span><select class="form-select" id="instances-service" name="service_status"><option value="">全部服务状态</option><option value="active" {if $instance_page.filters.service_status == 'active'}selected{/if}>服务正常</option><option value="expired_grace" {if $instance_page.filters.service_status == 'expired_grace'}selected{/if}>到期宽限期</option><option value="expired" {if $instance_page.filters.service_status == 'expired'}selected{/if}>已到期</option><option value="exempt" {if $instance_page.filters.service_status == 'exempt'}selected{/if}>免计费</option><option value="suspended_expired" {if $instance_page.filters.service_status == 'suspended_expired'}selected{/if}>到期停用</option><option value="suspending_expired" {if $instance_page.filters.service_status == 'suspending_expired'}selected{/if}>到期停用中</option><option value="suspend_failed" {if $instance_page.filters.service_status == 'suspend_failed'}selected{/if}>暂停失败</option><option value="resume_pending" {if $instance_page.filters.service_status == 'resume_pending'}selected{/if}>等待恢复</option><option value="resuming" {if $instance_page.filters.service_status == 'resuming'}selected{/if}>恢复中</option><option value="resume_failed" {if $instance_page.filters.service_status == 'resume_failed'}selected{/if}>恢复失败</option><option value="purge_stopping" {if $instance_page.filters.service_status == 'purge_stopping'}selected{/if}>清理前关机中</option><option value="purge_stop_failed" {if $instance_page.filters.service_status == 'purge_stop_failed'}selected{/if}>清理前关机失败</option><option value="purge_deleting" {if $instance_page.filters.service_status == 'purge_deleting'}selected{/if}>到期清理中</option><option value="purge_failed" {if $instance_page.filters.service_status == 'purge_failed'}selected{/if}>清理失败</option></select></label>
|
||||
<label class="col-xl-2 col-lg-4 col-6" for="instances-expiry"><span class="form-label d-block">到期范围</span><select class="form-select" id="instances-expiry" name="expiry"><option value="all">全部期限</option><option value="soon" {if $instance_page.filters.expiry == 'soon'}selected{/if}>7 天内到期</option><option value="expired" {if $instance_page.filters.expiry == 'expired'}selected{/if}>已到期</option><option value="exempt" {if $instance_page.filters.expiry == 'exempt'}selected{/if}>免计费</option></select></label>
|
||||
<label class="col-xl-2 col-lg-4 col-6" for="instances-focus"><span class="form-label d-block">关注事项</span><select class="form-select" id="instances-focus" name="attention"><option value="all">全部实例</option><option value="network" {if $instance_page.filters.attention == 'network'}selected{/if}>网络受限</option><option value="jobs" {if $instance_page.filters.attention == 'jobs'}selected{/if}>异常任务</option></select></label>
|
||||
<label class="col-xl-2 col-lg-4 col-6" for="instances-sort"><span class="form-label d-block">排序</span><select class="form-select" id="instances-sort" name="sort"><option value="newest">最近创建</option><option value="oldest" {if $instance_page.filters.sort == 'oldest'}selected{/if}>最早创建</option><option value="expiry" {if $instance_page.filters.sort == 'expiry'}selected{/if}>即将到期优先</option></select></label>
|
||||
<label class="col-xl-2 col-lg-4 col-6" for="instances-per-page"><span class="form-label d-block">每页条数</span><select class="form-select" id="instances-per-page" name="per_page"><option value="20">20 条</option><option value="50" {if $instance_page.pagination.per_page == 50}selected{/if}>50 条</option><option value="100" {if $instance_page.pagination.per_page == 100}selected{/if}>100 条</option></select></label>
|
||||
<div class="col-xl-4 col-lg-4 col-12 admin-form-actions admin-billing-filter-actions mt-0"><button class="btn btn-primary" type="submit">应用筛选</button><a class="btn btn-light" id="instances-reset" href="/admin/cloud/instances">清空条件</a></div>
|
||||
</form></div>
|
||||
</section>
|
||||
<section class="card" aria-labelledby="instances-list-title">
|
||||
<div class="card-header d-flex align-items-center justify-content-between gap-2 flex-wrap"><div><h2 class="h5 card-title mb-1" id="instances-list-title">实例列表</h2><span class="text-muted fs-13" id="instances-live-status" role="status">电源状态尚未获取</span></div><span class="badge text-bg-light" id="instances-count">共 {$instance_page.pagination.total|escape} 台</span></div>
|
||||
<div class="card-body"><div class="table-responsive admin-checkout-table-wrap"><table class="table table-hover align-middle mb-0 admin-checkout-table admin-instances-table"><caption class="visually-hidden">管理员虚拟机列表</caption><thead><tr><th scope="col">实例</th><th scope="col">用户</th><th scope="col">所在位置</th><th scope="col">公网 IP</th><th scope="col">配置</th><th scope="col">状态</th><th scope="col">用量与期限</th><th scope="col">操作</th></tr></thead><tbody id="instances-body">
|
||||
{foreach $instance_page.items as $vm}
|
||||
<tr data-instance-id="{$vm.id|escape}">
|
||||
<td data-label="实例"><span class="admin-checkout-user"><strong>{$vm.name|escape}</strong><span>#{$vm.id|escape} · {$vm.os_name|default:'系统未记录'|escape}</span></span></td>
|
||||
<td data-label="用户"><span class="admin-checkout-user">{if $vm.user_url}<a href="{$vm.user_url|escape}">{$vm.user_name|escape}</a>{else}<strong>{$vm.user_name|escape}</strong>{/if}<span>ID {$vm.user_id|escape}</span></span></td>
|
||||
<td data-label="所在位置"><span class="admin-checkout-user"><strong>{$vm.host_name|escape}</strong><span>{$vm.region|default:'地区未记录'|escape}</span></span></td>
|
||||
<td data-label="公网 IP"><span class="admin-instance-ip"><span class="admin-mono">{$vm.public_ip|default:'未记录'|escape}</span>{if $vm.public_ip}<button class="btn btn-light btn-sm" type="button" data-copy="{$vm.public_ip|escape}" aria-label="复制公网 IP {$vm.public_ip|escape}"><i class="mdi mdi-content-copy" aria-hidden="true"></i></button>{/if}</span></td>
|
||||
<td data-label="配置"><span class="admin-checkout-user"><strong>{$vm.display.configuration|escape}</strong><span>{$vm.plan_name|default:'无关联套餐'|escape}</span></span></td>
|
||||
<td data-label="状态"><div class="admin-instance-status"><span class="badge bg-light text-dark" data-power-status>电源:待获取</span><span class="fs-12">服务:{$vm.display.service|escape}</span><span class="fs-12">网络:{$vm.display.network|escape}</span>{if $vm.active_job}<span class="text-warning fs-12">任务 #{$vm.active_job.id|escape} · {if $vm.active_job.status == 'uncertain'}待核对{elseif $vm.active_job.status == 'running'}执行中{elseif $vm.active_job.status == 'queued'}已排队{else}{$vm.active_job.status|escape}{/if}</span>{/if}</div></td>
|
||||
<td data-label="用量与期限"><span class="admin-checkout-user"><strong>{$vm.display.traffic|escape}</strong><span>{$vm.display.expiry|escape}</span>{if $vm.service_expires_at && $vm.service_status != 'exempt'}<span>到期 {$vm.service_expires_at|date_format:'%Y-%m-%d'|escape}</span>{/if}</span></td>
|
||||
<td data-label="操作"><button class="btn btn-primary btn-sm" type="button" data-instance-detail="{$vm.id|escape}" aria-label="查看 {$vm.name|escape} 的详情">查看详情</button></td>
|
||||
</tr>
|
||||
{foreachelse}<tr><td colspan="8" class="text-center text-muted py-4">{if $instance_error}实例暂时无法读取,请点击刷新重试。{else}没有符合条件的实例。{/if}</td></tr>{/foreach}
|
||||
</tbody></table></div><nav class="admin-user-pagination" aria-label="实例列表分页"><button class="btn btn-light" id="instances-previous" type="button" {if $instance_page.pagination.page <= 1}disabled{/if}>上一页</button><span id="instances-page-label">第 {$instance_page.pagination.page|escape} / {$instance_page.pagination.total_pages|escape} 页 · 共 {$instance_page.pagination.total|escape} 台</span><button class="btn btn-light" id="instances-next" type="button" {if $instance_page.pagination.page >= $instance_page.pagination.total_pages}disabled{/if}>下一页</button></nav></div>
|
||||
</section>
|
||||
<noscript><p class="alert alert-info">已显示数据库中的实例信息。启用 JavaScript 后可分页、查看详情与实时电源状态。</p></noscript>
|
||||
</main>
|
||||
<dialog data-admin-instance-drawer id="instance-detail" aria-labelledby="instance-detail-title">
|
||||
<header class="admin-instance-drawer-header"><div><p class="text-muted fs-13 mb-1">实例详情</p><h2 class="h4 fw-semibold mb-0" id="instance-detail-title">虚拟机</h2></div><button class="admin-modal-close position-static flex-shrink-0" id="instance-detail-close" type="button" aria-label="关闭实例详情" autofocus><i class="mdi mdi-close" aria-hidden="true"></i></button></header>
|
||||
<div class="admin-instance-drawer-body"><p class="alert alert-info" id="instance-detail-notice" role="status" aria-live="polite">正在读取详情…</p>
|
||||
<div class="admin-instance-tabs" role="tablist" aria-label="实例详情分类"><button class="btn btn-light" type="button" id="instance-tab-basic" data-instance-tab="basic" role="tab" aria-controls="instance-panel-basic" aria-selected="true">基本信息</button><button class="btn btn-light" type="button" id="instance-tab-service" data-instance-tab="service" role="tab" aria-controls="instance-panel-service" aria-selected="false" tabindex="-1">服务与流量</button><button class="btn btn-light" type="button" id="instance-tab-jobs" data-instance-tab="jobs" role="tab" aria-controls="instance-panel-jobs" aria-selected="false" tabindex="-1">任务记录</button><button class="btn btn-light" type="button" id="instance-tab-invoices" data-instance-tab="invoices" role="tab" aria-controls="instance-panel-invoices" aria-selected="false" tabindex="-1">关联账单</button></div>
|
||||
<section id="instance-panel-basic" role="tabpanel" aria-labelledby="instance-tab-basic" tabindex="0"></section><section id="instance-panel-service" role="tabpanel" aria-labelledby="instance-tab-service" tabindex="0" hidden></section><section id="instance-panel-jobs" role="tabpanel" aria-labelledby="instance-tab-jobs" tabindex="0" hidden></section><section id="instance-panel-invoices" role="tabpanel" aria-labelledby="instance-tab-invoices" tabindex="0" hidden></section>
|
||||
</div>
|
||||
</section>
|
||||
<script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>
|
||||
<footer class="admin-instance-drawer-footer"><span class="text-muted fs-12" id="instance-detail-permission">当前详情为只读信息。</span><a class="btn btn-primary" id="instance-control-link" hidden>进入实例控制台</a></footer>
|
||||
</dialog>
|
||||
<script id="admin-instances-bootstrap" type="application/json">{$instance_bootstrap_json nofilter}</script>
|
||||
<script type="module" src="/cloud/admin-instances.js?v={$venix_asset_version}"></script>
|
||||
{include file='admin/static_footer.tpl'}
|
||||
|
||||
@ -1,2 +1,2 @@
|
||||
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
|
||||
{assign var=venix_asset_version value='2026093004' scope='global'}
|
||||
{assign var=venix_asset_version value='2026093005' scope='global'}
|
||||
|
||||
@ -0,0 +1,141 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
|
||||
if ((error_reporting() & $severity) && ($severity & (E_WARNING | E_USER_WARNING))) {
|
||||
throw new ErrorException($message, 0, $severity, $file, $line);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
// Non-production data also used by the local browser fixture (--fixture).
|
||||
$now = time();
|
||||
$common = [
|
||||
'uuid' => '11111111-1111-4111-8111-111111111111',
|
||||
'user_id' => 42, 'user_name' => '演示客户', 'user_email' => 'd***@example.test',
|
||||
'user_url' => '/admin/user/42/edit', 'host_id' => 7,
|
||||
'host_name' => '香港宿主机 A', 'region' => 'HongKong', 'plan_name' => '标准云服务器',
|
||||
'os_name' => 'Debian 12', 'vcpu' => 2, 'memory_mib' => 2048, 'disk_gib' => 40,
|
||||
'instance_status' => 'active', 'service_status' => 'active', 'network_status' => 'active',
|
||||
'service_expires_at' => $now + 4 * 86400, 'traffic_used_bytes' => 21474836480,
|
||||
'traffic_quota_bytes' => 107374182400, 'traffic_synced_at' => $now - 60,
|
||||
'created_at' => $now - 86400, 'active_job' => null, 'state' => 'unknown',
|
||||
'can_manage' => true,
|
||||
'display' => [
|
||||
'configuration' => '2 vCPU · 2 GiB · 40 GiB', 'traffic' => '20 GiB / 100 GiB',
|
||||
'expiry' => '4 天后到期', 'service' => '服务正常',
|
||||
'network' => '网络正常', 'lifecycle' => '在管',
|
||||
],
|
||||
];
|
||||
$items = [
|
||||
array_replace($common, ['id' => '101', 'name' => 'vm-production',
|
||||
'public_ip' => '192.0.2.101', 'detail_url' => '/user/cloud/instances/101']),
|
||||
array_replace($common, ['id' => '102', 'name' => 'vm-network-limited',
|
||||
'public_ip' => '192.0.2.102', 'detail_url' => '/user/cloud/instances/102',
|
||||
'network_status' => 'blocked_traffic', 'traffic_used_bytes' => 107374182400,
|
||||
'display' => array_replace($common['display'], [
|
||||
'traffic' => '100 GiB / 100 GiB', 'network' => '流量耗尽已断网',
|
||||
])]),
|
||||
array_replace($common, ['id' => '103', 'name' => 'vm-task-reconciliation',
|
||||
'public_ip' => '192.0.2.103', 'detail_url' => '/user/cloud/instances/103',
|
||||
'active_job' => ['id' => '61', 'kind' => 'reinstall', 'status' => 'uncertain',
|
||||
'attempts' => 3, 'error' => '等待核对操作结果', 'phase' => 'reconcile',
|
||||
'created_at' => $now - 300, 'updated_at' => $now - 10]]),
|
||||
];
|
||||
$page = [
|
||||
'items' => $items,
|
||||
'pagination' => ['page' => 1, 'per_page' => 20, 'total' => 43,
|
||||
'total_pages' => 3, 'from' => 1, 'to' => 3],
|
||||
'summary' => ['total' => 43, 'expiring' => 3, 'network_restricted' => 1, 'attention' => 1],
|
||||
'filters' => ['q' => '', 'user_id' => null, 'host_id' => null, 'service_status' => '',
|
||||
'expiry' => 'all', 'attention' => 'all', 'sort' => 'newest', 'page' => 1, 'per_page' => 20],
|
||||
'hosts' => [['id' => 7, 'name' => '香港宿主机 A', 'region' => 'HongKong']],
|
||||
'generated_at' => $now,
|
||||
];
|
||||
$detail = [
|
||||
'instance' => array_replace($items[0], [
|
||||
'public_ip_cidr' => '192.0.2.101/24', 'gateway' => '192.0.2.1',
|
||||
'dns_servers' => ['1.1.1.1', '8.8.8.8'], 'engine_name' => 'vc-1111111111114111',
|
||||
'bandwidth_mbps' => 100, 'os_source' => 'cloud', 'login_name' => 'root',
|
||||
'current_period_started_at' => $now - 26 * 86400,
|
||||
'current_period_ends_at' => $now + 4 * 86400, 'renewal_price' => '10.00',
|
||||
'renewal_days' => 30, 'renewal_traffic_bytes' => 107374182400,
|
||||
'traffic_download_bytes' => 10737418240, 'traffic_upload_bytes' => 10737418240,
|
||||
'updated_at' => $now - 60,
|
||||
]),
|
||||
'jobs' => [['id' => '62', 'kind' => 'action', 'status' => 'succeeded',
|
||||
'attempts' => 1, 'error' => null, 'phase' => 'complete',
|
||||
'created_at' => $now - 3600, 'updated_at' => $now - 3500]],
|
||||
'jobs_truncated' => false,
|
||||
'invoices' => [['id' => '201', 'purpose' => 'provision', 'status' => 'paid',
|
||||
'amount' => '10.00', 'created_at' => $now - 86400,
|
||||
'detail_url' => '/admin/billing?detail=201']],
|
||||
'invoices_truncated' => false,
|
||||
];
|
||||
|
||||
$smarty = new Smarty();
|
||||
$compileDir = sys_get_temp_dir() . '/admin-instance-view-' . bin2hex(random_bytes(6));
|
||||
mkdir($compileDir);
|
||||
$smarty->setCompileDir($compileDir);
|
||||
$smarty->setTemplateDir(dirname(__DIR__) . '/resources/views/venix');
|
||||
$smarty->assign('config', ['appName' => 'Venix Test']);
|
||||
$smarty->assign('cdn', '');
|
||||
$smarty->assign('user', (object) ['isLogin' => false]);
|
||||
$smarty->assign('admin_can_manage', true);
|
||||
$smarty->assign('admin_csrf_token', 'fixture-not-a-real-token');
|
||||
$render = static function (?array $payload, string $error = '') use ($smarty): string {
|
||||
$smarty->assign('instance_page', $payload);
|
||||
$smarty->assign('instance_error', $error);
|
||||
$smarty->assign('instance_bootstrap_json', json_encode($payload,
|
||||
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
|
||||
| JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE));
|
||||
return $smarty->fetch('admin/cloud/instances.tpl');
|
||||
};
|
||||
$assert = static function (bool $ok, string $message): void {
|
||||
if (!$ok) throw new RuntimeException($message);
|
||||
};
|
||||
$html = $render($page);
|
||||
if (in_array('--fixture', $argv ?? [], true)) {
|
||||
echo json_encode(['html' => $html, 'billing_html' => $smarty->fetch('admin/billing.tpl'),
|
||||
'page' => $page, 'detail' => $detail],
|
||||
JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
|
||||
exit;
|
||||
}
|
||||
|
||||
// The table is usable without waiting for JavaScript or any host connection.
|
||||
$dom = new DOMDocument();
|
||||
libxml_use_internal_errors(true);
|
||||
$dom->loadHTML('<?xml encoding="UTF-8">' . $html);
|
||||
$xpath = new DOMXPath($dom);
|
||||
$assert($xpath->query('//tbody//tr')->length === 3, 'SSR did not render all fixture rows.');
|
||||
$assert(str_contains($dom->textContent, '192.0.2.101')
|
||||
&& str_contains($dom->textContent, '20 GiB / 100 GiB')
|
||||
&& str_contains($dom->textContent, '香港宿主机 A'), 'Useful instance data is missing before scripts run.');
|
||||
$assert($xpath->query('//select[@name="per_page"]/option[@value="20"]')->length === 1
|
||||
&& $xpath->query('//select[@name="per_page"]/option[@selected and @value!="20"]')->length === 0,
|
||||
'SSR did not retain the current page size.');
|
||||
|
||||
$unsafe = $page;
|
||||
$unsafe['items'][0]['name'] = '</script><img src=x onerror=alert(1)>';
|
||||
$unsafe['items'][0]['user_name'] = '<script>window.bad=1</script>';
|
||||
$unsafe['items'][0]['host_name'] = '" onmouseover="alert(2)';
|
||||
$unsafeHtml = $render($unsafe);
|
||||
$dom->loadHTML('<?xml encoding="UTF-8">' . $unsafeHtml);
|
||||
$xpath = new DOMXPath($dom);
|
||||
$assert($xpath->query('//*[@onerror or @onmouseover]')->length === 0,
|
||||
'Untrusted row content escaped into an executable attribute.');
|
||||
$assert(!str_contains($unsafeHtml, '<script>window.bad=1</script>')
|
||||
&& str_contains($dom->textContent, '</script><img src=x onerror=alert(1)>'),
|
||||
'Untrusted names must render as text, not active markup.');
|
||||
|
||||
$empty = $page;
|
||||
$empty['items'] = [];
|
||||
$empty['pagination'] = ['page' => 1, 'per_page' => 20, 'total' => 0, 'total_pages' => 1, 'from' => 0, 'to' => 0];
|
||||
$empty['summary'] = ['total' => 0, 'expiring' => 0, 'network_restricted' => 0, 'attention' => 0];
|
||||
$emptyHtml = $render($empty);
|
||||
$assert(!str_contains($emptyHtml, 'vm-production'), 'Empty result retained an old instance.');
|
||||
$failedHtml = $render(null, '实例信息暂不可用,请重试');
|
||||
$assert(str_contains($failedHtml, '实例信息暂不可用,请重试')
|
||||
&& !str_contains($failedHtml, 'vm-production'), 'Unavailable data was disguised as a successful list.');
|
||||
|
||||
echo "Administrator instance SSR, escaping and empty/error rendering passed.\n";
|
||||
@ -0,0 +1,502 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services {
|
||||
final class AdminPermission
|
||||
{
|
||||
public static bool $superAdmin = true;
|
||||
|
||||
public static function isSuperAdmin(): bool
|
||||
{
|
||||
return self::$superAdmin;
|
||||
}
|
||||
}
|
||||
|
||||
final class Auth
|
||||
{
|
||||
public static $user = null;
|
||||
|
||||
public static function getUser()
|
||||
{
|
||||
return self::$user;
|
||||
}
|
||||
}
|
||||
|
||||
final class Config
|
||||
{
|
||||
public static function get($name, $default = null)
|
||||
{
|
||||
return $default;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace App\Services\Cloud {
|
||||
final class CloudSessionService
|
||||
{
|
||||
public static int $calls = 0;
|
||||
|
||||
public static function current($user): string
|
||||
{
|
||||
self::$calls++;
|
||||
throw new \RuntimeException('Database-only instance reads created an engine session.');
|
||||
}
|
||||
}
|
||||
|
||||
final class CloudEngineClient
|
||||
{
|
||||
public static int $calls = 0;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
self::$calls++;
|
||||
throw new \RuntimeException('Database-only instance reads contacted the engine.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Controllers\CloudAdminInstanceController;
|
||||
use App\Models\User;
|
||||
use App\Services\AdminPermission;
|
||||
use App\Services\Auth;
|
||||
use App\Services\Cloud\CloudAdminInstanceService;
|
||||
use App\Services\Cloud\CloudEngineClient;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudSessionService;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Slim\Http\Environment;
|
||||
use Slim\Http\Request;
|
||||
use Slim\Http\Response;
|
||||
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$expectError = static function (callable $callback, int $status, string $message) use ($assert): void {
|
||||
try {
|
||||
$callback();
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === $status, $message . ': unexpected HTTP status ' . $error->httpStatus);
|
||||
return;
|
||||
}
|
||||
throw new RuntimeException($message . ': request was accepted.');
|
||||
};
|
||||
$ids = static fn (array $items): array => array_map('intval', array_column($items, 'id'));
|
||||
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
$schema = $capsule->schema('default');
|
||||
$schema->create('user', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('user_name');
|
||||
$table->string('email');
|
||||
$table->boolean('is_admin')->default(false);
|
||||
$table->boolean('enable')->default(true);
|
||||
$table->string('pass')->default('must-not-expose-account-password');
|
||||
});
|
||||
$schema->create('cloud_hosts', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('name');
|
||||
$table->string('region')->default('');
|
||||
$table->string('country_code')->default('');
|
||||
$table->boolean('enabled')->default(true);
|
||||
});
|
||||
$schema->create('shop', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('name');
|
||||
});
|
||||
$schema->create('cloud_instances', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('uuid');
|
||||
$table->integer('host_id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('order_id')->nullable();
|
||||
$table->integer('plan_id')->nullable();
|
||||
$table->integer('current_period_id')->nullable();
|
||||
$table->string('name');
|
||||
$table->string('status')->default('active');
|
||||
$table->string('service_status')->default('active');
|
||||
$table->string('network_status')->default('active');
|
||||
$table->integer('expires_at')->nullable();
|
||||
$table->string('renewal_price')->nullable();
|
||||
$table->integer('renewal_days')->default(0);
|
||||
$table->integer('renewal_traffic_bytes')->default(0);
|
||||
$table->integer('traffic_quota_bytes')->default(0);
|
||||
$table->integer('traffic_download_bytes')->default(0);
|
||||
$table->integer('traffic_upload_bytes')->default(0);
|
||||
$table->integer('lifetime_download_bytes')->default(0);
|
||||
$table->integer('lifetime_upload_bytes')->default(0);
|
||||
$table->integer('traffic_synced_at')->default(0);
|
||||
$table->integer('suspended_at')->nullable();
|
||||
$table->integer('network_suspended_at')->nullable();
|
||||
$table->text('spec_json');
|
||||
$table->text('credential_cipher')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
$schema->create('cloud_service_periods', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('instance_id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('starts_at');
|
||||
$table->integer('ends_at');
|
||||
$table->string('status');
|
||||
});
|
||||
$schema->create('cloud_orders', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('instance_id')->nullable();
|
||||
$table->integer('user_id');
|
||||
$table->integer('plan_id')->nullable();
|
||||
$table->integer('host_id')->default(7);
|
||||
$table->string('amount')->default('10.00');
|
||||
$table->string('status')->default('succeeded');
|
||||
$table->text('spec_json')->default('{}');
|
||||
$table->text('payload_cipher')->default('must-not-expose-order-payload');
|
||||
$table->integer('created_at')->default(0);
|
||||
$table->integer('updated_at')->default(0);
|
||||
});
|
||||
$schema->create('cloud_jobs', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('operation_id');
|
||||
$table->integer('instance_id')->nullable();
|
||||
$table->integer('order_id')->nullable();
|
||||
$table->integer('user_id');
|
||||
$table->integer('host_id')->default(7);
|
||||
$table->string('kind');
|
||||
$table->string('status');
|
||||
$table->integer('attempts')->default(0);
|
||||
$table->string('error_code')->nullable();
|
||||
$table->text('payload_cipher')->default('must-not-expose-job-payload');
|
||||
$table->text('result_json')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
$schema->create('cloud_invoices', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('invoice_no');
|
||||
$table->string('purpose')->default('renewal');
|
||||
$table->integer('instance_id')->nullable();
|
||||
$table->integer('order_id')->nullable();
|
||||
$table->integer('user_id');
|
||||
$table->integer('plan_id')->nullable();
|
||||
$table->integer('renewal_id')->nullable();
|
||||
$table->integer('due_at');
|
||||
$table->string('amount')->default('10.00');
|
||||
$table->string('status')->default('open');
|
||||
$table->string('paid_via')->nullable();
|
||||
$table->string('payment_reference')->default('must-not-expose-payment-reference');
|
||||
$table->integer('paid_at')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
Capsule::table('user')->insert([
|
||||
['id' => 1, 'user_name' => 'Alice Ops', 'email' => 'alice@example.test'],
|
||||
['id' => 2, 'user_name' => 'Bob Client', 'email' => 'bob@example.test'],
|
||||
['id' => 99, 'user_name' => 'Root Operator', 'email' => 'root@example.test'],
|
||||
]);
|
||||
Capsule::table('cloud_hosts')->insert([
|
||||
['id' => 7, 'name' => 'Hong Kong 07', 'region' => 'HongKong', 'country_code' => 'HK'],
|
||||
['id' => 8, 'name' => 'Tokyo 08', 'region' => 'Tokyo', 'country_code' => 'JP'],
|
||||
]);
|
||||
Capsule::table('shop')->insert(['id' => 3, 'name' => 'Small Cloud']);
|
||||
$now = time();
|
||||
$base = [
|
||||
'host_id' => 7, 'user_id' => 1, 'plan_id' => 3,
|
||||
'status' => 'active', 'service_status' => 'active', 'network_status' => 'active',
|
||||
'expires_at' => $now + 30 * 86400, 'renewal_price' => '10.00',
|
||||
'renewal_days' => 30, 'renewal_traffic_bytes' => 2000,
|
||||
'traffic_quota_bytes' => 2000, 'traffic_download_bytes' => 300,
|
||||
'traffic_upload_bytes' => 200, 'traffic_synced_at' => $now - 30,
|
||||
'credential_cipher' => 'must-not-expose-instance-credential',
|
||||
'spec_json' => json_encode([
|
||||
'vcpu' => 2, 'memory_mib' => 2048, 'disk_gib' => 40,
|
||||
'os_source' => 'cloud_template', 'os_name' => 'AlmaLinux 10',
|
||||
'public_ip_cidr' => '198.51.100.10/24',
|
||||
'state' => 'running', 'console_port' => 5900,
|
||||
'password' => 'must-not-expose-spec-password',
|
||||
'api_token' => 'must-not-expose-api-token',
|
||||
'unreviewed_note' => 'must-not-expose-unknown-spec-field',
|
||||
'disks' => [['capacity_gib' => 40, 'source' => 'must-not-expose-disk-path']],
|
||||
]),
|
||||
'created_at' => $now - 600, 'updated_at' => $now - 300,
|
||||
];
|
||||
$insertInstance = static function (int $id, array $overrides = []) use ($base): void {
|
||||
Capsule::table('cloud_instances')->insert(array_replace($base, [
|
||||
'id' => $id, 'uuid' => sprintf('11111111-1111-4111-8111-%012d', $id),
|
||||
'name' => 'vm-' . $id,
|
||||
], $overrides));
|
||||
};
|
||||
for ($id = 1; $id <= 205; $id++) {
|
||||
$insertInstance($id);
|
||||
}
|
||||
$insertInstance(206, ['user_id' => 2, 'host_id' => 8, 'order_id' => 601,
|
||||
'current_period_id' => 1, 'expires_at' => $now + 2 * 86400]);
|
||||
$insertInstance(207, ['expires_at' => $now - 3600, 'service_status' => 'expired', 'order_id' => 602]);
|
||||
$insertInstance(208, ['expires_at' => null, 'service_status' => 'exempt']);
|
||||
$insertInstance(209, ['network_status' => 'blocked_traffic']);
|
||||
$insertInstance(210, ['network_status' => 'restore_failed']);
|
||||
$insertInstance(211, ['status' => 'deleted', 'expires_at' => $now + 3600]);
|
||||
$insertInstance(212, ['user_id' => 404, 'host_id' => 404, 'plan_id' => 404, 'expires_at' => null]);
|
||||
$insertInstance(213, ['name' => "tenant's 100%_ready"]);
|
||||
$insertInstance(214, ['spec_json' => json_encode([
|
||||
'public_ip_cidr' => '203.0.113.74/24', 'vcpu' => 4, 'memory_mib' => 4096,
|
||||
])]);
|
||||
Capsule::table('cloud_service_periods')->insert([
|
||||
'id' => 1, 'instance_id' => 206, 'user_id' => 2,
|
||||
'starts_at' => $now - 28 * 86400, 'ends_at' => $now + 2 * 86400, 'status' => 'active',
|
||||
]);
|
||||
Capsule::table('cloud_orders')->insert([
|
||||
['id' => 601, 'instance_id' => 206, 'user_id' => 2],
|
||||
['id' => 602, 'instance_id' => 207, 'user_id' => 2],
|
||||
]);
|
||||
$insertJob = static function (int $id, array $overrides = []) use ($now): void {
|
||||
Capsule::table('cloud_jobs')->insert(array_replace([
|
||||
'id' => $id, 'operation_id' => sprintf('%032d', $id),
|
||||
'instance_id' => 206, 'user_id' => 99, 'kind' => 'action',
|
||||
'status' => 'succeeded', 'created_at' => $now - 100, 'updated_at' => $now,
|
||||
'result_json' => json_encode([
|
||||
'phase' => 'finished', 'generated_password' => 'must-not-expose-job-password',
|
||||
'unreviewed_note' => 'must-not-expose-unknown-job-result',
|
||||
]),
|
||||
], $overrides));
|
||||
};
|
||||
for ($id = 1; $id <= 26; $id++) {
|
||||
$insertJob($id, ['status' => $id === 26 ? 'running' : 'succeeded']);
|
||||
}
|
||||
$insertJob(27, ['instance_id' => 209, 'status' => 'failed', 'error_code' => 'test_failure']);
|
||||
$insertJob(28, ['instance_id' => 210, 'status' => 'uncertain', 'updated_at' => $now - 172800]);
|
||||
$insertJob(29, ['instance_id' => 207, 'status' => 'failed', 'updated_at' => $now - 172800]);
|
||||
$insertJob(30, ['instance_id' => 211, 'status' => 'failed']);
|
||||
$insertInvoice = static function (int $id, array $overrides = []) use ($now): void {
|
||||
Capsule::table('cloud_invoices')->insert(array_replace([
|
||||
'id' => $id, 'invoice_no' => 'TEST-' . $id,
|
||||
'instance_id' => 206, 'user_id' => 2,
|
||||
'due_at' => $now + 3600, 'created_at' => $now - 100, 'updated_at' => $now,
|
||||
], $overrides));
|
||||
};
|
||||
for ($id = 1; $id <= 25; $id++) {
|
||||
$insertInvoice($id);
|
||||
}
|
||||
$insertInvoice(26, ['user_id' => 1]);
|
||||
$insertInvoice(27, ['instance_id' => null, 'order_id' => 601]);
|
||||
$insertInvoice(28, ['instance_id' => null, 'order_id' => 602, 'user_id' => 1]);
|
||||
|
||||
$admin = ['user_id' => 99, 'is_admin' => true, 'is_super_admin' => true, 'can_manage' => true];
|
||||
$readOnly = ['user_id' => 99, 'is_admin' => true, 'is_super_admin' => false, 'can_manage' => false];
|
||||
$customer = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false, 'can_manage' => false];
|
||||
|
||||
// All timestamps are deliberately identical: ordering must include the ID.
|
||||
$page = CloudAdminInstanceService::page($admin);
|
||||
$assert($page['pagination']['total'] === 213 && count($page['items']) === 20
|
||||
&& $ids($page['items']) === array_values(array_diff(range(214, 194), [211])),
|
||||
'Administrator first page lost records above 200, included deleted rows, or sorted ties unstably.');
|
||||
$assert($page['summary']['total'] === 213 && $page['summary']['expiring'] === 1
|
||||
&& $page['summary']['network_restricted'] === 2 && $page['summary']['attention'] === 2,
|
||||
'Database statistics must cover the complete filtered population and preserve state meanings.');
|
||||
$assert(!isset($page['summary']['running']) && !isset($page['summary']['stopped']),
|
||||
'Database-only summary fabricated a live power-state count.');
|
||||
$seen = [];
|
||||
for ($number = 1; $number <= 3; $number++) {
|
||||
$chunk = CloudAdminInstanceService::page($admin, ['page' => (string) $number, 'per_page' => '100']);
|
||||
$seen = array_merge($seen, $ids($chunk['items']));
|
||||
}
|
||||
$assert(count($seen) === 213 && count(array_unique($seen)) === 213
|
||||
&& $seen === array_values(array_diff(range(214, 1), [211])),
|
||||
'Paging beyond 200 duplicated or silently truncated instances.');
|
||||
$last = CloudAdminInstanceService::page($admin, ['page' => '9999', 'per_page' => '100']);
|
||||
$assert($last['pagination']['page'] === 3 && count($last['items']) === 13,
|
||||
'Out-of-range pages did not clamp to the last valid page.');
|
||||
$oldest = CloudAdminInstanceService::page($admin, ['sort' => 'oldest']);
|
||||
$assert($ids($oldest['items']) === range(1, 20), 'Oldest sorting needs a stable ascending ID order.');
|
||||
$expiry = CloudAdminInstanceService::page($admin, ['sort' => 'expiry']);
|
||||
$assert((int) $expiry['items'][0]['id'] === 207, 'Expiry sorting did not put the oldest expiry first.');
|
||||
|
||||
foreach ([['user_id' => '2'], ['host_id' => '8'], ['user_id' => '2', 'host_id' => '8']] as $filter) {
|
||||
$filtered = CloudAdminInstanceService::page($admin, $filter);
|
||||
$assert($ids($filtered['items']) === [206] && $filtered['summary']['total'] === 1
|
||||
&& $filtered['summary']['expiring'] === 1,
|
||||
'Exact owner/host filters or filtered summary crossed instance boundaries.');
|
||||
}
|
||||
$empty = CloudAdminInstanceService::page($admin, ['user_id' => '2', 'host_id' => '7']);
|
||||
$assert($empty['items'] === [] && $empty['pagination']['total'] === 0
|
||||
&& $empty['pagination']['total_pages'] === 1 && $empty['pagination']['page'] === 1
|
||||
&& $empty['summary']['total'] === 0,
|
||||
'Empty filtered collections returned stale rows or invalid pagination.');
|
||||
foreach ([
|
||||
"tenant's" => [213], '100%_ready' => [213], '%' => [213], '_ready' => [213],
|
||||
'203.0.113.74' => [214], "' OR 1=1 --" => [],
|
||||
'11111111-1111-4111-8111-000000000214' => [214],
|
||||
'bob@example.test' => [206],
|
||||
] as $query => $expected) {
|
||||
$searched = CloudAdminInstanceService::page($admin, ['q' => $query]);
|
||||
$assert($ids($searched['items']) === $expected,
|
||||
'Search must bind quotes, escape SQL wildcards, and correctly match IP/UUID/account: ' . $query);
|
||||
}
|
||||
foreach (['soon' => [206], 'expired' => [207], 'exempt' => [208]] as $mode => $expected) {
|
||||
$filtered = CloudAdminInstanceService::page($admin, ['expiry' => $mode]);
|
||||
$assert($ids($filtered['items']) === $expected,
|
||||
'Expiry filter confused paid periods, expired instances, or exempt instances: ' . $mode);
|
||||
}
|
||||
$exempt = CloudAdminInstanceService::page($admin, ['service_status' => 'exempt']);
|
||||
$assert($ids($exempt['items']) === [208], 'Exact service-status filter was ignored.');
|
||||
foreach (['network', 'jobs'] as $mode) {
|
||||
$attention = CloudAdminInstanceService::page($admin, ['attention' => $mode]);
|
||||
$assert($ids($attention['items']) === [210, 209],
|
||||
'Attention filter included deleted/old failed jobs or omitted unresolved jobs/network restrictions.');
|
||||
foreach ($attention['items'] as $item) {
|
||||
$assert($item['state'] === 'unknown', 'Business/network/job state was mistaken for live VM power state.');
|
||||
}
|
||||
}
|
||||
foreach (['page', 'per_page', 'q', 'user_id', 'host_id', 'service_status', 'expiry', 'attention', 'sort'] as $key) {
|
||||
$expectError(static fn () => CloudAdminInstanceService::page($admin, [$key => ['1']]), 400,
|
||||
'Array-valued filter must be rejected: ' . $key);
|
||||
}
|
||||
foreach ([['page' => '0'], ['page' => '-1'], ['page' => '1.5'], ['user_id' => '0'],
|
||||
['host_id' => '1 OR 1=1'], ['expiry' => 'running'], ['attention' => 'powered'],
|
||||
['sort' => 'id; DROP TABLE user'], ['service_status' => 'invented'], ['q' => str_repeat('x', 81)]] as $filter) {
|
||||
$expectError(static fn () => CloudAdminInstanceService::page($admin, $filter), 400,
|
||||
'Malformed filters must return a controlled client error');
|
||||
}
|
||||
$expectError(static fn () => CloudAdminInstanceService::page($customer), 403,
|
||||
'Ordinary customers must not access the administrator read model');
|
||||
$expectError(static fn () => CloudAdminInstanceService::detail($customer, '206'), 403,
|
||||
'Ordinary customers must not inspect another owner through admin detail');
|
||||
foreach (['211', '999999'] as $id) {
|
||||
$expectError(static fn () => CloudAdminInstanceService::detail($admin, $id), 404,
|
||||
'Missing or deleted detail must not disclose an instance');
|
||||
}
|
||||
$orphan = CloudAdminInstanceService::detail($admin, '212');
|
||||
$assert((int) $orphan['instance']['id'] === 212 && $orphan['instance']['state'] === 'unknown',
|
||||
'Missing user, host or plan caused an instance to disappear.');
|
||||
$assert($orphan['instance']['display']['service'] === '期限未记录',
|
||||
'An active record with an unknown billing deadline must not be labelled service-available.');
|
||||
|
||||
$detail = CloudAdminInstanceService::detail($admin, '206');
|
||||
$assert((int) $detail['instance']['active_job']['id'] === 26
|
||||
&& $detail['instance']['active_job']['status'] === 'running'
|
||||
&& $detail['instance']['can_manage'] === true,
|
||||
'An operation submitted by a super-admin was lost because the job actor differs from the instance owner.');
|
||||
$assert(count($detail['jobs']) === 20 && $detail['jobs_truncated'] === true
|
||||
&& $ids($detail['jobs']) === range(26, 7),
|
||||
'Instance tasks must be newest-first, bounded to 20, and explicitly marked truncated.');
|
||||
$expectedInvoiceIds = array_merge([27], range(25, 7));
|
||||
$assert(count($detail['invoices']) === 20 && $detail['invoices_truncated'] === true
|
||||
&& $ids($detail['invoices']) === $expectedInvoiceIds,
|
||||
'Invoice detail included a foreign owner, missed the valid order link, or silently truncated history.');
|
||||
$crossOwner = CloudAdminInstanceService::detail($admin, '207');
|
||||
$assert($crossOwner['invoices'] === [],
|
||||
'A same-owner invoice joined through another owner\'s order crossed the billing boundary.');
|
||||
foreach ($detail['invoices'] as $invoice) {
|
||||
$assert(str_starts_with($invoice['detail_url'], '/admin/billing?detail='),
|
||||
'Invoice links must target the administrator ledger, not the customer route.');
|
||||
}
|
||||
$encoded = json_encode([$page, $detail, $crossOwner, $orphan], JSON_THROW_ON_ERROR);
|
||||
$assert(!str_contains($encoded, 'must-not-expose')
|
||||
&& !str_contains($encoded, 'credential_cipher')
|
||||
&& !str_contains($encoded, 'payload_cipher')
|
||||
&& !str_contains($encoded, 'result_json')
|
||||
&& !str_contains($encoded, 'console_port')
|
||||
&& !str_contains($encoded, 'unreviewed_note'),
|
||||
'The administrator DTO allowlist leaked credentials, paths, or an unreviewed metadata/result field.');
|
||||
|
||||
AdminPermission::$superAdmin = false;
|
||||
$masked = CloudAdminInstanceService::page($readOnly, ['user_id' => '2']);
|
||||
$assert($masked['items'][0]['can_manage'] === false
|
||||
&& $masked['items'][0]['user_email'] !== 'bob@example.test'
|
||||
&& $masked['items'][0]['user_name'] !== 'Bob Client',
|
||||
'Read-only administrators gained global operation controls or unmasked account data.');
|
||||
$hiddenSearch = CloudAdminInstanceService::page($readOnly, ['q' => 'bob@example.test']);
|
||||
$assert($hiddenSearch['items'] === [], 'Read-only account search became an oracle for masked email addresses.');
|
||||
AdminPermission::$superAdmin = true;
|
||||
|
||||
$queryCounts = [];
|
||||
foreach ([20, 100] as $size) {
|
||||
$connection = Capsule::connection('default');
|
||||
$connection->flushQueryLog();
|
||||
$connection->enableQueryLog();
|
||||
CloudAdminInstanceService::page($admin, ['per_page' => (string) $size]);
|
||||
$queries = $connection->getQueryLog();
|
||||
$connection->disableQueryLog();
|
||||
$queryCounts[] = count($queries);
|
||||
foreach ($queries as $query) {
|
||||
$assert(preg_match('/^\s*(select|with)\b/i', $query['query']) === 1,
|
||||
'Instance reads unexpectedly wrote business or session data.');
|
||||
$assert(!str_contains(strtolower($query['query']), 'cloud_sessions'),
|
||||
'Database-only instance reads touched the private engine session table.');
|
||||
}
|
||||
}
|
||||
$assert($queryCounts[0] <= 8 && $queryCounts[1] <= $queryCounts[0],
|
||||
'Increasing page size introduced per-instance SQL queries: ' . implode(', ', $queryCounts));
|
||||
$login = static function (bool $isAdmin, bool $isSuper = false, bool $enabled = true): void {
|
||||
$user = new User();
|
||||
$user->id = $isAdmin ? 99 : 1;
|
||||
$user->enable = $enabled ? 1 : 0;
|
||||
$user->is_admin = $isAdmin;
|
||||
$user->isLogin = true;
|
||||
Auth::$user = $user;
|
||||
AdminPermission::$superAdmin = $isSuper;
|
||||
};
|
||||
$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
|
||||
require dirname(__DIR__) . '/config/routes_cloud.php';
|
||||
$requestApi = static function (string $path, array $query = []) use ($app): array {
|
||||
$request = Request::createFromEnvironment(Environment::mock([
|
||||
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => $path,
|
||||
]))->withQueryParams($query);
|
||||
$response = $app->process($request, new Response());
|
||||
return [$response, json_decode((string) $response->getBody(), true)];
|
||||
};
|
||||
$login(true, true);
|
||||
[$response, $payload] = $requestApi('/api/v1/admin/instances', ['user_id' => '2']);
|
||||
$assert($response->getStatusCode() === 200 && $ids($payload['items']) === [206]
|
||||
&& $response->getHeaderLine('Cache-Control') === 'private, no-store',
|
||||
'The registered administrator list route did not provide a private scoped database response.');
|
||||
[$response, $payload] = $requestApi('/api/v1/admin/instances/206');
|
||||
$assert($response->getStatusCode() === 200 && (int) $payload['instance']['id'] === 206,
|
||||
'The registered administrator detail route did not dispatch the database read model.');
|
||||
foreach ([['q' => ['bad']], ['page' => '0'], ['host_id' => ['8']]] as $query) {
|
||||
[$response, $payload] = $requestApi('/api/v1/admin/instances', $query);
|
||||
$assert($response->getStatusCode() === 400 && isset($payload['error']),
|
||||
'Malformed query parameters escaped CloudApi as a server error.');
|
||||
}
|
||||
foreach (['211', '999999'] as $id) {
|
||||
[$response] = $requestApi('/api/v1/admin/instances/' . $id);
|
||||
$assert($response->getStatusCode() === 404, 'Registered detail disclosed a missing/deleted instance.');
|
||||
}
|
||||
$login(true);
|
||||
[$response, $payload] = $requestApi('/api/v1/admin/instances/206');
|
||||
$assert($response->getStatusCode() === 200 && $payload['instance']['can_manage'] === false,
|
||||
'Read-only administrators must retain global read access without mutation capability.');
|
||||
$login(false);
|
||||
foreach (['/api/v1/admin/instances', '/api/v1/admin/instances/206'] as $path) {
|
||||
[$response] = $requestApi($path);
|
||||
$assert($response->getStatusCode() === 403, 'A customer reached a registered administrator route.');
|
||||
}
|
||||
$login(true, true, false);
|
||||
[$response] = $requestApi('/api/v1/admin/instances');
|
||||
$assert($response->getStatusCode() === 401, 'Disabled accounts bypassed CloudAccess authentication.');
|
||||
Auth::$user = null;
|
||||
[$response] = $requestApi('/api/v1/admin/instances');
|
||||
$assert($response->getStatusCode() === 401, 'Anonymous requests bypassed CloudAccess authentication.');
|
||||
|
||||
// The controller also works without middleware attributes and must request
|
||||
// actor(false), preserving the no-engine-session guarantee in this path.
|
||||
$login(true, true);
|
||||
$direct = (new CloudAdminInstanceController())->index(
|
||||
Request::createFromEnvironment(Environment::mock([
|
||||
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/api/v1/admin/instances',
|
||||
])), new Response()
|
||||
);
|
||||
$assert($direct->getStatusCode() === 200, 'Controller fallback authentication broke database-only reads.');
|
||||
$assert(CloudEngineClient::$calls === 0 && CloudSessionService::$calls === 0,
|
||||
'The service, middleware, or controller read path contacted the private engine/session service.');
|
||||
|
||||
echo 'Administrator instance SQL filtering, pagination, ownership, DTO safety and bounded queries passed ('
|
||||
. implode('/', $queryCounts) . " queries for 20/100 rows).\n";
|
||||
echo "Administrator instance registered API routes, authorization, validation and session isolation passed.\n";
|
||||
}
|
||||
Loading…
Reference in New Issue