Add per-user SSH public key library for cloud VMs

main
admin 2 months ago
parent 4474610ea9
commit 62c7b51c3e

@ -91,6 +91,8 @@ SELECT id, username, email FROM users WHERE id = 1;
选择模板后,填写 VM 资源、已分配给你的**具体公网 IPv4/CIDR**(如实际公网地址加 `/24` 或 `/28`)、同网段网关、1–4 个公网 DNS 地址,再选择一种 root 登录方式:填写 OpenSSH **公钥**时,只能用对应私钥登录 `root@<公网IP>`,密码输入会隐藏;不填公钥时,可以设置 12–128 字符的初始 root 密码,可用它从 VNC 和 SSH 登录;公钥和密码都不填时,面板会自动生成强初始 root 密码。客体登录密钥与连接宿主机的 root 私钥是两套独立凭据。面板会校验公网地址、网络/广播地址、网关和已由面板分配的重复 IP;它无法检测面板外设备的 IP 占用,也无法替服务商分配或路由公网 IP。当前版本只支持网关与 VM IP 同一子网的桥接 IPv4;服务商给出 `/32` 或异网段网关时不要强填,需另做路由网络模式。上游网络还必须允许 VM 使用额外 MAC,`br0` 本身不能保证公网可达。
每个已登录用户都可导入并命名自己的**单行 OpenSSH 公钥**:已审核账号从侧栏“公钥管理”进入,等待审核的账号可用“管理我的公钥”入口。可以粘贴 `.pub` 文件内容,或在浏览器选择本地 `.pub` 文件填入表单;面板只接受公钥,不要选择或粘贴私钥。列表只显示当前账户导入的公钥;管理员账户也不能把另一个用户的公钥当作自己的预设公钥使用。创建公网云镜像 VM 时可以选择已导入的公钥,不必重复粘贴;也可以继续临时手动填写公钥,或选择初始 root 密码。预设公钥、手动公钥与密码不能同时使用。未通过管理员审核的用户可以管理自己的公钥,但仍不能创建虚拟机。删除公钥只删除面板中的预设记录,**不会撤销已经写入现有虚拟机的 SSH 授权密钥**;要撤销现有 VM 的访问权限,需在客体系统中删除对应的 `authorized_keys` 条目或重装并更换登录密钥。
创建时,面板在 B 的磁盘池克隆独立 qcow2 磁盘并扩容,生成一个只读、不可启动的 `CIDATA` cloud-init 配置 ISO,经 libvirt 上传后挂载。客体首次直接从硬盘开机,cloud-init 按固定 MAC 配置静态公网 IP、默认网关和 DNS;**不会进入 VNC 安装程序**。[AlmaLinux 本地云镜像用法](https://wiki.almalinux.org/cloud/Generic-cloud-on-local)、[NoCloud 配置说明](https://docs.cloud-init.io/en/latest/reference/datasources/nocloud.html)。有公钥时,面板将其写入 root 的授权密钥并禁用 SSH 密码登录,root 密码保持锁定(VNC 密码登录也不可用);无公钥时,面板把加盐的 SHA-512-crypt 密码哈希写入配置 ISO,并开启 root 的 SSH 密码登录;生成或手填的初始密码还会在 MariaDB 中加密保存,供详情页按需查看或复制。密码模式会暴露公网 root 密码认证,建议优先使用公钥及限制 SSH 来源;宿主机上的配置 ISO 仍含密码哈希,必须防止未授权读取。网络或凭据填错后需离线修复或重建。删除 VM 时若勾选“同时删除虚拟磁盘”,面板也会删除其配置 ISO,但**保留共享模板镜像**。这项登录方式变更只对新创建的 VM 生效,不会修改已有 VM。
面板创建的公网云镜像 VM 在详情页有“重装”按钮。点击后选择当前宿主机已导入的云镜像模板,输入 VM 名称确认;可填写新的 root SSH 公钥或 12–128 字符的初始 root 密码,二者均不填时会生成强密码。密码模式下,无论密码是自动生成还是手动输入,成功重装后的初始密码都会在 MariaDB 中加密保存,并可在虚拟机详情页按需查看或复制;公钥模式会清除面板此前保存的密码。自动生成的密码仍会在任务成功后显示,管理员点击“已保存密码,完成”只会从**任务记录**中清除密码,不影响详情页保存的初始密码。同一浏览器标签页刷新或面板进程重启后仍可按任务编号查询,直到确认保存密码为止。重装自动读取原配置盘中的公网 IP/CIDR、网关、DNS 和 MAC,不要求再次手填网络。运行中的 VM 会先收到正常关机请求;120 秒内未关机则中止,不会强制断电,也不会切换或删除旧系统盘。面板会将所选模板克隆到新系统盘,生成新的 cloud-init 配置盘并启动 VM;新系统尚未启动时切换失败会恢复原定义,旧盘保留。如果启动调用结果不确定但发现新盘已在运行,则保留新旧两份磁盘并提示人工核查。**libvirt 报告新 VM 已启动后,面板会自动删除旧系统盘与旧配置盘;这并不能证明客体系统、网络或 SSH 已工作,旧数据一旦删除不可恢复。** 若旧盘清理失败,任务仍返回成功但附带警告,需在宿主机核查残留卷。此功能仅支持面板创建且配置未被外部修改的公网云镜像 VM,不支持 ISO 安装 VM、快照或多网卡/多磁盘 VM。

@ -25,6 +25,8 @@ const state = {
metricsPayload: null,
metricsResizeTimer: null,
resources: null,
sshKeys: [],
sshKeysLoad: null,
templateLoad: null,
templateImportJobId: null,
loadingVMs: false,
@ -216,6 +218,8 @@ function showLogin() {
state.approved = false;
state.hostReady = false;
state.vms = [];
state.sshKeys = [];
state.sshKeysLoad = null;
state.resources = null;
state.hostConfig = null;
state.templateLoad = null;
@ -227,6 +231,11 @@ function showLogin() {
fillSelect("vm-network", [], "network");
fillSelect("vm-iso", [], "iso");
fillTemplateSelect([]);
fillSshKeySelect([]);
byId("ssh-keys-list").replaceChildren();
byId("ssh-key-form").reset();
showError("ssh-key-form-error", "");
showError("ssh-keys-list-error", "");
text("vm-detail-name", "虚拟机");
text("vm-detail-header-ip", "未获取");
text("vm-detail-header-region", "未设置");
@ -271,8 +280,8 @@ function showAccessWait(kind) {
text("wait-eyebrow", approval ? "ACCOUNT APPROVAL" : "HOST SETUP");
text("wait-title", approval ? "等待管理员审核" : "等待管理员配置宿主机");
text("wait-description", approval
? "邮箱已验证,账号正在等待管理员审核。审核通过后才能创建和管理虚拟机。"
: "管理员尚未完成宿主机配置,暂时无法创建或管理虚拟机。请稍后点击“刷新状态”。");
? "邮箱已验证,账号正在等待管理员审核。审核通过后才能创建和管理虚拟机;现在可以先导入自己的公钥。"
: "管理员尚未完成宿主机配置,暂时无法创建或管理虚拟机。现在可以先导入自己的公钥,稍后点击“刷新状态”。");
byId("boot-screen").hidden = true;
for (const id of ["database-view", "setup-view", "login-view", "host-view", "unlock-view", "dashboard-view"]) byId(id).hidden = true;
byId("access-wait-view").hidden = false;
@ -434,6 +443,13 @@ async function showDashboard(session) {
function applySession(session) {
state.sessionEpoch += 1;
state.sshKeys = [];
state.sshKeysLoad = null;
fillSshKeySelect([]);
byId("ssh-keys-list").replaceChildren();
byId("ssh-key-form").reset();
showError("ssh-key-form-error", "");
showError("ssh-keys-list-error", "");
state.csrfToken = session.csrf_token || "";
state.username = session.username || "用户";
state.admin = session.admin === true;
@ -443,7 +459,7 @@ function applySession(session) {
for (const id of ["host-settings-button", "host-settings-mobile-button", "update-settings-button", "update-settings-mobile-button", "smtp-settings-button", "smtp-settings-mobile-button", "host-update-button", "unlock-update-button", "unlock-settings-button"]) {
byId(id).hidden = !state.admin;
}
byId("admin-menu").hidden = !state.admin;
byId("admin-menu").hidden = false;
byId("admin-menu").open = false;
byId("template-import").hidden = !state.admin;
text("current-username", state.username);
@ -481,6 +497,10 @@ async function initialize() {
}
function showVmWorkspace() {
if (!state.admin && (!state.approved || !state.hostReady)) {
showAccessWait(state.approved ? "host" : "approval");
return;
}
byId("admin-menu").open = false;
stopVmMetrics();
clearVmCredential();
@ -488,11 +508,14 @@ function showVmWorkspace() {
byId("vm-workspace").hidden = false;
byId("vm-list-view").hidden = false;
byId("vm-detail-view").hidden = true;
byId("ssh-keys-workspace").hidden = true;
byId("update-workspace").hidden = true;
byId("smtp-workspace").hidden = true;
byId("smtp-password").value = "";
byId("vm-navigation-button").classList.add("active");
byId("vm-navigation-button").setAttribute("aria-current", "page");
byId("ssh-keys-button").classList.remove("active");
byId("ssh-keys-button").removeAttribute("aria-current");
byId("update-settings-button").classList.remove("active");
byId("update-settings-button").removeAttribute("aria-current");
byId("smtp-settings-button").classList.remove("active");
@ -500,6 +523,131 @@ function showVmWorkspace() {
text("breadcrumb-current", "虚拟机");
}
async function showSshKeysWorkspace() {
if (!state.csrfToken) return;
byId("access-wait-view").hidden = true;
byId("dashboard-view").hidden = false;
byId("admin-menu").open = false;
state.updateReturnView = null;
stopVmMetrics();
clearVmCredential();
state.selectedVmId = null;
byId("vm-workspace").hidden = true;
byId("update-workspace").hidden = true;
byId("smtp-workspace").hidden = true;
byId("smtp-password").value = "";
byId("ssh-keys-workspace").hidden = false;
for (const id of ["vm-navigation-button", "update-settings-button", "smtp-settings-button"]) {
byId(id).classList.remove("active");
byId(id).removeAttribute("aria-current");
}
byId("ssh-keys-button").classList.add("active");
byId("ssh-keys-button").setAttribute("aria-current", "page");
text("breadcrumb-current", "公钥管理");
showError("ssh-key-form-error", "");
showError("ssh-keys-list-error", "");
if (!state.sshKeys.length) byId("ssh-keys-list").replaceChildren(makeElement("p", "muted", "正在加载…"));
try {
await loadSshKeys();
} catch (error) {
showError("ssh-keys-list-error", `无法读取公钥:${error.message}`);
}
}
function fillSshKeySelect(items) {
const select = byId("vm-guest-ssh-key-id");
const previous = select.value;
select.replaceChildren();
const placeholder = document.createElement("option");
placeholder.value = "";
placeholder.textContent = items.length ? "不使用已保存公钥" : "尚无已保存公钥,可手动填写";
select.append(placeholder);
for (const item of items) {
const id = Number(item?.id);
if (!Number.isSafeInteger(id) || id <= 0) continue;
const option = document.createElement("option");
option.value = String(id);
const fingerprint = String(item.fingerprint || "");
option.textContent = `${String(item.name || `公钥 ${id}`)}${fingerprint ? ` · ${fingerprint.slice(0, 20)}…` : ""}`;
select.append(option);
}
if (previous && Array.from(select.options).some((option) => option.value === previous)) select.value = previous;
select.disabled = selectedCreateSource() !== "cloud" || select.options.length <= 1;
updateCreateAuthMode();
}
function sshKeyCreatedAt(value) {
if (value === null || value === undefined || value === "") return "未记录";
const parsed = typeof value === "number" ? new Date(value * 1000) : new Date(value);
return Number.isFinite(parsed.getTime()) ? parsed.toLocaleString() : "未记录";
}
function renderSshKeys() {
const list = byId("ssh-keys-list");
list.replaceChildren();
if (!state.sshKeys.length) {
list.append(makeElement("p", "muted", "还没有保存公钥。导入后,创建云镜像虚拟机时即可直接选择。"));
return;
}
for (const key of state.sshKeys) {
const row = makeElement("div", "ssh-key-row");
const details = makeElement("div", "ssh-key-details");
details.append(makeElement("strong", "", key.name || `公钥 ${key.id}`));
details.append(makeElement("code", "", key.fingerprint || "指纹未记录"));
details.append(makeElement("small", "", `添加时间:${sshKeyCreatedAt(key.created_at)}`));
const actions = makeElement("div", "ssh-key-actions");
const copy = makeElement("button", "button button-outline small", "复制公钥");
copy.type = "button";
copy.disabled = !key.public_key;
copy.addEventListener("click", async () => {
try {
await copyText(key.public_key);
toast("公钥已复制。", "success");
} catch (error) {
toast(error.message, "error");
}
});
const remove = makeElement("button", "button button-outline small ssh-key-delete", "删除");
remove.type = "button";
remove.addEventListener("click", async () => {
if (!window.confirm(`确定删除公钥“${key.name}”?已经创建的虚拟机不会受影响。`)) return;
showError("ssh-keys-list-error", "");
setButtonBusy(remove, true, "删除中…");
try {
await api(`/api/v1/ssh-keys/${encodeURIComponent(String(key.id))}`, { method: "DELETE" });
await loadSshKeys();
toast("公钥已删除。", "success");
} catch (error) {
showError("ssh-keys-list-error", error.message);
} finally {
if (remove.isConnected) setButtonBusy(remove, false);
}
});
actions.append(copy, remove);
row.append(details, actions);
list.append(row);
}
}
async function loadSshKeys() {
if (state.sshKeysLoad) return state.sshKeysLoad;
const epoch = state.sessionEpoch;
const request = api("/api/v1/ssh-keys");
state.sshKeysLoad = request;
try {
const result = await request;
if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return;
state.sshKeys = (Array.isArray(result?.items) ? result.items : []).filter((item) => {
const id = Number(item?.id);
return Number.isSafeInteger(id) && id > 0;
});
fillSshKeySelect(state.sshKeys);
renderSshKeys();
} finally {
if (state.sshKeysLoad === request) state.sshKeysLoad = null;
}
}
function openUpdateFromGate(returnView) {
if (!state.admin) return;
if (returnView === "host") {
@ -536,11 +684,14 @@ async function showUpdateWorkspace() {
stopVmMetrics();
clearVmCredential();
byId("vm-workspace").hidden = true;
byId("ssh-keys-workspace").hidden = true;
byId("smtp-workspace").hidden = true;
byId("smtp-password").value = "";
byId("update-workspace").hidden = false;
byId("vm-navigation-button").classList.remove("active");
byId("vm-navigation-button").removeAttribute("aria-current");
byId("ssh-keys-button").classList.remove("active");
byId("ssh-keys-button").removeAttribute("aria-current");
byId("update-settings-button").classList.add("active");
byId("update-settings-button").setAttribute("aria-current", "page");
byId("smtp-settings-button").classList.remove("active");
@ -624,10 +775,13 @@ async function showSmtpWorkspace() {
stopVmMetrics();
clearVmCredential();
byId("vm-workspace").hidden = true;
byId("ssh-keys-workspace").hidden = true;
byId("update-workspace").hidden = true;
byId("smtp-workspace").hidden = false;
byId("vm-navigation-button").classList.remove("active");
byId("vm-navigation-button").removeAttribute("aria-current");
byId("ssh-keys-button").classList.remove("active");
byId("ssh-keys-button").removeAttribute("aria-current");
byId("update-settings-button").classList.remove("active");
byId("update-settings-button").removeAttribute("aria-current");
byId("smtp-settings-button").classList.add("active");
@ -1651,8 +1805,12 @@ function selectedCreateSource() {
function updateCreateAuthMode() {
const cloud = selectedCreateSource() === "cloud";
const publicKey = byId("vm-guest-ssh-public-key");
const savedKeySelected = cloud && Boolean(byId("vm-guest-ssh-key-id").value);
byId("vm-manual-ssh-key-field").hidden = savedKeySelected;
if (savedKeySelected) publicKey.value = "";
publicKey.disabled = !cloud || savedKeySelected;
const password = byId("vm-root-password");
const passwordMode = cloud && !publicKey.value.trim();
const passwordMode = cloud && !savedKeySelected && !publicKey.value.trim();
byId("vm-root-password-field").hidden = !passwordMode;
password.required = false;
password.disabled = !passwordMode;
@ -1673,6 +1831,8 @@ function updateCreateSource() {
const template = byId("vm-template");
template.required = cloud;
template.disabled = !cloud || template.options.length <= 1;
const savedKey = byId("vm-guest-ssh-key-id");
savedKey.disabled = !cloud || savedKey.options.length <= 1;
["vm-public-ip-cidr", "vm-gateway", "vm-dns"].forEach((id) => {
const input = byId(id);
input.required = cloud;
@ -1680,7 +1840,6 @@ function updateCreateSource() {
});
const publicKey = byId("vm-guest-ssh-public-key");
publicKey.required = false;
publicKey.disabled = !cloud;
updateCreateAuthMode();
const network = byId("vm-network");
@ -1709,6 +1868,7 @@ function closeModal() {
const returnFocus = state.lastFocus;
if (state.activeModal.id === "console-modal") disconnectConsole();
if (state.activeModal.id === "create-modal") {
byId("vm-guest-ssh-key-id").value = "";
byId("vm-guest-ssh-public-key").value = "";
byId("vm-root-password").value = "";
}
@ -1751,6 +1911,7 @@ function openCreate() {
if (!state.resources) {
void loadResources().catch((error) => showError("create-error", `无法加载宿主机资源:${error.message}`));
}
void loadSshKeys().catch((error) => showError("create-error", `无法读取已保存公钥:${error.message}。仍可手动填写公钥。`));
}
function openDelete(vm) {
@ -2176,6 +2337,7 @@ byId("wait-refresh-button").addEventListener("click", async () => {
setButtonBusy(button, false);
}
});
byId("wait-ssh-keys-button").addEventListener("click", () => void showSshKeysWorkspace());
byId("smtp-settings-form").addEventListener("submit", async (event) => {
event.preventDefault();
@ -2226,11 +2388,15 @@ byId("host-settings-mobile-button").addEventListener("click", () => showHostView
byId("host-update-button").addEventListener("click", () => openUpdateFromGate("host"));
byId("unlock-update-button").addEventListener("click", () => openUpdateFromGate("unlock"));
byId("vm-navigation-button").addEventListener("click", leaveUpdateWorkspace);
byId("vm-navigation-mobile-button").addEventListener("click", leaveUpdateWorkspace);
byId("ssh-keys-button").addEventListener("click", () => void showSshKeysWorkspace());
byId("ssh-keys-mobile-button").addEventListener("click", () => void showSshKeysWorkspace());
byId("update-settings-button").addEventListener("click", () => void showUpdateWorkspace());
byId("update-settings-mobile-button").addEventListener("click", () => void showUpdateWorkspace());
byId("smtp-settings-button").addEventListener("click", () => void showSmtpWorkspace());
byId("smtp-settings-mobile-button").addEventListener("click", () => void showSmtpWorkspace());
byId("smtp-back-button").addEventListener("click", showVmWorkspace);
byId("ssh-keys-back-button").addEventListener("click", showVmWorkspace);
byId("update-back-button").addEventListener("click", leaveUpdateWorkspace);
byId("unlock-settings-button").addEventListener("click", () => showHostView(state.hostConfig || { configured: true }));
byId("host-back-button").addEventListener("click", () => {
@ -2478,12 +2644,57 @@ byId("vm-detail-back-button").addEventListener("click", () => {
byId("search-input").addEventListener("input", () => renderVMs());
byId("state-filter").addEventListener("change", () => renderVMs());
byId("create-button").addEventListener("click", openCreate);
byId("ssh-key-file").addEventListener("change", async (event) => {
const file = event.currentTarget.files?.[0];
if (!file) return;
showError("ssh-key-form-error", "");
try {
if (file.size > 16384) throw new Error("公钥文件不能超过 16 KiB;请选择 .pub 公钥文件,不要选择私钥。");
const publicKey = (await file.text()).trim();
if (!validSshPublicKey(publicKey)) throw new Error("文件内容不是受支持的单行 OpenSSH 公钥;请确认选择的是 .pub 文件而非私钥。");
byId("ssh-key-public-key").value = publicKey;
if (!byId("ssh-key-name").value.trim()) byId("ssh-key-name").value = file.name.replace(/\.pub$/i, "").slice(0, 80);
} catch (error) {
showError("ssh-key-form-error", error.message);
} finally {
event.currentTarget.value = "";
}
});
byId("ssh-key-form").addEventListener("submit", async (event) => {
event.preventDefault();
showError("ssh-key-form-error", "");
const name = byId("ssh-key-name").value.trim();
const publicKey = byId("ssh-key-public-key").value.trim();
if (!name || name.length > 80) {
showError("ssh-key-form-error", "请填写 1 至 80 个字符的公钥名称。");
return;
}
if (!validSshPublicKey(publicKey)) {
showError("ssh-key-form-error", "请填写单行 OpenSSH 公钥,例如 ssh-ed25519 AAAA…;不要填写私钥。");
return;
}
const button = byId("ssh-key-save-button");
setButtonBusy(button, true, "正在保存…");
try {
await api("/api/v1/ssh-keys", { method: "POST", body: { name, public_key: publicKey } });
byId("ssh-key-form").reset();
if (state.sshKeysLoad) await state.sshKeysLoad.catch(() => {});
await loadSshKeys();
toast("公钥已保存,创建云镜像虚拟机时可以直接选择。", "success");
} catch (error) {
showError("ssh-key-form-error", error.message);
} finally {
setButtonBusy(button, false);
}
});
byId("vm-guest-ssh-public-key").addEventListener("input", updateCreateAuthMode);
byId("vm-guest-ssh-key-id").addEventListener("change", updateCreateAuthMode);
document.querySelectorAll('input[name="source"]').forEach((radio) => radio.addEventListener("change", () => {
showError("create-error", "");
updateCreateSource();
if (selectedCreateSource() === "cloud") {
void loadTemplates().catch((error) => showError("create-error", `无法加载云镜像模板:${error.message}`));
void loadSshKeys().catch((error) => showError("create-error", `无法读取已保存公钥:${error.message}。仍可手动填写公钥。`));
}
}));
@ -2608,7 +2819,17 @@ byId("create-form").addEventListener("submit", async (event) => {
body.public_ip_cidr = String(data.get("public_ip_cidr") || "").trim();
body.gateway = String(data.get("gateway") || "").trim();
body.dns_servers = String(data.get("dns_servers") || "").split(/[\s,;]+/).filter(Boolean);
body.guest_ssh_public_key = String(data.get("guest_ssh_public_key") || "").trim();
const selectedKeyId = String(data.get("guest_ssh_key_id") || "");
if (selectedKeyId) {
const keyId = Number(selectedKeyId);
if (!Number.isSafeInteger(keyId) || keyId <= 0 || !state.sshKeys.some((key) => Number(key.id) === keyId)) {
showError("create-error", "所选公钥已不可用,请刷新公钥列表或重新选择。");
return;
}
body.guest_ssh_key_id = keyId;
} else {
body.guest_ssh_public_key = String(data.get("guest_ssh_public_key") || "").trim();
}
if (!body.network.startsWith("bridge:")) {
showError("create-error", "公网云镜像需要 Linux 网桥。请先在宿主机设置中配置 bridge:br0 等网桥。");
return;
@ -2634,7 +2855,7 @@ byId("create-form").addEventListener("submit", async (event) => {
showError("create-error", "请粘贴单行 OpenSSH 公钥;不要粘贴私钥。");
return;
}
} else {
} else if (!body.guest_ssh_key_id) {
const requestedPassword = String(data.get("root_password") || "");
if (requestedPassword && (requestedPassword.length < 12 || requestedPassword.length > 128)) {
showError("create-error", "自行设置的初始 root 密码需为 12 至 128 个字符;留空将自动生成强密码。");
@ -2653,7 +2874,7 @@ byId("create-form").addEventListener("submit", async (event) => {
byId("vm-root-password").value = "";
setButtonBusy(button, true, "正在创建…");
try {
const autoPassword = source === "cloud" && !body.guest_ssh_public_key && !body.root_password;
const autoPassword = source === "cloud" && !body.guest_ssh_key_id && !body.guest_ssh_public_key && !body.root_password;
await api("/api/v1/vms", { method: "POST", body });
closeModal();
toast(autoPassword

@ -5,8 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#101d2c" />
<title>VirtPilot · 虚拟机管理</title>
<link rel="stylesheet" href="/static/styles.css?v=vm-age-1" />
<script type="module" src="/static/app.js?v=vm-age-1"></script>
<link rel="stylesheet" href="/static/styles.css?v=ssh-keys-1" />
<script type="module" src="/static/app.js?v=ssh-keys-1"></script>
</head>
<body>
<div id="boot-screen" class="boot-screen" role="status" aria-live="polite">
@ -142,7 +142,7 @@
<main id="access-wait-view" class="host-layout" hidden>
<header class="host-topbar"><div class="host-brand"><span class="brand-mark"><span></span></span> VirtPilot</div><div class="host-topbar-actions"><span id="wait-current-user" class="host-user"></span><button id="wait-logout-button" class="button button-ghost small" type="button">退出登录</button></div></header>
<div class="unlock-content"><section class="host-card unlock-card" aria-labelledby="wait-title"><span id="wait-eyebrow" class="eyebrow">ACCOUNT STATUS</span><h1 id="wait-title">等待管理员审核</h1><p id="wait-description" class="muted">邮箱已验证,账号正在等待管理员审核。审核通过后才能创建和管理虚拟机。</p><button id="wait-refresh-button" class="button button-outline" type="button">刷新状态</button></section></div>
<div class="unlock-content"><section class="host-card unlock-card" aria-labelledby="wait-title"><span id="wait-eyebrow" class="eyebrow">ACCOUNT STATUS</span><h1 id="wait-title">等待管理员审核</h1><p id="wait-description" class="muted">邮箱已验证,账号正在等待管理员审核。审核通过后才能创建和管理虚拟机。</p><div class="host-submit-actions"><button id="wait-refresh-button" class="button button-outline" type="button">刷新状态</button><button id="wait-ssh-keys-button" class="button button-primary" type="button">管理我的公钥</button></div></section></div>
</main>
<main id="host-view" class="host-layout" hidden>
@ -219,6 +219,7 @@
<div class="sidebar-brand"><span class="brand-mark"><span></span></span><span>VirtPilot<small>CONTROL PANEL</small></span></div>
<div class="sidebar-section-label">工作区</div>
<button id="vm-navigation-button" class="sidebar-link sidebar-button active" type="button" aria-current="page"><span class="nav-icon" aria-hidden="true">▦</span> 虚拟机 <span class="nav-arrow" aria-hidden="true">›</span></button>
<button id="ssh-keys-button" class="sidebar-link sidebar-button" type="button"><span class="nav-icon" aria-hidden="true">⌑</span> 公钥管理 <span class="nav-arrow" aria-hidden="true">›</span></button>
<button id="host-settings-button" class="sidebar-link sidebar-button" type="button"><span class="nav-icon" aria-hidden="true">⌁</span> 宿主机设置 <span class="nav-arrow" aria-hidden="true">›</span></button>
<button id="update-settings-button" class="sidebar-link sidebar-button" type="button"><span class="nav-icon" aria-hidden="true">↻</span> 网站更新 <span class="nav-arrow" aria-hidden="true">›</span></button>
<button id="smtp-settings-button" class="sidebar-link sidebar-button" type="button"><span class="nav-icon" aria-hidden="true">✉</span> 邮件与用户 <span class="nav-arrow" aria-hidden="true">›</span></button>
@ -231,7 +232,7 @@
<div class="main-area">
<header class="topbar">
<div class="breadcrumb">工作区 <span>/</span> <strong id="breadcrumb-current">虚拟机</strong></div>
<div class="topbar-right"><details id="admin-menu" class="admin-menu"><summary>管理 <span aria-hidden="true">▾</span></summary><div class="admin-menu-options"><button id="host-settings-mobile-button" class="button button-ghost small" type="button">宿主机设置</button><button id="update-settings-mobile-button" class="button button-ghost small" type="button">网站更新</button><button id="smtp-settings-mobile-button" class="button button-ghost small" type="button">邮件与用户</button></div></details><span class="topbar-user"><span class="avatar" aria-hidden="true">A</span><span id="current-username">用户</span></span><button id="logout-button" class="button button-ghost small" type="button">退出登录</button></div>
<div class="topbar-right"><details id="admin-menu" class="admin-menu"><summary>菜单 <span aria-hidden="true">▾</span></summary><div class="admin-menu-options"><button id="vm-navigation-mobile-button" class="button button-ghost small" type="button">虚拟机</button><button id="ssh-keys-mobile-button" class="button button-ghost small" type="button">公钥管理</button><button id="host-settings-mobile-button" class="button button-ghost small" type="button">宿主机设置</button><button id="update-settings-mobile-button" class="button button-ghost small" type="button">网站更新</button><button id="smtp-settings-mobile-button" class="button button-ghost small" type="button">邮件与用户</button></div></details><span class="topbar-user"><span class="avatar" aria-hidden="true">A</span><span id="current-username">用户</span></span><button id="logout-button" class="button button-ghost small" type="button">退出登录</button></div>
</header>
<main class="content">
@ -283,6 +284,26 @@
</section>
</section>
</div>
<div id="ssh-keys-workspace" hidden>
<div class="page-heading"><div><span class="eyebrow">ACCOUNT SSH KEYS</span><h1>公钥管理</h1><p>保存自己的 SSH 公钥,创建云镜像虚拟机时直接选择。每个用户只能管理自己的公钥。</p></div><button id="ssh-keys-back-button" class="button button-outline" type="button">返回虚拟机</button></div>
<div class="ssh-keys-grid">
<section class="host-card" aria-labelledby="ssh-key-add-title">
<div class="host-card-heading"><span class="host-card-number">+</span><div><h2 id="ssh-key-add-title">导入公钥</h2><p>仅粘贴单行 OpenSSH 公钥;不要上传私钥或填写私钥口令。</p></div></div>
<form id="ssh-key-form" class="form-stack">
<label for="ssh-key-name">公钥名称</label><input id="ssh-key-name" type="text" maxlength="80" required autocomplete="off" placeholder="例如 我的电脑" />
<label for="ssh-key-public-key">OpenSSH 公钥</label><textarea id="ssh-key-public-key" maxlength="16384" rows="5" required spellcheck="false" autocomplete="off" autocapitalize="off" placeholder="ssh-ed25519 AAAA…"></textarea>
<label for="ssh-key-file">或选择本地 .pub 文件</label><input id="ssh-key-file" type="file" accept=".pub,text/plain" aria-describedby="ssh-key-file-hint" /><small id="ssh-key-file-hint" class="ssh-key-file-hint">仅在浏览器读取文件内容;不会上传私钥文件。</small>
<p id="ssh-key-form-error" class="form-error" role="alert" hidden></p>
<button id="ssh-key-save-button" class="button button-primary" type="submit">保存公钥</button>
</form>
</section>
<section class="host-card" aria-labelledby="ssh-key-list-title">
<div class="host-card-heading"><span class="host-card-number">⌑</span><div><h2 id="ssh-key-list-title">我的公钥</h2><p>公钥不会向其他用户显示;删除后,不影响已经创建的虚拟机。</p></div></div>
<p id="ssh-keys-list-error" class="form-error" role="alert" hidden></p>
<div id="ssh-keys-list" class="ssh-keys-list" aria-live="polite"><p class="muted">正在加载…</p></div>
</section>
</div>
</div>
<div id="update-workspace" hidden>
<div class="page-heading"><div><span class="eyebrow">PANEL UPDATE</span><h1>网站更新</h1><p>从当前项目的私有 Gitea 仓库检查并安装新版本。</p></div><button id="update-back-button" class="button button-outline" type="button">返回虚拟机</button></div>
<div class="update-grid">
@ -363,7 +384,8 @@
<div class="field"><label for="vm-public-ip-cidr">公网 IPv4/CIDR <span>*</span></label><input id="vm-public-ip-cidr" name="public_ip_cidr" type="text" maxlength="18" inputmode="decimal" autocomplete="off" placeholder="填写服务商分配的公网 IP/28" disabled /><small>填写具体 IP 和前缀长度,不是网段地址。</small></div>
<div class="field"><label for="vm-gateway">同网段网关 IPv4 <span>*</span></label><input id="vm-gateway" name="gateway" type="text" maxlength="15" inputmode="decimal" autocomplete="off" placeholder="填写服务商提供的网关" disabled /></div>
<div class="field full"><label for="vm-dns">DNS IPv4 <span>*</span></label><input id="vm-dns" name="dns_servers" type="text" maxlength="128" autocomplete="off" placeholder="例如 1.1.1.1, 8.8.8.8" disabled /><small>多个地址用逗号或空格分隔。</small></div>
<div class="field full"><label for="vm-guest-ssh-public-key">root SSH 公钥(可选)</label><textarea id="vm-guest-ssh-public-key" name="guest_ssh_public_key" rows="3" maxlength="8192" spellcheck="false" autocomplete="off" autocapitalize="off" placeholder="粘贴 ssh-ed25519 AAAA… 开头的公钥;不要粘贴私钥" disabled></textarea><small>填写后导入 root 用户,使用对应私钥登录;此时无需设置 root 密码,也不开放密码登录。公钥和密码都留空时自动生成强密码。</small></div>
<div class="field full"><label for="vm-guest-ssh-key-id">选择已保存的 root SSH 公钥(可选)</label><select id="vm-guest-ssh-key-id" name="guest_ssh_key_id" disabled><option value="">不使用已保存公钥</option></select><small>可以先在侧栏“公钥管理”导入。选择后无需再次粘贴公钥,也不开放密码登录。</small></div>
<div class="field full" id="vm-manual-ssh-key-field"><label for="vm-guest-ssh-public-key">或手动填写 root SSH 公钥(可选)</label><textarea id="vm-guest-ssh-public-key" name="guest_ssh_public_key" rows="3" maxlength="8192" spellcheck="false" autocomplete="off" autocapitalize="off" placeholder="粘贴 ssh-ed25519 AAAA… 开头的公钥;不要粘贴私钥" disabled></textarea><small>填写后导入 root 用户,使用对应私钥登录;此时无需设置 root 密码,也不开放密码登录。公钥和密码都留空时自动生成强密码。</small></div>
<div class="field full" id="vm-root-password-field" hidden><label for="vm-root-password">初始 root 密码(可选)</label><input id="vm-root-password" name="root_password" type="password" minlength="12" maxlength="128" autocomplete="new-password" spellcheck="false" placeholder="可自行设置,留空则自动生成" disabled /><small>仅在未填写公钥时启用;留空自动生成强密码。面板加密保存新建虚拟机的初始密码,可在详情页按需查看。公网密码登录风险较高,请通过 HTTPS 使用面板。</small></div>
</div>
</div>

@ -72,6 +72,7 @@ input:focus,select:focus,button:focus-visible{outline:3px solid rgba(18,166,176,
.host-test-status{font-size:12px;color:#708095;background:#f4f7fa;padding:12px 14px;border-radius:8px;line-height:1.55;margin:0 0 15px}.host-test-status.success{background:#e7f8ef;color:#1d9168}.host-test-status.warning{background:#fff4e6;color:#9a641d}.host-submit-actions{display:flex;gap:9px;flex-wrap:wrap}.host-submit-actions .button{flex:1}.host-card .form-error{margin:0 0 13px}
.update-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:19px;align-items:start}.update-grid .host-card{min-width:0}.update-grid .form-stack input{margin-bottom:17px}.update-grid .form-stack .field-hint{display:block;color:#8395a5;font-size:11px;line-height:1.6;margin:-7px 0 17px}.update-grid .form-stack .button{align-self:flex-start}.update-grid .host-test-status{margin-top:17px;overflow-wrap:anywhere}.update-versions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:11px}.update-versions>div{border:1px solid #e2ebf0;border-radius:9px;padding:13px;background:#fbfdfd;min-width:0}.update-versions span{display:block;color:#8291a1;font-size:11px;margin-bottom:9px}.update-versions strong{display:block;color:#284459;font-size:12px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}
.update-grid .form-stack input[readonly]{background:#f4f7f9;color:#6c7d8d}
.ssh-keys-grid{display:grid;grid-template-columns:minmax(0,.9fr) minmax(0,1.1fr);gap:19px;align-items:start}.ssh-keys-grid .host-card{min-width:0}.ssh-keys-grid .form-stack .button{align-self:flex-start}.ssh-keys-grid .form-stack textarea{margin-bottom:19px}.ssh-key-file-hint{display:block;color:#8b9bab;font-size:11px;line-height:1.5;margin:-14px 0 20px}.ssh-keys-list{display:grid;gap:11px}.ssh-keys-list>.muted{margin:0}.ssh-key-row{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:14px;border:1px solid #e2ebef;border-radius:9px;background:#fbfdfd}.ssh-key-details{min-width:0;display:grid;gap:5px}.ssh-key-details strong{font-size:13px;color:#2b4358;overflow-wrap:anywhere}.ssh-key-details code{font-size:11px;color:#3b7a87;overflow-wrap:anywhere}.ssh-key-details small{font-size:10px;color:#95a4b2}.ssh-key-actions{display:flex;flex:none;gap:7px}.ssh-key-delete{color:#b94b57;border-color:#efd8dc}
.unlock-content{min-height:calc(100vh - 75px);display:flex;align-items:center;justify-content:center;padding:40px 24px}.unlock-card{width:min(100%,480px);padding:35px}.unlock-card h1{font-size:28px;letter-spacing:-.5px;margin:12px 0}.unlock-card .muted{margin:0 0 27px}.unlock-card .muted strong{color:#30445a;overflow-wrap:anywhere}.unlock-submit{width:100%;min-height:46px}.unlock-settings-button{margin-top:18px;padding-left:0}
.dashboard{min-height:100vh;display:grid;grid-template-columns:244px minmax(0,1fr)}
.sidebar{position:sticky;top:0;height:100vh;background:#101d2c;color:#d2dce6;padding:32px 15px 22px;display:flex;flex-direction:column}
@ -154,6 +155,7 @@ tbody tr:hover{background:#fcfefe}
@media(max-width:960px){.dashboard{display:block}.sidebar{position:relative;width:100%;height:65px;min-height:65px;padding:12px 24px}.sidebar-brand{padding:0}.sidebar-section-label,.sidebar-link,.sidebar-bottom{display:none}.admin-menu{display:block}.topbar{height:60px;padding:0 24px}.content{padding:30px 24px}.page-heading{margin-bottom:24px}}
@media(max-width:960px){.host-columns{grid-template-columns:1fr}.host-side-stack{grid-template-columns:repeat(2,minmax(0,1fr));align-items:start}.setup-layout{grid-template-columns:minmax(280px,36%) 1fr}}
@media(max-width:960px){.update-grid{grid-template-columns:1fr}}
@media(max-width:960px){.ssh-keys-grid{grid-template-columns:1fr}}
@media(max-width:960px){.vm-detail-grid{grid-template-columns:1fr}}
@media(max-width:740px){.vm-metrics-grid{grid-template-columns:1fr}.vm-metrics-heading{align-items:flex-start;flex-direction:column}.vm-metric-plot{height:190px}}
@media(max-width:740px){.login-layout{display:block;min-height:100vh}.login-art{display:none}.login-form-side{min-height:100vh;padding:32px 25px}.login-mobile-brand{display:flex;align-items:center;gap:10px;font-size:21px;font-weight:800;margin-bottom:70px}.login-card h2{font-size:29px}.page-heading{align-items:flex-start;flex-direction:column;gap:20px}.heading-actions{width:100%}.heading-actions .button{flex:1}.overview-grid{gap:9px}.stat-card{min-height:121px;padding:16px}.stat-card>strong{font-size:25px}.stat-top{font-size:10px}.stat-icon{width:27px;height:27px;font-size:12px}.stat-card>small{font-size:9px}.panel-heading{align-items:flex-start;flex-direction:column;padding:19px}.panel-tools{width:100%}.search-box{flex:1}.search-box input{width:100%}.footer-note{text-align:left}.console-toolbar{align-items:flex-start}.console-tools{flex-wrap:wrap;justify-content:flex-end}.console-tools .button{font-size:10px}}
@ -163,4 +165,5 @@ tbody tr:hover{background:#fcfefe}
@media(max-width:510px){.topbar-right{flex-wrap:nowrap;justify-content:flex-end;gap:5px;min-width:0}.topbar-user{min-width:0}.topbar-user #current-username{display:block;max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.topbar-user .avatar{display:none}.topbar-right #logout-button{font-size:10px;padding:5px;min-height:28px}.breadcrumb{white-space:nowrap}.breadcrumb span{padding:0 5px}.update-versions{grid-template-columns:1fr}}
@media(max-width:510px){.create-source-picker,.cloud-fields>.form-grid{grid-template-columns:1fr}}
@media(max-width:510px){.register-code-row{flex-wrap:wrap}.register-code-row input{flex-basis:100%}.register-code-row .button{width:100%}.pending-user-row{align-items:flex-start;flex-direction:column}.pending-user-row .button{width:100%}.smtp-card .form-grid{grid-template-columns:1fr}}
@media(max-width:510px){.ssh-key-row{align-items:flex-start;flex-direction:column}.ssh-key-actions{width:100%}.ssh-key-actions .button{flex:1}}
@media(max-width:510px){.vm-detail-heading .heading-actions{justify-content:space-between}.vm-detail-heading .heading-actions .button{flex:0 0 auto}.vm-detail-facts{grid-template-columns:1fr}.vm-detail-facts>div{padding:12px 0}.vm-detail-actions .row-button{flex:1 1 135px}.vm-table td{padding:10px 11px}.vm-identity{min-width:0}.vm-name-link{max-width:calc(100vw - 130px)}}

@ -222,12 +222,13 @@ def test_metric_and_user_tables_created_with_record_table():
store = DatabaseStore.__new__(DatabaseStore)
store._connect = lambda: connection
store._initialize_schema()
assert len(connection.fake_cursor.commands) == 5
assert len(connection.fake_cursor.commands) == 6
assert "vm_metric_samples" in connection.fake_cursor.commands[1][0]
assert "vm_metric_retention" in connection.fake_cursor.commands[1][0]
assert "CREATE TABLE IF NOT EXISTS users" in connection.fake_cursor.commands[2][0]
assert "CREATE TABLE IF NOT EXISTS registration_codes" in connection.fake_cursor.commands[3][0]
assert "CREATE TABLE IF NOT EXISTS vm_ownership" in connection.fake_cursor.commands[4][0]
assert "CREATE TABLE IF NOT EXISTS user_ssh_keys" in connection.fake_cursor.commands[5][0]
assert connection.commits == 1 and connection.closed

@ -26,6 +26,8 @@ from virsh_panel.config import Settings # noqa: E402
from virsh_panel.database import DatabasePanelState, DatabaseTemplateStore # noqa: E402
from virsh_panel.libvirt_service import VMError # noqa: E402
from virsh_panel.metrics import host_scope # noqa: E402
from virsh_panel.cloud_templates import template_scope # noqa: E402
from virsh_panel.ssh_keys import SSHKeyError, _name, _public_key # noqa: E402
ORIGIN = "https://panel.example.test"
@ -34,6 +36,51 @@ CREATE_VM = {
"name": "tenant-vm", "vcpu": 2, "memory_mib": 2048,
"disk_gib": 20, "network": "bridge:br0", "iso": "AlmaLinux-10.iso",
}
GUEST_PUBLIC_KEY = (
"ssh-ed25519 "
"AAAAC3NzaC1lZDI1NTE5AAAAIF7mFh4aYz3lRzNqjoFQasAQLpm7BdSULhe1iWuvj3y5 "
"panel-test"
)
CLOUD_VM = {
"source": "cloud", "template_id": "alma10-template",
"name": "tenant-cloud", "vcpu": 2, "memory_mib": 2048,
"disk_gib": 20, "network": "bridge:br0", "public_ip_cidr": "8.8.8.18/24",
"gateway": "8.8.8.1", "dns_servers": ["1.1.1.1"],
}
class _MemorySSHKeys:
"""Mimic the owner-scoped SQL boundary for production-mode HTTP tests."""
def __init__(self):
self.rows = {}
self.next_id = 1
def list_for_user(self, user_id):
return [row.copy() for owner, row in self.rows.values() if owner == user_id]
def create_for_user(self, user_id, name, public_key):
name = _name(name)
public_key, fingerprint = _public_key(public_key)
if any(owner == user_id and row["fingerprint"] == fingerprint
for owner, row in self.rows.values()):
raise SSHKeyError("此 SSH 公钥已添加到当前账户", 409)
key_id = self.next_id
self.next_id += 1
row = {"id": key_id, "name": name, "public_key": public_key,
"fingerprint": fingerprint, "created_at": 100}
self.rows[key_id] = (user_id, row)
return row.copy()
def get_for_user(self, user_id, key_id):
found = self.rows.get(key_id)
return found[1].copy() if found is not None and found[0] == user_id else None
def delete_for_user(self, user_id, key_id):
if self.get_for_user(user_id, key_id) is None:
return False
del self.rows[key_id]
return True
class _Manager:
@ -56,6 +103,7 @@ class _Service:
def __init__(self):
self.vms = {}
self.console_calls = []
self.cloud_specs = []
def create_vm(self, spec):
vm = {
@ -66,6 +114,16 @@ class _Service:
self.vms[vm["uuid"]] = vm
return vm
def create_cloud_vm(self, spec, volume_name):
self.cloud_specs.append((spec.copy(), volume_name))
vm = self.create_vm(spec)
vm.update({
"managed": True,
"os_source": "cloud_template",
"credential_generation": f"panel-seed-{vm['uuid']}.iso",
})
return vm
def list_vms(self):
return list(self.vms.values())
@ -321,3 +379,176 @@ def test_registration_smtp_approval_and_per_user_vm_isolation(monkeypatch, tmp_p
assert first.get("/api/v1/smtp/settings").status_code == 401
assert first.post("/api/v1/vms", json=CREATE_VM,
headers=first_headers).status_code == 401
def test_per_user_ssh_key_library_and_cloud_vm_selection(monkeypatch, tmp_path):
store = MemoryStore()
key_store = _MemorySSHKeys()
service = _Service()
def components(directory, *_args):
state = DatabasePanelState(directory, store, store.users)
state.ssh_keys = key_store
return state, _Manager(), DatabaseTemplateStore(store), store
monkeypatch.setattr(app_module, "make_components", components)
monkeypatch.setattr(app_module, "MetricsCollector", _NoMetrics)
settings = Settings(
data_dir=tmp_path / "data",
static_dir=Path(__file__).resolve().parents[1] / "static",
)
app = app_module.create_app(settings, service_factory=lambda _profile: service)
token = (settings.data_dir / "setup-token").read_text(encoding="ascii").strip()
with TestClient(app, base_url=ORIGIN) as admin:
assert admin.get("/api/v1/ssh-keys").status_code == 401
assert admin.post("/api/v1/ssh-keys", json={
"name": "initial", "public_key": GUEST_PUBLIC_KEY,
}).status_code == 401
assert admin.delete("/api/v1/ssh-keys/1").status_code == 401
assert admin.post("/api/v1/database/setup", json={
"host": "127.0.0.1", "port": 3306, "database": "virsh_panel",
"username": "panel", "password": "database-password", "setup_token": token,
}).status_code == 200
initial = admin.post("/api/v1/setup/admin", json={
"token": token, "username": "firstuser", "password": PASSWORD,
})
assert initial.status_code == 200
admin_headers = {"X-CSRF-Token": initial.json()["csrf_token"]}
store.users.promote("firstuser")
DatabaseTemplateStore(store).add(template_scope(_Manager.profile), {
"id": "alma10-template", "name": "AlmaLinux 10",
"volume_name": "panel-template-alma10.qcow2",
})
# Even an administrator has a personal key library, not every
# tenant's keys. No private-key content is accepted by the API.
assert admin.get("/api/v1/ssh-keys").json() == {"items": []}
rejected_private = admin.post("/api/v1/ssh-keys", json={
"name": "wrong", "public_key": "-----BEGIN OPENSSH PRIVATE KEY-----\nsecret",
}, headers=admin_headers)
assert rejected_private.status_code in (400, 422)
store.users.issue_registration_code("one@example.test", "123456")
first_account = store.users.register_with_code(
"tenantone", "one@example.test", PASSWORD, "123456",
)
store.users.issue_registration_code("two@example.test", "123456")
second_account = store.users.register_with_code(
"tenanttwo", "two@example.test", PASSWORD, "123456",
)
with TestClient(app, base_url=ORIGIN) as first, \
TestClient(app, base_url=ORIGIN) as second:
first_headers = _login(first, "one@example.test")
second_headers = _login(second, "two@example.test")
assert first.get("/api/v1/session").json()["approved"] is False
assert first.get("/api/v1/ssh-keys").json() == {"items": []}
assert first.post("/api/v1/ssh-keys", json={
"name": "laptop", "public_key": GUEST_PUBLIC_KEY,
}).status_code == 403
imported = first.post("/api/v1/ssh-keys", json={
"name": "laptop", "public_key": GUEST_PUBLIC_KEY,
}, headers=first_headers)
assert imported.status_code == 201
first_key = imported.json()
assert first_key["name"] == "laptop"
assert first_key["public_key"].startswith("ssh-ed25519 ")
assert first_key["fingerprint"].startswith("SHA256:")
assert isinstance(first_key["id"], int)
assert first.post("/api/v1/ssh-keys", json={
"name": "duplicate comment", "public_key": GUEST_PUBLIC_KEY,
}, headers=first_headers).status_code == 409
assert first.get("/api/v1/ssh-keys").json()["items"] == [first_key]
assert second.get("/api/v1/ssh-keys").json() == {"items": []}
assert admin.get("/api/v1/ssh-keys").json() == {"items": []}
assert first.post("/api/v1/vms", json={
**CLOUD_VM, "guest_ssh_key_id": first_key["id"],
}, headers=first_headers).status_code == 403
# The same public key is allowed in another account, but its
# record has a different ID and remains independently owned.
second_import = second.post("/api/v1/ssh-keys", json={
"name": "other laptop", "public_key": GUEST_PUBLIC_KEY,
}, headers=second_headers)
assert second_import.status_code == 201
second_key = second_import.json()
assert second_key["id"] != first_key["id"]
assert second.get("/api/v1/ssh-keys").json()["items"] == [second_key]
assert second.delete(f"/api/v1/ssh-keys/{first_key['id']}",
headers=second_headers).status_code == 404
assert first.delete("/api/v1/ssh-keys/-1",
headers=first_headers).status_code == 404
assert admin.delete(f"/api/v1/ssh-keys/{first_key['id']}",
headers=admin_headers).status_code == 404
assert first.get("/api/v1/ssh-keys").json()["items"] == [first_key]
assert admin.post(f"/api/v1/users/{first_account['id']}/approve",
headers=admin_headers).status_code == 200
assert admin.post(f"/api/v1/users/{second_account['id']}/approve",
headers=admin_headers).status_code == 200
before = len(service.cloud_specs)
for client, headers, forbidden_id in (
(first, first_headers, second_key["id"]),
(second, second_headers, first_key["id"]),
(admin, admin_headers, first_key["id"]),
):
forbidden = client.post("/api/v1/vms", json={
**CLOUD_VM, "guest_ssh_key_id": forbidden_id,
}, headers=headers)
assert forbidden.status_code == 404
missing = first.post("/api/v1/vms", json={
**CLOUD_VM, "guest_ssh_key_id": 999999,
}, headers=first_headers)
assert missing.status_code == 404
for conflicting in (
{"guest_ssh_key_id": first_key["id"],
"guest_ssh_public_key": GUEST_PUBLIC_KEY},
{"guest_ssh_key_id": first_key["id"],
"root_password": "A-strong-guest-password-2026"},
):
response = first.post("/api/v1/vms", json={
**CLOUD_VM, **conflicting,
}, headers=first_headers)
assert response.status_code == 422
assert len(service.cloud_specs) == before
selected = first.post("/api/v1/vms", json={
**CLOUD_VM, "guest_ssh_key_id": first_key["id"],
}, headers=first_headers)
assert selected.status_code == 201
spec, _volume = service.cloud_specs[-1]
assert spec["guest_ssh_public_key"] == first_key["public_key"]
assert "guest_ssh_key_id" not in spec
assert not spec.get("root_password_hash")
assert selected.json()["auth_mode"] == "ssh_key"
assert second.get(f"/api/v1/vms/{selected.json()['uuid']}").status_code == 404
# Existing create paths continue to accept a one-off pasted key
# or an initial root password without a saved-key ID.
manual = first.post("/api/v1/vms", json={
**CLOUD_VM, "name": "manual-key-vm",
"public_ip_cidr": "8.8.8.19/24",
"guest_ssh_public_key": GUEST_PUBLIC_KEY,
}, headers=first_headers)
assert manual.status_code == 201
assert service.cloud_specs[-1][0]["guest_ssh_public_key"] == GUEST_PUBLIC_KEY
password = first.post("/api/v1/vms", json={
**CLOUD_VM, "name": "password-vm",
"public_ip_cidr": "8.8.8.20/24",
"root_password": "A-strong-guest-password-2026",
}, headers=first_headers)
assert password.status_code == 201
assert password.json()["auth_mode"] == "password"
assert first.delete(f"/api/v1/ssh-keys/{first_key['id']}").status_code == 403
deleted = first.delete(f"/api/v1/ssh-keys/{first_key['id']}",
headers=first_headers)
assert 200 <= deleted.status_code < 300
assert first.get("/api/v1/ssh-keys").json() == {"items": []}
assert second.get("/api/v1/ssh-keys").json()["items"] == [second_key]
assert first.post("/api/v1/vms", json={
**CLOUD_VM, "name": "deleted-key-vm",
"guest_ssh_key_id": first_key["id"],
}, headers=first_headers).status_code == 404
assert first.get(f"/api/v1/vms/{selected.json()['uuid']}").status_code == 200

@ -0,0 +1,168 @@
"""Owner-isolated MariaDB SSH public key records, using a SQL test adapter."""
from __future__ import annotations
import base64
import hashlib
import sqlite3
import struct
import pytest
from virsh_panel.ssh_keys import DatabaseSSHKeyStore, SSHKeyError
def _valid_key(seed: bytes = b"a", comment: str = "operator@example") -> str:
blob = struct.pack("!I", 11) + b"ssh-ed25519" + struct.pack("!I", 32) + seed * 32
return "ssh-ed25519 " + base64.b64encode(blob).decode("ascii") + " " + comment
class _Cursor:
def __init__(self, connection: sqlite3.Connection) -> None:
self._cursor = connection.cursor()
def __enter__(self):
return self
def __exit__(self, *_exc):
self._cursor.close()
def execute(self, statement, parameters=()):
try:
self._cursor.execute(statement.replace("%s", "?"), parameters)
except sqlite3.IntegrityError as exc:
import pymysql
raise pymysql.err.IntegrityError(1062, str(exc)) from exc
return self
def fetchone(self):
row = self._cursor.fetchone()
return None if row is None else dict(row)
def fetchall(self):
return [dict(row) for row in self._cursor.fetchall()]
@property
def lastrowid(self):
return self._cursor.lastrowid
@property
def rowcount(self):
return self._cursor.rowcount
class _Connection:
def __init__(self) -> None:
self.raw = sqlite3.connect(":memory:")
self.raw.row_factory = sqlite3.Row
self.raw.execute("PRAGMA foreign_keys=ON")
self.raw.executescript("""
CREATE TABLE users (id INTEGER PRIMARY KEY);
INSERT INTO users (id) VALUES (1), (2);
CREATE TABLE user_ssh_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
public_key TEXT NOT NULL,
fingerprint TEXT NOT NULL,
created_at INTEGER NOT NULL,
UNIQUE (user_id, fingerprint)
);
""")
def cursor(self):
return _Cursor(self.raw)
def commit(self):
self.raw.commit()
def rollback(self):
self.raw.rollback()
def close(self):
# A single in-memory database must outlive individual store calls.
pass
class _Store:
def __init__(self) -> None:
self.connection = _Connection()
def _connect(self):
return self.connection
@pytest.fixture
def key_store():
store = _Store()
yield DatabaseSSHKeyStore(store), store.connection.raw
store.connection.raw.close()
def test_keys_are_strictly_isolated_by_user_on_all_operations(key_store):
repository, database = key_store
first = repository.create_for_user(1, "生产环境", _valid_key(), now=100)
second = repository.create_for_user(2, "另一用户", _valid_key(), now=101)
assert first["id"] != second["id"]
assert first["fingerprint"] == second["fingerprint"]
assert first["public_key"] == _valid_key().rsplit(" ", 1)[0]
blob = base64.b64decode(first["public_key"].split()[1])
assert first["fingerprint"] == (
"SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip("=")
)
assert repository.list_for_user(1) == [first]
assert repository.list_for_user(2) == [second]
assert repository.get_for_user(1, second["id"]) is None
assert repository.get_for_user(2, first["id"]) is None
assert repository.delete_for_user(2, first["id"]) is False
assert repository.get_for_user(1, first["id"]) == first
assert repository.delete_for_user(1, first["id"]) is True
assert repository.delete_for_user(1, first["id"]) is False
assert repository.list_for_user(1) == []
assert repository.list_for_user(2) == [second]
database.execute("DELETE FROM users WHERE id=2")
database.commit()
assert database.execute("SELECT COUNT(*) FROM user_ssh_keys").fetchone()[0] == 0
def test_same_wire_key_cannot_be_saved_twice_per_user_even_with_new_comment(key_store):
repository, _database = key_store
repository.create_for_user(1, "第一把", _valid_key(comment="first"))
with pytest.raises(SSHKeyError) as duplicate:
repository.create_for_user(1, "第二把", _valid_key(comment="second"))
assert duplicate.value.status == 409
assert len(repository.list_for_user(1)) == 1
# Unique constraint is owner-scoped, not a global ban on shared keys.
assert repository.create_for_user(2, "允许跨用户重复", _valid_key(comment="second"))["id"] > 0
@pytest.mark.parametrize("invalid_key", [
"-----BEGIN OPENSSH PRIVATE KEY-----\nAAAA\n-----END OPENSSH PRIVATE KEY-----",
"ssh-ed25519 not-base64",
"ssh-rsa " + _valid_key().split()[1],
_valid_key() + "\nssh-ed25519 another-key",
"",
])
def test_private_or_invalid_public_keys_are_rejected_without_writes(key_store, invalid_key):
repository, _database = key_store
with pytest.raises(SSHKeyError) as invalid:
repository.create_for_user(1, "键", invalid_key)
assert invalid.value.status == 400
assert repository.list_for_user(1) == []
@pytest.mark.parametrize("invalid_name", ["", " ", " leading", "trailing ", "bad\nname", "x" * 81])
def test_key_name_must_be_safe_and_bounded(key_store, invalid_name):
repository, _database = key_store
with pytest.raises(SSHKeyError):
repository.create_for_user(1, invalid_name, _valid_key())
assert repository.list_for_user(1) == []
def test_list_is_newest_first_and_exposes_no_owner_id(key_store):
repository, _database = key_store
first = repository.create_for_user(1, "first", _valid_key(b"a"), now=100)
second = repository.create_for_user(1, "second", _valid_key(b"b"), now=200)
assert repository.list_for_user(1) == [second, first]
assert "user_id" not in second

@ -37,6 +37,7 @@ from .metrics import (MAX_QUERY_POINTS, RETENTION_SECONDS, RANGES, MetricsCollec
host_scope, query_interval_seconds)
from .panel_state import PanelState, SetupError
from .remote_host import HostProfile, RemoteHostError, RemoteHostManager
from .ssh_keys import SSHKeyError
from .smtp_service import SMTPError, SMTPSettingsStore, send_verification_code
from .updater import BRANCH, REPOSITORY_URL, UpdateError, Updater
from .users import UserError, normalize_email
@ -179,9 +180,17 @@ class CreateCloudBody(BaseModel):
gateway: str = Field(min_length=7, max_length=64)
dns_servers: list[str] = Field(min_length=1, max_length=4)
guest_ssh_public_key: str = Field(default="", max_length=16384)
guest_ssh_key_id: int | None = Field(default=None, ge=1)
root_password: SecretStr | None = None
class SSHKeyBody(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str = Field(min_length=1, max_length=80)
public_key: str = Field(min_length=1, max_length=16384)
class ImportTemplateBody(BaseModel):
model_config = ConfigDict(extra="forbid")
@ -519,6 +528,10 @@ def create_app(
async def handle_smtp_error(_request: Request, exc: SMTPError):
return JSONResponse(status_code=exc.status, content={"error": str(exc)})
@app.exception_handler(SSHKeyError)
async def handle_ssh_key_error(_request: Request, exc: SSHKeyError):
return JSONResponse(status_code=exc.status, content={"error": str(exc)})
def account_for_session(session: Session) -> dict:
if database_mode:
if state is None:
@ -600,6 +613,11 @@ def create_app(
raise SMTPError("请先完成数据库配置", 409)
return SMTPSettingsStore(data_store)
def ssh_key_store():
if not database_mode or state is None:
raise SSHKeyError("请先完成数据库配置", 409)
return state.ssh_keys
def current_updater() -> Updater:
nonlocal updater
if data_store is None:
@ -902,6 +920,28 @@ def create_app(
response.delete_cookie(COOKIE_NAME, path="/")
return response
@app.get("/api/v1/ssh-keys")
def list_ssh_keys(_session: Session = Depends(require_session)):
account = account_for_session(_session)
return {"items": ssh_key_store().list_for_user(account["id"])}
@app.post("/api/v1/ssh-keys", status_code=201)
def create_ssh_key(body: SSHKeyBody,
_session: Session = Depends(require_write)):
account = account_for_session(_session)
return ssh_key_store().create_for_user(
account["id"], body.name, body.public_key,
)
@app.delete("/api/v1/ssh-keys/{key_id}")
def delete_ssh_key(key_id: int, _session: Session = Depends(require_write)):
if key_id < 1:
raise SSHKeyError("公钥不存在", 404)
account = account_for_session(_session)
if not ssh_key_store().delete_for_user(account["id"], key_id):
raise SSHKeyError("公钥不存在", 404)
return {"deleted": True}
@app.get("/api/v1/smtp/settings")
def get_smtp_settings(_session: Session = Depends(require_admin)):
return smtp_store().public_status()
@ -1256,6 +1296,18 @@ def create_app(
public_key = body.guest_ssh_public_key.strip()
root_password = (body.root_password.get_secret_value()
if body.root_password is not None else "")
if body.guest_ssh_key_id is not None:
if public_key or root_password:
raise HTTPException(
status_code=422,
detail="已保存公钥、手动公钥和初始 root 密码只能选择一种",
)
saved_key = ssh_key_store().get_for_user(
account["id"], body.guest_ssh_key_id,
)
if saved_key is None:
raise SSHKeyError("公钥不存在", 404)
public_key = saved_key["public_key"]
if public_key and root_password:
raise HTTPException(
status_code=422,
@ -1270,7 +1322,9 @@ def create_app(
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
record = templates.get(template_scope(profile), body.template_id)
spec = body.model_dump(exclude={"source", "template_id", "root_password"})
spec = body.model_dump(exclude={
"source", "template_id", "root_password", "guest_ssh_key_id",
})
spec["os_name"] = record.get("name")
spec["guest_ssh_public_key"] = public_key
if password_hash is not None:

@ -121,6 +121,21 @@ CREATE TABLE IF NOT EXISTS vm_ownership (
ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""
_USER_SSH_KEYS_SCHEMA = """
CREATE TABLE IF NOT EXISTS user_ssh_keys (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id BIGINT UNSIGNED NOT NULL,
name VARCHAR(80) NOT NULL,
public_key TEXT CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
fingerprint VARCHAR(80) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
created_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY user_ssh_key_fingerprint (user_id, fingerprint),
KEY user_ssh_key_listing (user_id, created_at),
CONSTRAINT user_ssh_key_user_fk FOREIGN KEY (user_id) REFERENCES users(id)
ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""
_METRIC_COLUMNS = (
"cpu_percent", "memory_used_mib", "memory_total_mib", "disk_read_bps",
"disk_write_bps", "network_rx_bps", "network_tx_bps",
@ -209,6 +224,7 @@ class DatabaseStore:
cursor.execute(_USERS_SCHEMA)
cursor.execute(_REGISTRATION_CODE_SCHEMA)
cursor.execute(_VM_OWNERSHIP_SCHEMA)
cursor.execute(_USER_SSH_KEYS_SCHEMA)
connection.commit()
except pymysql.MySQLError as exc:
connection.rollback()
@ -465,6 +481,8 @@ class DatabasePanelState(PanelState):
super().__init__(data_dir)
self.store = store
self.users = users
from .ssh_keys import DatabaseSSHKeyStore
self.ssh_keys = DatabaseSSHKeyStore(store)
def admin(self) -> tuple[str, str] | None:
raise RuntimeError("Database-backed authentication must use state.users")

@ -0,0 +1,165 @@
"""Per-account OpenSSH public keys for cloud-image guest access.
Only public key material is stored. Every lookup and mutation includes the
authenticated user's database ID, so an ID from another account is not an
authorization bypass. The unique fingerprint is calculated from the decoded
SSH wire-format blob, independent of whitespace or a trailing comment.
"""
from __future__ import annotations
import base64
import hashlib
import time
from typing import Any
from .cloud_init import _validate_ssh_public_key
from .database import DatabaseError, DatabaseStore, pymysql
class SSHKeyError(Exception):
def __init__(self, message: str, status: int = 400) -> None:
super().__init__(message)
self.status = status
def _user_id(value: int) -> int:
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
raise ValueError("Invalid user ID")
return value
def _key_id(value: int) -> int:
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
raise ValueError("Invalid SSH key ID")
return value
def _name(value: str) -> str:
if (not isinstance(value, str) or value != value.strip()
or not 1 <= len(value) <= 80
or any(ord(char) < 32 or ord(char) == 127 for char in value)):
raise SSHKeyError("公钥名称须为 1 至 80 个非控制字符")
return value
def _public_key(value: str) -> tuple[str, str]:
try:
validated = _validate_ssh_public_key(value)
except ValueError as exc:
raise SSHKeyError(str(exc)) from exc
key_type, encoded = validated.split(maxsplit=2)[:2]
blob = base64.b64decode(encoded, validate=True)
# Comments are operator hints, not key material. The user-chosen name is
# retained instead, and the canonical form avoids charset surprises.
canonical = f"{key_type} {base64.b64encode(blob).decode('ascii')}"
fingerprint = "SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode("ascii").rstrip("=")
return canonical, fingerprint
def _row(row: dict[str, Any] | None) -> dict[str, Any] | None:
if row is None:
return None
return {
"id": int(row["id"]),
"name": row["name"],
"public_key": row["public_key"],
"fingerprint": row["fingerprint"],
"created_at": int(row["created_at"]),
}
class DatabaseSSHKeyStore:
"""MariaDB-backed key library with owner-scoped SQL queries."""
def __init__(self, store: DatabaseStore) -> None:
self._store = store
def _connect(self):
return self._store._connect()
def list_for_user(self, user_id: int) -> list[dict[str, Any]]:
_user_id(user_id)
connection = self._connect()
try:
with connection.cursor() as cursor:
cursor.execute(
"SELECT id, name, public_key, fingerprint, created_at "
"FROM user_ssh_keys WHERE user_id=%s ORDER BY created_at DESC, id DESC",
(user_id,),
)
return [_row(row) for row in cursor.fetchall()]
except pymysql.MySQLError as exc:
raise DatabaseError("无法读取 SSH 公钥") from exc
finally:
connection.close()
def create_for_user(self, user_id: int, name: str, public_key: str,
*, now: int | None = None) -> dict[str, Any]:
_user_id(user_id)
name = _name(name)
public_key, fingerprint = _public_key(public_key)
timestamp = int(time.time()) if now is None else now
if isinstance(timestamp, bool) or not isinstance(timestamp, int) or timestamp < 0:
raise ValueError("Invalid SSH key creation time")
connection = self._connect()
try:
with connection.cursor() as cursor:
cursor.execute(
"INSERT INTO user_ssh_keys "
"(user_id, name, public_key, fingerprint, created_at) "
"VALUES (%s, %s, %s, %s, %s)",
(user_id, name, public_key, fingerprint, timestamp),
)
key_id = cursor.lastrowid
connection.commit()
return {
"id": key_id, "name": name, "public_key": public_key,
"fingerprint": fingerprint, "created_at": timestamp,
}
except pymysql.err.IntegrityError as exc:
connection.rollback()
if exc.args and exc.args[0] == 1062:
raise SSHKeyError("此 SSH 公钥已添加到当前账户", 409) from exc
raise DatabaseError("无法保存 SSH 公钥") from exc
except pymysql.MySQLError as exc:
connection.rollback()
raise DatabaseError("无法保存 SSH 公钥") from exc
finally:
connection.close()
def get_for_user(self, user_id: int, key_id: int) -> dict[str, Any] | None:
_user_id(user_id)
_key_id(key_id)
connection = self._connect()
try:
with connection.cursor() as cursor:
cursor.execute(
"SELECT id, name, public_key, fingerprint, created_at "
"FROM user_ssh_keys WHERE user_id=%s AND id=%s",
(user_id, key_id),
)
return _row(cursor.fetchone())
except pymysql.MySQLError as exc:
raise DatabaseError("无法读取 SSH 公钥") from exc
finally:
connection.close()
def delete_for_user(self, user_id: int, key_id: int) -> bool:
_user_id(user_id)
_key_id(key_id)
connection = self._connect()
try:
with connection.cursor() as cursor:
cursor.execute(
"DELETE FROM user_ssh_keys WHERE user_id=%s AND id=%s",
(user_id, key_id),
)
deleted = cursor.rowcount > 0
connection.commit()
return deleted
except pymysql.MySQLError as exc:
connection.rollback()
raise DatabaseError("无法删除 SSH 公钥") from exc
finally:
connection.close()
Loading…
Cancel
Save