From 4c3e98cad7caffc0640f463e0d86125ea70fa011 Mon Sep 17 00:00:00 2001 From: admin Date: Tue, 29 Sep 2026 18:21:59 +0800 Subject: [PATCH] perf: server-render SSH key page --- web/app/Controllers/CloudPageController.php | 15 +- web/app/Middleware/CloudApi.php | 8 +- web/public/cloud/ssh-keys.js | 247 +++++++++++++++--- .../views/venix/cloud/pages/keys.tpl | 20 +- web/resources/views/venix/layout_assets.tpl | 2 +- web/tests/CloudSessionSecurityTest.php | 35 +++ web/tests/CloudSshKeyPageSsrContractTest.php | 95 +++++++ 7 files changed, 382 insertions(+), 40 deletions(-) create mode 100644 web/tests/CloudSshKeyPageSsrContractTest.php diff --git a/web/app/Controllers/CloudPageController.php b/web/app/Controllers/CloudPageController.php index 3053e481..3a716505 100644 --- a/web/app/Controllers/CloudPageController.php +++ b/web/app/Controllers/CloudPageController.php @@ -116,7 +116,18 @@ final class CloudPageController public function sshKeys($request, $response, $args) { - return $this->render($response, 'keys', 'SSH 公钥'); + $actor = CloudAccess::actor(false); + $user = $request->getAttribute('auth_user') ?? Auth::getUser(); + $keys = CloudDeploymentPageService::sshKeys((int) $actor['user_id']); + $payload = [ + 'user' => $this->userBootstrap($user, $actor), + 'ssh_keys' => $keys, + ]; + + return $this->render($response, 'keys', 'SSH 公钥', '', '', [ + 'cloud_ssh_keys' => $keys, + 'cloud_ssh_keys_bootstrap_json' => $this->safeJson($payload), + ]); } public function invoices($request, $response, $args) @@ -265,6 +276,8 @@ final class CloudPageController $smarty->assign('cloud_deploy_default_host_id', 0); $smarty->assign('cloud_deploy_catalog_unavailable', false); $smarty->assign('cloud_deploy_bootstrap_json', '{}'); + $smarty->assign('cloud_ssh_keys', []); + $smarty->assign('cloud_ssh_keys_bootstrap_json', '{}'); $smarty->assign('cloud_reinstall_vm', []); $smarty->assign('cloud_reinstall_template_groups', []); $smarty->assign('cloud_reinstall_ssh_keys', []); diff --git a/web/app/Middleware/CloudApi.php b/web/app/Middleware/CloudApi.php index 0a6e9254..4ac61dd6 100644 --- a/web/app/Middleware/CloudApi.php +++ b/web/app/Middleware/CloudApi.php @@ -12,10 +12,12 @@ final class CloudApi { try { $path = (string) $request->getUri()->getPath(); - // Billing and paginated instance snapshots are owned entirely by - // PHP and never call the private libvirt engine. Authenticating - // these routes must therefore not create a cloud_sessions row. + // Billing, SSH keys and paginated instance snapshots are owned + // entirely by PHP and never call the private libvirt engine. + // Authenticating these routes must therefore not create a + // cloud_sessions row. $databaseOnly = preg_match('#^/api/v1/invoices(?:/|$)#D', $path) === 1 + || preg_match('#^/api/v1/ssh-keys(?:/|$)#D', $path) === 1 || $path === '/api/v1/vms/page'; $actor = CloudAccess::actor(!$databaseOnly); if (AdminCsrf::requiresProtection($request->getMethod())) { diff --git a/web/public/cloud/ssh-keys.js b/web/public/cloud/ssh-keys.js index c1e6e136..eec519f5 100644 --- a/web/public/cloud/ssh-keys.js +++ b/web/public/cloud/ssh-keys.js @@ -1,38 +1,217 @@ -const runtimeUrl = new URL('/cloud/runtime.js', location.origin); -const assetVersion = new URL(import.meta.url).searchParams.get('v'); -if (assetVersion) runtimeUrl.searchParams.set('v', assetVersion); -const { - api, bindPageCleanup, byId, initializeSession, loadKeys, showError, toast, -} = await import(runtimeUrl.href); - -export async function initialize() { +// The saved-key list and the user/CSRF bootstrap are rendered into the +// first HTML response. This module owns only the add/delete interactions and +// deliberately does not load the all-feature VM runtime or a session endpoint. +const byId = id => document.getElementById(id); +const state = { csrfToken: '', keys: [], mutationBusy: false }; + +function showError(id, message = '') { + const target = byId(id); + if (!target) return; + target.textContent = message; + target.hidden = !message; +} + +let toastTimer; +function toast(message, kind = '') { + const target = byId('toast'); + if (!target) return; + target.textContent = message; + target.className = `toast ${kind}`; + target.hidden = false; + clearTimeout(toastTimer); + toastTimer = setTimeout(() => { target.hidden = true; }, 5000); +} + +function requireSecureTransport() { + if (location.protocol !== 'https:' + && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) { + throw new Error('请通过 HTTPS 管理 SSH 公钥。'); + } +} + +async function api(path, options = {}) { + const method = String(options.method || 'GET').toUpperCase(); + const headers = new Headers({ Accept: 'application/json', ...options.headers }); + if (!['GET', 'HEAD'].includes(method)) { + requireSecureTransport(); + headers.set('X-CSRF-Token', state.csrfToken); + if (options.body !== undefined) headers.set('Content-Type', 'application/json'); + } + const response = await fetch(path, { + ...options, + method, + headers, + credentials: 'same-origin', + cache: 'no-store', + body: options.body === undefined ? undefined : JSON.stringify(options.body), + }); + let payload = null; + if (response.status !== 204) { + try { payload = await response.json(); } + catch { throw new Error('服务返回了非 JSON 数据,请检查 PHP 及反代配置。'); } + } + if (response.status === 401) { + location.assign('/auth/login'); + throw new Error('登录已过期。'); + } + if (!response.ok || payload?.ret === 0) { + const detail = Array.isArray(payload?.detail) + ? payload.detail.map(item => item.msg || '输入错误').join(';') : payload?.detail; + throw new Error(String(detail || payload?.message || payload?.msg || payload?.error + || `请求失败 (${response.status})`)); + } + return payload; +} + +function normalizeKey(value) { + if (!value || typeof value !== 'object' || Array.isArray(value)) return null; + const id = String(value.id ?? ''); + const name = String(value.name ?? '').trim(); + if (!/^[1-9]\d*$/.test(id) || !name) return null; + return { id, name, fingerprint: String(value.fingerprint ?? '').trim() }; +} + +function readBootstrap() { + const source = byId('ssh-keys-bootstrap'); + if (!source) throw new Error('公钥页面初始数据缺失,请刷新后重试。'); + let payload; + try { payload = JSON.parse(source.textContent || '{}'); } + catch { throw new Error('公钥页面初始数据无效,请刷新后重试。'); } + const user = payload?.user; + if (!user || typeof user !== 'object' + || !/^[a-f0-9]{64}$/.test(String(user.csrf_token || '')) + || !/^[1-9]\d*$/.test(String(user.user_id || '')) + || !Array.isArray(payload?.ssh_keys)) { + throw new Error('公钥页面初始数据不完整,请刷新后重试。'); + } + const keys = payload.ssh_keys.map(normalizeKey); + if (keys.some(key => key === null)) { + throw new Error('公钥列表数据无效,请刷新后重试。'); + } + state.csrfToken = String(user.csrf_token); + state.keys = keys; +} + +function makeElement(tag, className = '', content) { + const element = document.createElement(tag); + if (className) element.className = className; + if (content !== undefined) element.textContent = String(content); + return element; +} + +function renderKeys() { + const container = byId('ssh-keys-list'); + if (!container) return; + container.replaceChildren(); + if (!state.keys.length) { + container.append(makeElement('p', 'muted', '还没有公钥。')); + return; + } + for (const key of state.keys) { + const row = makeElement('div', 'ssh-key-row'); + row.dataset.sshKeyId = key.id; + const details = makeElement('div', 'ssh-key-details'); + details.append(makeElement('strong', '', key.name), + makeElement('small', '', key.fingerprint)); + const actions = makeElement('div', 'ssh-key-actions'); + const button = makeElement('button', 'row-button ssh-key-delete', '删除'); + button.type = 'button'; + button.dataset.sshKeyDelete = key.id; + actions.append(button); + row.append(details, actions); + container.append(row); + } +} + +function setMutationBusy(busy) { + state.mutationBusy = busy; + const save = byId('ssh-key-save-button'); + if (save) save.disabled = busy; + byId('ssh-keys-list')?.setAttribute('aria-busy', String(busy)); + document.querySelectorAll('[data-ssh-key-delete]').forEach(button => { + button.disabled = busy; + }); +} + +async function addKey(event) { + event.preventDefault(); + if (state.mutationBusy) return; + setMutationBusy(true); + showError('ssh-key-form-error'); try { - if (!await initializeSession('keys')) return; - bindPageCleanup(); - byId('ssh-key-form')?.addEventListener('submit', async event => { - event.preventDefault(); - const button = byId('ssh-key-save-button'); - button.disabled = true; - showError('ssh-key-form-error', ''); - try { - await api('/api/v1/ssh-keys', { method: 'POST', body: { - name: byId('ssh-key-name').value.trim(), - public_key: byId('ssh-key-public-key').value.trim(), - } }); - byId('ssh-key-form').reset(); - await loadKeys(); - toast('公钥已保存。', 'success'); - } catch (error) { showError('ssh-key-form-error', error.message); } - finally { button.disabled = false; } + const result = await api('/api/v1/ssh-keys', { method: 'POST', body: { + name: byId('ssh-key-name').value.trim(), + public_key: byId('ssh-key-public-key').value.trim(), + } }); + const key = normalizeKey(result); + if (!key) throw new Error('公钥已保存,但服务返回的列表数据无效,请刷新页面。'); + state.keys = [...state.keys.filter(item => item.id !== key.id), key]; + byId('ssh-key-form').reset(); + renderKeys(); + toast('公钥已保存。', 'success'); + } catch (error) { + showError('ssh-key-form-error', error?.message || '公钥保存失败,请稍后重试。'); + } finally { + setMutationBusy(false); + } +} + +async function deleteKey(button) { + if (state.mutationBusy) return; + const id = String(button.dataset.sshKeyDelete || ''); + const key = state.keys.find(item => item.id === id); + if (!key || !confirm(`删除公钥“${key.name}”?已创建的虚拟机不受影响。`)) return; + setMutationBusy(true); + showError('ssh-keys-list-error'); + try { + await api(`/api/v1/ssh-keys/${encodeURIComponent(id)}`, { method: 'DELETE' }); + state.keys = state.keys.filter(item => item.id !== id); + renderKeys(); + toast('公钥已删除。', 'success'); + } catch (error) { + showError('ssh-keys-list-error', error?.message || '公钥删除失败,请稍后重试。'); + } finally { + setMutationBusy(false); + } +} + +async function importKeyFile(event) { + showError('ssh-key-form-error'); + const file = event.target.files?.[0]; + if (!file) return; + if (file.size > 16384) { + showError('ssh-key-form-error', '公钥文件超过 16 KiB 限制。'); + return; + } + try { + const content = await file.text(); + if (/PRIVATE KEY/.test(content)) { + showError('ssh-key-form-error', '不能导入私钥,只能导入 .pub 公钥。'); + return; + } + byId('ssh-key-public-key').value = content.trim(); + } catch { + showError('ssh-key-form-error', '无法读取公钥文件,请重新选择。'); + } +} + +export function initialize() { + try { + readBootstrap(); + byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout')); + byId('ssh-key-form')?.addEventListener('submit', addKey); + byId('ssh-key-file')?.addEventListener('change', importKeyFile); + byId('ssh-keys-list')?.addEventListener('click', event => { + const button = event.target instanceof Element + ? event.target.closest('[data-ssh-key-delete]') : null; + if (button) void deleteKey(button); }); - byId('ssh-key-file')?.addEventListener('change', async event => { - const file = event.target.files?.[0]; - if (!file) return; - if (file.size > 16384) return showError('ssh-key-form-error', '公钥文件超过 16 KiB 限制。'); - const content = await file.text(); - if (/PRIVATE KEY/.test(content)) return showError('ssh-key-form-error', '不能导入私钥,只能导入 .pub 公钥。'); - byId('ssh-key-public-key').value = content.trim(); + } catch (error) { + showError('cloud-page-error', error?.message + || '公钥页面初始化失败,请刷新后重试。'); + byId('ssh-key-save-button')?.setAttribute('disabled', ''); + document.querySelectorAll('[data-ssh-key-delete]').forEach(button => { + button.disabled = true; }); - await loadKeys(); - } catch (error) { showError('cloud-page-error', error.message); } + } } diff --git a/web/resources/views/venix/cloud/pages/keys.tpl b/web/resources/views/venix/cloud/pages/keys.tpl index 22388ef0..04c0c3bf 100644 --- a/web/resources/views/venix/cloud/pages/keys.tpl +++ b/web/resources/views/venix/cloud/pages/keys.tpl @@ -14,7 +14,25 @@
⌑

我的公钥

公钥不会向其他用户显示;删除后,不影响已经创建的虚拟机。

-

正在加载…

+
+ {if empty($cloud_ssh_keys)} +

还没有公钥。

+ {else} + {foreach $cloud_ssh_keys as $key} +
+
+ {$key.name|escape:"html"} + {$key.fingerprint|escape:"html"} +
+
+ +
+
+ {/foreach} + {/if} +
+ + diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 9d8546e2..513dc452 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1 +1 @@ -{assign var=venix_asset_version value='2026092901' scope='global'} +{assign var=venix_asset_version value='2026092902' scope='global'} diff --git a/web/tests/CloudSessionSecurityTest.php b/web/tests/CloudSessionSecurityTest.php index c8843674..5d3a7d30 100644 --- a/web/tests/CloudSessionSecurityTest.php +++ b/web/tests/CloudSessionSecurityTest.php @@ -94,6 +94,28 @@ namespace { $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 an engine cloud session.'); $billingRequest = Request::createFromEnvironment(Environment::mock([ 'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/api/v1/invoices/1/status', ])); @@ -120,6 +142,19 @@ namespace { && is_array($instancePageActor) && ($instancePageActor['session_id'] ?? null) === '' && CloudSession::count() === $sessionCount, 'Database-only VM pagination created or queried an engine 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 an engine 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"; } diff --git a/web/tests/CloudSshKeyPageSsrContractTest.php b/web/tests/CloudSshKeyPageSsrContractTest.php new file mode 100644 index 00000000..b666343a --- /dev/null +++ b/web/tests/CloudSshKeyPageSsrContractTest.php @@ -0,0 +1,95 @@ +sshKeyOptions(')) + && str_contains($pageMethod, "'user' => \$this->userBootstrap(\$user, \$actor)") + && str_contains($pageMethod, "'ssh_keys' => \$keys") + && str_contains($pageMethod, "'cloud_ssh_keys' => \$keys") + && str_contains($pageMethod, "'cloud_ssh_keys_bootstrap_json' => \$this->safeJson(\$payload)"), + 'SSH-key controller must embed an owner-scoped first-paint list and session bootstrap.'); +$assert(str_contains($controller, 'JSON_HEX_TAG') + && str_contains($controller, "'csrf_token' => AdminCsrf::token()") + && str_contains($controller, "withHeader('Cache-Control', 'private, no-store')"), + 'SSH-key HTML bootstrap must be script-safe, authenticated and non-cacheable.'); +$assert(str_contains($keyService, "CloudSSHKey::where('user_id', \$userId)") + && str_contains($keyService, "'id', 'name', 'fingerprint', 'created_at'") + && !str_contains($keyService, "'public_key'") + && !str_contains($keyOptions, "'public_key'"), + 'The server-rendered key list must be owner scoped and omit key material.'); + +$assert(str_contains($template, 'id="ssh-keys-bootstrap" type="application/json"') + && str_contains($template, '{$cloud_ssh_keys_bootstrap_json nofilter}') + && str_contains($template, '{foreach $cloud_ssh_keys as $key}') + && str_contains($template, '{$key.name|escape:"html"}') + && str_contains($template, '{$key.fingerprint|escape:"html"}') + && str_contains($template, '还没有公钥。') + && !str_contains($template, '正在加载') + && !str_contains($template, '$key.public_key'), + 'SSH-key HTML must render the initial owner-scoped rows instead of a loading shell.'); + +$assert(!str_contains($module, '/cloud/runtime.js') + && !str_contains($module, '/api/v1/session') + && !str_contains($module, 'initializeSession') + && str_contains($module, 'ssh-keys-bootstrap') + && (str_contains($module, 'function hydrate(') + || str_contains($module, 'function readBootstrap(')), + 'SSH-key interactions must hydrate the embedded payload without the all-feature runtime or session API.'); +$assert($initialize !== '' + && !preg_match("/api\\(\\s*['\"]\\/api\\/v1\\/ssh-keys['\"]\\s*\\)/", $module) + && !preg_match("/fetch\\(\\s*['\"]\\/api\\/v1\\/ssh-keys['\"]\\s*\\)/", $module), + 'SSH-key first paint must not issue an unqualified collection GET after hydration.'); +$assert(str_contains($module, '/api/v1/ssh-keys') + && str_contains($module, "method: 'POST'") + && str_contains($module, "method: 'DELETE'"), + 'SSH-key JavaScript must retain explicit create and delete mutations.'); +$assert(str_contains($keyApi, + "['id' => (int) \$key->id, 'name' => \$key->name, 'fingerprint' => \$key->fingerprint]") + && !str_contains($keyApi, "'public_key' => \$key->public_key"), + 'SSH-key create API must return the safe fields required for local list hydration.'); + +$assert(str_contains($middleware, 'CloudAccess::actor(!$databaseOnly)') + && str_contains($middleware, '#^/api/v1/ssh-keys(?:/|$)#D'), + 'SSH-key API calls are database-only and must not create or contact a cloud engine session.'); + +echo "SSH-key server-rendered first-page performance contract passed.\n";