Allow combined SSH key and strong root password auth

main
admin 2 months ago
parent e3168e257f
commit 6ec172154b

@ -71,7 +71,7 @@ SELECT id, username, email FROM users WHERE id = 1;
虚拟机列表只展示状态、地区、系统或安装镜像、IP、规格和磁盘;点击虚拟机名称进入该机管理页,控制台、电源、重装和删除等操作都在管理页。地区取自当前宿主机设置。新建或重装的云镜像 VM 会记录所选模板名称及配置的公网 IP/CIDR;这个 IP 是**配置记录**,不是连通性探测。详情页的公网 IP 不显示 `/24` 等掩码后缀,可点击旁边的按钮复制;磁盘信息只显示总容量,不再显示磁盘块数。ISO 安装 VM 只记录安装镜像文件名,不能据此确认客体最终安装的系统;旧 VM 或面板外创建的 VM 若无可靠记录,会显示“未识别”或“未获取”,不会猜测客体系统与 IP。
云镜像 VM 的详情页显示 SSH 登录名 `root`。面板保存了初始 root 密码时,默认以星号遮盖;管理员或该 VM 的所属用户可按需点击图标查看、复制,不会在虚拟机列表或普通详情数据中直接返回密码。只有本版本以后由面板新建、或成功重装的密码模式云镜像 VM 才能查看其加密保存的初始密码;公钥模式不保存也不显示密码,ISO 安装和面板外创建的 VM 的客体密码则不由面板管理。旧 VM 曾使用但面板未保存的密码无法从密码哈希或虚拟机系统中还原。客体内修改 root 密码后,详情页保存的**初始**密码不会自动更新,可能已无法用于登录;请妥善保护数据库备份和面板主密钥。
云镜像 VM 的详情页显示 SSH 登录名 `root`。面板保存了初始 root 密码时,默认以星号遮盖;管理员或该 VM 的所属用户可按需点击图标查看、复制,不会在虚拟机列表或普通详情数据中直接返回密码。新建或成功重装的云镜像 VM 若设置了密码,即使同时选择了 SSH 公钥,也会保存可查看的初始密码;只选公钥而不填写密码时,密码登录保持关闭。ISO 安装和面板外创建的 VM 的客体密码不由面板管理。旧 VM 曾使用但面板未保存的密码无法从密码哈希或虚拟机系统中还原。客体内修改 root 密码后,详情页保存的**初始**密码不会自动更新,可能已无法用于登录;请妥善保护数据库备份和面板主密钥。
虚拟机详情页显示 CPU、客体内存、磁盘 I/O 和网络收发四张历史走势图,可切换最近 1 小时、24 小时、7 天和 30 天。面板后台定时从 [libvirt 域统计](https://libvirt.org/manpages/virsh.html#domstats)采样并写入 MariaDB,即使无人登录也会继续记录,前提是宿主机连接可用且加密私钥能自动解锁。旧配置若只在内存中解锁、没有重新保存口令,重启后后台采样会暂停,直到管理员解锁;按上述步骤保存口令后可避免这种中断。查询**只返回最近 30 天**的数据;运行中的面板会分批清理更早的数据库记录。面板停机或数据库不可用时物理清理会暂停,恢复后继续追赶,因此中断期间数据库中可能暂时留有超期记录。CPU 是按 vCPU 数归一化、最高显示 100% 的使用率,磁盘和网络显示每秒速率而不是累计量或网络带宽上限;网络收发方向以虚拟机为准。磁盘与网卡只汇总 libvirt 实际提供计数的设备,未提供计数的设备无法纳入统计。内存占用依赖客体内存气球统计,客户机不提供或统计过期时会显示无数据,不会把宿主机 QEMU 进程占用误当客体内存。初次采样、虚拟机停机、面板/宿主机不可达或计数器重置期间可能出现空白;面板停机期间不会补录历史。较长时间范围会聚合采样,短暂的停机或采样缺口可能不明显。
@ -93,15 +93,15 @@ SELECT id, username, email FROM users WHERE id = 1;
“虚拟机网卡前缀”与可分配地址池是独立设置:留空时客体使用地址池前缀;如果现场确认服务商要求 VM 内配置 `/24`,而实际只获配上述 `/28`,这里填 `24`,新建 VM 将获得例如 `123.123.123.114/24`,但面板仍只会从 `123.123.123.112/28` 挑选地址。可填写的客体前缀范围为 `/24` 到地址池前缀,以确保整个地址池中的 IP 与网关处于同一客体子网。修改此项不会自动改写已创建 VM;云镜像重装会保留该 VM 首次创建时的网络前缀。若使用 `/28` 不通,其具体原因仍需结合宿主机路由、网桥及服务商网络确认;仅改变面板掩码无法替代上游放行或路由配置。
配置地址池后,创建时会自动选择一个尚未使用的地址,并沿用宿主机设置的网关和 DNS;用户不能在创建请求中另填 IP、网关或 DNS 来绕过地址池。面板会跳过网络地址、广播地址、网关、保留地址、宿主机自身的字面 IPv4,以及 libvirt 可见虚拟机元数据中的已用 IP,并防止面板并发创建分到相同地址。地址池用尽时创建会报错,不会复用仍占用的地址;面板删除 VM 后会释放其地址占用记录。旧宿主机若未配置地址池,仍可按原方式手填已分配给你的**具体公网 IPv4/CIDR**(如 `/24` 或 `/28`)、同网段网关和 1–4 个 DNS 地址。在创建窗口的卡片中选择已保存的 SSH 公钥时,只能用对应私钥登录 `root@<公网IP>`,密码输入会隐藏;不选公钥时,可以设置 12–128 字符的初始 root 密码,可用它从 VNC 和 SSH 登录;公钥和密码都不选填时,面板会自动生成强初始 root 密码。客体登录密钥与连接宿主机的 root 私钥是两套独立凭据。面板无法探测面板及 libvirt 元数据之外的设备是否占用地址,也无法替服务商分配或路由公网 IP。当前版本只支持网关与 VM IP 同一子网的桥接 IPv4;服务商给出 `/32` 或异网段网关时不要强填,需另做路由网络模式。上游网络还必须允许 VM 使用额外 MAC,`br0` 本身不能保证公网可达。
配置地址池后,创建时会自动选择一个尚未使用的地址,并沿用宿主机设置的网关和 DNS;用户不能在创建请求中另填 IP、网关或 DNS 来绕过地址池。面板会跳过网络地址、广播地址、网关、保留地址、宿主机自身的字面 IPv4,以及 libvirt 可见虚拟机元数据中的已用 IP,并防止面板并发创建分到相同地址。地址池用尽时创建会报错,不会复用仍占用的地址;面板删除 VM 后会释放其地址占用记录。旧宿主机若未配置地址池,仍可按原方式手填已分配给你的**具体公网 IPv4/CIDR**(如 `/24` 或 `/28`)、同网段网关和 1–4 个 DNS 地址。在创建窗口中可选一个已保存的 SSH 公钥,同时设置初始 root 密码,登录时可用对应私钥或密码;不选择公钥也可以只用密码。手动密码须为 12–128 个字符,包含大写字母、小写字母和符号;只选公钥且密码留空时保持仅公钥登录,未选公钥且密码留空时面板自动生成并加密保存初始密码。客体登录密钥与连接宿主机的 root 私钥是两套独立凭据。面板无法探测面板及 libvirt 元数据之外的设备是否占用地址,也无法替服务商分配或路由公网 IP。当前版本只支持网关与 VM IP 同一子网的桥接 IPv4;服务商给出 `/32` 或异网段网关时不要强填,需另做路由网络模式。上游网络还必须允许 VM 使用额外 MAC,`br0` 本身不能保证公网可达。
若 DNS 本身位于该地址池中,它的地址也会自动跳过。面板创建成功后会保留 IP 占用记录,只有通过面板删除 VM 才自动释放;如果直接在宿主机或其他工具中删除 VM,旧占用记录会保守保留,避免误将该 IP 分给新 VM,需核查真实占用情况后再处理。
每个已登录用户都可导入并命名自己的**单行 OpenSSH 公钥**:已审核账号从侧栏“公钥管理”进入,等待审核的账号可用“管理我的公钥”入口。可以粘贴 `.pub` 文件内容,或在浏览器选择本地 `.pub` 文件填入表单;面板只接受公钥,不要选择或粘贴私钥。公钥管理列表只显示当前账户导入的公钥;管理员账户也不能把另一个用户的公钥当作自己的预设公钥使用。创建与重装公网云镜像 VM 时,SSH 公钥以卡片形式选择,卡片只显示公钥名称,不显示公钥内容或指纹;不再有手动粘贴公钥输入框。未选择公钥时可设置初始 root 密码,密码也留空则自动生成。未通过管理员审核的用户可以管理自己的公钥,但仍不能创建虚拟机。删除公钥只删除面板中的预设记录,**不会撤销已经写入现有虚拟机的 SSH 授权密钥**;要撤销现有 VM 的访问权限,需在客体系统中删除对应的 `authorized_keys` 条目或重装并更换登录密钥。
每个已登录用户都可导入并命名自己的**单行 OpenSSH 公钥**:已审核账号从侧栏“公钥管理”进入,等待审核的账号可用“管理我的公钥”入口。可以粘贴 `.pub` 文件内容,或在浏览器选择本地 `.pub` 文件填入表单;面板只接受公钥,不要选择或粘贴私钥。公钥管理列表只显示当前账户导入的公钥;管理员账户也不能把另一个用户的公钥当作自己的预设公钥使用。创建与重装公网云镜像 VM 时,SSH 公钥以卡片形式选择,卡片只显示公钥名称,不显示公钥内容或指纹;再次点击已选卡片可取消选择,不再有手动粘贴公钥输入框。初始 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。
创建时,面板在 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 的授权密钥;若同时填写初始 root 密码,也会将其加盐 SHA-512-crypt 哈希写入配置 ISO,并开启 root 的 SSH 密码登录,此时两种登录方式可以共存。只选公钥时密码仍锁定、SSH 密码登录关闭。生成或手填的初始密码还会在 MariaDB 中加密保存,供详情页按需查看或复制。启用密码登录会暴露公网 root 密码认证,建议在宿主机或上游防火墙限制 SSH 来源;宿主机上的配置 ISO 若含密码哈希,必须防止未授权读取。网络或凭据填错后需离线修复或重建。删除 VM 时若勾选“同时删除虚拟磁盘”,面板也会删除其配置 ISO,但**保留共享模板镜像**。这项登录方式变更只对新创建的 VM 生效,不会修改已有 VM。
面板创建的公网云镜像 VM 在详情页有“重装”按钮。点击后选择当前宿主机已导入的云镜像模板,输入 VM 名称确认;可在卡片中选择自己保存的 SSH 公钥,或设置 12–128 字符的初始 root 密码,两者都不选填时会生成强密码。密码模式下,无论密码是自动生成还是手动输入,成功重装后的初始密码都会在 MariaDB 中加密保存,并可在虚拟机详情页按需查看或复制;公钥模式会清除面板此前保存的密码。自动生成的密码仍会在任务成功后显示,管理员点击“已保存密码,完成”只会从**任务记录**中清除密码,不影响详情页保存的初始密码。同一浏览器标签页刷新或面板进程重启后仍可按任务编号查询,直到确认保存密码为止。重装自动读取原配置盘中的公网 IP/CIDR、网关、DNS 和 MAC,不要求再次手填网络。运行中的 VM 会先收到正常关机请求;120 秒内未关机则中止,不会强制断电,也不会切换或删除旧系统盘。面板会将所选模板克隆到新系统盘,生成新的 cloud-init 配置盘并启动 VM;新系统尚未启动时切换失败会恢复原定义,旧盘保留。如果启动调用结果不确定但发现新盘已在运行,则保留新旧两份磁盘并提示人工核查。**libvirt 报告新 VM 已启动后,面板会自动删除旧系统盘与旧配置盘;这并不能证明客体系统、网络或 SSH 已工作,旧数据一旦删除不可恢复。** 若旧盘清理失败,任务仍返回成功但附带警告,需在宿主机核查残留卷。此功能仅支持面板创建且配置未被外部修改的公网云镜像 VM,不支持 ISO 安装 VM、快照或多网卡/多磁盘 VM。
面板创建的公网云镜像 VM 在详情页有“重装”按钮。点击后选择当前宿主机已导入的云镜像模板,输入 VM 名称确认;可在卡片中选择自己保存的 SSH 公钥,并同时设置初始 root 密码。手动密码须为 12–128 个字符并包含大写字母、小写字母及符号;只选公钥而不填写密码时保持仅公钥登录,两者都留空时自动生成强密码。设置或生成的初始密码会在成功重装后加密保存至 MariaDB,并可在虚拟机详情页按需查看或复制。自动生成的密码仍会在任务成功后显示,管理员点击“已保存密码,完成”只会从**任务记录**中清除密码,不影响详情页保存的初始密码。同一浏览器标签页刷新或面板进程重启后仍可按任务编号查询,直到确认保存密码为止。重装自动读取原配置盘中的公网 IP/CIDR、网关、DNS 和 MAC,不要求再次手填网络。运行中的 VM 会先收到正常关机请求;120 秒内未关机则中止,不会强制断电,也不会切换或删除旧系统盘。面板会将所选模板克隆到新系统盘,生成新的 cloud-init 配置盘并启动 VM;新系统尚未启动时切换失败会恢复原定义,旧盘保留。如果启动调用结果不确定但发现新盘已在运行,则保留新旧两份磁盘并提示人工核查。**libvirt 报告新 VM 已启动后,面板会自动删除旧系统盘与旧配置盘;这并不能证明客体系统、网络或 SSH 已工作,旧数据一旦删除不可恢复。** 若旧盘清理失败,任务仍返回成功但附带警告,需在宿主机核查残留卷。此功能仅支持面板创建且配置未被外部修改的公网云镜像 VM,不支持 ISO 安装 VM、快照或多网卡/多磁盘 VM。
## 网页一键更新

@ -562,43 +562,44 @@ async function showSshKeysWorkspace() {
}
function selectedSshKeyId(containerId) {
return byId(containerId).querySelector('input[type="radio"]:checked')?.value || "";
return byId(containerId).querySelector('.ssh-key-option[aria-pressed="true"]')?.dataset.keyId || "";
}
function renderSshKeyPicker(containerId, fieldName, items, onChange) {
function clearSshKeyPicker(containerId) {
byId(containerId).querySelectorAll(".ssh-key-option").forEach((option) => option.setAttribute("aria-pressed", "false"));
}
function renderSshKeyPicker(containerId, items) {
const container = byId(containerId);
const previous = selectedSshKeyId(containerId);
const available = items.filter((item) => Number.isSafeInteger(Number(item?.id)) && Number(item.id) > 0);
const selected = available.some((item) => String(item.id) === previous) ? previous : "";
const card = (value, title, detail = "") => {
const label = makeElement("label", "ssh-key-option");
const input = document.createElement("input");
input.type = "radio";
input.name = fieldName;
input.value = value;
input.defaultChecked = value === "";
input.checked = value === selected;
input.addEventListener("change", onChange);
const body = makeElement("div", "ssh-key-option-body");
body.append(makeElement("strong", "", title));
if (detail) body.append(makeElement("small", "", detail));
label.append(input, body);
return label;
};
const cards = [card("", "使用 root 密码", "不选公钥,可填写密码或自动生成")];
for (const item of available) {
cards.push(card(String(item.id), String(item.name || `公钥 ${item.id}`)));
}
const cards = available.map((item) => {
const button = makeElement("button", "ssh-key-option");
button.type = "button";
button.dataset.keyId = String(item.id);
button.setAttribute("aria-pressed", String(button.dataset.keyId === selected));
button.append(makeElement("strong", "", String(item.name || `公钥 ${item.id}`)));
button.addEventListener("click", () => {
const wasSelected = button.getAttribute("aria-pressed") === "true";
container.querySelectorAll(".ssh-key-option").forEach((option) => option.setAttribute("aria-pressed", "false"));
button.setAttribute("aria-pressed", String(!wasSelected));
if (containerId === "vm-guest-ssh-key-cards") updateRootPasswordHint("vm-root-password", "vm-root-password-hint");
else updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint");
});
return button;
});
if (!available.length) {
cards.push(makeElement("p", "ssh-key-picker-empty", "还没有保存 SSH 公钥。可点击下方“管理我的公钥”先添加。"));
}
container.replaceChildren(...cards);
onChange();
if (containerId === "vm-guest-ssh-key-cards") updateRootPasswordHint("vm-root-password", "vm-root-password-hint");
else updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint");
}
function fillSshKeyCards(items) {
renderSshKeyPicker("vm-guest-ssh-key-cards", "guest_ssh_key_id", items, updateCreateAuthMode);
renderSshKeyPicker("reinstall-ssh-key-cards", "ssh_key_id", items, updateReinstallAuthMode);
renderSshKeyPicker("vm-guest-ssh-key-cards", items);
renderSshKeyPicker("reinstall-ssh-key-cards", items);
}
function sshKeyCreatedAt(value) {
@ -1364,7 +1365,7 @@ function renderVmCredentialStatus(vm) {
const mode = String(vm.auth_mode || "unknown");
const passwordAvailable = vm.password_available === true;
if (state.credentialVmId && (state.credentialVmId !== uuid || !passwordAvailable)) clearVmCredential();
const knownRoot = vm.managed && (vm.os_source === "cloud_template" || mode === "password" || mode === "ssh_key");
const knownRoot = vm.managed && (vm.os_source === "cloud_template" || mode === "password" || mode === "ssh_key" || mode === "ssh_key_password");
text("vm-detail-ssh-user", knownRoot ? "root" : "未记录");
const shown = passwordAvailable && state.credentialVmId === uuid && state.credentialVisible && !!state.credentialPassword;
text("vm-detail-root-password", passwordAvailable
@ -1868,21 +1869,34 @@ function configuredPublicPool() {
function updateCreateAuthMode() {
const cloud = selectedCreateSource() === "cloud";
const savedKeySelected = cloud && Boolean(selectedSshKeyId("vm-guest-ssh-key-cards"));
const password = byId("vm-root-password");
const passwordMode = cloud && !savedKeySelected;
byId("vm-root-password-field").hidden = !passwordMode;
password.required = false;
password.disabled = !passwordMode;
if (!passwordMode) password.value = "";
}
function updateReinstallAuthMode() {
const savedKeySelected = Boolean(selectedSshKeyId("reinstall-ssh-key-cards"));
const password = byId("reinstall-root-password");
byId("reinstall-root-password-field").hidden = savedKeySelected;
password.disabled = savedKeySelected;
if (savedKeySelected) password.value = "";
password.disabled = !cloud;
updateRootPasswordHint("vm-root-password", "vm-root-password-hint");
}
function manualRootPasswordIssue(value) {
if (!value) return "";
const missing = [];
const characters = Array.from(value);
if (characters.length < 12) missing.push("至少 12 个字符");
if (characters.length > 128) missing.push("不超过 128 个字符");
if (!/[A-Z]/.test(value)) missing.push("大写字母");
if (!/[a-z]/.test(value)) missing.push("小写字母");
if (!/[^\p{L}\p{N}\s]/u.test(value)) missing.push("符号");
if (characters.some((character) => character !== " " && /[\p{C}\p{Z}]/u.test(character))) missing.push("仅使用可打印字符");
return missing.length ? `自行设置的初始 root 密码还需:${missing.join("、")}。` : "";
}
function updateRootPasswordHint(inputId, hintId) {
const value = byId(inputId).value;
const hint = byId(hintId);
const issue = manualRootPasswordIssue(value);
const keySelected = Boolean(selectedSshKeyId(inputId === "vm-root-password" ? "vm-guest-ssh-key-cards" : "reinstall-ssh-key-cards"));
hint.classList.toggle("root-password-hint-error", !!issue);
hint.classList.toggle("root-password-hint-success", !!value && !issue);
hint.textContent = issue || (value
? "密码符合要求,可与 SSH 公钥同时使用。"
: `${keySelected ? "留空时仅允许 SSH 公钥登录,不生成密码" : "不选公钥且留空时自动生成强密码"};自行设置需至少 12 个字符,包含大写字母、小写字母和符号。`);
}
function updateCreateSource() {
@ -1944,6 +1958,7 @@ function closeModal() {
if (state.activeModal.id === "create-modal") {
byId("create-form").reset();
byId("vm-root-password").value = "";
updateRootPasswordHint("vm-root-password", "vm-root-password-hint");
}
if (state.activeModal.id === "reinstall-modal") {
state.reinstallPollToken += 1;
@ -1954,6 +1969,7 @@ function closeModal() {
state.reinstallPasswordPendingAck = false;
byId("reinstall-form").reset();
byId("reinstall-root-password").value = "";
updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint");
byId("reinstall-generated-password").textContent = "";
}
state.activeModal.hidden = true;
@ -1975,6 +1991,7 @@ function openCreate() {
if (!state.admin && (!state.approved || !state.hostReady)) return;
byId("create-form").reset();
fillSshKeyCards(state.sshKeys);
clearSshKeyPicker("vm-guest-ssh-key-cards");
byId("vm-root-password").value = "";
byId("template-import").open = !!state.templateImportJobId;
showTemplateImportStatus(state.templateImportJobId ? "宿主机仍在后台导入模板。查询会自动更新;若中断,可点击“导入模板”继续查看。" : "");
@ -2005,6 +2022,8 @@ function openReinstall(vm) {
}
byId("reinstall-form").reset();
fillSshKeyCards(state.sshKeys);
clearSshKeyPicker("reinstall-ssh-key-cards");
updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint");
byId("reinstall-fields").hidden = false;
byId("reinstall-progress").hidden = true;
byId("reinstall-result").hidden = true;
@ -2770,6 +2789,9 @@ for (const id of ["vm-open-ssh-keys", "reinstall-open-ssh-keys"]) {
void showSshKeysWorkspace();
});
}
for (const [inputId, hintId] of [["vm-root-password", "vm-root-password-hint"], ["reinstall-root-password", "reinstall-root-password-hint"]]) {
byId(inputId).addEventListener("input", () => updateRootPasswordHint(inputId, hintId));
}
document.querySelectorAll('input[name="source"]').forEach((radio) => radio.addEventListener("change", () => {
showError("create-error", "");
updateCreateSource();
@ -2945,7 +2967,7 @@ byId("create-form").addEventListener("submit", async (event) => {
body.gateway = String(data.get("gateway") || "").trim();
body.dns_servers = String(data.get("dns_servers") || "").split(/[\s,;]+/).filter(Boolean);
}
const selectedKeyId = String(data.get("guest_ssh_key_id") || "");
const selectedKeyId = selectedSshKeyId("vm-guest-ssh-key-cards");
if (selectedKeyId) {
const keyId = Number(selectedKeyId);
if (!Number.isSafeInteger(keyId) || keyId <= 0 || !state.sshKeys.some((key) => Number(key.id) === keyId)) {
@ -2974,14 +2996,14 @@ byId("create-form").addEventListener("submit", async (event) => {
showError("create-error", "请填写 1 至 4 个有效的 DNS IPv4 地址,用逗号或空格分隔。");
return;
}
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 个字符;留空将自动生成强密码。");
return;
}
if (requestedPassword) body.root_password = requestedPassword;
const requestedPassword = String(data.get("root_password") || "");
const passwordIssue = manualRootPasswordIssue(requestedPassword);
if (passwordIssue) {
showError("create-error", passwordIssue);
byId("vm-root-password").focus();
return;
}
if (requestedPassword) body.root_password = requestedPassword;
} else {
body.iso = String(data.get("iso") || "");
if (!body.network || !body.iso) {
@ -2991,6 +3013,7 @@ byId("create-form").addEventListener("submit", async (event) => {
}
data.delete("root_password");
byId("vm-root-password").value = "";
updateRootPasswordHint("vm-root-password", "vm-root-password-hint");
setButtonBusy(button, true, "正在创建…");
try {
const autoPassword = source === "cloud" && !body.guest_ssh_key_id && !body.root_password;
@ -3007,6 +3030,7 @@ byId("create-form").addEventListener("submit", async (event) => {
} finally {
delete body.root_password;
byId("vm-root-password").value = "";
updateRootPasswordHint("vm-root-password", "vm-root-password-hint");
setButtonBusy(button, false);
}
});
@ -3024,12 +3048,14 @@ byId("reinstall-form").addEventListener("submit", async (event) => {
showError("reinstall-error", "请先选择已导入的云镜像模板。若列表为空,请在“创建虚拟机”窗口先导入模板。");
return;
}
if (selectedKeyId && (rootPassword || !state.sshKeys.some((key) => String(key.id) === selectedKeyId))) {
showError("reinstall-error", "所选公钥已不可用或与密码设置冲突,请刷新公钥列表并重试。");
if (selectedKeyId && !state.sshKeys.some((key) => String(key.id) === selectedKeyId)) {
showError("reinstall-error", "所选公钥已不可用,请刷新公钥列表并重试。");
return;
}
if (rootPassword && (rootPassword.length < 12 || rootPassword.length > 128)) {
showError("reinstall-error", "初始 root 密码需要 12 至 128 个字符。");
const passwordIssue = manualRootPasswordIssue(rootPassword);
if (passwordIssue) {
showError("reinstall-error", passwordIssue);
byId("reinstall-root-password").focus();
return;
}
if (confirmationName !== vm.name) {
@ -3042,7 +3068,7 @@ byId("reinstall-form").addEventListener("submit", async (event) => {
confirmation_name: confirmationName,
};
if (selectedKeyId) body.ssh_key_id = Number(selectedKeyId);
else if (rootPassword) body.root_password = rootPassword;
if (rootPassword) body.root_password = rootPassword;
state.reinstallInProgress = true;
state.reinstallExpectGeneratedPassword = !selectedKeyId && !rootPassword;
byId("reinstall-close-top").disabled = true;
@ -3069,6 +3095,7 @@ byId("reinstall-form").addEventListener("submit", async (event) => {
} finally {
delete body.root_password;
byId("reinstall-root-password").value = "";
updateRootPasswordHint("reinstall-root-password", "reinstall-root-password-hint");
setButtonBusy(button, false);
}
});

@ -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=ssh-key-cards-1" />
<script type="module" src="/static/app.js?v=ssh-key-cards-1"></script>
<link rel="stylesheet" href="/static/styles.css?v=cloud-auth-2" />
<script type="module" src="/static/app.js?v=cloud-auth-2"></script>
</head>
<body>
<div id="boot-screen" class="boot-screen" role="status" aria-live="polite">
@ -397,11 +397,11 @@
<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>
<div class="form-grid vm-cloud-auth-fields">
<div class="field full"><span class="ssh-key-picker-title">SSH 公钥(可选)</span><div id="vm-guest-ssh-key-cards" class="ssh-key-picker" role="radiogroup" aria-label="创建虚拟机时选择 SSH 公钥"></div><small>只显示你在“公钥管理”中添加的公钥。选择后可用对应私钥登录 root,密码登录将关闭;不选则可设置密码或自动生成。</small><button id="vm-open-ssh-keys" class="ssh-key-picker-manage" type="button">管理我的公钥</button></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 class="field full"><span class="ssh-key-picker-title">SSH 公钥(可选)</span><div id="vm-guest-ssh-key-cards" class="ssh-key-picker" role="group" aria-label="创建虚拟机时选择 SSH 公钥"></div><small>只显示你在“公钥管理”中添加的公钥;再次点击已选公钥可取消。填写密码时可与公钥同时使用。</small><button id="vm-open-ssh-keys" class="ssh-key-picker-manage" type="button">管理我的公钥</button></div>
<div class="field full" id="vm-root-password-field"><label for="vm-root-password">初始 root 密码(可选)</label><input id="vm-root-password" name="root_password" type="password" maxlength="256" autocomplete="new-password" spellcheck="false" aria-describedby="vm-root-password-hint" placeholder="可自行设置,留空时按公钥选择决定" disabled /><small id="vm-root-password-hint" aria-live="polite">不选公钥且留空时自动生成强密码;自行设置需至少 12 个字符,包含大写字母、小写字母和符号。</small></div>
</div>
</div>
</div><div id="create-iso-tip" class="form-tip"><span aria-hidden="true">ⓘ</span><p>创建后会自动开机,可通过 VNC 安装系统。安装程序首次重启时虚拟机会先停机;之后在面板点“开机”,将从硬盘启动且不再挂载 ISO。</p></div><div id="create-cloud-tip" class="form-tip" hidden><span aria-hidden="true">ⓘ</span><p>云镜像首次启动由 cloud-init 写入静态 IP、DNS 和 root 登录凭据,无需 VNC 安装。选择已保存的 SSH 公钥时用 <code>root</code> 和对应私钥登录;不选公钥时可设置密码,密码也留空则自动生成。初始密码可在虚拟机详情页查看,请确认网络配置并妥善保护凭据。</p></div><p id="create-error" class="form-error" role="alert" hidden></p></div>
</div><div id="create-iso-tip" class="form-tip"><span aria-hidden="true">ⓘ</span><p>创建后会自动开机,可通过 VNC 安装系统。安装程序首次重启时虚拟机会先停机;之后在面板点“开机”,将从硬盘启动且不再挂载 ISO。</p></div><div id="create-cloud-tip" class="form-tip" hidden><span aria-hidden="true">ⓘ</span><p>云镜像首次启动由 cloud-init 写入静态 IP、DNS 和 root 登录凭据,无需 VNC 安装。可同时使用已保存的 SSH 公钥和自行设置的 root 密码;选公钥且密码留空时仅可用私钥登录,不选公钥且密码留空时才自动生成密码。初始密码可在虚拟机详情页查看。</p></div><p id="create-error" class="form-error" role="alert" hidden></p></div>
<div class="modal-footer"><button class="button button-outline" type="button" data-close-modal>取消</button><button id="create-submit" class="button button-primary" type="submit">创建并启动</button></div>
</form>
</section>
@ -424,8 +424,8 @@
<p class="reinstall-network">沿用首次创建的公网网络信息:<strong id="reinstall-public-ip"></strong>。网桥、MAC、网关和 DNS 也会保持原配置。</p>
<div class="form-grid">
<div class="field full"><label for="reinstall-template">重装模板 <span>*</span></label><select id="reinstall-template" name="template_id" required><option value="">正在加载模板…</option></select><small>仅显示当前宿主机已经导入的云镜像模板;模板必须支持 cloud-init。</small></div>
<div class="field full"><span class="ssh-key-picker-title">SSH 公钥(可选)</span><div id="reinstall-ssh-key-cards" class="ssh-key-picker" role="radiogroup" aria-label="重装系统时选择 SSH 公钥"></div><small>直接选择你在“公钥管理”中保存的公钥,无需重新粘贴;不选则使用初始 root 密码。</small><button id="reinstall-open-ssh-keys" class="ssh-key-picker-manage" type="button">管理我的公钥</button></div>
<div class="field full" id="reinstall-root-password-field"><label for="reinstall-root-password">初始 root 密码(可选)</label><input id="reinstall-root-password" name="root_password" type="password" minlength="12" maxlength="128" autocomplete="new-password" spellcheck="false" placeholder="至少 12 个字符;留空可自动生成" /><small>不选择公钥时可填写密码,留空则自动生成强密码。成功重装后,面板记录的初始密码可在虚拟机详情页查看。</small></div>
<div class="field full"><span class="ssh-key-picker-title">SSH 公钥(可选)</span><div id="reinstall-ssh-key-cards" class="ssh-key-picker" role="group" aria-label="重装系统时选择 SSH 公钥"></div><small>直接选择“公钥管理”中保存的公钥;再次点击已选公钥可取消。填写密码时可与公钥同时使用。</small><button id="reinstall-open-ssh-keys" class="ssh-key-picker-manage" type="button">管理我的公钥</button></div>
<div class="field full" id="reinstall-root-password-field"><label for="reinstall-root-password">初始 root 密码(可选)</label><input id="reinstall-root-password" name="root_password" type="password" maxlength="256" autocomplete="new-password" spellcheck="false" aria-describedby="reinstall-root-password-hint" placeholder="可自行设置,留空时按公钥选择决定" /><small id="reinstall-root-password-hint" aria-live="polite">不选公钥且留空时自动生成强密码;自行设置需至少 12 个字符,包含大写字母、小写字母和符号。</small></div>
<div class="field full"><label for="reinstall-confirm-name">输入虚拟机名称以确认删除旧系统盘 <span>*</span></label><input id="reinstall-confirm-name" name="confirmation_name" type="text" required autocomplete="off" spellcheck="false" placeholder="请输入完整的虚拟机名称" /><small id="reinstall-confirm-hint"></small></div>
</div>
</div>

@ -74,7 +74,8 @@ input:focus,select:focus,button:focus-visible{outline:3px solid rgba(18,166,176,
.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}
.ssh-key-picker-title{display:block;color:#34445a;font-size:12px;font-weight:700}.ssh-key-picker{display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:10px;margin-top:10px}.ssh-key-option{position:relative;display:block;min-width:0;cursor:pointer}.ssh-key-option input{position:absolute;opacity:0;width:1px;height:1px}.ssh-key-option-body{display:flex;flex-direction:column;gap:5px;min-height:74px;padding:12px 14px;border:1px solid #dce4eb;border-radius:9px;background:#fff}.ssh-key-option-body strong{font-size:12px;color:#334a5f;overflow-wrap:anywhere}.ssh-key-option-body small{margin:0!important;color:#8999a8;font-size:10px;overflow-wrap:anywhere}.ssh-key-option input:checked+.ssh-key-option-body{border-color:#3bb5bc;background:#effafa;box-shadow:0 0 0 2px rgba(20,166,175,.08)}.ssh-key-option input:focus-visible+.ssh-key-option-body{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}.ssh-key-picker-empty{grid-column:1/-1;margin:0;color:#8b9bab;font-size:11px}.ssh-key-picker-manage{margin-top:9px;padding:0;border:0;background:transparent;color:#148c98;font-size:11px;font-weight:700;cursor:pointer}.ssh-key-picker-manage:hover{text-decoration:underline}
.ssh-key-picker-title{display:block;color:#34445a;font-size:12px;font-weight:700}.ssh-key-picker{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin-top:10px}.ssh-key-option{display:flex;align-items:center;width:100%;min-width:0;min-height:74px;padding:12px 14px;text-align:left;border:1px solid #dce4eb;border-radius:9px;background:#fff;color:#334a5f;cursor:pointer}.ssh-key-option strong{font-size:12px;line-height:1.5;overflow-wrap:anywhere}.ssh-key-option[aria-pressed="true"]{border-color:#3bb5bc;background:#effafa;box-shadow:0 0 0 2px rgba(20,166,175,.08)}.ssh-key-option:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}.ssh-key-picker-empty{grid-column:1/-1;margin:0;color:#8b9bab;font-size:11px}.ssh-key-picker-manage{margin-top:9px;padding:0;border:0;background:transparent;color:#148c98;font-size:11px;font-weight:700;cursor:pointer}.ssh-key-picker-manage:hover{text-decoration:underline}.field small.root-password-hint-error{color:#b73e4c}.field small.root-password-hint-success{color:#247f67}
@media(max-width:510px){.ssh-key-picker{grid-template-columns:1fr}}
.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}

@ -759,11 +759,17 @@ def test_cloud_template_import_job_and_create_dispatch(web):
if key not in {"source", "template_id"}}
expected_spec["os_name"] = "AlmaLinux 10"
expected_spec["vm_uuid"] = created.json()["uuid"]
assert ("create_cloud_vm", expected_spec, volume_name) in service.calls
created_cloud_calls = [call for call in service.calls
if call[0] == "create_cloud_vm"]
assert len(created_cloud_calls) == 1
_operation, actual_spec, actual_volume = created_cloud_calls[0]
assert actual_volume == volume_name
assert "root_password_hash" not in actual_spec
assert actual_spec == expected_spec
assert ("create_vm", expected_spec) not in service.calls
def test_cloud_vm_root_login_uses_either_key_or_hashed_initial_password(web):
def test_cloud_vm_root_login_supports_key_and_hashed_initial_password(web):
client, state, token, service, manager, _ = web
csrf = setup_admin(client, token)
host_body = {**HOST_BODY, "default_network": "bridge:br0"}
@ -798,6 +804,19 @@ def test_cloud_vm_root_login_uses_either_key_or_hashed_initial_password(web):
"login_name": "root", "auth_mode": "ssh_key", "password": None,
}
both_body = {**key_body, "name": "key-password-vm",
"root_password": GUEST_PASSWORD}
both_response = client.post("/api/v1/vms", json=both_body, headers=headers)
assert both_response.status_code == 201
both_spec = service.calls[-1][1]
assert both_spec["guest_ssh_public_key"] == CLOUD_CREATE_BODY["guest_ssh_public_key"]
assert both_spec["root_password_hash"].startswith("$6$")
assert GUEST_PASSWORD not in repr(service.calls)
assert both_response.json()["auth_mode"] == "ssh_key_password"
assert client.post(
f"/api/v1/vms/{both_response.json()['uuid']}/credential", headers=headers,
).json()["password"] == GUEST_PASSWORD
password_body = {
**key_body, "guest_ssh_public_key": "", "root_password": GUEST_PASSWORD,
}
@ -829,15 +848,17 @@ def test_cloud_vm_root_login_uses_either_key_or_hashed_initial_password(web):
service.vm["credential_generation"] = original_generation
for invalid_body in (
{**key_body, "root_password": GUEST_PASSWORD},
{**password_body, "root_password": "too-short"},
{**password_body, "root_password": "X" * 129},
{**key_body, "root_password": "alllowercase123!"},
{**key_body, "root_password": "ALLUPPERCASE123!"},
{**key_body, "root_password": "NoSymbolPassword123"},
):
rejected = client.post("/api/v1/vms", json=invalid_body,
headers=headers)
assert rejected.status_code == 422
assert len([call for call in service.calls
if call[0] == "create_cloud_vm"]) == 2
if call[0] == "create_cloud_vm"]) == 3
no_credential = {**key_body, "guest_ssh_public_key": ""}
generated = client.post("/api/v1/vms", json=no_credential,
@ -852,7 +873,7 @@ def test_cloud_vm_root_login_uses_either_key_or_hashed_initial_password(web):
assert generated_password not in client.get("/api/v1/vms").text
assert generated_password not in repr(service.calls)
assert len([call for call in service.calls
if call[0] == "create_cloud_vm"]) == 3
if call[0] == "create_cloud_vm"]) == 4
assert client.delete(
f"/api/v1/vms/{generated.json()['uuid']}", headers=headers,
).status_code == 200
@ -878,7 +899,7 @@ def test_unknown_vm_has_no_recoverable_password(web):
assert not old_cloud["password_available"]
def test_reinstall_password_record_is_removed_when_switching_to_ssh_key(web):
def test_reinstall_key_without_password_removes_old_password(web):
client, _state, _token, _service, _manager, _ = web
csrf, template_id, _volume_name = configure_reinstall_case(web)
headers = {"X-CSRF-Token": csrf}
@ -897,9 +918,12 @@ def test_reinstall_password_record_is_removed_when_switching_to_ssh_key(web):
"ssh_public_key": CLOUD_CREATE_BODY["guest_ssh_public_key"]}, headers=headers,
)
assert key_job.status_code == 202
assert wait_for_reinstall_job(client, key_job.json()["job_id"], csrf)["status"] == "succeeded"
completed = wait_for_reinstall_job(client, key_job.json()["job_id"], csrf)
assert completed["status"] == "succeeded"
assert "generated_password" not in completed
assert client.post(f"/api/v1/vms/{VM_ID}/credential",
headers=headers).json()["password"] is None
assert client.get(f"/api/v1/vms/{VM_ID}").json()["auth_mode"] == "ssh_key"
deleted = client.delete(f"/api/v1/vms/{VM_ID}", headers=headers)
assert deleted.status_code == 200
assert client.get(f"/api/v1/vms/{VM_ID}").json()["auth_mode"] == "unknown"
@ -959,25 +983,46 @@ def test_reinstall_auto_password_job_ack_keeps_vm_credential(web):
assert client.post(ack_url, headers=headers).status_code == 401
def test_reinstall_key_mode_has_no_generated_password(web):
def test_reinstall_key_and_manual_password_has_no_generated_password(web):
client, _state, _token, service, _manager, _ = web
csrf, template_id, volume_name = configure_reinstall_case(web)
public_key = CLOUD_CREATE_BODY["guest_ssh_public_key"]
queued = client.post(
f"/api/v1/vms/{VM_ID}/reinstall",
json={"template_id": template_id, "confirmation_name": "cloud-vm",
"ssh_public_key": public_key},
"ssh_public_key": public_key, "root_password": GUEST_PASSWORD},
headers={"X-CSRF-Token": csrf},
)
assert queued.status_code == 202
completed = wait_for_reinstall_job(client, queued.json()["job_id"], csrf)
assert completed["status"] == "succeeded"
assert "generated_password" not in completed
assert client.get(f"/api/v1/vms/{VM_ID}").json()["auth_mode"] == "ssh_key"
assert client.get(f"/api/v1/vms/{VM_ID}").json()["auth_mode"] == "ssh_key_password"
assert client.post(f"/api/v1/vms/{VM_ID}/credential",
headers={"X-CSRF-Token": csrf}).json()["password"] is None
assert ("reinstall_cloud_vm", VM_ID, volume_name, public_key, None,
"AlmaLinux 10") in service.calls
headers={"X-CSRF-Token": csrf}).json()["password"] == GUEST_PASSWORD
reinstall_call = next(call for call in service.calls
if call[0] == "reinstall_cloud_vm")
assert reinstall_call[1:4] == (VM_ID, volume_name, public_key)
assert reinstall_call[4].startswith("$6$")
assert reinstall_call[5] == "AlmaLinux 10"
@pytest.mark.parametrize("weak_password", [
"short-A!", "alllowercase123!", "ALLUPPERCASE123!", "NoSymbolPassword123",
])
def test_reinstall_rejects_weak_manual_root_password(web, weak_password):
client, _state, _token, service, _manager, _ = web
csrf, template_id, _volume_name = configure_reinstall_case(web)
response = client.post(
f"/api/v1/vms/{VM_ID}/reinstall",
json={"template_id": template_id, "confirmation_name": "cloud-vm",
"ssh_public_key": CLOUD_CREATE_BODY["guest_ssh_public_key"],
"root_password": weak_password},
headers={"X-CSRF-Token": csrf},
)
assert response.status_code == 422
assert "初始 root 密码" in response.json()["detail"]
assert not any(call[0] == "reinstall_cloud_vm" for call in service.calls)
def test_reinstall_requires_exact_name_and_blocks_duplicate_or_lifecycle_actions(web):

@ -9,7 +9,8 @@ import uuid
import pytest
from virsh_panel.cloud_init import (
build_seed_iso, hash_root_password, read_seed_network, validate_cloud_network,
build_seed_iso, generate_root_password, hash_root_password, read_seed_network,
validate_cloud_network,
)
@ -48,7 +49,7 @@ def test_public_network_accepts_24_and_28(address, gateway):
}
def test_cloud_login_requires_exactly_one_root_credential():
def test_cloud_login_accepts_key_and_root_password_together():
network = ("8.8.8.18/24", "8.8.8.1", ["1.1.1.1"])
password_hash = hash_root_password(GUEST_PASSWORD)
assert password_hash.startswith("$6$")
@ -61,13 +62,40 @@ def test_cloud_login_requires_exactly_one_root_credential():
assert validated["root_password_hash"] == password_hash
assert not validated["guest_ssh_public_key"]
for key, hashed in (("", None), (PUBLIC_KEY, password_hash)):
with pytest.raises(ValueError):
validate_cloud_network(*network, key, root_password_hash=hashed)
together = validate_cloud_network(
*network, PUBLIC_KEY, root_password_hash=password_hash,
)
assert together["guest_ssh_public_key"] == PUBLIC_KEY
assert together["root_password_hash"] == password_hash
with pytest.raises(ValueError):
validate_cloud_network(*network, "", root_password_hash=None)
with pytest.raises(ValueError):
validate_cloud_network(*network, "", root_password_hash=GUEST_PASSWORD)
@pytest.mark.parametrize("invalid", [
"Short1!", "alllowercase12!", "ALLUPPERCASE12!", "NoSymbolPassword12",
"A-lowercase\npassword12", "A-lowercase-password-" + "x" * 110,
])
def test_manual_root_password_requires_length_case_and_symbol(invalid):
with pytest.raises(ValueError, match="初始 root 密码"):
hash_root_password(invalid)
def test_generated_root_password_always_meets_policy():
samples = set()
for _ in range(50):
password = generate_root_password()
samples.add(password)
assert len(password) == 32
assert any(char.isupper() for char in password)
assert any(char.islower() for char in password)
assert any(not char.isalnum() for char in password)
assert len(samples) == 50
assert hash_root_password(password).startswith("$6$")
@pytest.mark.parametrize(
("address", "gateway"),
[
@ -177,3 +205,26 @@ def test_password_seed_sets_root_hash_and_enables_ssh_password_login():
assert "PermitRootLogin yes" in sshd_dropin["content"]
assert "PasswordAuthentication yes" in sshd_dropin["content"]
assert GUEST_PASSWORD.encode() not in seed
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_seed_allows_root_password_and_ssh_key_together():
password_hash = hash_root_password(GUEST_PASSWORD)
validated = validate_cloud_network(
"8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], PUBLIC_KEY,
root_password_hash=password_hash,
)
seed = build_seed_iso(
str(uuid.uuid4()), "both-vm", "52:54:00:12:34:56", validated,
)
user_data = _user_data(seed)
root = user_data["users"][0]
assert root["name"] == "root"
assert root["lock_passwd"] is False
assert root["ssh_authorized_keys"] == [PUBLIC_KEY]
assert root["hashed_passwd"] == password_hash
assert user_data["ssh_pwauth"] is True
assert "PermitRootLogin yes" in user_data["write_files"][0]["content"]
assert "PasswordAuthentication yes" in user_data["write_files"][0]["content"]
assert GUEST_PASSWORD.encode() not in seed

@ -523,8 +523,6 @@ def test_per_user_ssh_key_library_and_cloud_vm_selection(monkeypatch, tmp_path):
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,
@ -534,15 +532,39 @@ def test_per_user_ssh_key_library_and_cloud_vm_selection(monkeypatch, tmp_path):
selected = first.post("/api/v1/vms", json={
**CLOUD_VM, "guest_ssh_key_id": first_key["id"],
"root_password": "A-strong-guest-password-2026",
}, 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 spec["root_password_hash"].startswith("$6$")
assert selected.json()["auth_mode"] == "ssh_key_password"
assert selected.json()["password_available"]
assert first.post(
f"/api/v1/vms/{selected.json()['uuid']}/credential",
headers=first_headers,
).json()["password"] == "A-strong-guest-password-2026"
assert second.get(f"/api/v1/vms/{selected.json()['uuid']}").status_code == 404
key_only = first.post("/api/v1/vms", json={
**CLOUD_VM, "name": "saved-key-only",
"public_ip_cidr": "8.8.8.21/24",
"guest_ssh_key_id": first_key["id"],
}, headers=first_headers)
assert key_only.status_code == 201
key_spec, _key_volume = service.cloud_specs[-1]
assert key_spec["guest_ssh_public_key"] == first_key["public_key"]
assert "root_password_hash" not in key_spec
assert key_only.json()["auth_mode"] == "ssh_key"
assert not key_only.json()["password_available"]
key_credential = first.post(
f"/api/v1/vms/{key_only.json()['uuid']}/credential",
headers=first_headers,
).json()
assert key_credential["auth_mode"] == "ssh_key"
assert key_credential["password"] is None
reinstall_url = f"/api/v1/vms/{selected.json()['uuid']}/reinstall"
reinstall_body = {"template_id": "alma10-template",
"confirmation_name": "tenant-cloud"}
@ -558,12 +580,13 @@ def test_per_user_ssh_key_library_and_cloud_vm_selection(monkeypatch, tmp_path):
}, headers=second_headers).status_code == 404
assert first.post(reinstall_url, json={
**reinstall_body, "ssh_key_id": first_key["id"],
"root_password": "A-strong-guest-password-2026",
"ssh_public_key": GUEST_PUBLIC_KEY,
}, headers=first_headers).status_code == 422
assert service.reinstall_specs == []
queued = first.post(reinstall_url, json={
**reinstall_body, "ssh_key_id": first_key["id"],
"root_password": "A-strong-guest-password-2026",
}, headers=first_headers)
assert queued.status_code == 202
for _ in range(100):
@ -575,7 +598,12 @@ def test_per_user_ssh_key_library_and_cloud_vm_selection(monkeypatch, tmp_path):
time.sleep(0.01)
assert job.json()["status"] == "succeeded"
assert service.reinstall_specs[-1][2] == first_key["public_key"]
assert service.reinstall_specs[-1][3] is None
assert service.reinstall_specs[-1][3].startswith("$6$")
assert "generated_password" not in job.json()
assert first.post(
f"/api/v1/vms/{selected.json()['uuid']}/credential",
headers=first_headers,
).json()["password"] == "A-strong-guest-password-2026"
# Existing create paths continue to accept a one-off pasted key
# or an initial root password without a saved-key ID.

@ -7,7 +7,6 @@ import hmac
import ipaddress
import json
import logging
import secrets
import subprocess
import threading
import time
@ -23,7 +22,7 @@ from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, ConfigDict, Field, SecretStr
from .auth import DatabaseSessionStore, LoginLimiter, Session, SessionStore, verify_password
from .cloud_init import _validate_guest_auth, hash_root_password
from .cloud_init import _validate_guest_auth, generate_root_password, hash_root_password
from .cloud_templates import (
TemplateError, TemplateStore, download_verified_image, template_id_for,
template_scope, template_volume_name, validate_image_url, validate_template_name,
@ -510,8 +509,8 @@ def create_app(
except (TypeError, ValueError) as exc:
raise DatabaseError("虚拟机登录凭据记录损坏") from exc
if (not isinstance(value, dict)
or value.get("auth_mode") not in ("password", "ssh_key")
or (value["auth_mode"] == "password"
or value.get("auth_mode") not in ("password", "ssh_key", "ssh_key_password")
or (value["auth_mode"] in ("password", "ssh_key_password")
and (not isinstance(value.get("password"), str)
or not value["password"]))
or not isinstance(value.get("generation"), str)
@ -537,7 +536,8 @@ def create_app(
"login_name": "root" if cloud else None,
"auth_mode": current_credential["auth_mode"] if current_credential else "unknown",
"password_available": bool(current_credential and
current_credential["auth_mode"] == "password"),
current_credential["auth_mode"] in (
"password", "ssh_key_password")),
}
def save_job(kind: str, job_id: str, job: dict) -> None:
@ -1448,10 +1448,10 @@ def create_app(
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:
if public_key:
raise HTTPException(
status_code=422,
detail="已保存公钥、手动公钥和初始 root 密码只能选择一种",
detail="已保存公钥和手动公钥只能选择一种",
)
saved_key = ssh_key_store().get_for_user(
account["id"], body.guest_ssh_key_id,
@ -1459,13 +1459,8 @@ def create_app(
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,
detail="虚拟机 SSH 公钥和初始 root 密码只能填写一项",
)
if not public_key and not root_password:
root_password = secrets.token_urlsafe(24)
if not root_password and not public_key:
root_password = generate_root_password()
password_hash = None
if root_password:
try:
@ -1513,7 +1508,8 @@ def create_app(
state.users.assign_vm(host_scope(profile), requested_uuid, owner_id)
owner_assigned = True
save_credential(profile, requested_uuid,
"ssh_key" if public_key else "password",
("ssh_key_password" if public_key and root_password
else "ssh_key" if public_key else "password"),
f"panel-seed-{requested_uuid}.iso",
root_password or None)
vm = service.create_cloud_vm(spec, record["volume_name"])
@ -1591,7 +1587,8 @@ def create_app(
)
vm_reinstalled = True
save_credential(profile, vm_id,
"ssh_key" if ssh_public_key else "password",
("ssh_key_password" if ssh_public_key and credential_password
else "ssh_key" if ssh_public_key else "password"),
result["credential_generation"],
credential_password)
with reinstall_lock:
@ -1640,34 +1637,26 @@ def create_app(
ssh_public_key = body.ssh_public_key.strip()
supplied_password = (body.root_password.get_secret_value()
if body.root_password is not None else "")
if not supplied_password.strip():
supplied_password = ""
if body.ssh_key_id is not None:
if ssh_public_key or supplied_password:
if ssh_public_key:
raise HTTPException(
status_code=422,
detail="已保存公钥、手动公钥和初始 root 密码只能选择一种",
detail="已保存公钥和手动公钥只能选择一种",
)
account = account_for_session(_session)
saved_key = ssh_key_store().get_for_user(account["id"], body.ssh_key_id)
if saved_key is None:
raise SSHKeyError("公钥不存在", 404)
ssh_public_key = saved_key["public_key"]
if ssh_public_key and supplied_password:
raise HTTPException(
status_code=422,
detail="SSH 公钥和初始 root 密码只能填写一种",
)
generated_password = None
if not ssh_public_key and not supplied_password:
generated_password = secrets.token_urlsafe(24)
if not supplied_password and not ssh_public_key:
generated_password = generate_root_password()
supplied_password = generated_password
try:
if ssh_public_key:
ssh_public_key, _unused_hash = _validate_guest_auth(ssh_public_key, None)
root_password_hash = None
else:
root_password_hash = hash_root_password(supplied_password)
root_password_hash = (hash_root_password(supplied_password)
if supplied_password else None)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc

@ -1,6 +1,6 @@
"""Validate public IPv4 guest settings and build a NoCloud seed ISO.
The seed may contain a guest SSH public key or a salted root password hash,
The seed may contain a guest SSH public key and a salted root password hash,
but never a plaintext password, private key, or panel credential. JSON is
used as a YAML subset so untrusted fields cannot inject directives.
"""
@ -12,6 +12,8 @@ import binascii
import ipaddress
import json
import re
import secrets
import string
import uuid
from io import BytesIO
from typing import Any
@ -34,14 +36,32 @@ _SHA512_CRYPT = re.compile(
def hash_root_password(password: str) -> str:
"""Hash a guest root password for /etc/shadow before writing the seed."""
if (not isinstance(password, str) or not 12 <= len(password) <= 128
or password.isspace() or any(ord(char) < 32 or ord(char) == 127
for char in password)):
raise ValueError("初始 root 密码须为 12 至 128 个非控制字符")
or any(not char.isprintable() for char in password)):
raise ValueError("初始 root 密码须为 12 至 128 个可打印字符")
if (not any(char in string.ascii_uppercase for char in password)
or not any(char in string.ascii_lowercase for char in password)
or not any(not char.isalnum() and not char.isspace()
for char in password)):
raise ValueError("初始 root 密码须包含大写字母、小写字母和符号")
from passlib.hash import sha512_crypt
return sha512_crypt.using(rounds=100_000).hash(password)
def generate_root_password() -> str:
"""Generate a high-entropy password satisfying the same guest policy."""
symbols = "!@#$%*-_=+?"
alphabet = string.ascii_letters + string.digits + symbols
password = [
secrets.choice(string.ascii_uppercase),
secrets.choice(string.ascii_lowercase),
secrets.choice(symbols),
]
password.extend(secrets.choice(alphabet) for _ in range(29))
secrets.SystemRandom().shuffle(password)
return "".join(password)
def _validate_guest_auth(guest_ssh_public_key: Any,
root_password_hash: Any) -> tuple[str, str | None]:
if not isinstance(guest_ssh_public_key, str):
@ -49,16 +69,15 @@ def _validate_guest_auth(guest_ssh_public_key: Any,
public_key = guest_ssh_public_key.strip()
if not public_key and not root_password_hash:
raise ValueError("请填写虚拟机 SSH 公钥或初始 root 密码")
if public_key and root_password_hash:
raise ValueError("SSH 公钥和初始 root 密码只能选择一种")
if public_key:
return _validate_ssh_public_key(public_key), None
if not isinstance(root_password_hash, str):
raise ValueError("初始 root 密码哈希格式无效")
match = _SHA512_CRYPT.fullmatch(root_password_hash)
if match is None or not 100_000 <= int(match.group(1)) <= 1_000_000:
raise ValueError("初始 root 密码哈希格式无效")
return "", root_password_hash
public_key = _validate_ssh_public_key(public_key)
if root_password_hash is not None:
if not isinstance(root_password_hash, str):
raise ValueError("初始 root 密码哈希格式无效")
match = _SHA512_CRYPT.fullmatch(root_password_hash)
if match is None or not 100_000 <= int(match.group(1)) <= 1_000_000:
raise ValueError("初始 root 密码哈希格式无效")
return public_key, root_password_hash
def _ssh_string(blob: bytes, offset: int) -> tuple[bytes, int]:
@ -223,22 +242,23 @@ def build_seed_iso(
if not hostname:
hostname = f"vm-{instance_id[:8]}"
use_public_key = bool(network["guest_ssh_public_key"])
root_user: dict[str, Any] = {"name": "root", "lock_passwd": use_public_key}
use_password = bool(network.get("root_password_hash"))
root_user: dict[str, Any] = {"name": "root", "lock_passwd": not use_password}
if use_public_key:
root_user["ssh_authorized_keys"] = [network["guest_ssh_public_key"]]
else:
if use_password:
root_user["hashed_passwd"] = network["root_password_hash"]
# RHEL/AlmaLinux 10 defaults to prohibit-password for root. An early
# drop-in makes the two requested authentication modes explicit; cloud-init
# itself writes a later 50-cloud-init.conf for PasswordAuthentication.
sshd_config = (
"PermitRootLogin prohibit-password\nPasswordAuthentication no\n"
if use_public_key else
"PermitRootLogin yes\nPasswordAuthentication yes\n"
) + "KbdInteractiveAuthentication no\n"
("PermitRootLogin yes\nPasswordAuthentication yes\n" if use_password else
"PermitRootLogin prohibit-password\nPasswordAuthentication no\n")
+ "KbdInteractiveAuthentication no\n"
)
user_data = {
"users": [root_user],
"ssh_pwauth": not use_public_key,
"ssh_pwauth": use_password,
"disable_root": False,
"write_files": [{
"path": "/etc/ssh/sshd_config.d/00-virsh-panel-root.conf",

Loading…
Cancel
Save