Add host public IPv4 pool and automatic VM IP allocation

main
admin 2 months ago
parent 62c7b51c3e
commit 70f2349129

@ -64,7 +64,7 @@ SELECT id, username, email FROM users WHERE id = 1;
核对查询结果中的邮箱和管理员标志后,再刷新面板;权限会从数据库即时读取,不必重启。此后用邮箱登录,不能用用户名登录。不要把 `admin=1` 给公开注册用户。
3. 管理员在网页配置 SMTP 地址、端口、SSL/STARTTLS、发件邮箱及需要时的 SMTP 账号密码;设置加密保存在 MariaDB,页面不回显密码。完成后,访客可用邮箱验证码注册(10 分钟有效,重复发送与输错次数受限);邮箱验证成功即可登录,但须由管理员在“用户审核”批准后才能创建虚拟机。普通用户不能添加宿主机、导入云镜像模板、配置 SMTP 或更新面板,也看不到其他人的虚拟机和初始密码。面板外创建或管理员创建的未归属虚拟机仅管理员可见;当前没有从网页将旧 VM 分配给用户的功能。
4. 在网页填写 B 的 IP/DNS、SSH 端口、虚拟机地区、现有的 **root 客户端 SSH 私钥**、磁盘目录、ISO 目录和网络名称。地区是这台宿主机上虚拟机共用的展示标签,可留空;它不影响 SSH 连接或已导入的模板。私钥必须与 B 的 root 账号**已经授权的公钥**匹配;仅有 root 密码或 B 的 SSH 主机密钥不能代替它。加密私钥还需填写其口令。保存宿主机设置时,面板会将口令与私钥加密写入 MariaDB,以便面板重启后自动连接和无人登录时继续采样;设置 API 不回显口令,面板代码也不将其写入浏览器存储。**旧版本中只在内存解锁过的口令无法自动恢复**:升级后进入“宿主机设置”,不必重新粘贴原私钥,填写原口令并重新保存一次。只在“解锁宿主机 SSH 私钥”页面输入不会持久保存。
4. 在网页填写 B 的 IP/DNS、SSH 端口、虚拟机地区、现有的 **root 客户端 SSH 私钥**、磁盘目录、ISO 目录和网络名称。还可配置由服务商分配且已路由到该宿主机的**公网 IPv4 `/24` 地址池**、同网段网关、DNS,以及不能分配给虚拟机的保留地址。地区是这台宿主机上虚拟机共用的展示标签,可留空;它不影响 SSH 连接或已导入的模板。私钥必须与 B 的 root 账号**已经授权的公钥**匹配;仅有 root 密码或 B 的 SSH 主机密钥不能代替它。加密私钥还需填写其口令。保存宿主机设置时,面板会将口令与私钥加密写入 MariaDB,以便面板重启后自动连接和无人登录时继续采样;设置 API 不回显口令,面板代码也不将其写入浏览器存储。**旧版本中只在内存解锁过的口令无法自动恢复**:升级后进入“宿主机设置”,不必重新粘贴原私钥,填写原口令并重新保存一次。只在“解锁宿主机 SSH 私钥”页面输入不会持久保存。
5. 点击“扫描主机指纹”,再通过 B 的可信控制台运行 `ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub` 独立核对;确认后在网页测试、保存。保存前会重扫并测试 SSH 与 libvirt API,失败不会覆盖现有连接。
宿主机私钥、已填写的私钥口令和配置加密保存在 MariaDB。数据库备份与 `data/master.key` 同时泄露时,这些凭据可以被解密,因此须分别严密保护;运行中的 root 面板进程同样能使用它们。OpenSSH 连接时需要读取私钥文件,Linux 上面板会将其临时还原到权限为 `0700` 的 `/dev/shm` 内存文件系统目录;面板关闭时清除。`data/runtime-wrappers/` 只包含不带密钥的启动包装器。若 SSH agent 异常退出,后台采样会限频尝试使用已保存口令恢复连接;若保存的口令错误,仍需管理员检查并重新保存。面板仅支持单个 Uvicorn worker。
@ -89,7 +89,9 @@ SELECT id, username, email FROM users WHERE id = 1;
面板的“创建虚拟机”现在有独立的“公网云镜像”方式。先在宿主机设置中选择已工作的 Linux 网桥,例如 `bridge:br0`;打开创建弹窗的“导入新的云镜像模板”,填写 [AlmaLinux 10 官方 Generic Cloud qcow2 镜像](https://wiki.almalinux.org/cloud/Generic-cloud)在 `https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/` 下的下载地址、发布方 SHA-256 和模板显示名。地址必须是官方 HTTPS 直链,面板不会跟随重定向。面板服务器 A 需要能访问该地址。导入在后台运行,一次只允许一个任务,面板下载、校验 SHA-256 后通过当前 libvirt SSH 连接把模板镜像上传到 B 的磁盘池;无需登录 B 手工复制。模板目录记录加密保存在 MariaDB,绑定当前宿主机身份和磁盘池。不要在导入期间关闭面板进程;若进程异常退出,运行中的导入任务记录不会恢复,可能需要检查项目 `data/` 中的 `.cloud-image-*` 临时文件和 B 磁盘池中 `panel-template-*` 卷,不要未经核对就删除。
选择模板后,填写 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` 本身不能保证公网可达。
选择模板后填写 VM 资源和 root 登录方式。如果宿主机已配置公网 `/24` 地址池,创建时会自动选择一个尚未使用的地址,并沿用宿主机设置的网关和 DNS;用户不能在创建请求中另填 IP、网关或 DNS 来绕过地址池。面板会跳过网络地址、广播地址、网关、保留地址、宿主机自身的字面 IPv4,以及 libvirt 可见虚拟机元数据中的已用 IP,并防止面板并发创建分到相同地址。地址池用尽时创建会报错,不会复用仍占用的地址;面板删除 VM 后会释放其地址占用记录。旧宿主机若未配置地址池,仍可按原方式手填已分配给你的**具体公网 IPv4/CIDR**(如 `/24` 或 `/28`)、同网段网关和 1–4 个 DNS 地址。填写 OpenSSH **公钥**时,只能用对应私钥登录 `root@<公网IP>`,密码输入会隐藏;不填公钥时,可以设置 12–128 字符的初始 root 密码,可用它从 VNC 和 SSH 登录;公钥和密码都不填时,面板会自动生成强初始 root 密码。客体登录密钥与连接宿主机的 root 私钥是两套独立凭据。面板无法探测面板及 libvirt 元数据之外的设备是否占用地址,也无法替服务商分配或路由公网 IP;**不要把未由服务商分配或路由给你的整个 `/24` 填入地址池**。当前版本只支持网关与 VM IP 同一子网的桥接 IPv4;服务商给出 `/32` 或异网段网关时不要强填,需另做路由网络模式。上游网络还必须允许 VM 使用额外 MAC,`br0` 本身不能保证公网可达。
若 DNS 本身位于该 `/24` 中,它的地址也会自动跳过。面板创建成功后会保留 IP 占用记录,只有通过面板删除 VM 才自动释放;如果直接在宿主机或其他工具中删除 VM,旧占用记录会保守保留,避免误将该 IP 分给新 VM,需核查真实占用情况后再处理。
每个已登录用户都可导入并命名自己的**单行 OpenSSH 公钥**:已审核账号从侧栏“公钥管理”进入,等待审核的账号可用“管理我的公钥”入口。可以粘贴 `.pub` 文件内容,或在浏览器选择本地 `.pub` 文件填入表单;面板只接受公钥,不要选择或粘贴私钥。列表只显示当前账户导入的公钥;管理员账户也不能把另一个用户的公钥当作自己的预设公钥使用。创建公网云镜像 VM 时可以选择已导入的公钥,不必重复粘贴;也可以继续临时手动填写公钥,或选择初始 root 密码。预设公钥、手动公钥与密码不能同时使用。未通过管理员审核的用户可以管理自己的公钥,但仍不能创建虚拟机。删除公钥只删除面板中的预设记录,**不会撤销已经写入现有虚拟机的 SSH 授权密钥**;要撤销现有 VM 的访问权限,需在客体系统中删除对应的 `authorized_keys` 条目或重装并更换登录密钥。

@ -190,7 +190,7 @@ function stopPolling() {
}
function clearAdminContent() {
for (const id of ["smtp-host", "smtp-username", "smtp-password", "smtp-from-address", "host-address", "host-region", "host-storage-pool", "host-iso-pool", "host-network"]) byId(id).value = "";
for (const id of ["smtp-host", "smtp-username", "smtp-password", "smtp-from-address", "host-address", "host-region", "host-storage-pool", "host-iso-pool", "host-network", "host-public-pool-cidr", "host-public-gateway", "host-public-dns", "host-public-reserved"]) byId(id).value = "";
byId("smtp-port").value = 465;
byId("smtp-tls-mode").value = "ssl";
byId("smtp-status").hidden = true;
@ -390,6 +390,10 @@ function showHostView(hostConfig = { configured: false }) {
byId("host-storage-pool").value = configured ? (hostConfig.storage_pool || "default") : "default";
byId("host-iso-pool").value = configured ? (hostConfig.iso_pool || "iso") : "iso";
byId("host-network").value = configured ? (hostConfig.default_network || "default") : "default";
byId("host-public-pool-cidr").value = configured ? (hostConfig.public_pool_cidr || "") : "";
byId("host-public-gateway").value = configured ? (hostConfig.public_gateway || "") : "";
byId("host-public-dns").value = configured && Array.isArray(hostConfig.public_dns_servers) ? hostConfig.public_dns_servers.join(", ") : "";
byId("host-public-reserved").value = configured && Array.isArray(hostConfig.public_reserved_ips) ? hostConfig.public_reserved_ips.join("\n") : "";
text("host-key-required-mark", configured ? "" : "*");
text("host-key-hint", configured
? "留空则继续使用已保存的私钥;填写或选择文件会替换它。已保存私钥不会回显。"
@ -945,6 +949,27 @@ function hostPayload() {
if (!privateKey && !state.hostConfig?.private_key_configured) {
throw new Error("首次连接需要提供宿主机 root 账号已有的 SSH 私钥。");
}
const publicPoolCidr = byId("host-public-pool-cidr").value.trim();
const publicGateway = byId("host-public-gateway").value.trim();
const publicDnsServers = byId("host-public-dns").value.split(/[\s,;]+/).filter(Boolean);
const publicReservedIps = [...new Set(byId("host-public-reserved").value.split(/[\s,;]+/).filter(Boolean))];
if (!publicPoolCidr && (publicGateway || publicDnsServers.length || publicReservedIps.length)) {
throw new Error("填写公网网关、DNS 或保留地址时,必须先填写允许分配的 /24 网段;如需关闭地址池,请将这四项全部清空。");
}
if (publicPoolCidr) {
if (!validPublicPoolCidr(publicPoolCidr)) {
throw new Error("公网地址池必须是服务商实际分配给该宿主机的可路由 IPv4 /24 网段地址,不可填写单台主机 IP 或示例保留网段。");
}
if (!validPoolMember(publicGateway, publicPoolCidr)) {
throw new Error("公网地址池网关必须是该 /24 网段内有效的 IPv4 地址,且不能是网段或广播地址。");
}
if (publicDnsServers.length < 1 || publicDnsServers.length > 4 || !publicDnsServers.every((address) => ipv4Parts(address))) {
throw new Error("公网地址池需配置 1 至 4 个有效的 DNS IPv4 地址。");
}
if (!publicReservedIps.every((address) => validPoolMember(address, publicPoolCidr))) {
throw new Error("额外保留的 IP 必须是该 /24 网段内的有效主机地址,不能填写网段或广播地址。");
}
}
return {
host,
port,
@ -956,6 +981,10 @@ function hostPayload() {
storage_pool: byId("host-storage-pool").value.trim(),
iso_pool: byId("host-iso-pool").value.trim(),
default_network: byId("host-network").value.trim(),
public_pool_cidr: publicPoolCidr,
public_gateway: publicGateway,
public_dns_servers: publicDnsServers,
public_reserved_ips: publicReservedIps,
};
}
@ -1802,6 +1831,13 @@ function selectedCreateSource() {
return document.querySelector('input[name="source"]:checked')?.value || "iso";
}
function configuredPublicPool() {
if (state.resources && Object.prototype.hasOwnProperty.call(state.resources, "public_pool_cidr")) {
return String(state.resources.public_pool_cidr || "").trim();
}
return String(state.hostConfig?.public_pool_cidr || "").trim();
}
function updateCreateAuthMode() {
const cloud = selectedCreateSource() === "cloud";
const publicKey = byId("vm-guest-ssh-public-key");
@ -1819,11 +1855,18 @@ function updateCreateAuthMode() {
function updateCreateSource() {
const cloud = selectedCreateSource() === "cloud";
const publicPool = configuredPublicPool();
const automaticPublicIp = cloud && Boolean(publicPool);
byId("vm-iso-field").hidden = cloud;
byId("vm-template-field").hidden = !cloud;
byId("vm-cloud-fields").hidden = !cloud;
byId("create-iso-tip").hidden = cloud;
byId("create-cloud-tip").hidden = !cloud;
byId("vm-auto-public-pool").hidden = !automaticPublicIp;
text("vm-auto-public-pool-description", publicPool
? `创建时将从 ${publicPool} 中选择未使用的公网 IP,并自动配置宿主机保存的网关和 DNS。`
: "创建时将从宿主机地址池中选择未使用的 IP,并自动写入网关和 DNS。");
byId("vm-manual-public-network").hidden = automaticPublicIp;
const iso = byId("vm-iso");
iso.required = !cloud;
@ -1835,8 +1878,8 @@ function updateCreateSource() {
savedKey.disabled = !cloud || savedKey.options.length <= 1;
["vm-public-ip-cidr", "vm-gateway", "vm-dns"].forEach((id) => {
const input = byId(id);
input.required = cloud;
input.disabled = !cloud;
input.required = cloud && !automaticPublicIp;
input.disabled = !cloud || automaticPublicIp;
});
const publicKey = byId("vm-guest-ssh-public-key");
publicKey.required = false;
@ -2406,7 +2449,7 @@ byId("host-back-button").addEventListener("click", () => {
});
byId("host-address").addEventListener("input", resetFingerprint);
byId("host-port").addEventListener("input", resetFingerprint);
for (const id of ["host-region", "host-storage-pool", "host-iso-pool", "host-network"]) {
for (const id of ["host-region", "host-storage-pool", "host-iso-pool", "host-network", "host-public-pool-cidr", "host-public-gateway", "host-public-dns", "host-public-reserved"]) {
byId(id).addEventListener("input", markHostTestStale);
}
byId("host-private-key").addEventListener("input", () => {
@ -2779,6 +2822,23 @@ function validPublicIpCidr(value) {
return true;
}
function validPublicPoolCidr(value) {
const match = /^([^/]+)\/24$/.exec(value);
const parts = match && ipv4Parts(match[1]);
if (!parts || parts[3] !== 0) return false;
if ((parts[0] === 192 && parts[1] === 0 && parts[2] === 2)
|| (parts[0] === 198 && parts[1] === 51 && parts[2] === 100)
|| (parts[0] === 203 && parts[1] === 0 && parts[2] === 113)) return false;
return validPublicIpCidr(`${parts[0]}.${parts[1]}.${parts[2]}.1/24`);
}
function validPoolMember(value, publicPoolCidr) {
const parts = ipv4Parts(value);
const network = ipv4Parts(publicPoolCidr.split("/")[0]);
return Boolean(parts && network && parts[0] === network[0] && parts[1] === network[1]
&& parts[2] === network[2] && parts[3] >= 1 && parts[3] <= 254);
}
function validGatewayForCidr(gateway, publicIpCidr) {
const gatewayParts = ipv4Parts(gateway);
const [ip, prefixText] = publicIpCidr.split("/");
@ -2816,9 +2876,12 @@ byId("create-form").addEventListener("submit", async (event) => {
if (source === "cloud") {
body.source = "cloud";
body.template_id = String(data.get("template_id") || "");
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);
const automaticPublicIp = Boolean(configuredPublicPool());
if (!automaticPublicIp) {
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);
}
const selectedKeyId = String(data.get("guest_ssh_key_id") || "");
if (selectedKeyId) {
const keyId = Number(selectedKeyId);
@ -2838,15 +2901,15 @@ byId("create-form").addEventListener("submit", async (event) => {
showError("create-error", "请先选择或导入云镜像模板。");
return;
}
if (!validPublicIpCidr(body.public_ip_cidr)) {
if (!automaticPublicIp && !validPublicIpCidr(body.public_ip_cidr)) {
showError("create-error", "请填写有效的公网 IPv4/CIDR,例如已分配给你的地址和 /24 或 /28 前缀;不能填写网段或广播地址。");
return;
}
if (!validGatewayForCidr(body.gateway, body.public_ip_cidr)) {
if (!automaticPublicIp && !validGatewayForCidr(body.gateway, body.public_ip_cidr)) {
showError("create-error", "请填写与虚拟机 IP 同网段的有效网关 IPv4,且不能与虚拟机 IP 相同。非同网段网关暂不支持。");
return;
}
if (!body.dns_servers.length || body.dns_servers.length > 4 || !body.dns_servers.every((address) => ipv4Parts(address))) {
if (!automaticPublicIp && (!body.dns_servers.length || body.dns_servers.length > 4 || !body.dns_servers.every((address) => ipv4Parts(address)))) {
showError("create-error", "请填写 1 至 4 个有效的 DNS IPv4 地址,用逗号或空格分隔。");
return;
}
@ -2875,11 +2938,12 @@ byId("create-form").addEventListener("submit", async (event) => {
setButtonBusy(button, true, "正在创建…");
try {
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 });
const createdVm = await api("/api/v1/vms", { method: "POST", body });
closeModal();
const createdIp = String(createdVm?.public_ip_cidr || "").split("/")[0];
toast(autoPassword
? `虚拟机 ${body.name} 创建成功。初始 root 密码可在虚拟机详情页查看。`
: `虚拟机 ${body.name} 创建成功。`, "success");
? `虚拟机 ${body.name} 创建成功${createdIp ? `,公网 IP:${createdIp}` : ""}。初始 root 密码可在虚拟机详情页查看。`
: `虚拟机 ${body.name} 创建成功${createdIp ? `,公网 IP:${createdIp}` : ""}。`, "success");
await loadVMs(true);
window.setTimeout(() => void loadVMs(true), 1200);
} catch (error) {

@ -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-keys-1" />
<script type="module" src="/static/app.js?v=ssh-keys-1"></script>
<link rel="stylesheet" href="/static/styles.css?v=public-ip-pool-1" />
<script type="module" src="/static/app.js?v=public-ip-pool-1"></script>
</head>
<body>
<div id="boot-screen" class="boot-screen" role="status" aria-live="polite">
@ -164,6 +164,15 @@
<div class="field"><label for="host-storage-pool">虚拟机磁盘目录或存储池名</label><input id="host-storage-pool" name="storage_pool" type="text" maxlength="4096" value="default" required autocomplete="off" placeholder="例如 /home/kvm 或 default" /><small>可直接填写宿主机上的绝对路径,如 /home/kvm;也兼容现有 libvirt 存储池名称。</small></div>
<div class="field"><label for="host-iso-pool">ISO 目录或存储池名</label><input id="host-iso-pool" name="iso_pool" type="text" maxlength="4096" value="iso" required autocomplete="off" placeholder="例如 /home/iso 或 iso" /><small>可直接填写宿主机上的绝对路径,如 /home/iso;不是面板服务器的路径。</small></div>
<div class="field"><label for="host-network">默认虚拟网络或网桥</label><input id="host-network" name="default_network" type="text" maxlength="128" value="default" required autocomplete="off" placeholder="例如 default 或 bridge:br0" /><small>libvirt 虚拟网络填名称;宿主机现有 Linux 网桥 br0 填 bridge:br0。</small></div>
<div class="host-public-pool full" role="group" aria-labelledby="host-public-pool-title">
<div class="host-public-pool-heading"><strong id="host-public-pool-title">公网 IPv4 地址池</strong><small>仅用于云镜像虚拟机;配置后创建时由面板从该 /24 网段自动分配未占用的地址。请先确认这些公网 IP 已分配给该宿主机,并由上游网络允许虚拟机使用。</small></div>
<div class="form-grid">
<div class="field"><label for="host-public-pool-cidr">允许分配的 /24 网段</label><input id="host-public-pool-cidr" name="public_pool_cidr" type="text" maxlength="18" inputmode="decimal" autocomplete="off" placeholder="填写服务商分配的公网网段/24" /><small>填写真实可路由的网段地址,不是某台虚拟机的 IP;留空则继续手动指定公网 IP。</small></div>
<div class="field"><label for="host-public-gateway">网关 IPv4</label><input id="host-public-gateway" name="public_gateway" type="text" maxlength="15" inputmode="decimal" autocomplete="off" placeholder="填写该 /24 网段内的网关" /><small>网关不会被分配给虚拟机。</small></div>
<div class="field full"><label for="host-public-dns">DNS IPv4</label><input id="host-public-dns" name="public_dns_servers" type="text" maxlength="128" autocomplete="off" placeholder="例如 1.1.1.1, 8.8.8.8" /><small>填写 1 至 4 个 DNS 地址,用逗号或空格分隔。</small></div>
<div class="field full"><label for="host-public-reserved">额外保留的公网 IP(可选)</label><textarea id="host-public-reserved" name="public_reserved_ips" rows="3" maxlength="4096" spellcheck="false" autocomplete="off" placeholder="已有其他用途的地址,每行一个;也可用逗号或空格分隔"></textarea><small>这些地址不会自动分配。请填写面板之外已占用的地址;若宿主机地址填的是域名,也请把宿主机自身的公网 IP 填在这里。</small></div>
</div>
</div>
<div class="field full"><label for="host-private-key">现有 SSH 私钥 <span id="host-key-required-mark">*</span></label><textarea id="host-private-key" name="private_key" rows="5" maxlength="65536" spellcheck="false" autocomplete="off" placeholder="粘贴 -----BEGIN OPENSSH PRIVATE KEY----- 开头的完整内容,或从下方选择文件"></textarea><small id="host-key-hint">仅通过 HTTPS 传输并保存在面板服务器。请确保这把密钥已在宿主机 root 账号上获得授权。</small></div>
<div class="field full"><label for="host-private-key-file">或从本机选择私钥文件</label><input id="host-private-key-file" type="file" /><small id="host-key-file-label">未选择文件;已保存的密钥不会在这里显示。</small></div>
<div class="field full"><label for="host-private-key-passphrase">SSH 私钥口令(如果设置了)</label><input id="host-private-key-passphrase" name="private_key_passphrase" type="password" maxlength="1024" autocomplete="off" spellcheck="false" placeholder="输入用于解锁私钥的口令" /><small id="host-passphrase-hint">保存时会加密写入面板数据库,供重启后自动连接和后台持续采样;面板不会回显口令或写入浏览器存储。</small></div>
@ -362,7 +371,7 @@
<div class="modal-header"><div><span class="eyebrow">NEW VIRTUAL MACHINE</span><h2 id="create-title">创建虚拟机</h2><p>选择 ISO 安装,或从云镜像模板直接创建系统。</p></div><button class="icon-button" type="button" data-close-modal aria-label="关闭">×</button></div>
<form id="create-form">
<div class="modal-body">
<fieldset class="create-source-picker"><legend>系统来源</legend><label><input type="radio" name="source" value="iso" checked /><span><strong>ISO 安装</strong><small>通过 VNC 安装系统</small></span></label><label><input type="radio" name="source" value="cloud" /><span><strong>公网云镜像</strong><small>设置静态 IP 后直接开机</small></span></label></fieldset>
<fieldset class="create-source-picker"><legend>系统来源</legend><label><input type="radio" name="source" value="iso" checked /><span><strong>ISO 安装</strong><small>通过 VNC 安装系统</small></span></label><label><input type="radio" name="source" value="cloud" /><span><strong>公网云镜像</strong><small>自动或手动配置公网 IP 后直接开机</small></span></label></fieldset>
<div class="form-grid">
<div class="field full"><label for="vm-name">名称 <span>*</span></label><input id="vm-name" name="name" type="text" required minlength="1" maxlength="63" pattern="[a-zA-Z0-9][a-zA-Z0-9._-]*" autocomplete="off" placeholder="例如 web-prod-01" /><small>使用英文字母、数字、点、下划线或连字符。</small></div>
<div class="field"><label for="vm-vcpu">vCPU <span>*</span></label><div class="input-suffix"><input id="vm-vcpu" name="vcpu" type="number" min="1" max="64" value="2" required /><span>核</span></div></div>
@ -379,11 +388,14 @@
</div></details>
</div>
<div class="cloud-fields full" id="vm-cloud-fields" hidden>
<div class="cloud-fields-heading"><strong>公网网络配置</strong><small>仅支持已配置的 Linux 网桥,例如 bridge:br0。IP 必须已分配给你,网关必须在同一网段,上游网络还需允许虚拟机的 MAC 地址。</small></div>
<div class="form-grid">
<div class="cloud-fields-heading"><strong>公网网络配置</strong><small>仅支持已配置的 Linux 网桥,例如 bridge:br0;上游网络还需允许虚拟机的 MAC 地址。</small></div>
<div id="vm-auto-public-pool" class="vm-auto-public-pool" role="status" hidden><strong>自动分配公网 IP</strong><span id="vm-auto-public-pool-description">创建时将从宿主机地址池中选择未使用的 IP,并自动写入网关和 DNS。</span></div>
<div class="form-grid" id="vm-manual-public-network">
<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>
<div class="form-grid vm-cloud-auth-fields">
<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>

@ -68,6 +68,7 @@ input:focus,select:focus,button:focus-visible{outline:3px solid rgba(18,166,176,
.host-content{max-width:1380px;padding:39px clamp(22px,5vw,76px) 70px;margin:0 auto}.host-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:20px;margin-bottom:29px}.host-heading h1{font-size:29px;letter-spacing:-.6px;margin:8px 0}.host-heading p{color:#8090a0;font-size:13px;line-height:1.6;margin:0}
.host-columns{display:grid;grid-template-columns:minmax(0,1.25fr) minmax(350px,.85fr);gap:19px;align-items:start}.host-side-stack{display:grid;gap:19px}.host-card{background:#fff;border:1px solid #e6edf2;border-radius:13px;padding:26px;box-shadow:0 10px 30px rgba(19,42,65,.027)}.host-card-heading{display:flex;gap:12px;align-items:flex-start;margin-bottom:24px}.host-card-number{display:flex;align-items:center;justify-content:center;flex:none;width:31px;height:31px;background:#e7f8f8;color:#0e919b;border-radius:9px;font-size:13px;font-weight:800}.host-card-heading h2{font-size:17px;margin:2px 0 5px;letter-spacing:-.2px}.host-card-heading p{font-size:11px;color:#91a1b0;margin:0;line-height:1.6}
.host-card textarea{width:100%;min-height:125px;padding:12px 13px;border:1px solid #dce4eb;border-radius:9px;color:#15243a;font:11px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;resize:vertical;background:#fff}.host-card textarea:focus{border-color:#35b9c0;box-shadow:0 0 0 4px rgba(25,179,187,.1);outline:none}.host-card input[type=file]{height:auto;min-height:43px;padding:9px;font-size:11px}.host-card input[type=file]::file-selector-button{border:0;border-radius:6px;padding:5px 10px;margin-right:9px;background:#e9f6f6;color:#137e89;font-weight:700;cursor:pointer}
.host-public-pool{grid-column:1/-1;border-top:1px solid #e8eef2;padding-top:18px}.host-public-pool-heading{margin-bottom:16px}.host-public-pool-heading strong{display:block;color:#34445a;font-size:13px}.host-public-pool-heading small{display:block;margin-top:6px;color:#8798a7;font-size:10px;line-height:1.6}.host-public-pool textarea{min-height:78px}
.fingerprint-result{margin:18px 0 14px;padding:14px;border:1px solid #b9e6e5;background:#effafa;border-radius:9px}.fingerprint-result>span{display:block;color:#417c85;font-size:11px;font-weight:700;margin-bottom:8px}.fingerprint-result code{display:block;color:#1b5260;font-size:12px;font-weight:800;line-height:1.7;overflow-wrap:anywhere}.host-security-note{font-size:11px;color:#8191a1;line-height:1.75;margin:16px 0 0}.host-security-note code{color:#41566e;font-size:10px;overflow-wrap:anywhere}.host-confirm{margin-top:17px;background:#f0fbf8;border-color:#cce9e0}.host-confirm strong{color:#217d6e}.host-confirm small{color:#659a90}
.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}
@ -141,6 +142,7 @@ tbody tr:hover{background:#fcfefe}
.create-source-picker{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;border:0;padding:0;margin:0 0 23px;min-width:0}.create-source-picker legend{color:#34445a;font-size:13px;font-weight:700;padding:0;margin-bottom:10px}.create-source-picker label{position:relative;display:block;cursor:pointer}.create-source-picker input{position:absolute;opacity:0;width:1px;height:1px}.create-source-picker label span{display:block;border:1px solid #dce4eb;border-radius:9px;padding:12px 14px;min-height:65px;background:#fff}.create-source-picker input:checked+span{border-color:#3bb5bc;background:#effafa;box-shadow:0 0 0 2px rgba(20,166,175,.08)}.create-source-picker input:focus-visible+span{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}.create-source-picker strong{display:block;color:#334a5f;font-size:12px}.create-source-picker small{display:block;color:#8999a8;font-size:10px;margin-top:5px}
.template-import{border:1px solid #e0e9ee;border-radius:9px;margin-top:12px;background:#fbfdfd}.template-import summary{cursor:pointer;padding:11px 13px;color:#148c98;font-size:11px;font-weight:700}.template-import-fields{display:grid;gap:13px;padding:2px 13px 14px}.template-import-fields .field input{height:42px}.template-import-fields .form-error{margin:0}.template-import-fields .button{justify-self:start}.template-import-status{margin:0;color:#317c85;font-size:11px;line-height:1.6}
.cloud-fields{grid-column:1/-1;border-top:1px solid #e7edf2;padding-top:18px}.cloud-fields-heading{margin-bottom:17px}.cloud-fields-heading strong{display:block;color:#34445a;font-size:13px}.cloud-fields-heading small{display:block;color:#8798a7;font-size:10px;line-height:1.6;margin-top:6px}.cloud-fields textarea{width:100%;min-height:79px;padding:11px 13px;border:1px solid #dce4eb;border-radius:9px;color:#15243a;font:11px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;resize:vertical;background:#fff}.cloud-fields textarea:focus{border-color:#35b9c0;box-shadow:0 0 0 4px rgba(25,179,187,.1);outline:none}
.vm-auto-public-pool{display:grid;gap:5px;margin:0 0 18px;padding:13px 15px;border:1px solid #cce9e0;border-radius:9px;background:#f0fbf8}.vm-auto-public-pool strong{font-size:12px;color:#217d6e}.vm-auto-public-pool span{font-size:11px;line-height:1.6;color:#5b837a}.vm-cloud-auth-fields{margin-top:18px}
.input-suffix{position:relative}.input-suffix input{padding-right:48px}.input-suffix span{position:absolute;right:13px;top:13px;color:#97a4b2;font-size:12px}
.form-tip{display:flex;gap:10px;background:#f1f9fa;border:1px solid #e1f2f3;border-radius:9px;padding:12px 14px;color:#318b96;margin-top:22px}.form-tip>span{font-size:16px;line-height:1}.form-tip p{font-size:11px;line-height:1.55;margin:0}.modal-body>.form-error{margin:18px 0 0}
.delete-copy{font-size:13px;color:#647388;line-height:1.8;margin:0 0 19px}.delete-copy strong{color:#263c54;overflow-wrap:anywhere}.danger-text{color:#d64753}
@ -164,6 +166,7 @@ tbody tr:hover{background:#fcfefe}
@media(max-width:510px){.topbar{padding:0 17px}.content{padding:25px 14px}.page-heading{padding:0 3px}.overview-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.stat-card{padding:13px 11px;min-height:112px}.stat-card>strong{font-size:23px}.stat-icon{display:none}.topbar-right{gap:4px}.topbar-user{font-size:11px}.breadcrumb{font-size:11px}.modal-backdrop{padding:10px}.modal-header,.modal-body{padding-left:19px;padding-right:19px}.modal-footer{padding:14px 19px}.form-grid{gap:15px 10px}.console-backdrop{padding:0}.console-modal{height:100vh;max-height:100vh;border-radius:0}.console-stage{flex:1;height:auto}.console-tools .button{display:none}.console-password{flex-wrap:wrap}.console-password input{flex:1;min-width:130px}}
@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){.host-public-pool>.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)}}

@ -35,7 +35,7 @@ from virsh_panel.config import Settings # noqa: E402
from virsh_panel.libvirt_service import VMError # noqa: E402
from virsh_panel.metrics import host_scope, query_interval_seconds # noqa: E402
from virsh_panel.panel_state import PanelState # noqa: E402
from virsh_panel.remote_host import RemoteHostError # noqa: E402
from virsh_panel.remote_host import RemoteHostError, validate_public_pool # noqa: E402
PASSWORD = "correct-horse-battery-staple"
@ -82,6 +82,7 @@ class FakeVMService:
"uuid": VM_ID, "name": "alma-test", "state": "running", "vcpu": 2,
"memory_mib": 2048, "disks": [], "autostart": False,
}
self.other_vms: list[dict] = []
def resources(self):
self.calls.append(("resources",))
@ -98,7 +99,7 @@ class FakeVMService:
self.calls.append(("list_vms",))
if self.list_error:
raise VMError("libvirt API 不可用", 502)
return [self.vm]
return [self.vm, *self.other_vms]
def get_vm(self, vm_id):
self.calls.append(("get_vm", vm_id))
@ -112,6 +113,8 @@ class FakeVMService:
def create_cloud_vm(self, spec, template_volume_name):
self.calls.append(("create_cloud_vm", spec, template_volume_name))
if self.vm.get("os_source") == "cloud_template":
self.other_vms.append(self.vm.copy())
self.vm = {
**self.vm, "uuid": spec["vm_uuid"], "name": spec["name"],
"managed": True, "os_source": "cloud_template",
@ -168,6 +171,10 @@ class FakeRemoteManager:
"fingerprint": "SHA256:example", "known_hosts_line": HOST_BODY["host_key"]}
def stage(self, profile, confirmed_fingerprint):
validate_public_pool(
profile.public_pool_cidr, profile.public_gateway,
profile.public_dns_servers, profile.public_reserved_ips, profile.host,
)
self.calls.append(("stage", profile.host, profile.port, confirmed_fingerprint))
self.staged_profiles.append(profile)
return SimpleNamespace(
@ -195,6 +202,10 @@ class FakeRemoteManager:
"iso_pool": staged.profile.iso_pool,
"default_network": staged.profile.default_network,
"region": staged.profile.region,
"public_pool_cidr": getattr(staged.profile, "public_pool_cidr", ""),
"public_gateway": getattr(staged.profile, "public_gateway", ""),
"public_dns_servers": list(getattr(staged.profile, "public_dns_servers", [])),
"public_reserved_ips": list(getattr(staged.profile, "public_reserved_ips", [])),
"libvirt_uri": "qemu+ssh://root@vp-managed/system?no_tty=1&command=/fake/ssh-wrapper",
"ssh_target": "vp-managed", "ssh_config_file": "/fake/config",
"ssh_known_hosts_file": "/fake/known_hosts",
@ -432,6 +443,43 @@ def test_host_region_is_returned_with_host_and_vms(web):
headers=headers).status_code == 422
def test_host_public_pool_round_trips_and_rejects_invalid_networks(web):
client, _, token, _service, manager, _ = web
csrf = setup_admin(client, token)
headers = {"X-CSRF-Token": csrf}
body = {
**HOST_BODY,
"host": "8.8.8.3",
"default_network": "bridge:br0",
"public_pool_cidr": "8.8.8.0/24",
"public_gateway": "8.8.8.1",
"public_dns_servers": ["1.1.1.1", "8.8.4.4"],
"public_reserved_ips": ["8.8.8.2", "8.8.8.5"],
}
tested = client.post("/api/v1/host/test", json=body, headers=headers)
assert tested.status_code == 200
saved = client.put("/api/v1/host", json=body, headers=headers)
assert saved.status_code == 200
current = client.get("/api/v1/host")
assert current.status_code == 200
for key in ("public_pool_cidr", "public_gateway", "public_dns_servers",
"public_reserved_ips"):
assert getattr(manager.staged_profiles[0], key) == body[key]
assert saved.json()[key] == current.json()[key] == body[key]
assert manager.current()[key] == body[key]
for changes in (
{"public_pool_cidr": "8.8.8.0/25"},
{"public_pool_cidr": "10.0.0.0/24", "public_gateway": "10.0.0.1"},
{"public_gateway": "9.9.9.1"},
{"public_dns_servers": ["invalid-dns"]},
{"public_reserved_ips": ["9.9.9.2"]},
):
rejected = client.put("/api/v1/host", json={**body, **changes}, headers=headers)
assert rejected.status_code in (400, 422)
assert manager.current()["public_pool_cidr"] == body["public_pool_cidr"]
def test_private_key_passphrase_reaches_host_profile_but_is_never_echoed(web):
client, _, token, _, manager, _ = web
csrf = setup_admin(client, token)

@ -199,6 +199,9 @@ def test_remote_host_is_rebuilt_from_database_without_durable_private_key(tmp_pa
host="host.example", port=22, private_key=PRIVATE_KEY,
host_key=scan["known_hosts_line"], storage_pool="/home/kvm",
iso_pool="/home/iso", default_network="bridge:br0", region="东京",
public_pool_cidr="1.2.3.0/24", public_gateway="1.2.3.1",
public_dns_servers=["1.1.1.1", "8.8.8.8"],
public_reserved_ips=["1.2.3.10"],
)
staged = first.stage(profile, scan["fingerprint"])
assert first.test(staged)["libvirt"] == "available"
@ -216,6 +219,10 @@ def test_remote_host_is_rebuilt_from_database_without_durable_private_key(tmp_pa
assert second.current()["storage_pool"] == "/home/kvm"
assert second.current()["default_network"] == "bridge:br0"
assert second.current()["region"] == "东京"
assert second.current()["public_pool_cidr"] == "1.2.3.0/24"
assert second.current()["public_gateway"] == "1.2.3.1"
assert second.current()["public_dns_servers"] == ["1.1.1.1", "8.8.8.8"]
assert second.current()["public_reserved_ips"] == ["1.2.3.10"]
assert (second._current_generation() / "id_private").read_text() == PRIVATE_KEY
assert not list(data_dir.rglob("id_private"))
second.close()
@ -223,11 +230,16 @@ def test_remote_host_is_rebuilt_from_database_without_durable_private_key(tmp_pa
legacy = json.loads(store.records[("host", "current")])
legacy["metadata"].pop("region")
for key in ("public_pool_cidr", "public_gateway", "public_dns_servers", "public_reserved_ips"):
legacy["metadata"].pop(key)
store.records[("host", "current")] = json.dumps(legacy)
third = DatabaseRemoteHostManager(
store, data_dir, runtime_parent=runtime_parent, runner=_fake_ssh,
)
assert third.current()["region"] == ""
assert third.current()["public_pool_cidr"] == ""
assert third.current()["public_gateway"] == ""
assert third.current()["public_dns_servers"] == []
third.close()

@ -0,0 +1,75 @@
"""Validation of a host's public IPv4 allocation range."""
from __future__ import annotations
import pytest
from virsh_panel.remote_host import RemoteHostError, validate_public_pool
_DEFAULT = object()
def validate(cidr="1.2.3.0/24", gateway="1.2.3.1", dns=_DEFAULT, reserved=_DEFAULT):
return validate_public_pool(
cidr,
gateway,
["1.1.1.1", "8.8.8.8"] if dns is _DEFAULT else dns,
[] if reserved is _DEFAULT else reserved,
"1.2.3.2",
)
def test_unconfigured_public_pool_has_empty_defaults():
assert validate_public_pool("", "", [], [], "host.example") == {
"public_pool_cidr": "",
"public_gateway": "",
"public_dns_servers": [],
"public_reserved_ips": [],
}
def test_public_pool_normalizes_and_deduplicates_addresses():
assert validate(
dns=["1.1.1.1", "1.1.1.1", "8.8.8.8"],
reserved=["1.2.3.10", "1.2.3.10", "1.2.3.20"],
) == {
"public_pool_cidr": "1.2.3.0/24",
"public_gateway": "1.2.3.1",
"public_dns_servers": ["1.1.1.1", "8.8.8.8"],
"public_reserved_ips": ["1.2.3.10", "1.2.3.20"],
}
@pytest.mark.parametrize(
("cidr", "gateway", "dns", "reserved"),
[
("1.2.3.0/24", "", ["1.1.1.1"], []),
("", "1.2.3.1", ["1.1.1.1"], []),
("1.2.3.0/24", "1.2.3.1", [], []),
("", "", [], ["1.2.3.10"]),
("1.2.3.1/24", "1.2.3.1", ["1.1.1.1"], []),
("1.2.3.0/25", "1.2.3.1", ["1.1.1.1"], []),
("10.0.0.0/24", "10.0.0.1", ["1.1.1.1"], []),
("203.0.113.0/24", "203.0.113.1", ["1.1.1.1"], []),
("2001:db8::/24", "2001:db8::1", ["1.1.1.1"], []),
("1.2.3.0/24", "1.2.4.1", ["1.1.1.1"], []),
("1.2.3.0/24", "1.2.3.0", ["1.1.1.1"], []),
("1.2.3.0/24", "1.2.3.255", ["1.1.1.1"], []),
("1.2.3.0/24", "1.2.3.1", ["10.0.0.1"], []),
("1.2.3.0/24", "1.2.3.1",
["1.1.1.1", "8.8.8.8", "9.9.9.9", "208.67.222.222", "208.67.220.220"], []),
("1.2.3.0/24", "1.2.3.1", ["1.1.1.1"], ["1.2.4.2"]),
("1.2.3.0/24", "1.2.3.1", ["1.1.1.1"], ["1.2.3.0"]),
("1.2.3.0/24", "1.2.3.1", ["1.1.1.1"], ["1.2.3.255"]),
],
)
def test_public_pool_rejects_invalid_configuration(cidr, gateway, dns, reserved):
with pytest.raises(RemoteHostError):
validate(cidr, gateway, dns, reserved)
@pytest.mark.parametrize("value", [None, "1.1.1.1", ["1.1.1.1", None]])
def test_dns_must_be_list_of_ip_strings(value):
with pytest.raises(RemoteHostError):
validate(dns=value)

@ -3,6 +3,7 @@
from __future__ import annotations
import asyncio
import ipaddress
import json
import sys
import types
@ -120,10 +121,14 @@ class _Service:
vm.update({
"managed": True,
"os_source": "cloud_template",
"public_ip_cidr": spec["public_ip_cidr"],
"credential_generation": f"panel-seed-{vm['uuid']}.iso",
})
return vm
def resources(self):
return {"networks": ["bridge:br0"], "isos": [], "storage_pool": "/home/kvm"}
def list_vms(self):
return list(self.vms.values())
@ -533,6 +538,17 @@ def test_per_user_ssh_key_library_and_cloud_vm_selection(monkeypatch, tmp_path):
}, headers=first_headers)
assert manual.status_code == 201
assert service.cloud_specs[-1][0]["guest_ssh_public_key"] == GUEST_PUBLIC_KEY
manual_claim = f"{host_scope(_Manager.profile)}.8.8.8.19"
assert store.get("ip_claim", manual_claim) is not None
duplicate_manual = first.post("/api/v1/vms", json={
**CLOUD_VM, "name": "duplicate-manual-ip",
"public_ip_cidr": "8.8.8.19/24",
"guest_ssh_public_key": GUEST_PUBLIC_KEY,
}, headers=first_headers)
assert duplicate_manual.status_code == 409
assert first.delete(f"/api/v1/vms/{manual.json()['uuid']}",
headers=first_headers).status_code == 200
assert store.get("ip_claim", manual_claim) is None
password = first.post("/api/v1/vms", json={
**CLOUD_VM, "name": "password-vm",
"public_ip_cidr": "8.8.8.20/24",
@ -552,3 +568,174 @@ def test_per_user_ssh_key_library_and_cloud_vm_selection(monkeypatch, tmp_path):
"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
def test_host_public_pool_allocates_globally_and_preserves_tenant_isolation(
monkeypatch, tmp_path,
):
store = MemoryStore()
service = _Service()
manager = _Manager()
manager.profile = {
**_Manager.profile,
"host": "8.8.8.3",
"public_pool_cidr": "8.8.8.0/24",
"public_gateway": "8.8.8.1",
"public_dns_servers": ["1.1.1.1", "8.8.4.4"],
"public_reserved_ips": ["8.8.8.2", "8.8.8.5"],
}
# An existing, panel-visible libvirt guest already occupies one address.
service.vms["00000000-0000-4000-8000-000000000004"] = {
"uuid": "00000000-0000-4000-8000-000000000004",
"name": "existing-vm", "state": "running", "vcpu": 1,
"memory_mib": 1024, "disks": [], "autostart": True,
"public_ip_cidr": "8.8.8.4/24",
}
monkeypatch.setattr(app_module, "make_components", lambda directory, *_: (
DatabasePanelState(directory, store, store.users), manager,
DatabaseTemplateStore(store), store,
))
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()
automatic_body = {
key: value for key, value in CLOUD_VM.items()
if key not in {"public_ip_cidr", "gateway", "dns_servers"}
}
automatic_body["guest_ssh_public_key"] = GUEST_PUBLIC_KEY
network = ipaddress.ip_network(manager.profile["public_pool_cidr"])
excluded = {"8.8.8.0", "8.8.8.1", "8.8.8.2", "8.8.8.3",
"8.8.8.4", "8.8.8.5", "8.8.8.6", "8.8.8.255"}
with TestClient(app, base_url=ORIGIN) as admin:
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": "operator", "password": PASSWORD,
})
assert initial.status_code == 200
admin_headers = {"X-CSRF-Token": initial.json()["csrf_token"]}
store.users.promote("operator")
DatabaseTemplateStore(store).add(template_scope(manager.profile), {
"id": "alma10-template", "name": "AlmaLinux 10",
"volume_name": "panel-template-alma10.qcow2",
})
# A claim from another panel worker remains occupied even when its VM
# is not yet visible through libvirt's list API.
pool_scope = host_scope(manager.profile)
assert store.insert("ip_claim", f"{pool_scope}.8.8.8.6", json.dumps({
"vm_uuid": "00000000-0000-4000-8000-000000000006",
}))
for username in ("tenantone", "tenanttwo"):
email = f"{username}@example.test"
store.users.issue_registration_code(email, "123456")
account = store.users.register_with_code(username, email, PASSWORD, "123456")
assert admin.post(f"/api/v1/users/{account['id']}/approve",
headers=admin_headers).status_code == 200
with TestClient(app, base_url=ORIGIN) as first, \
TestClient(app, base_url=ORIGIN) as second:
first_headers = _login(first, "tenantone@example.test")
second_headers = _login(second, "tenanttwo@example.test")
resources = first.get("/api/v1/resources")
assert resources.status_code == 200
assert resources.json()["public_pool_enabled"] is True
assert resources.json()["public_pool_cidr"] == "8.8.8.0/24"
assert first.get("/api/v1/host").status_code == 403
# Explicit client-side networking cannot bypass the host pool.
for field, value in (
("public_ip_cidr", "8.8.8.99/24"),
("gateway", "8.8.8.1"),
("dns_servers", ["1.1.1.1"]),
):
rejected = first.post("/api/v1/vms", json={
**automatic_body, field: value,
}, headers=first_headers)
assert rejected.status_code == 422
assert service.cloud_specs == []
first_created = first.post("/api/v1/vms", json=automatic_body,
headers=first_headers)
second_created = second.post("/api/v1/vms", json={
**automatic_body, "name": "tenant-two-cloud",
}, headers=second_headers)
assert first_created.status_code == second_created.status_code == 201
first_ip = service.cloud_specs[0][0]["public_ip_cidr"]
second_ip = service.cloud_specs[1][0]["public_ip_cidr"]
for ip_cidr in (first_ip, second_ip):
interface = ipaddress.ip_interface(ip_cidr)
assert interface.network == network
assert str(interface.ip) not in excluded
assert first_ip != second_ip
for spec, _volume in service.cloud_specs:
assert spec["gateway"] == "8.8.8.1"
assert spec["dns_servers"] == ["1.1.1.1", "8.8.4.4"]
first_id = first_created.json()["uuid"]
second_id = second_created.json()["uuid"]
assert first.get(f"/api/v1/vms/{second_id}").status_code == 404
assert second.get(f"/api/v1/vms/{first_id}").status_code == 404
# Every usable address is occupied in libvirt metadata: no IP may
# be reused even after the allocator has exhausted the /24 pool.
for address in network.hosts():
ip = str(address)
if ip not in excluded and ip not in {first_ip.split("/")[0],
second_ip.split("/")[0]}:
service.vms[f"used-{ip}"] = {"uuid": f"used-{ip}",
"public_ip_cidr": f"{ip}/24"}
exhausted = first.post("/api/v1/vms", json={
**automatic_body, "name": "no-ip-left",
}, headers=first_headers)
assert exhausted.status_code == 409
assert len(service.cloud_specs) == 2
first_claim = f"{pool_scope}.{first_ip.split('/')[0]}"
assert store.get("ip_claim", first_claim) is not None
deleted = first.delete(f"/api/v1/vms/{first_id}", headers=first_headers)
assert deleted.status_code == 200
assert store.get("ip_claim", first_claim) is None
replacement = first.post("/api/v1/vms", json={
**automatic_body, "name": "freed-ip-reused",
}, headers=first_headers)
assert replacement.status_code == 201
assert service.cloud_specs[-1][0]["public_ip_cidr"] == first_ip
# With exactly one free address, a clearly rolled-back libvirt
# failure must release the temporary claim for the next attempt.
del service.vms["used-8.8.8.250"]
free_claim = f"{pool_scope}.8.8.8.250"
original_create = service.create_cloud_vm
def rolled_back(_spec, _volume):
raise VMError("模拟创建失败,回滚已完成", 502)
monkeypatch.setattr(service, "create_cloud_vm", rolled_back)
failed = first.post("/api/v1/vms", json={
**automatic_body, "name": "rolled-back-vm",
}, headers=first_headers)
assert failed.status_code == 502
assert store.get("ip_claim", free_claim) is None
# If libvirt reports incomplete rollback, conservatively retain
# the address claim even though this fake exposes no resulting VM.
def incomplete_rollback(_spec, _volume):
raise VMError("模拟回滚不完整,请人工检查", 502)
monkeypatch.setattr(service, "create_cloud_vm", incomplete_rollback)
uncertain = first.post("/api/v1/vms", json={
**automatic_body, "name": "uncertain-vm",
}, headers=first_headers)
assert uncertain.status_code == 502
assert store.get("ip_claim", free_claim) is not None
monkeypatch.setattr(service, "create_cloud_vm", original_create)
still_exhausted = first.post("/api/v1/vms", json={
**automatic_body, "name": "uncertain-ip-protected",
}, headers=first_headers)
assert still_exhausted.status_code == 409

@ -10,6 +10,7 @@ import shutil
import stat
import struct
import subprocess
from dataclasses import replace
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
@ -100,6 +101,35 @@ def test_region_survives_host_save_and_legacy_metadata_defaults_empty(tmp_path):
assert manager.current()["region"] == ""
def test_public_pool_survives_host_save_and_legacy_metadata_defaults_empty(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
profile = replace(
make_profile(scanned),
public_pool_cidr="1.2.3.0/24",
public_gateway="1.2.3.1",
public_dns_servers=["1.1.1.1", "8.8.8.8"],
public_reserved_ips=["1.2.3.10", "1.2.3.10"],
)
staged = manager.stage(profile, scanned["fingerprint"])
assert staged.metadata["public_reserved_ips"] == ["1.2.3.10"]
manager.test(staged)
current = manager.commit(staged)
assert current["public_pool_cidr"] == "1.2.3.0/24"
assert current["public_gateway"] == "1.2.3.1"
assert current["public_dns_servers"] == ["1.1.1.1", "8.8.8.8"]
assert current["public_reserved_ips"] == ["1.2.3.10"]
metadata_path = staged.path / "profile.json"
legacy = json.loads(metadata_path.read_text(encoding="utf-8"))
for key in ("public_pool_cidr", "public_gateway", "public_dns_servers", "public_reserved_ips"):
legacy.pop(key)
metadata_path.write_text(json.dumps(legacy), encoding="utf-8")
assert manager.current()["public_pool_cidr"] == ""
assert manager.current()["public_dns_servers"] == []
assert manager.current()["public_reserved_ips"] == []
class FakeAgent:
sequence = itertools.count()

@ -139,6 +139,10 @@ class HostBody(HostScanBody):
default_network: str = Field(default="default", min_length=1, max_length=128)
region: str = Field(default="", max_length=64,
pattern=r"^[^\x00-\x1f\x7f]*$")
public_pool_cidr: str = Field(default="", max_length=18)
public_gateway: str = Field(default="", max_length=15)
public_dns_servers: list[str] = Field(default_factory=list, max_length=4)
public_reserved_ips: list[str] = Field(default_factory=list, max_length=254)
def profile(self) -> HostProfile:
return HostProfile(
@ -151,6 +155,10 @@ class HostBody(HostScanBody):
iso_pool=self.iso_pool,
default_network=self.default_network,
region=self.region,
public_pool_cidr=self.public_pool_cidr,
public_gateway=self.public_gateway,
public_dns_servers=self.public_dns_servers,
public_reserved_ips=self.public_reserved_ips,
)
@ -176,9 +184,9 @@ class CreateCloudBody(BaseModel):
disk_gib: int = Field(ge=1, le=4096)
network: str = Field(min_length=1, max_length=128)
template_id: str = Field(min_length=1, max_length=80)
public_ip_cidr: str = Field(min_length=3, max_length=64)
gateway: str = Field(min_length=7, max_length=64)
dns_servers: list[str] = Field(min_length=1, max_length=4)
public_ip_cidr: str = Field(default="", max_length=64)
gateway: str = Field(default="", max_length=64)
dns_servers: list[str] = Field(default_factory=list, 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
@ -222,8 +230,15 @@ def _public_host(profile: dict | None) -> dict:
"iso_pool", "default_network", "private_key_configured",
"private_key_encrypted", "key_locked", "private_key_passphrase_saved",
)
return {"configured": True, **{key: profile[key] for key in keys if key in profile},
"region": profile.get("region", "")}
return {
"configured": True,
**{key: profile[key] for key in keys if key in profile},
"region": profile.get("region", ""),
"public_pool_cidr": profile.get("public_pool_cidr", ""),
"public_gateway": profile.get("public_gateway", ""),
"public_dns_servers": profile.get("public_dns_servers", []),
"public_reserved_ips": profile.get("public_reserved_ips", []),
}
def _peer(request: Request) -> str:
@ -330,6 +345,125 @@ def create_app(
# nonce. The in-memory fallback is only for injected, database-free tests.
test_credentials: dict[str, str] = {}
def ip_claim_key(profile: dict, address: str) -> str:
return f"{host_scope(profile)}.{address}"
def insert_public_ip_claim(profile: dict, address: str, vm_id: str) -> bool:
if data_store is None:
return True
claim = json.dumps({"vm_uuid": vm_id, "reserved_at": int(time.time())},
separators=(",", ":"))
return data_store.insert("ip_claim", ip_claim_key(profile, address), claim)
def allocate_public_ip(profile: dict, service: VMService,
vm_id: str) -> str:
"""Choose and reserve a public IP, including across panel processes.
Claims remain after a successful create and are released on panel VM
deletion. A claim from an uncertain create is retained rather than
risking reuse of an address whose guest may still exist.
"""
try:
network = ipaddress.IPv4Network(profile["public_pool_cidr"], strict=True)
gateway = ipaddress.IPv4Address(profile["public_gateway"])
if (network.prefixlen != 24 or not network.network_address.is_global
or not network.broadcast_address.is_global
or gateway not in network
or gateway in (network.network_address, network.broadcast_address)):
raise ValueError("Invalid host public IPv4 pool")
blocked = {network.network_address, network.broadcast_address, gateway}
for value in (*profile.get("public_reserved_ips", []),
*profile.get("public_dns_servers", [])):
address = ipaddress.ip_address(value)
if isinstance(address, ipaddress.IPv4Address) and address in network:
blocked.add(address)
try:
host_address = ipaddress.ip_address(profile["host"])
except ValueError:
host_address = None
if isinstance(host_address, ipaddress.IPv4Address) and host_address in network:
blocked.add(host_address)
except (KeyError, TypeError, ValueError) as exc:
raise VMError("宿主机公网地址池配置损坏,请管理员重新保存设置", 500) from exc
# Include all libvirt-visible panel IPs, regardless of VM ownership.
# VMService also checks duplicates under its own create lock.
for existing_vm in service.list_vms():
configured = existing_vm.get("public_ip_cidr")
if isinstance(configured, str):
try:
address = ipaddress.IPv4Address(configured.split("/", 1)[0])
except ValueError:
continue
if address in network:
blocked.add(address)
scope_prefix = f"{host_scope(profile)}."
if data_store is not None:
for key in data_store.list("ip_claim"):
if key.startswith(scope_prefix):
try:
address = ipaddress.IPv4Address(key[len(scope_prefix):])
except ValueError:
continue
if address in network:
blocked.add(address)
for address in network.hosts():
if address in blocked:
continue
if not insert_public_ip_claim(profile, str(address), vm_id):
continue
return f"{address}/{network.prefixlen}"
raise VMError("公网 /24 地址池中没有可分配的 IP,请检查已用和保留地址", 409)
def claim_explicit_public_ip(profile: dict, public_ip_cidr: str,
vm_id: str) -> None:
if data_store is None:
return
try:
address = str(ipaddress.IPv4Interface(public_ip_cidr).ip)
except (TypeError, ValueError):
# The libvirt create path returns the detailed input error.
return
if not insert_public_ip_claim(profile, address, vm_id):
raise VMError("该公网 IP 已被面板中的虚拟机或创建任务占用", 409)
def release_public_ip_claim(profile: dict, public_ip_cidr: str,
vm_id: str) -> None:
if data_store is None:
return
try:
address = str(ipaddress.IPv4Interface(public_ip_cidr).ip)
key = ip_claim_key(profile, address)
except (TypeError, ValueError, KeyError):
return
raw = data_store.get("ip_claim", key)
if raw is None:
return
try:
claim = json.loads(raw)
except (TypeError, ValueError):
LOG.error("Could not parse public IP claim for %s", key)
return
if isinstance(claim, dict) and claim.get("vm_uuid") == vm_id:
data_store.delete("ip_claim", key)
def release_vm_public_ip_claims(profile: dict, vm_id: str) -> None:
if data_store is None:
return
prefix = f"{host_scope(profile)}."
for key, raw in data_store.list("ip_claim").items():
if not key.startswith(prefix):
continue
try:
claim = json.loads(raw)
except (TypeError, ValueError):
LOG.error("Could not parse public IP claim for %s", key)
continue
if isinstance(claim, dict) and claim.get("vm_uuid") == vm_id:
data_store.delete("ip_claim", key)
def credential_key(profile: dict, vm_id: str) -> str:
try:
canonical_id = str(uuid.UUID(vm_id))
@ -1125,7 +1259,12 @@ def create_app(
@app.get("/api/v1/resources")
def resources(_session: Session = Depends(require_approved)):
return current_service().resources()
profile = current_profile()
return {
**new_service(profile).resources(),
"public_pool_cidr": profile.get("public_pool_cidr", ""),
"public_pool_enabled": bool(profile.get("public_pool_cidr")),
}
@app.get("/api/v1/vm-templates")
def list_templates(_session: Session = Depends(require_approved)):
@ -1321,6 +1460,19 @@ def create_app(
password_hash = hash_root_password(root_password)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
auto_public_ip = bool(profile.get("public_pool_cidr"))
if auto_public_ip and (body.public_ip_cidr or body.gateway or body.dns_servers):
raise HTTPException(
status_code=422,
detail="宿主机已配置公网地址池,创建时不能手动指定 IP、网关或 DNS",
)
if not auto_public_ip and not (
body.public_ip_cidr and body.gateway and body.dns_servers
):
raise HTTPException(
status_code=422,
detail="宿主机尚未配置公网地址池,请手动填写 IP、网关和 DNS",
)
record = templates.get(template_scope(profile), body.template_id)
spec = body.model_dump(exclude={
"source", "template_id", "root_password", "guest_ssh_key_id",
@ -1331,14 +1483,28 @@ def create_app(
spec["root_password_hash"] = password_hash
requested_uuid = str(uuid.uuid4())
spec["vm_uuid"] = requested_uuid
if owner_id is not None:
state.users.assign_vm(host_scope(profile), requested_uuid, owner_id)
service = new_service(profile)
allocated_ip = ""
owner_assigned = False
try:
if auto_public_ip:
allocated_ip = allocate_public_ip(
profile, service, requested_uuid,
)
spec["public_ip_cidr"] = allocated_ip
spec["gateway"] = profile["public_gateway"]
spec["dns_servers"] = list(profile["public_dns_servers"])
else:
claim_explicit_public_ip(profile, body.public_ip_cidr, requested_uuid)
allocated_ip = body.public_ip_cidr
if owner_id is not None:
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",
f"panel-seed-{requested_uuid}.iso",
root_password or None)
vm = new_service(profile).create_cloud_vm(spec, record["volume_name"])
vm = service.create_cloud_vm(spec, record["volume_name"])
except Exception as exc:
# An incomplete libvirt rollback may have left the guest
# behind. Keep its credential in that exceptional case so
@ -1350,8 +1516,16 @@ def create_app(
delete_credential(profile, requested_uuid)
except DatabaseError:
LOG.exception("Could not remove unused VM credential for %s", requested_uuid)
if owner_id is not None:
state.users.delete_vm_owner(host_scope(profile), requested_uuid)
if owner_assigned:
try:
state.users.delete_vm_owner(host_scope(profile), requested_uuid)
except DatabaseError:
LOG.exception("Could not remove unused VM owner for %s", requested_uuid)
if allocated_ip:
try:
release_public_ip_claim(profile, allocated_ip, requested_uuid)
except DatabaseError:
LOG.exception("Could not release unused public IP claim for %s", requested_uuid)
raise
vm = verified_created_vm(profile, vm, requested_uuid)
else:
@ -1588,6 +1762,11 @@ def create_app(
except DatabaseError:
LOG.exception("Could not remove credential for deleted VM %s", result["uuid"])
result = {**result, "warning": "虚拟机已删除,但数据库中的登录凭据或归属记录未能完全清理;请检查数据库状态"}
try:
release_vm_public_ip_claims(profile, result["uuid"])
except DatabaseError:
LOG.exception("Could not release public IP claim for deleted VM %s", result["uuid"])
result = {**result, "warning": "虚拟机已删除,但公网 IP 占用记录未能清理;请检查数据库状态"}
LOG.info(
"vm deleted: uuid=%s delete_disks=%s admin=%s",
result.get("uuid"), delete_disks, _session.username,

@ -52,6 +52,7 @@ from .remote_host import (
_validate_private_key,
_validate_region,
_write_private,
validate_public_pool,
)
from .ssh_agent import SSHAgentSession, _ASKPASS_SOURCE
@ -820,6 +821,13 @@ class DatabaseRemoteHostManager(RemoteHostManager):
iso_pool = _validate_pool_selector(metadata["iso_pool"], "ISO 池")
default_network = _validate_network_selector(metadata["default_network"])
region = _validate_region(metadata.get("region", ""))
public_pool = validate_public_pool(
metadata.get("public_pool_cidr", ""),
metadata.get("public_gateway", ""),
metadata.get("public_dns_servers", []),
metadata.get("public_reserved_ips", []),
host,
)
private_key = _validate_private_key(record["private_key"])
known_hosts = record["known_hosts"].strip()
key_type, encoded = _key_parts(known_hosts)
@ -880,7 +888,8 @@ class DatabaseRemoteHostManager(RemoteHostManager):
_write_private(generation / "profile.json", json.dumps(
{**metadata, "host": host, "port": port,
"storage_pool": storage_pool, "iso_pool": iso_pool,
"default_network": default_network, "region": region},
"default_network": default_network, "region": region,
**public_pool},
ensure_ascii=False,
).encode("utf-8"))
wrapper = self._write_wrapper(generation)

@ -65,6 +65,10 @@ class HostProfile:
iso_pool: str = "iso"
default_network: str = "default"
region: str = ""
public_pool_cidr: str = ""
public_gateway: str = ""
public_dns_servers: list[str] = field(default_factory=list)
public_reserved_ips: list[str] = field(default_factory=list)
@dataclass
@ -148,6 +152,91 @@ def _validate_region(value: str) -> str:
return value
def validate_public_pool(
public_pool_cidr: str,
public_gateway: str,
public_dns_servers: list[str],
public_reserved_ips: list[str],
host: str,
) -> dict[str, Any]:
"""Validate one host's public IPv4 pool without probing live network use.
The SSH host address is deliberately not persisted in the reserved list:
the allocator excludes a literal host IPv4 address while allocating, so
the operator can still distinguish explicit reservations from that rule.
"""
if not isinstance(public_pool_cidr, str) or not isinstance(public_gateway, str):
raise RemoteHostError("公网地址池和网关格式无效")
if (not isinstance(public_dns_servers, (list, tuple))
or not isinstance(public_reserved_ips, (list, tuple))):
raise RemoteHostError("公网 DNS 和保留 IP 必须是地址列表")
cidr = public_pool_cidr.strip()
gateway = public_gateway.strip()
dns_input = list(public_dns_servers)
reserved_input = list(public_reserved_ips)
if not any((cidr, gateway, dns_input, reserved_input)):
return {
"public_pool_cidr": "",
"public_gateway": "",
"public_dns_servers": [],
"public_reserved_ips": [],
}
if not cidr or not gateway or not dns_input:
raise RemoteHostError("启用公网地址池时必须同时填写 /24 网段、网关和 DNS")
if len(reserved_input) > 254:
raise RemoteHostError("保留 IP 最多可填写 254 个地址")
try:
network = ipaddress.IPv4Network(cidr, strict=True)
except (ValueError, ipaddress.AddressValueError, ipaddress.NetmaskValueError) as exc:
raise RemoteHostError("公网地址池必须填写规范的 IPv4 /24 网段地址") from exc
if (network.prefixlen != 24 or not network.network_address.is_global
or not network.broadcast_address.is_global):
raise RemoteHostError("公网地址池必须是可路由的 IPv4 /24 网段")
def parse_ipv4(value: str, label: str) -> ipaddress.IPv4Address:
if not isinstance(value, str) or not value or value != value.strip():
raise RemoteHostError(f"{label}必须是 IPv4 地址")
try:
return ipaddress.IPv4Address(value)
except (ValueError, ipaddress.AddressValueError) as exc:
raise RemoteHostError(f"{label}必须是 IPv4 地址") from exc
gateway_ip = parse_ipv4(gateway, "公网网关")
if gateway_ip not in network or gateway_ip in (
network.network_address, network.broadcast_address):
raise RemoteHostError("公网网关必须位于所配置 /24 网段内")
def unique_ips(values: list[str], label: str, *, in_pool: bool) -> list[str]:
normalized: list[str] = []
seen: set[str] = set()
for value in values:
address = parse_ipv4(value, label)
if in_pool:
if address not in network or address in (
network.network_address, network.broadcast_address):
raise RemoteHostError(f"{label}必须位于所配置 /24 网段内")
elif not address.is_global:
raise RemoteHostError(f"{label}必须是可路由的公网 IPv4 地址")
address_text = str(address)
if address_text not in seen:
seen.add(address_text)
normalized.append(address_text)
return normalized
dns = unique_ips(dns_input, "公网 DNS", in_pool=False)
reserved = unique_ips(reserved_input, "保留 IP", in_pool=True)
if len(dns) > 4:
raise RemoteHostError("公网 DNS 最多可填写 4 个地址")
if not dns:
raise RemoteHostError("启用公网地址池时必须填写 DNS")
return {
"public_pool_cidr": str(network),
"public_gateway": str(gateway_ip),
"public_dns_servers": dns,
"public_reserved_ips": reserved,
}
def _key_parts(line: str) -> tuple[str, str]:
if not isinstance(line, str) or len(line) > 4096 or any(c in line for c in "\r\n\x00"):
raise RemoteHostError("主机公钥格式无效")
@ -325,6 +414,13 @@ class RemoteHostManager:
iso_pool = _validate_pool_selector(profile.iso_pool, "ISO 池")
default_network = _validate_network_selector(profile.default_network)
region = _validate_region(profile.region)
public_pool = validate_public_pool(
profile.public_pool_cidr,
profile.public_gateway,
profile.public_dns_servers,
profile.public_reserved_ips,
host,
)
if not isinstance(confirmed_fingerprint, str) or not _FINGERPRINT.fullmatch(confirmed_fingerprint):
raise RemoteHostError("请确认扫描得到的 SHA256 主机指纹")
try:
@ -433,6 +529,7 @@ class RemoteHostManager:
"iso_pool": iso_pool,
"default_network": default_network,
"region": region,
**public_pool,
}
_write_private(
generation / "profile.json",
@ -665,11 +762,19 @@ class RemoteHostManager:
raise RemoteHostError("已保存的宿主机配置损坏", status=500)
try:
region = _validate_region(metadata.get("region", ""))
public_pool = validate_public_pool(
metadata.get("public_pool_cidr", ""),
metadata.get("public_gateway", ""),
metadata.get("public_dns_servers", []),
metadata.get("public_reserved_ips", []),
metadata["host"],
)
except RemoteHostError as exc:
raise RemoteHostError("已保存的宿主机配置损坏", status=500) from exc
return {
**{field: metadata[field] for field in fields},
"region": region,
**public_pool,
"private_key_encrypted": bool(metadata.get("private_key_encrypted", False)),
"key_locked": bool(metadata.get("private_key_encrypted", False)) and not (
generation in self._agents and self._agents[generation].alive

Loading…
Cancel
Save