diff --git a/engine/tests/test_cloud_init.py b/engine/tests/test_cloud_init.py index fc54899e..3242cb89 100644 --- a/engine/tests/test_cloud_init.py +++ b/engine/tests/test_cloud_init.py @@ -12,7 +12,7 @@ from virsh_panel.cloud_init import ( ROOT_PASSWORD_ALPHABET, ROOT_PASSWORD_DIGITS, ROOT_PASSWORD_LENGTH, ROOT_PASSWORD_LOWERCASE, ROOT_PASSWORD_SYMBOLS, ROOT_PASSWORD_UPPERCASE, build_seed_iso, generate_root_password, hash_root_password, - read_seed_network, validate_cloud_network, + read_seed_network, replace_seed_network, validate_cloud_network, ) @@ -352,3 +352,49 @@ def test_seed_allows_root_password_and_ssh_key_together(): assert "PermitRootLogin yes" in user_data["write_files"][0]["content"] assert "PasswordAuthentication yes" in user_data["write_files"][0]["content"] assert GUEST_PASSWORD.encode() not in seed + + +@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None, + reason="pycdlib is not installed") +def test_replace_seed_network_preserves_user_data_and_metadata(): + password_hash = hash_root_password(GUEST_PASSWORD) + validated = validate_cloud_network( + "8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], PUBLIC_KEY, + root_password_hash=password_hash, + ) + seed = build_seed_iso( + str(uuid.uuid4()), "network-change-vm", "52:54:00:12:34:56", validated, + ) + import pycdlib + from io import BytesIO + + def file_bytes(image: bytes, path: str) -> bytes: + iso = pycdlib.PyCdlib() + iso.open_fp(BytesIO(image)) + output = BytesIO() + iso.get_file_from_iso_fp(output, rr_path=path) + iso.close() + return output.getvalue() + + user_data = file_bytes(seed, "/user-data") + metadata = file_bytes(seed, "/meta-data") + changed = replace_seed_network( + seed, "8.8.8.19/28", "8.8.8.17", ["8.8.8.8"], + ) + assert file_bytes(changed, "/user-data") == user_data + assert file_bytes(changed, "/meta-data") == metadata + assert read_seed_network(changed) == { + "public_ip_cidr": "8.8.8.19/28", + "gateway": "8.8.8.17", + "dns_servers": ["8.8.8.8"], + "mac": "52:54:00:12:34:56", + } + + +@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None, + reason="pycdlib is not installed") +def test_replace_seed_network_rejects_non_panel_seed(): + with pytest.raises(ValueError, match="无法读取原 cloud-init 配置盘"): + replace_seed_network( + b"not-an-iso", "8.8.8.19/28", "8.8.8.17", ["8.8.8.8"], + ) diff --git a/engine/tests/test_libvirt_service.py b/engine/tests/test_libvirt_service.py index 570fc407..dea16e08 100644 --- a/engine/tests/test_libvirt_service.py +++ b/engine/tests/test_libvirt_service.py @@ -684,6 +684,59 @@ class VMServiceTests(unittest.TestCase): self.assertEqual(self.backend.clones, []) self.assertEqual(self.backend.domains, []) + def test_cloud_network_change_restarts_guest_and_updates_seed_and_filter(self): + service = self.cloud_service() + spec = self.cloud_spec() + created = self.create_cloud_vm(service, spec) + domain = self.backend.domains[0] + old_seed = domain.root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed").get("seed-volume") + mac = domain.root.find("./devices/interface/mac").get("address") + network = { + "public_ip_cidr": "8.8.8.19/24", + "gateway": "8.8.8.1", + "dns_servers": ["1.1.1.1", "8.8.8.8"], + } + with patch.object(self.service_module, "read_seed_network", return_value={ + "public_ip_cidr": "8.8.8.18/24", "gateway": "8.8.8.1", + "dns_servers": ["1.1.1.1", "8.8.8.8"], + "mac": mac, + }), patch.object(self.service_module, "replace_seed_network", + return_value=b"NEW-SEED"): + result = service.change_cloud_vm_network( + created["uuid"], network, confirm_restart=True) + + self.assertTrue(result["network_changed"]) + self.assertEqual(result["public_ip_cidr"], "8.8.8.19/24") + self.assertEqual(result["vm"]["state"], "running") + self.assertEqual(self.backend.shutdown_calls, 1) + managed = domain.root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed") + self.assertEqual(managed.get("public-ip-cidr"), "8.8.8.19/24") + filterref = domain.root.find("./devices/interface/filterref") + self.assertEqual(filterref.get("filter"), "clean-traffic") + self.assertEqual(filterref.find("parameter").get("value"), "8.8.8.19") + self.assertEqual( + bytes(self.backend.pools["images"].volumes[old_seed].contents), + b"NEW-SEED", + ) + + def test_cloud_network_change_rejects_unconfirmed_restart_without_touching_vm(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + domain = self.backend.domains[0] + before = ET.tostring(domain.root) + with self.assertRaises(self.error_type) as raised: + service.change_cloud_vm_network( + created["uuid"], { + "public_ip_cidr": "8.8.8.19/24", + "gateway": "8.8.8.1", + "dns_servers": ["1.1.1.1"], + }, confirm_restart=False) + self.assertEqual(raised.exception.status, 422) + self.assertEqual(ET.tostring(domain.root), before) + self.assertEqual(self.backend.shutdown_calls, 0) + def test_user_iso_isolated_directory_import_create_and_delete(self): service = self.service.__class__( self.service.uri, "images", "/home/iso", "default") diff --git a/engine/virsh_panel/app.py b/engine/virsh_panel/app.py index 7f02634d..caef2891 100644 --- a/engine/virsh_panel/app.py +++ b/engine/virsh_panel/app.py @@ -29,7 +29,10 @@ from fastapi.staticfiles import StaticFiles from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator from .auth import DatabaseSessionStore, LoginLimiter, Session, SessionStore, verify_password -from .cloud_init import _validate_guest_auth, generate_root_password, hash_root_password +from .cloud_init import ( + _validate_guest_auth, generate_root_password, hash_root_password, + validate_cloud_network, +) from .cloud_templates import ( TemplateError, TemplateStore, download_verified_image, image_metadata_for, template_id_for, template_scope, template_volume_name, validate_template_name, @@ -220,6 +223,13 @@ class CreateCloudBody(BaseModel): root_password: SecretStr | None = None +class ChangeNetworkBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + public_ip_cidr: str = Field(min_length=7, max_length=64) + confirm_restart: bool = False + + class SSHKeyBody(BaseModel): model_config = ConfigDict(extra="forbid") @@ -3279,6 +3289,122 @@ def create_app( return apply_private_vm_target( vm_id, _session, "network_resume", "网络恢复") + @app.post("/api/v1/vms/{vm_id}/network") + def change_network_vm( + vm_id: str, + body: ChangeNetworkBody, + _session: Session = Depends(require_internal_service_write), + ): + """Change one managed cloud VM's public IPv4 on the same host. + + The engine validates the host pool and holds the new claim before + touching libvirt. A 5xx/transport failure deliberately keeps both IP + claims for reconciliation; only deterministic validation failures + release the new reservation. + """ + with reinstall_lock, rescue_lock: + forbid_long_job_during_update() + profile = current_profile() + try: + normalized_id = str(uuid.UUID(vm_id)) + except (TypeError, ValueError, AttributeError) as exc: + raise VMError("虚拟机 UUID 无效", 400) from exc + require_vm_access(_session, profile, normalized_id) + if (template_scope(profile), normalized_id) in pending_reinstalls: + raise VMError("虚拟机正在重装系统,暂时不能修改网络", 409) + if (host_scope(profile), normalized_id) in pending_rescues: + raise VMError("虚拟机正在切换救援模式,请先修改完成后再试", 409) + service = new_service(profile) + vm = service.get_vm(normalized_id) + if (not vm.get("managed") or vm.get("os_source") != "cloud_template" + or not vm.get("public_ip_cidr")): + raise VMError("只有面板创建的公网云镜像虚拟机支持更换 IP", 409) + if not body.confirm_restart: + raise VMError("更换公网 IP 前必须确认会短暂重启虚拟机", 422) + + try: + pool = ipaddress.IPv4Network( + profile["public_pool_cidr"], strict=True) + target = ipaddress.IPv4Interface(body.public_ip_cidr) + guest_prefix = profile.get("public_vm_prefix") + if guest_prefix is None: + guest_prefix = pool.prefixlen + if (target.network.prefixlen != guest_prefix + or target.ip not in pool): + raise ValueError + blocked = { + str(ipaddress.IPv4Address(profile["public_gateway"])), + *(str(ipaddress.IPv4Address(value)) + for value in profile.get("public_dns_servers", [])), + *(str(ipaddress.IPv4Address(value)) + for value in profile.get("public_reserved_ips", [])), + } + try: + host_address = ipaddress.IPv4Address(profile.get("host", "")) + except (TypeError, ValueError): + host_address = None + if host_address is not None: + blocked.add(str(host_address)) + if str(target.ip) in blocked: + raise ValueError + validated = validate_cloud_network( + str(target), profile["public_gateway"], + profile["public_dns_servers"], require_auth=False, + ) + except (KeyError, TypeError, ValueError) as exc: + raise VMError("目标公网 IP 不属于宿主机可分配地址池", 422) from exc + + old_ip = str(vm["public_ip_cidr"]) + try: + old_interface = ipaddress.IPv4Interface(old_ip) + except ValueError as exc: + raise VMError("虚拟机当前公网 IP 配置无效,已停止网络修改", 409) from exc + if (old_interface.network.prefixlen != guest_prefix + or old_interface.ip not in pool): + raise VMError("虚拟机当前公网 IP 不属于宿主机地址池,已停止网络修改", 409) + if validated["public_ip_cidr"] == old_ip: + return { + "vm": vm, + "public_ip_cidr": old_ip, + "gateway": validated["gateway"], + "dns_servers": list(validated["dns_servers"]), + "network_changed": False, + } + for existing in service.list_vms(): + if existing.get("uuid") == normalized_id: + continue + if (isinstance(existing.get("public_ip_cidr"), str) + and existing["public_ip_cidr"].split("/", 1)[0] + == str(target.ip)): + raise VMError("该公网 IP 已分配给宿主机上的另一台虚拟机", 409) + + claim_explicit_public_ip( + profile, validated["public_ip_cidr"], normalized_id) + claim_reserved = True + try: + result = service.change_cloud_vm_network( + normalized_id, validated, + confirm_restart=body.confirm_restart, + ) + except Exception as exc: + # A successful libvirt request can lose its response. Never + # release a new claim on a 5xx/unknown result; doing so could + # allocate the same address to a second guest. + if (claim_reserved and isinstance(exc, VMError) + and exc.status < 500): + release_public_ip_claim( + profile, validated["public_ip_cidr"], normalized_id) + raise + warning = None + try: + release_public_ip_claim(profile, old_ip, normalized_id) + except DatabaseError: + LOG.exception("Could not release old public IP claim for %s", normalized_id) + warning = "新公网 IP 已生效,但旧 IP 占用记录未能自动清理,请检查引擎状态" + if warning: + result = {**result, "warning": warning} + return result + @app.post("/api/v1/vms/{vm_id}/actions") def action(vm_id: str, body: ActionBody, _session: Session = Depends(require_approved_write)): with reinstall_lock, rescue_lock: diff --git a/engine/virsh_panel/cloud_init.py b/engine/virsh_panel/cloud_init.py index ca3a2fe3..8b8d0973 100644 --- a/engine/virsh_panel/cloud_init.py +++ b/engine/virsh_panel/cloud_init.py @@ -178,6 +178,8 @@ def validate_cloud_network( dns_servers: list[str] | tuple[str, ...], guest_ssh_public_key: str = "", root_password_hash: str | None = None, + *, + require_auth: bool = True, ) -> dict[str, Any]: """Return canonical guest network fields or raise ``ValueError``. @@ -218,8 +220,16 @@ def validate_cloud_network( dns = [str(address) for address in dns_ips] if len(set(dns)) != len(dns): raise ValueError("DNS 地址不能重复") - public_key, password_hash = _validate_guest_auth( - guest_ssh_public_key, root_password_hash) + if not isinstance(require_auth, bool): + raise ValueError("网络认证校验选项无效") + if require_auth: + public_key, password_hash = _validate_guest_auth( + guest_ssh_public_key, root_password_hash) + else: + # A network-only update must not require, receive, or regenerate the + # guest credential. The existing user-data remains byte-for-byte + # untouched in ``replace_seed_network``. + public_key, password_hash = "", None result = { "public_ip_cidr": str(interface), "gateway": str(gateway_ip), @@ -358,6 +368,11 @@ def build_seed_iso( ("/NETWORK.;1", "network-config", "/network-config", json.dumps(network_config, ensure_ascii=True).encode("ascii") + b"\n"), ) + return _build_seed_iso(files) + + +def _build_seed_iso(files: tuple[tuple[str, str, str, bytes], ...]) -> bytes: + """Build a bounded CIDATA image from trusted, already-encoded files.""" import pycdlib iso = pycdlib.PyCdlib() @@ -365,17 +380,101 @@ def build_seed_iso( try: iso.new(vol_ident="CIDATA", rock_ridge="1.09", joliet=3) for iso_path, rock_ridge_name, joliet_path, contents in files: + if not isinstance(contents, bytes) or len(contents) > 256 * 1024: + raise ValueError("cloud-init 配置文件过大") payload = BytesIO(contents) payloads.append(payload) # pycdlib reads these during write_fp. iso.add_fp(payload, len(contents), iso_path=iso_path, rr_name=rock_ridge_name, joliet_path=joliet_path) output = BytesIO() iso.write_fp(output) - return output.getvalue() + result = output.getvalue() + if not result or len(result) > 1024 * 1024: + raise ValueError("cloud-init 配置盘大小无效") + return result finally: iso.close() +def replace_seed_network( + seed: bytes, + public_ip_cidr: str, + gateway: str, + dns_servers: list[str] | tuple[str, ...], +) -> bytes: + """Replace only ``network-config`` in a panel-created NoCloud seed. + + ``user-data`` and ``meta-data`` are copied without parsing or rewriting; + this is intentional because user-data may contain SSH keys/password + hashes. Reject non-panel seeds instead of trying to infer their format. + """ + if not isinstance(seed, bytes) or not seed or len(seed) > 1024 * 1024: + raise ValueError("原 cloud-init 配置盘大小无效") + import pycdlib + + iso = pycdlib.PyCdlib() + opened = False + files: dict[str, bytes] = {} + try: + iso.open_fp(BytesIO(seed)) + opened = True + for rr_path, key in (("/user-data", "user-data"), + ("/meta-data", "meta-data"), + ("/network-config", "network-config")): + output = BytesIO() + iso.get_file_from_iso_fp(output, rr_path=rr_path) + value = output.getvalue() + if not value or len(value) > 256 * 1024: + raise ValueError("原 cloud-init 配置文件大小无效") + files[key] = value + except (OSError, KeyError, TypeError, ValueError, + pycdlib.pycdlibexception.PyCdlibException) as exc: + raise ValueError("无法读取原 cloud-init 配置盘") from exc + finally: + if opened: + iso.close() + + try: + config = json.loads(files["network-config"]) + if (config.get("version") != 2 + or not isinstance(config.get("ethernets"), dict) + or set(config["ethernets"]) != {"public0"}): + raise ValueError + public = config["ethernets"]["public0"] + match = public.get("match") + mac = match.get("macaddress") if isinstance(match, dict) else None + if (public.get("dhcp4") is not False or public.get("dhcp6") is not False + or not isinstance(mac, str) or not _MAC.fullmatch(mac) + or not isinstance(public.get("addresses"), list) + or len(public["addresses"]) != 1 + or not isinstance(public.get("routes"), list) + or len(public["routes"]) != 1): + raise ValueError + route = public["routes"][0] + if route.get("to") != "0.0.0.0/0": + raise ValueError + # Validate only fields that are changing. No credential is accepted + # by this operation, so the original user-data remains opaque. + network = validate_cloud_network( + public_ip_cidr, gateway, dns_servers, require_auth=False) + public["addresses"] = [network["public_ip_cidr"]] + route["via"] = network["gateway"] + nameservers = public.get("nameservers") + if not isinstance(nameservers, dict): + raise ValueError + nameservers["addresses"] = list(network["dns_servers"]) + network_data = (json.dumps(config, ensure_ascii=True).encode("ascii") + + b"\n") + rebuilt = ( + ("/USERDATA.;1", "user-data", "/user-data", files["user-data"]), + ("/METADATA.;1", "meta-data", "/meta-data", files["meta-data"]), + ("/NETWORK.;1", "network-config", "/network-config", network_data), + ) + return _build_seed_iso(rebuilt) + except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: + raise ValueError("原 cloud-init 网络配置格式无效") from exc + + def read_seed_network(seed: bytes) -> dict[str, Any]: """Read the network settings from a panel-created NoCloud ISO. diff --git a/engine/virsh_panel/internal.py b/engine/virsh_panel/internal.py index daf7feff..3a75c0a5 100644 --- a/engine/virsh_panel/internal.py +++ b/engine/virsh_panel/internal.py @@ -69,7 +69,7 @@ WRITE_PATHS = { "POST": (r"host/(?:scan|unlock|test|discover-vms)", r"vm-templates/(?:import|upload)", r"rescue-templates", r"user-isos/import", - r"vms", rf"vms/{VM_ID}/(?:actions|credential|reinstall|rescue|console-ticket)", + r"vms", rf"vms/{VM_ID}/(?:actions|credential|reinstall|network|rescue|console-ticket)", rf"vms/{VM_ID}/(?:service|network)-(?:suspend|resume)", rf"vms/{VM_ID}/rescue/(?:exit|force-start)", r"reinstall-jobs/[A-Za-z0-9_-]+/ack-password"), "PUT": (r"host",), @@ -542,7 +542,7 @@ class EngineApplication: create = scope["method"] == "POST" and resource == "vms" mutation = scope["method"] == "DELETE" and resource.startswith("vms/") or ( scope["method"] == "POST" and bool(re.fullmatch( - rf"vms/{VM_ID}/(?:actions|reinstall|" + rf"vms/{VM_ID}/(?:actions|reinstall|network|" rf"(?:service|network)-(?:suspend|resume)|" rf"rescue(?:/exit|/force-start)?)", resource))) diff --git a/engine/virsh_panel/libvirt_service.py b/engine/virsh_panel/libvirt_service.py index 25b7219f..3c9b8746 100644 --- a/engine/virsh_panel/libvirt_service.py +++ b/engine/virsh_panel/libvirt_service.py @@ -23,7 +23,10 @@ from typing import Any, Callable, Iterator import libvirt -from virsh_panel.cloud_init import build_seed_iso, read_seed_network, validate_cloud_network +from virsh_panel.cloud_init import ( + build_seed_iso, read_seed_network, replace_seed_network, + validate_cloud_network, +) from virsh_panel.metrics import RawVMStats from virsh_panel.user_isos import ( MAX_USER_ISO_BYTES, MAX_USER_ISOS, MAX_USER_ISO_TOTAL_BYTES, @@ -52,6 +55,8 @@ RESCUE_VOLUME_RE = re.compile(r"panel-rescue-[0-9a-f]{32}\.iso\Z") _CREATE_LOCK = threading.RLock() REINSTALL_SHUTDOWN_TIMEOUT = 120 REINSTALL_SHUTDOWN_POLL_INTERVAL = 1 +NETWORK_CHANGE_SHUTDOWN_TIMEOUT = 120 +NETWORK_CHANGE_SHUTDOWN_POLL_INTERVAL = 1 SERVICE_SUSPEND_SHUTDOWN_TIMEOUT = 30 SERVICE_SUSPEND_SHUTDOWN_POLL_INTERVAL = 0.5 MIN_RESCUE_ISO_BYTES = 1024 * 1024 @@ -160,6 +165,27 @@ class VMService: filter=CLEAN_TRAFFIC_FILTER) ET.SubElement(filterref, "parameter", name="IP", value=public_ip) + @staticmethod + def _update_clean_traffic_filter(interface: ET.Element, + public_ip_cidr: str) -> None: + """Update or add the panel anti-spoofing filter on one interface.""" + public_ip = public_ip_cidr.split("/", 1)[0] + refs = [node for node in interface.findall("filterref") + if node.get("filter") == CLEAN_TRAFFIC_FILTER] + if len(refs) > 1: + raise VMError("虚拟机存在重复的 clean-traffic 过滤器,已停止网络修改", 409) + if not refs: + VMService._attach_clean_traffic_filter(interface, public_ip_cidr) + return + parameters = refs[0].findall("parameter") + if len(parameters) > 1: + raise VMError("虚拟机的 clean-traffic 参数重复,已停止网络修改", 409) + parameter = parameters[0] if parameters else ET.SubElement( + refs[0], "parameter", name="IP", value=public_ip) + if parameter.get("name") != "IP": + raise VMError("虚拟机的 clean-traffic 参数无效,已停止网络修改", 409) + parameter.set("value", public_ip) + @staticmethod def _pool_path(reference: str) -> str | None: if not reference.startswith("/"): @@ -2495,6 +2521,210 @@ class VMService: phase("completed") return result + def change_cloud_vm_network( + self, + vm_id: str, + network: dict[str, Any], + *, + confirm_restart: bool = False, + progress: Callable[[str], None] | None = None, + ) -> dict[str, Any]: + """Replace a managed cloud VM's public IPv4 configuration. + + The operation deliberately rewrites only the network-config file in + the existing NoCloud seed. Credentials and metadata remain opaque and + untouched. A running guest is gracefully stopped and started again; + a stopped guest remains stopped. Any transport error after QEMU has + started is surfaced as a 502 so the durable internal operation becomes + ``uncertain`` instead of guessing whether the guest applied the IP. + """ + if confirm_restart is not True: + raise VMError("更换公网 IP 前必须确认会短暂重启虚拟机", 422) + if self.bridge_name is None: + raise VMError("公网云镜像更换 IP 需要原 Linux 网桥配置", 409) + if not isinstance(network, dict): + raise VMError("网络配置无效", 422) + try: + validated = validate_cloud_network( + network.get("public_ip_cidr"), network.get("gateway"), + network.get("dns_servers"), require_auth=False, + ) + except (TypeError, ValueError) as exc: + raise VMError(str(exc), 422) from exc + + def phase(value: str) -> None: + if progress is not None: + progress(value) + + with _CREATE_LOCK, self._connect() as conn: + self._require_clean_traffic_filter(conn) + domain = self._domain(conn, vm_id) + if not domain.isPersistent(): + raise VMError("只能修改持久化虚拟机", 409) + if getattr(domain, "hasManagedSaveImage", lambda _flags: 0)(0): + raise VMError("虚拟机存在托管保存状态,请先处理后再修改网络", 409) + if domain.snapshotNum(0) > 0: + raise VMError("虚拟机存在快照,请先处理后再修改网络", 409) + original_root = self._vm_xml(domain) + managed = original_root.find(f"./metadata/{{{PANEL_NS}}}managed") + if (managed is None or managed.get("version") != "2" + or managed.get("os-source") != "cloud_template" + or not managed.get("seed-volume") + or not managed.get("public-ip-cidr")): + raise VMError("只有面板创建的公网云镜像虚拟机支持更换 IP", 409) + interfaces = original_root.findall("./devices/interface") + if len(interfaces) != 1: + raise VMError("虚拟机必须只有一个公网网卡,已停止网络修改", 409) + interface = interfaces[0] + source = interface.find("source") + mac_node = interface.find("mac") + if (interface.get("type") != "bridge" or source is None + or source.get("bridge") != self.bridge_name + or mac_node is None or not mac_node.get("address")): + raise VMError("虚拟机网桥或 MAC 已变化,不能自动修改网络", 409) + mac = mac_node.get("address").lower() + old_ip = managed.get("public-ip-cidr") + if validated["public_ip_cidr"] == old_ip: + return { + "vm": self._vm_dict(domain), + "public_ip_cidr": old_ip, + "gateway": validated["gateway"], + "dns_servers": list(validated["dns_servers"]), + "network_changed": False, + "was_running": bool(domain.isActive()), + } + old_seed = self._owned_seed_volume(conn, domain) + if old_seed is None: + raise VMError("找不到原 cloud-init 配置盘,已停止网络修改", 409) + original_seed = self._download_seed_volume(conn, old_seed) + try: + original_network = read_seed_network(original_seed) + except (ImportError, ValueError) as exc: + raise VMError("原 cloud-init 配置盘不是面板生成格式,已停止网络修改", 409) from exc + if (original_network["mac"] != mac + or original_network["public_ip_cidr"] != old_ip): + raise VMError("原配置盘的公网 IP 或 MAC 与虚拟机不一致,已停止网络修改", 409) + try: + replacement_seed = replace_seed_network( + original_seed, validated["public_ip_cidr"], + validated["gateway"], validated["dns_servers"], + ) + except ImportError as exc: + raise VMError("面板缺少 pycdlib,无法修改 cloud-init 配置盘", 503) from exc + except ValueError as exc: + raise VMError("原 cloud-init 网络配置格式无效,已停止网络修改", 409) from exc + + phase("shutting_down") + was_running = bool(domain.isActive()) + if was_running: + try: + domain.shutdown() + except libvirt.libvirtError as exc: + raise VMError("虚拟机正常关机失败,网络未修改", 409) from exc + deadline = time.monotonic() + NETWORK_CHANGE_SHUTDOWN_TIMEOUT + while domain.isActive(): + if time.monotonic() >= deadline: + raise VMError("正常关机超时,网络未修改", 409) + time.sleep(NETWORK_CHANGE_SHUTDOWN_POLL_INTERVAL) + + # Re-read inactive XML after shutdown. This protects the seed and + # filter update from a concurrent operator edit. + old_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) + inactive_root = ET.fromstring(old_xml) + inactive_managed = inactive_root.find(f"./metadata/{{{PANEL_NS}}}managed") + inactive_interface = inactive_root.find("./devices/interface") + inactive_mac = (inactive_interface.find("mac") + if inactive_interface is not None else None) + inactive_source = (inactive_interface.find("source") + if inactive_interface is not None else None) + if (inactive_managed is None + or inactive_managed.get("seed-volume") != old_seed.name() + or inactive_managed.get("public-ip-cidr") != old_ip + or inactive_interface is None + or inactive_mac is None + or (inactive_mac.get("address") or "").lower() != mac + or inactive_interface.get("type") != "bridge" + or inactive_source is None + or inactive_source.get("bridge") != self.bridge_name): + raise VMError("关机后虚拟机配置已变化,网络修改已停止", 409) + + new_root = ET.fromstring(old_xml) + new_managed = new_root.find(f"./metadata/{{{PANEL_NS}}}managed") + new_interface = new_root.find("./devices/interface") + if new_managed is None or new_interface is None: + raise VMError("虚拟机配置已变化,网络修改已停止", 409) + new_managed.set("public-ip-cidr", validated["public_ip_cidr"]) + self._update_clean_traffic_filter( + new_interface, validated["public_ip_cidr"]) + switched = False + try: + phase("updating_network") + # The volume is raw and already bounded at one MiB. Grow it + # only when the replacement image is larger; shrinking raw + # volumes is not portable and is unnecessary for NoCloud. + current_capacity = int(old_seed.info()[1]) + if len(replacement_seed) > current_capacity: + old_seed.resize(len(replacement_seed), 0) + self._upload_volume( + conn, old_seed, iter((replacement_seed,)), + len(replacement_seed), + ) + new_domain = conn.defineXML(ET.tostring(new_root, encoding="unicode")) + if new_domain is None: + raise VMError("宿主机未能保存新的虚拟机网络配置", 502) + switched = True + if was_running: + phase("starting") + try: + new_domain.create() + except libvirt.libvirtError as exc: + if new_domain.isActive(): + # The request may have reached QEMU despite a lost + # response. Keep the new definition and let the + # internal operation become uncertain. + raise VMError( + "虚拟机已发送启动指令但结果不确定,请查询任务状态", 502, + ) from exc + raise + except Exception as exc: + if switched and was_running and domain.isActive(): + raise VMError( + "网络修改结果不确定,请查询任务状态;未释放原公网 IP", 502, + ) from exc + restored = True + try: + self._upload_volume(conn, old_seed, iter((original_seed,)), + len(original_seed)) + except Exception: + LOG.exception("Could not restore original seed for %s", vm_id) + restored = False + if switched: + try: + restored_domain = conn.defineXML(old_xml) + if restored_domain is None: + restored = False + except Exception: + LOG.exception("Could not restore original VM XML for %s", vm_id) + restored = False + if not restored: + raise VMError( + "网络修改失败且自动回滚不完整;原配置仍保留,请检查虚拟机", 502, + ) from exc + if isinstance(exc, VMError): + raise + raise VMError("网络修改失败,已恢复原配置", 502) from exc + + phase("completed") + result = self._vm_dict(new_domain) + return { + "vm": result, + "public_ip_cidr": validated["public_ip_cidr"], + "gateway": validated["gateway"], + "dns_servers": list(validated["dns_servers"]), + "network_changed": True, + "was_running": was_running, + } + @staticmethod def _requested_create_uuid(spec: dict[str, Any]) -> str | None: requested_uuid = spec.get("vm_uuid") diff --git a/web/app/Controllers/CloudAdminInstanceController.php b/web/app/Controllers/CloudAdminInstanceController.php index af494c92..a951d70f 100644 --- a/web/app/Controllers/CloudAdminInstanceController.php +++ b/web/app/Controllers/CloudAdminInstanceController.php @@ -4,8 +4,11 @@ namespace App\Controllers; use App\Services\Cloud\CloudAccess; use App\Services\Cloud\CloudAdminInstanceService; +use App\Services\Cloud\CloudError; +use App\Services\Cloud\CloudInput; +use App\Services\Cloud\CloudJobService; -/** Read-only database snapshots; live power state uses the existing VM API. */ +/** Administrator inventory snapshots plus explicitly queued VM mutations. */ final class CloudAdminInstanceController { public function index($request, $response) @@ -23,4 +26,47 @@ final class CloudAdminInstanceController (string) ($args['id'] ?? '') ))->withHeader('Cache-Control', 'private, no-store'); } + + /** + * Queue a controlled same-host public IPv4 replacement. + * + * The engine owns the actual address pool and performs the shutdown, + * cloud-init/network update, clean-traffic update and claim swap. PHP + * only validates the administrative boundary and records the durable job; + * it deliberately does not update spec_json until the worker receives a + * successful engine result. + */ + public function network($request, $response, $args) + { + $actor = $request->getAttribute('cloud_actor') ?? CloudAccess::actor(false); + CloudAccess::manage($actor); + $instance = CloudAccess::instance((string) ($args['id'] ?? ''), $actor, true); + if ((string) $instance->status !== 'active') { + throw new CloudError('只有处于活动状态的虚拟机可以更换公网 IP', 409); + } + $body = CloudInput::object($request); + CloudInput::only($body, ['public_ip_cidr', 'confirm_restart']); + if (($body['confirm_restart'] ?? false) !== true) { + throw new CloudError('更换公网 IP 前必须确认虚拟机会短暂重启'); + } + $cidr = CloudInput::publicIpCidr($body['public_ip_cidr'] ?? null); + $spec = json_decode((string) $instance->spec_json, true); + if (!is_array($spec) || array_is_list($spec) + || ($spec['managed'] ?? false) !== true + || ($spec['os_source'] ?? null) !== 'cloud_template') { + throw new CloudError('当前虚拟机不是支持网络配置的面板云镜像实例', 409); + } + $current = is_string($spec['public_ip_cidr'] ?? null) + ? trim($spec['public_ip_cidr']) : ''; + if ($current !== '' && $current === $cidr) { + throw new CloudError('新公网 IP 与当前配置相同', 409); + } + $job = CloudJobService::enqueue($instance, $actor, 'network_change', 'POST', + '/network', ['public_ip_cidr' => $cidr, 'confirm_restart' => true]); + return $response->withJson([ + 'job_id' => (string) $job->id, + 'status_url' => '/api/v1/jobs/' . $job->id, + 'public_ip_cidr' => $cidr, + ], 202)->withHeader('Cache-Control', 'no-store'); + } } diff --git a/web/app/Services/Cloud/CloudInput.php b/web/app/Services/Cloud/CloudInput.php index 048418f1..4184aa66 100644 --- a/web/app/Services/Cloud/CloudInput.php +++ b/web/app/Services/Cloud/CloudInput.php @@ -117,6 +117,27 @@ final class CloudInput return $value; } + /** + * Validate the public IPv4 address/prefix accepted by a network-change + * task. The engine remains authoritative for the host's configured pool; + * this boundary only rejects malformed or non-IPv4 input before a job is + * persisted. + */ + public static function publicIpCidr($value): string + { + if (!is_string($value)) { + throw new CloudError('公网 IPv4 地址必须使用 CIDR 格式'); + } + $value = trim($value); + $parts = explode('/', $value, 2); + if (count($parts) !== 2 + || filter_var($parts[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false + || preg_match('/^(?:[1-9]|[12][0-9]|3[0-2])$/D', $parts[1]) !== 1) { + throw new CloudError('公网 IPv4 地址必须使用有效的 CIDR 格式,例如 203.0.113.10/24'); + } + return $parts[0] . '/' . (int) $parts[1]; + } + public static function safeResult(array $value): array { foreach ($value as $key => $item) { diff --git a/web/app/Services/Cloud/CloudJobService.php b/web/app/Services/Cloud/CloudJobService.php index 73fa5e33..6c0b56a2 100644 --- a/web/app/Services/Cloud/CloudJobService.php +++ b/web/app/Services/Cloud/CloudJobService.php @@ -20,6 +20,14 @@ final class CloudJobService CloudInput::template($body['template_id'] ?? '') ); } + if ($kind === 'network_change') { + if (($body['confirm_restart'] ?? false) !== true) { + throw new CloudError('更换公网 IP 前必须确认虚拟机会短暂重启'); + } + $body['public_ip_cidr'] = CloudInput::publicIpCidr( + $body['public_ip_cidr'] ?? null + ); + } $locked = CloudInstance::where('id', $instance->id)->lockForUpdate()->first(); if ($locked === null || (string) $locked->status === 'deleted') { throw new CloudError('虚拟机不存在', 404); diff --git a/web/app/Services/Cloud/CloudWorkerService.php b/web/app/Services/Cloud/CloudWorkerService.php index 913c4422..725b5431 100644 --- a/web/app/Services/Cloud/CloudWorkerService.php +++ b/web/app/Services/Cloud/CloudWorkerService.php @@ -541,6 +541,28 @@ final class CloudWorkerService JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } + } elseif ($job->kind === 'network_change') { + // The address cache is updated only after the engine + // confirms the same requested CIDR. The engine is + // authoritative for pool membership, claim swaps and + // the guest seed; PHP must never make a successful + // database-only change look applied. + $requested = is_array($payload['body'] ?? null) + ? ($payload['body']['public_ip_cidr'] ?? null) : null; + $confirmed = is_array($result) + ? ($result['public_ip_cidr'] ?? null) : null; + if (!is_string($requested) || !is_string($confirmed) + || $requested !== $confirmed) { + throw new CloudError('引擎成功结果缺少已确认的公网 IP', 502); + } + $decoded = json_decode((string) $instance->spec_json, true); + if (!is_array($decoded) || array_is_list($decoded)) { + throw new CloudError('虚拟机配置记录损坏,无法保存新的公网 IP', 409); + } + $decoded['public_ip_cidr'] = $confirmed; + $instance->spec_json = json_encode($decoded, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE); } elseif ($job->kind === 'service_suspend' && in_array((string) $instance->service_status, ['suspending_expired', 'resume_pending', 'resuming', diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php index 6eb7ea3a..a13bdd67 100644 --- a/web/config/routes_cloud.php +++ b/web/config/routes_cloud.php @@ -51,6 +51,7 @@ $app->group('/api/v1', function () { $this->post('/admin/hosts/scan', 'App\Controllers\CloudAdminController:scan'); $this->get('/admin/instances', 'App\Controllers\CloudAdminInstanceController:index'); $this->get('/admin/instances/{id:[0-9]+}', 'App\Controllers\CloudAdminInstanceController:detail'); + $this->patch('/admin/instances/{id:[0-9]+}/network', 'App\Controllers\CloudAdminInstanceController:network'); $this->get('/admin/operations', 'App\Controllers\CloudAdminOperationsController:index'); $this->get('/admin/operations/health', 'App\Controllers\CloudAdminRuntimeController:index'); $this->get('/admin/operations/jobs/{id:[0-9]+}', 'App\Controllers\CloudAdminOperationsController:detail'); diff --git a/web/public/cloud/admin-instances.js b/web/public/cloud/admin-instances.js index 8360cbb7..f61d1bb7 100644 --- a/web/public/cloud/admin-instances.js +++ b/web/public/cloud/admin-instances.js @@ -7,9 +7,11 @@ const state = { items: [], pagination: { page: 1, per_page: 20, total: 0, total_pages: 1 }, request: null, serial: 0, loading: false, hasData: false, active: true, timer: null, statusRequest: null, statusFailures: 0, detailRequest: null, detailId: null, - opener: null, scroll: null, + opener: null, scroll: null, networkRequest: null, }; +const canManage = window.ADMIN_CAN_MANAGE === true; + function el(tag, className = '', text) { const node = document.createElement(tag); node.className = className; @@ -82,6 +84,40 @@ async function api(path, controller) { } finally { clearTimeout(timeout); } } +async function mutate(path, body, controller) { + if (!canManage) throw new Error('当前管理员仅可查看,不能修改实例配置。'); + if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) { + throw new Error('请通过 HTTPS 修改实例网络配置。'); + } + const timeout = setTimeout(() => controller.abort('timeout'), 30000); + try { + const response = await fetch(path, { + method: 'PATCH', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'X-CSRF-Token': window.ADMIN_CSRF_TOKEN || '', + }, + credentials: 'same-origin', cache: 'no-store', signal: controller.signal, + body: JSON.stringify(body), + }); + if (response.status === 401) throw new Error('登录已过期,请重新登录。'); + let payload; + try { payload = await response.json(); } + catch { throw new Error('服务返回异常,请检查服务器日志后重试。'); } + if (!response.ok || payload?.ret === 0) { + const detail = Array.isArray(payload?.detail) + ? payload.detail.map(item => item?.msg || '输入错误').join(';') + : payload?.detail; + throw new Error(typeof detail === 'string' ? detail : (payload?.message || `请求失败 (${response.status})`)); + } + return payload; + } catch (error) { + if (controller.signal.reason === 'timeout') throw new Error('请求超时,请稍后重试。'); + throw error; + } finally { clearTimeout(timeout); } +} + function copyButton(value, label = '复制') { const button = el('button', 'btn btn-light btn-sm'); button.type = 'button'; @@ -118,6 +154,7 @@ function jobKind(value) { return ({ create: '创建实例', provision: '开通', action: '电源操作', start: '开机', shutdown: '关机', reboot: '重启', destroy: '强制断电', reset: '强制重置', reinstall: '重装', delete: '删除', suspend: '暂停网络', resume: '恢复网络', rescue: '救援', + network_change: '更换公网 IP', service_suspend: '到期停用', service_resume: '服务恢复', network_suspend: '限制网络', network_resume: '恢复网络', expiry_delete: '到期清理', })[value] || text(value, '操作任务'); @@ -326,6 +363,86 @@ function detailNotice(message, error = false) { node.setAttribute('role', error ? 'alert' : 'status'); } +function networkEditor(vm) { + const section = el('section', 'admin-instance-network-settings mt-4'); + section.setAttribute('aria-labelledby', 'instance-network-title'); + const heading = el('div', 'd-flex align-items-start justify-content-between gap-3 flex-wrap'); + const copy = el('div'); + copy.append(el('h3', 'h6 fw-semibold mb-1', '网络配置'), el('p', 'text-muted fs-13 mb-0', '更换公网 IP 会触发一次受控重启,网关和 DNS 由宿主机地址池自动校验。')); + heading.append(copy); + if (canManage) { + const edit = el('button', 'btn btn-light btn-sm', '更换公网 IP'); + edit.type = 'button'; edit.dataset.networkEdit = 'open'; + edit.setAttribute('aria-expanded', 'false'); + heading.append(edit); + } + section.append(heading); + const current = el('div', 'admin-instance-network-current mt-3'); + current.append(el('span', 'text-muted fs-13', '当前公网地址'), el('strong', 'admin-mono', text(vm.public_ip_cidr, vm.public_ip, '未记录'))); + section.append(current); + const form = el('form', 'admin-instance-network-form mt-3'); + form.hidden = true; + form.noValidate = true; + const label = el('label', 'form-label', '新的公网 IP / CIDR'); + const input = el('input', 'form-control', ''); + input.type = 'text'; input.name = 'public_ip_cidr'; input.required = true; input.maxLength = 64; + input.autocomplete = 'off'; input.spellcheck = false; input.placeholder = '例如 216.236.1.20/24'; + input.value = String(vm.public_ip_cidr || vm.public_ip || ''); + label.append(input); + form.append(label, el('p', 'form-text mb-2', '仅允许该宿主机地址池中的可用 IPv4;本操作不会移动实例到其他宿主机。')); + const feedback = el('p', 'admin-instance-network-feedback text-muted fs-13 mb-2'); + feedback.hidden = true; feedback.setAttribute('role', 'status'); + const actions = el('div', 'd-flex justify-content-end gap-2 flex-wrap'); + const cancel = el('button', 'btn btn-light btn-sm', '取消'); + cancel.type = 'button'; cancel.dataset.networkEdit = 'cancel'; + const submit = el('button', 'btn btn-primary btn-sm', '提交更换'); + submit.type = 'submit'; + actions.append(cancel, submit); + form.append(feedback, actions); + section.append(form); + + if (!canManage) { + section.append(el('p', 'text-muted fs-12 mt-3 mb-0', '当前管理员仅可查看,超级管理员才可以修改实例网络。')); + } + form.addEventListener('submit', async event => { + event.preventDefault(); + if (state.networkRequest || !canManage) return; + const value = input.value.trim(); + if (!/^\d{1,3}(?:\.\d{1,3}){3}\/\d{1,2}$/.test(value)) { + feedback.hidden = false; feedback.className = 'admin-instance-network-feedback text-danger fs-13 mb-2'; + feedback.textContent = '请输入有效的 IPv4 CIDR,例如 216.236.1.20/24。'; + input.focus(); return; + } + const controller = new AbortController(); state.networkRequest = controller; + input.disabled = true; submit.disabled = true; cancel.disabled = true; + feedback.hidden = false; feedback.className = 'admin-instance-network-feedback text-muted fs-13 mb-2'; + feedback.textContent = '正在提交网络变更任务,请勿重复提交…'; + try { + const result = await mutate(`/api/v1/admin/instances/${encodeURIComponent(vm.id)}/network`, { + public_ip_cidr: value, confirm_restart: true, + }, controller); + const jobId = result?.job_id ?? result?.job?.id ?? result?.operation_id; + const status = result?.job?.status || result?.status; + feedback.className = `admin-instance-network-feedback ${status === 'failed' ? 'text-danger' : 'text-success'} fs-13 mb-2`; + feedback.textContent = jobId + ? `网络变更任务已创建 #${jobId}(${jobStatus(status || 'queued')})。实例将在后台重启应用新地址。` + : '网络变更请求已提交,实例将在后台重启应用新地址。'; + form.hidden = true; + const edit = section.querySelector('[data-network-edit="open"]'); + if (edit) { edit.disabled = false; edit.setAttribute('aria-expanded', 'false'); } + detailNotice(jobId ? `网络变更任务已创建 #${jobId},请在任务记录中核对执行结果。` : '网络变更请求已提交,请在任务记录中核对执行结果。'); + } catch (error) { + if (controller.signal.aborted && controller.signal.reason !== 'timeout') return; + feedback.className = 'admin-instance-network-feedback text-danger fs-13 mb-2'; + feedback.textContent = error.message; + input.disabled = false; submit.disabled = false; cancel.disabled = false; + } finally { + if (state.networkRequest === controller) state.networkRequest = null; + } + }); + return section; +} + function renderDetail(payload) { const vm = payload.instance; if (!vm || String(vm.id) !== state.detailId) throw new Error('实例详情与请求不一致,请重新打开。'); @@ -333,7 +450,8 @@ function renderDetail(payload) { const uuid = el('span', 'admin-instance-ip text-break'); uuid.append(el('span', 'admin-mono', text(vm.uuid))); if (vm.uuid) uuid.append(copyButton(vm.uuid, '复制 UUID')); - byId('instance-panel-basic').replaceChildren(infoList([ + const basic = byId('instance-panel-basic'); + basic.replaceChildren(infoList([ ['实例编号', `#${vm.id}`], ['UUID', uuid], ['引擎标识', text(vm.engine_name, '未记录')], ['生命周期', vm.display?.lifecycle], ['所属用户', text(vm.user_name, `用户 #${vm.user_id}`)], ['用户 ID', vm.user_id], ['宿主机', text(vm.host_name)], ['地区', text(vm.region, '未记录')], @@ -342,7 +460,7 @@ function renderDetail(payload) { ['DNS', Array.isArray(vm.dns_servers) ? text(vm.dns_servers.join('、'), '未记录') : text(vm.dns_servers, '未记录')], ['带宽上限', vm.bandwidth_mbps ? `${vm.bandwidth_mbps} Mbps` : '未记录'], ['创建时间', date(vm.created_at)], - ])); + ]), networkEditor(vm)); byId('instance-panel-service').replaceChildren(infoList([ ['套餐', text(vm.plan_name, '无关联套餐')], ['服务状态', vm.display?.service], ['网络状态', vm.display?.network], ['服务到期', vm.service_status === 'exempt' ? '免计费' : date(vm.service_expires_at)], @@ -401,6 +519,8 @@ function lockDetailScroll() { function closeDetail() { state.detailRequest?.abort(); state.detailRequest = null; + state.networkRequest?.abort('closed'); + state.networkRequest = null; state.detailId = null; const dialog = byId('instance-detail'); if (dialog.open) dialog.close(); @@ -480,6 +600,23 @@ if (root) { } const tab = event.target.closest('[data-instance-tab]'); if (tab) chooseTab(tab.dataset.instanceTab); + const networkAction = event.target.closest('[data-network-edit]'); + if (networkAction) { + const section = networkAction.closest('.admin-instance-network-settings'); + const form = section?.querySelector('.admin-instance-network-form'); + const input = form?.elements?.namedItem('public_ip_cidr'); + const feedback = section?.querySelector('.admin-instance-network-feedback'); + if (form && networkAction.dataset.networkEdit === 'open') { + form.hidden = false; networkAction.setAttribute('aria-expanded', 'true'); + feedback.hidden = true; input?.focus(); + } else if (form && networkAction.dataset.networkEdit === 'cancel') { + form.hidden = true; + const opener = section.querySelector('[data-network-edit="open"]'); + opener?.setAttribute('aria-expanded', 'false'); + if (input) form.reset(); + if (feedback) feedback.hidden = true; + } + } const button = event.target.closest('[data-copy]'); if (button) void copy(button.dataset.copy); const link = event.target.closest('a[href]'); diff --git a/web/public/theme/venix/css/admin-home.css b/web/public/theme/venix/css/admin-home.css index 379fa011..9aad6baa 100644 --- a/web/public/theme/venix/css/admin-home.css +++ b/web/public/theme/venix/css/admin-home.css @@ -329,6 +329,53 @@ html.admin-instance-detail-open body { overflow-wrap: anywhere; } +[data-admin-instance-drawer] .admin-instance-network-settings { + padding-top: 20px; + border-top: 1px solid var(--bs-border-color, #e8eef5); +} + +[data-admin-instance-drawer] .admin-instance-network-current { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + min-width: 0; + padding: 12px 14px; + border: 1px solid #dce5ef; + border-radius: 8px; + background: #fbfcfe; +} + +[data-admin-instance-drawer] .admin-instance-network-current strong { + min-width: 0; + color: #08785b; + overflow-wrap: anywhere; + text-align: right; +} + +[data-admin-instance-drawer] .admin-instance-network-form { + padding: 14px; + border: 1px solid rgba(24, 168, 127, 0.24); + border-radius: 8px; + background: rgba(93, 216, 158, 0.07); +} + +[data-admin-instance-drawer] .admin-instance-network-form .form-label { + margin-bottom: 7px; + color: #344054; + font-weight: 800; +} + +[data-admin-instance-drawer] .admin-instance-network-form .form-text { + color: #7d8a9c; + line-height: 1.5; +} + +[data-admin-instance-drawer] .admin-instance-network-feedback { + margin-top: 8px; + overflow-wrap: anywhere; +} + [data-admin-instance-drawer] [hidden] { display: none !important; } @@ -372,6 +419,15 @@ html.admin-instance-detail-open body { [data-admin-instance-drawer] .admin-instance-details { grid-template-columns: 94px minmax(0, 1fr); } + + [data-admin-instance-drawer] .admin-instance-network-current { + align-items: flex-start; + flex-direction: column; + } + + [data-admin-instance-drawer] .admin-instance-network-current strong { + text-align: left; + } } .admin-stat-card h3 { diff --git a/web/tests/CloudProtocolTest.php b/web/tests/CloudProtocolTest.php index 216fc98c..ba0bf095 100644 --- a/web/tests/CloudProtocolTest.php +++ b/web/tests/CloudProtocolTest.php @@ -65,6 +65,26 @@ namespace { 'Generated guest passwords repeat or retain a fixed prefix.'); $assert(strlen(CloudInput::password('Aa1!' . str_repeat('x', 124))) === 128, 'Guest manual password bounds wrong.'); + $assert(CloudInput::publicIpCidr('203.0.113.10/24') === '203.0.113.10/24' + && CloudInput::publicIpCidr('198.51.100.2/32') === '198.51.100.2/32', + 'Network-change IPv4 CIDR validation rejected a valid public address.'); + foreach (['203.0.113.10', '203.0.113.10/0', '203.0.113.10/33', + '2001:db8::10/64', '203.0.113.999/24', '203.0.113.10/24/1'] as $badCidr) { + try { + CloudInput::publicIpCidr($badCidr); + throw new RuntimeException('Invalid network-change CIDR accepted: ' . $badCidr); + } catch (CloudError $expected) { + $assert($expected->httpStatus === 422, 'Invalid network-change CIDR returned an unexpected status.'); + } + } + $controllerSource = file_get_contents(dirname(__DIR__) . '/app/Controllers/CloudAdminInstanceController.php'); + $workerSource = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudWorkerService.php'); + $assert(is_string($controllerSource) && str_contains($controllerSource, "CloudAccess::manage($actor)") + && str_contains($controllerSource, "'network_change'") + && str_contains($controllerSource, "'/network'") + && is_string($workerSource) && str_contains($workerSource, "\$job->kind === 'network_change'") + && str_contains($workerSource, "引擎成功结果缺少已确认的公网 IP"), + 'Administrator network-change route lost its super-admin queue or post-engine confirmation contract.'); $automaticName = CloudInput::generateInstanceName(); $assert(preg_match('/^vm-[abcdefghjkmnpqrstuvwxyz23456789]{6}$/D', $automaticName) === 1