可以先在侧栏“公钥管理”导入。选择后无需再次粘贴公钥,也不开放密码登录。
填写后导入 root 用户,使用对应私钥登录;此时无需设置 root 密码,也不开放密码登录。公钥和密码都留空时自动生成强密码。
仅在未填写公钥时启用;留空自动生成强密码。面板加密保存新建虚拟机的初始密码,可在详情页按需查看。公网密码登录风险较高,请通过 HTTPS 使用面板。
diff --git a/static/styles.css b/static/styles.css
index d03ac22f..d8516b8f 100644
--- a/static/styles.css
+++ b/static/styles.css
@@ -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)}}
diff --git a/tests/test_app.py b/tests/test_app.py
index dad60678..79fe1c2b 100644
--- a/tests/test_app.py
+++ b/tests/test_app.py
@@ -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)
diff --git a/tests/test_database.py b/tests/test_database.py
index eef3de83..bc9f672c 100644
--- a/tests/test_database.py
+++ b/tests/test_database.py
@@ -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()
diff --git a/tests/test_public_ip_pool.py b/tests/test_public_ip_pool.py
new file mode 100644
index 00000000..993e2fa0
--- /dev/null
+++ b/tests/test_public_ip_pool.py
@@ -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)
diff --git a/tests/test_registration_http.py b/tests/test_registration_http.py
index f708aac3..8b257611 100644
--- a/tests/test_registration_http.py
+++ b/tests/test_registration_http.py
@@ -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
diff --git a/tests/test_remote_host.py b/tests/test_remote_host.py
index 2156b29f..a22bd2e1 100644
--- a/tests/test_remote_host.py
+++ b/tests/test_remote_host.py
@@ -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()
diff --git a/virsh_panel/app.py b/virsh_panel/app.py
index dc754528..024ad47b 100644
--- a/virsh_panel/app.py
+++ b/virsh_panel/app.py
@@ -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,
diff --git a/virsh_panel/database.py b/virsh_panel/database.py
index dc7f27a8..b3c3571b 100644
--- a/virsh_panel/database.py
+++ b/virsh_panel/database.py
@@ -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)
diff --git a/virsh_panel/remote_host.py b/virsh_panel/remote_host.py
index b6846049..e99c7313 100644
--- a/virsh_panel/remote_host.py
+++ b/virsh_panel/remote_host.py
@@ -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