feat: add admin instance settings controls

dev
admin 2 months ago
parent a442dd0292
commit 95787ca9c3

@ -14,7 +14,8 @@ from virsh_panel.cloud_init import (
_build_seed_iso, _enable_network_updates, build_seed_iso,
generate_root_password,
hash_root_password,
read_seed_network, replace_seed_network, validate_cloud_network,
read_seed_network, replace_seed_network, replace_seed_settings,
validate_cloud_network, validate_guest_hostname,
)
@ -102,6 +103,22 @@ def test_manual_root_password_requires_ascii_and_all_character_classes(invalid):
hash_root_password(invalid)
@pytest.mark.parametrize("value", [
"node-1", "node.example.com", "A-Node.Example",
])
def test_guest_hostname_is_canonical_and_bounded(value):
assert validate_guest_hostname(value) == value.lower()
@pytest.mark.parametrize("value", [
"", ".node", "node.", "node..example", "-node", "node-",
"node_name", "node with spaces", "节点", "a" * 64,
])
def test_guest_hostname_rejects_unsafe_values(value):
with pytest.raises(ValueError):
validate_guest_hostname(value)
def test_generated_root_password_always_meets_policy():
assert ROOT_PASSWORD_ALPHABET == (
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
@ -442,3 +459,32 @@ def test_replace_seed_network_rejects_non_panel_seed():
replace_seed_network(
b"not-an-iso", "8.8.8.19/28", "8.8.8.17", ["8.8.8.8"],
)
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_replace_seed_settings_rotates_generation_without_exposing_password():
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()), "settings-vm", "52:54:00:12:34:56", validated,
)
changed = replace_seed_settings(
seed, hostname="Node.Example", root_password_hash=hash_root_password(
"Another-strong-password-2026!"
), ssh_public_key=PUBLIC_KEY,
)
user_data = _user_data(changed)
root = user_data["users"][0]
assert root["ssh_authorized_keys"] == [PUBLIC_KEY]
assert root["lock_passwd"] is False
assert root["hashed_passwd"].startswith("$6$")
assert GUEST_PASSWORD.encode() not in changed
assert b"Another-strong-password-2026!" not in changed
assert user_data["ssh_pwauth"] is True
assert _meta_data(changed)["local-hostname"] == "node.example"
assert _meta_data(changed)["instance-id"].startswith("virt-cloud-settings-")
assert read_seed_network(changed) == read_seed_network(seed)

@ -737,6 +737,57 @@ class VMServiceTests(unittest.TestCase):
self.assertEqual(ET.tostring(domain.root), before)
self.assertEqual(self.backend.shutdown_calls, 0)
def test_cloud_settings_change_restarts_and_returns_no_credentials(self):
service = self.cloud_service()
spec = self.cloud_spec()
created = self.create_cloud_vm(service, spec)
domain = self.backend.domains[0]
seed_name = domain.root.find(
f"./metadata/{{{self.service_module.PANEL_NS}}}managed").get("seed-volume")
with patch.object(self.service_module, "replace_seed_settings",
return_value=b"NEW-SETTINGS-SEED"), \
patch.object(self.service_module, "read_seed_network", return_value={
"public_ip_cidr": spec["public_ip_cidr"],
"gateway": spec["gateway"],
"dns_servers": spec["dns_servers"],
"mac": domain.root.find("./devices/interface/mac").get("address"),
}):
result = service.change_cloud_vm_settings(
created["uuid"], hostname="node.example",
root_password_hash="$6$rounds=100000$abcdefghijklmnop$" + "a" * 86,
ssh_public_key=spec["guest_ssh_public_key"],
confirm_restart=True,
)
self.assertTrue(result["settings_changed"])
self.assertEqual(result["hostname"], "node.example")
self.assertEqual(result["vm"]["state"], "running")
self.assertNotIn("root_password", result)
self.assertNotIn("ssh_public_key", result)
self.assertEqual(self.backend.shutdown_calls, 1)
managed = domain.root.find(
f"./metadata/{{{self.service_module.PANEL_NS}}}managed")
self.assertEqual(managed.get("guest-hostname"), "node.example")
self.assertEqual(
bytes(self.backend.pools["images"].volumes[seed_name].contents),
b"NEW-SETTINGS-SEED",
)
def test_cloud_settings_change_requires_restart_confirmation(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 patch.object(self.service_module, "replace_seed_settings",
side_effect=AssertionError("must validate confirmation first")), \
self.assertRaises(self.error_type) as raised:
service.change_cloud_vm_settings(
created["uuid"], hostname="node.example", 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_cloud_network_change_rejects_gateway_or_dns_drift(self):
service = self.cloud_service()
spec = self.cloud_spec()

@ -30,8 +30,8 @@ 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,
validate_cloud_network,
_validate_guest_auth, _validate_ssh_public_key, generate_root_password,
hash_root_password, validate_cloud_network, validate_guest_hostname,
)
from .cloud_templates import (
TemplateError, TemplateStore, download_verified_image, image_metadata_for,
@ -230,6 +230,24 @@ class ChangeNetworkBody(BaseModel):
confirm_restart: bool = False
class VMSettingsBody(BaseModel):
model_config = ConfigDict(extra="forbid")
# Every field is optional so an administrator can change one setting at a
# time. The validator below rejects an empty patch; omitted credentials
# are preserved from the existing cloud-init seed.
hostname: str | None = Field(default=None, max_length=253)
root_password: SecretStr | None = Field(default=None, min_length=12, max_length=128)
ssh_public_key: str | None = Field(default=None, max_length=16384)
confirm_restart: bool = False
@model_validator(mode="after")
def require_setting(self):
if self.hostname is None and self.root_password is None and self.ssh_public_key is None:
raise ValueError("至少需要修改一项虚拟机设置")
return self
class SSHKeyBody(BaseModel):
model_config = ConfigDict(extra="forbid")
@ -3730,6 +3748,92 @@ def create_app(
result = {**result, "warning": warning}
return result
@app.post("/api/v1/vms/{vm_id}/settings")
def change_vm_settings(
vm_id: str,
body: VMSettingsBody,
_session: Session = Depends(require_admin_write),
):
"""Change guest hostname/root credentials from the admin boundary.
The public-key value is validated directly from this request. This
endpoint never accepts an SSH-key ID and never reads the tenant key
catalog. Password hashing and credential persistence happen inside
the authenticated engine so plaintext is not written to operation
records or logs.
"""
with reinstall_lock, rescue_lock:
forbid_long_job_during_update()
profile = current_profile()
canonical_id = require_vm_access(_session, profile, vm_id)
if (template_scope(profile), canonical_id) in pending_reinstalls:
raise VMError("虚拟机正在重装系统,暂时不能修改设置", 409)
if (host_scope(profile), canonical_id) in pending_rescues:
raise VMError("虚拟机正在切换救援模式,请等待任务完成", 409)
hostname = body.hostname
if hostname is not None:
try:
hostname = validate_guest_hostname(hostname)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
public_key = body.ssh_public_key
if public_key is not None:
try:
public_key = _validate_ssh_public_key(public_key.strip())
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
password = (body.root_password.get_secret_value()
if body.root_password is not None else None)
password_hash = None
if password is not None:
try:
password_hash = hash_root_password(password)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
service = new_service(profile)
current_vm = service.get_vm(canonical_id)
if (not current_vm.get("managed")
or current_vm.get("os_source") != "cloud_template"):
raise VMError("只有面板创建的公网云镜像虚拟机支持修改设置", 409)
result = service.change_cloud_vm_settings(
canonical_id,
hostname=hostname,
root_password_hash=password_hash,
ssh_public_key=public_key,
confirm_restart=body.confirm_restart,
)
# Keep the panel's encrypted reveal credential in sync only after
# the engine confirms the seed was replaced. A missing legacy
# record is left untouched rather than inventing an auth mode.
existing = get_credential(profile, canonical_id)
if password is not None or public_key is not None:
if existing is not None:
generation = existing["generation"]
auth_mode = existing["auth_mode"]
saved_password = existing.get("password")
else:
generation = (result.get("vm", {}).get("credential_generation")
if isinstance(result.get("vm"), dict) else None)
if not isinstance(generation, str) or not generation:
generation = f"panel-seed-{canonical_id}.iso"
auth_mode = "ssh_key" if public_key is not None and password is None else "password"
saved_password = None
if password is not None:
saved_password = password
auth_mode = "ssh_key_password" if public_key is not None or auth_mode in {
"ssh_key", "ssh_key_password"
} else "password"
elif public_key is not None and auth_mode == "password":
auth_mode = "ssh_key_password"
save_credential(profile, canonical_id, auth_mode, generation, saved_password)
LOG.info("vm settings changed: uuid=%s admin=%s", canonical_id, _session.username)
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:

@ -20,6 +20,10 @@ from typing import Any
_VM_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,62}\Z")
# Linux host names are case-insensitive DNS labels. Keep the panel contract
# deliberately narrower than the kernel's permissive hostname(5) parser so a
# pasted value can never become a cloud-init directive or an ambiguous FQDN.
_HOSTNAME_LABEL = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\Z")
_MAC = re.compile(r"(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}\Z")
_NETWORK_POLICY_KEY = "virt-cloud-network-policy"
_NETWORK_POLICY_VALUE = "boot-v1"
@ -46,6 +50,39 @@ ROOT_PASSWORD_ALPHABET = (
)
def validate_guest_hostname(value: Any) -> str:
"""Return a canonical guest hostname suitable for cloud-init metadata.
A single-label hostname and a DNS-style FQDN are both accepted. Leading
or trailing dots, empty labels, underscores, whitespace, Unicode and
control characters are rejected; the returned value is lower-case so a
retry of the same settings request is deterministic.
"""
if not isinstance(value, str):
raise ValueError("主机名格式无效")
hostname = value.strip().lower()
if not 1 <= len(hostname) <= 253 or hostname.endswith("."):
raise ValueError("主机名长度必须为 1 到 253 个字符")
labels = hostname.split(".")
if any(not _HOSTNAME_LABEL.fullmatch(label) for label in labels):
raise ValueError("主机名只能包含字母、数字、连字符和点,且每段不能以连字符开头或结尾")
return hostname
def default_guest_hostname(name: str, vm_uuid: str | None = None) -> str:
"""Derive the initial guest hostname using the same rule as seed creation."""
if not isinstance(name, str) or not _VM_NAME.fullmatch(name):
raise ValueError("虚拟机名称无效")
hostname = re.sub(r"[^a-z0-9-]", "-", name.lower()).strip("-")[:63]
if hostname:
return hostname
try:
suffix = str(uuid.UUID(vm_uuid)).replace("-", "")[:8] if vm_uuid else "guest"
except (ValueError, TypeError, AttributeError):
suffix = "guest"
return f"vm-{suffix}"
def _root_password_has_required_classes(password: str) -> bool:
return (
any(char in ROOT_PASSWORD_UPPERCASE for char in password)
@ -278,9 +315,7 @@ def build_seed_iso(
# Keep Linux hostname valid even when the libvirt VM name contains dots or
# underscores. The libvirt name itself remains unchanged.
hostname = re.sub(r"[^a-z0-9-]", "-", name.lower()).strip("-")[:63]
if not hostname:
hostname = f"vm-{instance_id[:8]}"
hostname = default_guest_hostname(name, instance_id)
use_public_key = bool(network["guest_ssh_public_key"])
use_password = bool(network.get("root_password_hash"))
root_user: dict[str, Any] = {"name": "root", "lock_passwd": not use_password}
@ -595,6 +630,236 @@ def replace_seed_network(
raise ValueError("原 cloud-init 网络配置格式无效") from exc
def _read_seed_files(seed: bytes) -> dict[str, bytes]:
"""Read the three bounded files from a panel-generated NoCloud seed."""
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()
return files
def _decode_seed_user_data(user_data: bytes) -> dict[str, Any]:
"""Decode the bounded JSON cloud-config emitted by this panel."""
prefix = b"#cloud-config\n"
if (not isinstance(user_data, bytes) or not user_data
or len(user_data) > 256 * 1024
or not user_data.startswith(prefix)):
raise ValueError("原 cloud-init 用户数据格式无效")
try:
value = json.loads(user_data[len(prefix):])
except (TypeError, ValueError, UnicodeError, json.JSONDecodeError) as exc:
raise ValueError("原 cloud-init 用户数据格式无效") from exc
if not isinstance(value, dict) or not value:
raise ValueError("原 cloud-init 用户数据格式无效")
return value
def _root_user(config: dict[str, Any]) -> dict[str, Any]:
users = config.get("users")
if not isinstance(users, list) or len(users) > 32:
raise ValueError("原 cloud-init 用户配置格式无效")
matches = [item for item in users
if isinstance(item, dict) and item.get("name") == "root"]
if len(matches) != 1:
raise ValueError("原 cloud-init root 用户配置格式无效")
root = matches[0]
lock_passwd = root.get("lock_passwd")
if lock_passwd is not None and not isinstance(lock_passwd, bool):
raise ValueError("原 cloud-init root 用户配置格式无效")
existing_hash = root.get("hashed_passwd")
if existing_hash is not None:
try:
_validate_guest_auth("", existing_hash)
except ValueError as exc:
raise ValueError("原 cloud-init root 密码配置格式无效") from exc
if lock_passwd is True:
raise ValueError("原 cloud-init root 密码配置无效")
keys = root.get("ssh_authorized_keys")
if keys is not None:
if (not isinstance(keys, list) or len(keys) > 64
or any(not isinstance(item, str) for item in keys)):
raise ValueError("原 cloud-init SSH 公钥配置格式无效")
for key in keys:
try:
_validate_ssh_public_key(key)
except ValueError as exc:
raise ValueError("原 cloud-init SSH 公钥配置格式无效") from exc
return root
def _update_root_sshd_config(config: dict[str, Any], *, use_password: bool) -> None:
"""Keep the panel-managed root sshd drop-in aligned with credentials."""
if not isinstance(use_password, bool):
raise ValueError("root 密码配置无效")
write_files = config.get("write_files")
if write_files is None:
write_files = []
config["write_files"] = write_files
if not isinstance(write_files, list) or len(write_files) > 128:
raise ValueError("原 cloud-init 写入文件配置格式无效")
path = "/etc/ssh/sshd_config.d/00-virsh-panel-root.conf"
matches = [item for item in write_files
if isinstance(item, dict) and item.get("path") == path]
if len(matches) > 1:
raise ValueError("原 cloud-init SSH 配置重复")
content = (
("PermitRootLogin yes\nPasswordAuthentication yes\n" if use_password
else "PermitRootLogin prohibit-password\nPasswordAuthentication no\n")
+ "KbdInteractiveAuthentication no\n"
)
if matches:
item = matches[0]
if (item.get("permissions", "0644") != "0644"
or any(key not in {"path", "content", "permissions"}
for key in item)):
raise ValueError("原 cloud-init SSH 配置格式无效")
item["content"] = content
item["permissions"] = "0644"
else:
write_files.append({"path": path, "content": content,
"permissions": "0644"})
config["ssh_pwauth"] = use_password
config["disable_root"] = False
def _replace_root_authorized_keys(config: dict[str, Any], public_key: str) -> None:
"""Make the requested SSH key replacement explicit and deterministic.
``users[].ssh_authorized_keys`` is retained for distro compatibility, but
a panel-managed write_files entry guarantees that an old authorized_keys
line is replaced rather than merely appended by a distro cloud-init
implementation. The key has already passed strict OpenSSH validation and
is JSON-encoded, so no shell interpolation is involved.
"""
public_key = _validate_ssh_public_key(public_key)
write_files = config.get("write_files")
if write_files is None:
write_files = []
config["write_files"] = write_files
if (not isinstance(write_files, list) or len(write_files) > 128
or any(not isinstance(item, dict) for item in write_files)):
raise ValueError("原 cloud-init 写入文件配置格式无效")
path = "/root/.ssh/authorized_keys"
matches = [item for item in write_files if item.get("path") == path]
if len(matches) > 1:
raise ValueError("原 cloud-init SSH 公钥文件配置重复")
replacement = {
"path": path,
"content": public_key + "\n",
"owner": "root:root",
"permissions": "0600",
}
if matches:
item = matches[0]
if any(key not in {"path", "content", "owner", "permissions"}
for key in item):
raise ValueError("原 cloud-init SSH 公钥文件配置格式无效")
item.clear()
item.update(replacement)
else:
write_files.append(replacement)
def replace_seed_settings(
seed: bytes,
*,
hostname: str | None = None,
root_password_hash: str | None = None,
ssh_public_key: str | None = None,
) -> bytes:
"""Replace panel-managed guest hostname/password/key in a NoCloud seed.
``None`` means "leave this setting unchanged"; an empty value is never a
request to clear credentials. The metadata instance ID is rotated so
cloud-init treats the next boot as a new panel configuration and applies
the changed users/hostname modules. Network data is copied unchanged and
is validated through :func:`read_seed_network` before any output is built.
"""
if hostname is None and root_password_hash is None and ssh_public_key is None:
raise ValueError("至少需要修改一项虚拟机设置")
if hostname is not None:
hostname = validate_guest_hostname(hostname)
if root_password_hash is not None:
try:
_validate_guest_auth("", root_password_hash)
except ValueError as exc:
raise ValueError("root 密码哈希格式无效") from exc
if ssh_public_key is not None:
ssh_public_key = _validate_ssh_public_key(ssh_public_key)
files = _read_seed_files(seed)
try:
metadata = _decode_seed_metadata(files["meta-data"])
# Also verify that this is a panel network seed before retaining it.
read_seed_network(seed)
# Upgrade legacy panel seeds to the network-on-boot policy while the
# settings generation is already being rotated. This keeps a later
# IP replacement from silently losing its cloud-init refresh hook.
user_data = _decode_seed_user_data(
_enable_network_updates(files["user-data"])
)
root = _root_user(user_data)
except (KeyError, TypeError, ValueError) as exc:
raise ValueError("原 cloud-init 配置格式无效") from exc
if hostname is not None:
metadata["local-hostname"] = hostname
if not isinstance(metadata.get("local-hostname"), str):
raise ValueError("原 cloud-init 主机名配置格式无效")
if root_password_hash is not None:
root["hashed_passwd"] = root_password_hash
root["lock_passwd"] = False
if ssh_public_key is not None:
root["ssh_authorized_keys"] = [ssh_public_key]
_replace_root_authorized_keys(user_data, ssh_public_key)
# A panel-generated seed either has a validated hash or explicitly locks
# root. Preserve the existing state for key-only changes; changing a
# password always enables password authentication above.
use_password = bool(root.get("hashed_passwd"))
if "hashed_passwd" not in root and root.get("lock_passwd") is False:
# Do not silently preserve a malformed unlocked root record.
raise ValueError("原 cloud-init root 密码配置格式无效")
root["lock_passwd"] = not use_password
_update_root_sshd_config(user_data, use_password=use_password)
user_data = json.loads(json.dumps(user_data, ensure_ascii=True))
metadata["instance-id"] = f"virt-cloud-settings-{uuid.uuid4().hex}"
metadata[_NETWORK_POLICY_KEY] = _NETWORK_POLICY_VALUE
rebuilt = (
("/USERDATA.;1", "user-data", "/user-data",
b"#cloud-config\n" + json.dumps(user_data, ensure_ascii=True).encode("ascii") + b"\n"),
("/METADATA.;1", "meta-data", "/meta-data",
json.dumps(metadata, ensure_ascii=True).encode("ascii") + b"\n"),
("/NETWORK.;1", "network-config", "/network-config",
files["network-config"]),
)
return _build_seed_iso(rebuilt)
def read_seed_network(seed: bytes) -> dict[str, Any]:
"""Read the network settings from a panel-created NoCloud ISO.

@ -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|network|rescue|console-ticket)",
r"vms", rf"vms/{VM_ID}/(?:actions|credential|reinstall|network|settings|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|network|"
rf"vms/{VM_ID}/(?:actions|reinstall|network|settings|"
rf"(?:service|network)-(?:suspend|resume)|"
rf"rescue(?:/exit|/force-start)?)",
resource)))

@ -24,8 +24,10 @@ from typing import Any, Callable, Iterator
import libvirt
from virsh_panel.cloud_init import (
build_seed_iso, read_seed_network, replace_seed_network,
validate_cloud_network,
_validate_guest_auth, _validate_ssh_public_key,
build_seed_iso, default_guest_hostname, read_seed_network,
replace_seed_network, replace_seed_settings, validate_cloud_network,
validate_guest_hostname,
)
from virsh_panel.metrics import RawVMStats
from virsh_panel.user_isos import (
@ -575,6 +577,7 @@ class VMService:
"created_at": managed.get("created-at") if managed is not None else None,
"credential_generation": managed.get("seed-volume") if os_source == "cloud_template" else None,
"os_name": managed.get("os-name") if os_source == "cloud_template" else None,
"hostname": managed.get("guest-hostname") if os_source == "cloud_template" else None,
"os_source": os_source,
"install_iso": managed.get("install-iso") if os_source == "iso" else None,
"rescue_mode": rescue is not None,
@ -672,6 +675,10 @@ class VMService:
managed.get("os-name")
if managed is not None and os_source == "cloud_template" else None
),
"hostname": (
managed.get("guest-hostname")
if managed is not None and os_source == "cloud_template" else None
),
"os_source": os_source,
"install_iso": (
managed.get("install-iso")
@ -955,6 +962,14 @@ class VMService:
managed.set("display-name", spec["name"])
if spec.get("created_at"):
managed.set("created-at", spec["created_at"])
if spec.get("source") == "cloud" or spec.get("os_name") is not None:
# Keep the guest-side hostname visible to the panel without
# reading cloud-init user-data (which contains credentials) on
# every inventory call. Older VMs may not have this marker.
try:
managed.set("guest-hostname", default_guest_hostname(spec["name"], vm_uuid))
except ValueError as exc:
raise VMError("无法生成虚拟机初始主机名", 422) from exc
if "iso" in spec:
# The installation media does not prove which OS was installed.
managed.set("os-source", "iso")
@ -2745,6 +2760,248 @@ class VMService:
"was_running": was_running,
}
def change_cloud_vm_settings(
self,
vm_id: str,
*,
hostname: str | None = None,
root_password_hash: str | None = None,
ssh_public_key: str | None = None,
confirm_restart: bool = False,
progress: Callable[[str], None] | None = None,
) -> dict[str, Any]:
"""Update a panel cloud guest's hostname or root authentication.
The guest settings are carried by the existing NoCloud seed. The
operation writes a replacement seed only after validating the managed
VM and then defines the updated metadata before restarting a running
guest. Any deterministic failure restores the original seed and XML;
a transport error after QEMU has started is reported as uncertain and
intentionally keeps the new generation for reconciliation.
The method accepts a *hashed* root password. Plaintext credentials
must be converted by the authenticated API boundary and are never
logged, returned, or persisted by this service.
"""
if hostname is None and root_password_hash is None and ssh_public_key is None:
raise VMError("至少需要修改一项虚拟机设置", 422)
if confirm_restart is not True:
raise VMError("修改实例设置前必须确认会短暂重启虚拟机", 422)
if hostname is not None:
try:
hostname = validate_guest_hostname(hostname)
except ValueError as exc:
raise VMError(str(exc), 422) from exc
if root_password_hash is not None:
try:
_validate_guest_auth("", root_password_hash)
except ValueError as exc:
raise VMError("root 密码哈希格式无效", 422) from exc
if ssh_public_key is not None:
try:
ssh_public_key = _validate_ssh_public_key(ssh_public_key)
except 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:
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)
was_running = bool(domain.isActive())
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("只有面板创建的公网云镜像虚拟机支持修改设置", 409)
interfaces = original_root.findall("./devices/interface")
if len(interfaces) != 1:
raise VMError("虚拟机网卡配置已变化,已停止修改设置", 409)
interface = interfaces[0]
mac_node = interface.find("mac")
if mac_node is None or not mac_node.get("address"):
raise VMError("虚拟机 MAC 配置已变化,已停止修改设置", 409)
mac = mac_node.get("address").lower()
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"] != managed.get("public-ip-cidr")):
raise VMError("原配置盘的公网 IP 或 MAC 与虚拟机不一致,已停止修改设置", 409)
try:
replacement_seed = replace_seed_settings(
original_seed,
hostname=hostname,
root_password_hash=root_password_hash,
ssh_public_key=ssh_public_key,
)
except ImportError as exc:
raise VMError("面板缺少 pycdlib,无法修改 cloud-init 配置盘", 503) from exc
except ValueError as exc:
raise VMError("原 cloud-init 配置格式无效,已停止修改设置", 409) from exc
# Everything after a successful shutdown is inside one rollback
# boundary. A validation, upload or define failure must restore
# the original running state; otherwise a failed settings update
# would unexpectedly leave a previously running guest powered off.
old_xml = original_root
new_domain = domain
restored_domain = domain
switched = False
seed_touched = False
start_attempted = False
try:
if was_running:
phase("shutting_down")
try:
domain.shutdown()
except libvirt.libvirtError as exc:
try:
still_active = bool(domain.isActive())
except Exception as state_error:
raise VMError(
"虚拟机关机结果不确定,请查询实例状态;设置未修改", 502,
) from state_error
if still_active:
raise VMError("虚拟机正常关机失败,设置未修改", 409) from exc
raise VMError(
"虚拟机已关机但结果不确定,请查询实例状态;设置未修改", 502,
) 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 the inactive definition after shutdown. This
# protects the seed attachment 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")
if (inactive_managed is None
or inactive_managed.get("seed-volume") != old_seed.name()
or inactive_managed.get("public-ip-cidr") != managed.get("public-ip-cidr")):
raise VMError("关机后虚拟机配置已变化,设置修改已停止", 409)
new_root = ET.fromstring(old_xml)
new_managed = new_root.find(f"./metadata/{{{PANEL_NS}}}managed")
if new_managed is None:
raise VMError("虚拟机面板元数据已变化,设置修改已停止", 409)
if hostname is not None:
new_managed.set("guest-hostname", hostname)
phase("updating_settings")
current_capacity = int(old_seed.info()[1])
# Mark the volume before resize/upload. A short write must be
# restored as well; otherwise a partial seed can be booted.
seed_touched = True
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),
)
if hostname is not None:
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")
start_attempted = True
try:
new_domain.create()
except libvirt.libvirtError as exc:
try:
active_after_start_error = bool(new_domain.isActive())
except Exception as state_error:
raise VMError(
"虚拟机启动结果不确定,请查询实例状态;新配置已保留", 502,
) from state_error
if active_after_start_error:
# QEMU may have accepted the request despite a
# lost response. Keep the new generation for
# reconciliation instead of overwriting a live VM.
raise VMError(
"虚拟机已发送启动指令但结果不确定,请查询实例状态", 502,
) from exc
raise
except Exception as exc:
if start_attempted:
try:
active_after_failure = bool(new_domain.isActive())
except Exception as state_error:
raise VMError(
"实例设置修改结果不确定,请查询实例状态;新配置已保留", 502,
) from state_error
if active_after_failure:
raise VMError(
"实例设置修改结果不确定,请查询实例状态;新配置已保留", 502,
) from exc
restored = True
if seed_touched:
try:
self._upload_volume(conn, old_seed, iter((original_seed,)),
len(original_seed))
except Exception:
LOG.exception("Could not restore original settings 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 restored and was_running:
try:
if not restored_domain.isActive():
restored_domain.create()
if not restored_domain.isActive():
restored = False
except Exception:
LOG.exception("Could not restart original VM after settings rollback: %s", vm_id)
restored = False
if not restored:
raise VMError(
"实例设置修改失败且自动回滚不完整;请检查虚拟机配置", 502,
) from exc
if isinstance(exc, VMError):
raise
LOG.warning("Could not update VM settings %s: %s", vm_id, exc)
raise VMError("实例设置修改失败,已恢复原配置", 502) from exc
phase("completed")
result = self._vm_dict(new_domain)
result_hostname = (
hostname if hostname is not None
else (managed.get("guest-hostname") if managed is not None else None)
)
response: dict[str, Any] = {
"vm": result,
"settings_changed": True,
"was_running": was_running,
}
if result_hostname is not None:
response["hostname"] = result_hostname
return response
@staticmethod
def _requested_create_uuid(spec: dict[str, Any]) -> str | None:
requested_uuid = spec.get("vm_uuid")

@ -10,7 +10,10 @@ use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudEngineClient;
use App\Services\Cloud\CloudInput;
use App\Services\Cloud\CloudJobService;
use App\Services\Cloud\CloudOperationCatalog;
use App\Services\Cloud\CloudOperationErrorCatalog;
use App\Services\Cloud\CloudSecrets;
use App\Services\Cloud\CloudSSHKeys;
/** Administrator inventory snapshots plus explicitly queued VM mutations. */
final class CloudAdminInstanceController
@ -162,6 +165,136 @@ final class CloudAdminInstanceController
], 202)->withHeader('Cache-Control', 'no-store');
}
/**
* Queue a controlled guest-settings update for a panel-managed instance.
*
* The public-key field is intentionally parsed from this request only;
* unlike the tenant reinstall flow it never accepts an SSH-key id and
* never reads the owner's saved key collection. Password material stays
* in the encrypted job/credential path and is not returned to the browser.
*/
public function settings($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('只有处于活动状态的虚拟机可以修改实例设置', 409);
}
$body = CloudInput::object($request);
CloudInput::only($body, ['hostname', 'root_password', 'ssh_public_key', 'confirm_restart']);
if (($body['confirm_restart'] ?? false) !== true) {
throw new CloudError('修改实例设置前必须确认虚拟机会短暂重启');
}
$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'
|| (!is_string($spec['public_ip_cidr'] ?? null)
&& !is_string($spec['public_ip'] ?? null))) {
throw new CloudError('当前虚拟机不是支持实例设置的面板云镜像实例', 409);
}
$engineBody = ['confirm_restart' => true];
$existingCredential = self::credentialSnapshot($instance);
$credential = null;
$changed = false;
if (array_key_exists('hostname', $body)) {
if (!is_string($body['hostname']) || trim($body['hostname']) === '') {
throw new CloudError('主机名不能为空');
}
$engineBody['hostname'] = CloudInput::hostname($body['hostname']);
$changed = true;
}
if (array_key_exists('root_password', $body)) {
if (!is_string($body['root_password']) || $body['root_password'] === '') {
throw new CloudError('实例密码不能为空');
}
$password = CloudInput::password($body['root_password']);
$engineBody['root_password'] = $password;
$credential = ['password' => $password, 'login_name' => 'root',
'auth_mode' => 'password'];
$changed = true;
}
if (array_key_exists('ssh_public_key', $body)) {
if (!is_string($body['ssh_public_key']) || trim($body['ssh_public_key']) === '') {
throw new CloudError('SSH 公钥不能为空');
}
// Direct input only. Do not call CloudSSHKeys::owned() here.
$parsed = CloudSSHKeys::parse($body['ssh_public_key']);
$engineBody['ssh_public_key'] = $parsed['public_key'];
$changed = true;
}
if (!$changed) {
throw new CloudError('请至少填写一项需要修改的实例设置');
}
// Keep PHP's reveal metadata aligned with the guest seed. A key-only
// change preserves an existing password marker, while a password-only
// change preserves the fact that the old key remains in the guest.
// The public key itself is deliberately not copied into this record.
if (array_key_exists('root_password', $engineBody)
|| array_key_exists('ssh_public_key', $engineBody)) {
$previousMode = (string) ($existingCredential['auth_mode'] ?? '');
$previousPassword = $existingCredential['password'] ?? null;
$savedPassword = array_key_exists('root_password', $engineBody)
? $engineBody['root_password'] : $previousPassword;
$hasPassword = is_string($savedPassword) && $savedPassword !== '';
$hasKey = array_key_exists('ssh_public_key', $engineBody)
|| in_array($previousMode,
['password_and_key', 'ssh_key', 'ssh_key_password'], true);
$credential = [
'password' => $hasPassword ? $savedPassword : null,
'login_name' => 'root',
'auth_mode' => $hasPassword
? ($hasKey ? 'password_and_key' : 'password') : 'ssh_key',
];
}
$job = CloudJobService::enqueue($instance, $actor, 'instance_settings', 'POST',
'/settings', $engineBody, $credential);
$labels = CloudOperationCatalog::labels((string) $job->kind);
return $response->withJson([
'job_id' => (string) $job->id,
'status_url' => '/api/v1/jobs/' . $job->id,
'kind' => (string) $job->kind,
'kind_label' => $labels['kind_label'],
], 202)->withHeader('Cache-Control', 'no-store');
}
/**
* Read only the existing non-key credential metadata needed to preserve
* login-mode state across an administrator settings update. A malformed
* encrypted record must not be silently replaced with an incomplete DTO.
*/
private static function credentialSnapshot($instance): ?array
{
if ($instance->credential_cipher === null) {
return null;
}
try {
$value = CloudSecrets::decrypt((string) $instance->credential_cipher);
} catch (\Throwable $exception) {
throw new CloudError('实例凭据记录异常,暂不能修改实例设置', 503);
}
if (!is_array($value)
|| !in_array($value['auth_mode'] ?? null,
['password', 'password_and_key', 'ssh_key', 'ssh_key_password'], true)
|| (($value['password'] ?? null) !== null
&& !is_string($value['password']))
|| (in_array($value['auth_mode'],
['password', 'password_and_key', 'ssh_key_password'], true)
&& (!is_string($value['password'] ?? null)
|| $value['password'] === ''))
|| ($value['auth_mode'] === 'ssh_key'
&& ($value['password'] ?? null) !== null)) {
throw new CloudError('实例凭据记录异常,暂不能修改实例设置', 503);
}
return ['auth_mode' => (string) $value['auth_mode'],
'password' => $value['password'] ?? null];
}
private static function safeText($value, int $length): ?string
{
if (!is_string($value) || trim($value) !== $value || $value === ''

@ -369,6 +369,7 @@ final class CloudAdminInstanceService
'plan_name' => self::text($spec['plan_name'] ?? null, 120)
?? self::text($instance->plan_name, 120) ?? '',
'os_name' => self::text($spec['os_name'] ?? $spec['install_iso'] ?? null, 255) ?? '',
'guest_hostname' => self::hostname($spec['guest_hostname'] ?? $spec['hostname'] ?? null),
'public_ip' => $publicIp ?? '',
'vcpu' => self::positiveOrNull($spec['vcpu'] ?? null),
'memory_mib' => self::positiveOrNull($spec['memory_mib'] ?? null),
@ -444,6 +445,15 @@ final class CloudAdminInstanceService
? $value : null;
}
private static function hostname($value): ?string
{
if (!is_string($value) || strlen($value) > 253 || str_ends_with($value, '.')
|| preg_match('/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/D', $value) !== 1) {
return null;
}
return $value;
}
private static function jobText($value): ?string
{
// Progress and error text both cross the administrator API boundary;

@ -52,6 +52,30 @@ final class CloudInput
return $value;
}
/**
* Validate a guest hostname without accepting shell/control characters.
* Linux accepts a dotted hostname, but each label remains bounded so the
* value is safe to place in cloud-init metadata and administrator DTOs.
*/
public static function hostname($value): string
{
if (!is_string($value)) {
throw new CloudError('主机名格式无效');
}
$value = trim($value);
if ($value === '' || strlen($value) > 253 || str_ends_with($value, '.')) {
throw new CloudError('主机名最多 253 个字符,且不能以点结尾');
}
$labels = explode('.', $value);
foreach ($labels as $label) {
if ($label === '' || strlen($label) > 63
|| preg_match('/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/D', $label) !== 1) {
throw new CloudError('主机名只能包含英文、数字、连字符和点');
}
}
return strtolower($value);
}
public static function optionalName($value): ?string
{
if ($value === null || $value === '') {
@ -141,7 +165,7 @@ final class CloudInput
public static function safeResult(array $value): array
{
foreach ($value as $key => $item) {
if (preg_match('/password|secret|private.?key|passphrase|token|credential/i', (string) $key)) {
if (preg_match('/password|secret|(?:public|private).?key|ssh.?key|passphrase|token|credential/i', (string) $key)) {
unset($value[$key]);
} elseif (is_array($item)) {
$value[$key] = self::safeResult($item);

@ -24,6 +24,32 @@ final class CloudJobService
$body['public_ip_cidr'] ?? null
);
}
if ($kind === 'instance_settings') {
CloudInput::only($body, ['hostname', 'root_password', 'ssh_public_key', 'confirm_restart']);
if (($body['confirm_restart'] ?? false) !== true) {
throw new CloudError('修改实例设置前必须确认虚拟机会短暂重启');
}
$changed = false;
if (array_key_exists('hostname', $body)) {
$body['hostname'] = CloudInput::hostname($body['hostname']);
$changed = true;
}
if (array_key_exists('root_password', $body)) {
if (!is_string($body['root_password']) || $body['root_password'] === '') {
throw new CloudError('实例密码不能为空');
}
$body['root_password'] = CloudInput::password($body['root_password']);
$changed = true;
}
if (array_key_exists('ssh_public_key', $body)) {
$parsed = CloudSSHKeys::parse((string) $body['ssh_public_key']);
$body['ssh_public_key'] = $parsed['public_key'];
$changed = true;
}
if (!$changed) {
throw new CloudError('请至少填写一项需要修改的实例设置');
}
}
$locked = CloudInstance::where('id', $instance->id)->lockForUpdate()->first();
if ($locked === null || (string) $locked->status === 'deleted') {
throw new CloudError('虚拟机不存在', 404);

@ -18,6 +18,7 @@ final class CloudOperationCatalog
'rescue' => '救援操作',
'delete' => '删除实例',
'network_change' => '更换公网 IP',
'instance_settings' => '实例设置',
'service_suspend' => '到期停用',
'service_resume' => '恢复服务',
'network_suspend' => '限制网络',

@ -35,6 +35,8 @@ final class CloudOperationErrorCatalog
'重装系统失败,请查看面板日志',
'重装失败,已恢复原虚拟机定义及旧系统盘',
'网络修改失败,已恢复原配置',
'实例设置失败,已恢复原配置',
'实例设置修改失败,已恢复原配置',
'虚拟机名称已存在',
'虚拟机 UUID 已存在',
'虚拟机配置已变化,请重新提交救援操作',
@ -115,8 +117,9 @@ final class CloudOperationErrorCatalog
* adding a key to its JSON envelope.
*/
private const SAFE_RESULT_KEYS = [
'phase', 'status', 'state', 'uuid', 'name', 'job_id',
'phase', 'status', 'state', 'uuid', 'name', 'hostname', 'job_id',
'public_ip', 'public_ip_cidr', 'network_changed', 'skipped',
'settings_changed',
'service_was_running', 'service_was_running_hint', 'vm',
'vcpu', 'cpu_cores', 'memory_mib', 'ram_mib', 'disk_gib',
'os_source', 'os_name', 'install_iso', 'login_name',
@ -337,6 +340,7 @@ final class CloudOperationErrorCatalog
'rescue' => '救援操作失败,请核对实例状态后重试',
'delete', 'expiry_delete' => '删除实例失败,请核对实例状态后重试',
'network_change' => '更换公网 IP 失败,请核对实例状态后重试',
'instance_settings' => '实例设置失败,请核对实例状态后重试',
'service_suspend', 'service_resume', 'network_suspend', 'network_resume'
=> '实例策略执行失败,请稍后重试',
default => '虚拟机操作失败,请稍后重试',
@ -439,7 +443,7 @@ final class CloudOperationErrorCatalog
private static function safeResultScalar(string $key, $value)
{
if (is_bool($value)) {
return in_array($key, ['network_changed', 'skipped',
return in_array($key, ['network_changed', 'settings_changed', 'skipped',
'service_was_running', 'service_was_running_hint',
'autostart', 'managed'], true) ? $value : null;
}
@ -484,7 +488,7 @@ final class CloudOperationErrorCatalog
$number = (int) $value;
return $number >= 1 && $number <= $maximums[$key] ? $number : null;
}
if (in_array($key, ['network_changed', 'skipped',
if (in_array($key, ['network_changed', 'settings_changed', 'skipped',
'service_was_running', 'service_was_running_hint',
'autostart', 'managed'], true)) {
return null;
@ -528,6 +532,12 @@ final class CloudOperationErrorCatalog
if ($key === 'job_id' && preg_match('/^[A-Za-z0-9_-]{8,128}$/D', $value) !== 1) {
return null;
}
if ($key === 'hostname') {
if (strlen($value) > 253 || str_ends_with($value, '.')
|| preg_match('/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/D', $value) !== 1) {
return null;
}
}
if ($key === 'os_source' && !in_array($value, ['cloud_template', 'iso', 'unknown'], true)) {
return null;
}

@ -10,7 +10,8 @@ final class CloudSSHKeys
$parts = preg_split('/\s+/', trim($publicKey), 3);
$type = $parts[0] ?? '';
if (!in_array($type, ['ssh-ed25519', 'ssh-rsa', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521'], true)
|| strlen($publicKey) > 16384 || str_contains($publicKey, "\n")) {
|| strlen($publicKey) > 16384
|| preg_match('/[\x00-\x1f\x7f]/', $publicKey) === 1) {
throw new CloudError('请输入单行 OpenSSH 公钥,不是私钥');
}
$raw = base64_decode($parts[1] ?? '', true);

@ -570,6 +570,39 @@ final class CloudWorkerService
$instance->spec_json = json_encode($decoded,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE);
} elseif ($job->kind === 'instance_settings') {
// The engine must acknowledge the controlled seed
// replacement before PHP changes any cached metadata.
// Passwords and public keys are intentionally never
// copied into spec_json or result_json.
if (!is_array($result) || ($result['settings_changed'] ?? false) !== true) {
throw new CloudError('引擎成功结果缺少已确认的实例设置', 502);
}
if (isset($payload['credential'])
&& is_array($payload['credential'])) {
$instance->credential_cipher = CloudSecrets::encrypt(
$payload['credential']
);
}
$requested = is_array($payload['body'] ?? null)
? $payload['body'] : [];
$decoded = json_decode((string) $instance->spec_json, true);
if (!is_array($decoded) || array_is_list($decoded)) {
throw new CloudError('虚拟机配置记录损坏,无法保存实例设置', 409);
}
if (array_key_exists('hostname', $requested)) {
$confirmed = $result['hostname'] ?? null;
if (!is_string($confirmed)
|| $confirmed !== $requested['hostname']
|| preg_match('/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/D', $confirmed) !== 1
|| strlen($confirmed) > 253) {
throw new CloudError('引擎成功结果缺少已确认的主机名', 502);
}
$decoded['guest_hostname'] = $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',

@ -53,6 +53,7 @@ $app->group('/api/v1', function () {
$this->get('/admin/instances/{id:[0-9]+}', 'App\Controllers\CloudAdminInstanceController:detail');
$this->get('/admin/instances/{id:[0-9]+}/network-options', 'App\Controllers\CloudAdminInstanceController:networkOptions');
$this->patch('/admin/instances/{id:[0-9]+}/network', 'App\Controllers\CloudAdminInstanceController:network');
$this->patch('/admin/instances/{id:[0-9]+}/settings', 'App\Controllers\CloudAdminInstanceController:settings');
$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');

@ -9,6 +9,8 @@ const state = {
statusRequest: null, statusFailures: 0, detailRequest: null, detailId: null,
opener: null, scroll: null, networkRequest: null, networkOptionsRequest: null,
networkPollRequest: null, networkPollTimer: null, networkPollResolve: null, networkSerial: 0,
settingsRequest: null, settingsPollRequest: null, settingsPollTimer: null,
settingsPollResolve: null, settingsSerial: 0,
};
function el(tag, className = '', text) {
@ -179,7 +181,7 @@ async function api(path, controller) {
async function mutate(path, body, controller) {
if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) {
throw new Error('请通过 HTTPS 修改实例网络配置。');
throw new Error('请通过 HTTPS 修改实例配置。');
}
const timeout = setTimeout(() => controller.abort('timeout'), 30000);
try {
@ -499,6 +501,209 @@ function cancelNetworkActivity(reason = 'cancelled') {
state.networkSerial += 1;
}
function setSettingsFeedback(section, message, tone = 'muted') {
const node = section?.querySelector('[data-settings-feedback]');
if (!node) return;
node.hidden = !message;
node.className = `admin-instance-settings-feedback text-${tone} fs-13 mb-2`;
node.textContent = message || '';
}
function cancelSettingsActivity(reason = 'cancelled') {
clearTimeout(state.settingsPollTimer);
state.settingsPollTimer = null;
state.settingsPollResolve?.(false);
state.settingsPollResolve = null;
state.settingsPollRequest?.abort(reason);
state.settingsRequest?.abort(reason);
state.settingsPollRequest = null;
state.settingsRequest = null;
state.settingsSerial += 1;
}
function waitForSettingsPoll(ms, serial) {
return new Promise(resolve => {
clearTimeout(state.settingsPollTimer);
state.settingsPollResolve = resolve;
state.settingsPollTimer = setTimeout(() => {
state.settingsPollTimer = null;
state.settingsPollResolve = null;
resolve(serial === state.settingsSerial);
}, ms);
});
}
function settingsJobState(job) {
return String(job?.status || job?.job?.status || '').toLowerCase();
}
function settingsStatusPath(jobId, statusUrl) {
return typeof statusUrl === 'string' && statusUrl.startsWith('/api/v1/')
? statusUrl : `/api/v1/jobs/${encodeURIComponent(jobId)}`;
}
function settingsFormValues(form) {
const hostname = String(form.elements.namedItem('hostname')?.value || '').trim().toLowerCase();
const password = String(form.elements.namedItem('root_password')?.value || '');
const confirmation = String(form.elements.namedItem('root_password_confirmation')?.value || '');
const publicKey = String(form.elements.namedItem('ssh_public_key')?.value || '').trim();
if (!hostname && !password && !publicKey) throw new Error('请至少填写一项要修改的实例设置。');
if (hostname && !/^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/.test(hostname)) {
throw new Error('主机名只能包含英文、数字、连字符和点,每段不能以连字符开头或结尾,最多 253 个字符。');
}
if (password || confirmation) {
if (!password) throw new Error('请输入新的实例密码。');
if (password !== confirmation) throw new Error('两次输入的实例密码不一致。');
if (password.length < 12 || password.length > 128 || !/^[\x21-\x7e]+$/.test(password)
|| !/[A-Z]/.test(password) || !/[a-z]/.test(password)
|| !/[0-9]/.test(password) || !/[^A-Za-z0-9]/.test(password)) {
throw new Error('实例密码需为 12 至 128 位可打印字符,并包含大写、小写、数字和符号。');
}
}
if (publicKey) {
if (publicKey.length > 16384 || /[\r\n\x00-\x1f\x7f]/.test(publicKey)) {
throw new Error('SSH 公钥必须是一行且不能包含控制字符。');
}
if (!/^(?:ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp256|ecdsa-sha2-nistp384|ecdsa-sha2-nistp521)\s+[A-Za-z0-9+/]+={0,3}(?:\s+[^\r\n]*)?$/.test(publicKey)) {
throw new Error('请输入有效的单行 OpenSSH 公钥,不要粘贴私钥。');
}
}
const body = { confirm_restart: true };
if (hostname) body.hostname = hostname;
if (password) body.root_password = password;
if (publicKey) body.ssh_public_key = publicKey;
return body;
}
function settingsSetBusy(form, busy) {
for (const control of form.querySelectorAll('input, textarea, button')) {
control.disabled = busy;
}
}
function unlockSettingsForm(form, activeJob = false) {
if (!form) return;
for (const control of form.querySelectorAll('input, textarea, button')) {
control.disabled = activeJob;
}
}
async function pollSettingsJob(vm, section, jobId, statusUrl) {
const serial = state.settingsSerial;
const path = settingsStatusPath(jobId, statusUrl);
for (let attempt = 0; attempt < 150; attempt += 1) {
if (serial !== state.settingsSerial || state.detailId !== String(vm.id)) return;
const controller = new AbortController();
state.settingsPollRequest = controller;
try {
const job = await api(path, controller);
if (serial !== state.settingsSerial || state.detailId !== String(vm.id)) return;
const status = settingsJobState(job);
const phase = job?.phase || job?.job?.phase;
if (['succeeded', 'completed', 'done'].includes(status)) {
setSettingsFeedback(section, `任务 #${jobId} 已完成,正在刷新实例设置…`, 'success');
detailNotice(`实例设置任务 #${jobId} 已完成,正在刷新详情。`);
state.settingsPollRequest = null;
clearTimeout(state.settingsPollTimer);
state.settingsPollTimer = null;
await refreshDetail(vm.id);
return;
}
if (['failed', 'cancelled'].includes(status)) {
setSettingsFeedback(section, `任务 #${jobId}${phase ? `:${phase}` : '执行失败'},请修正设置后重试。`, 'danger');
section.dataset.settingsRetry = 'true';
unlockSettingsForm(section.querySelector('[data-instance-settings-form]'));
return;
}
if (status === 'uncertain') {
setSettingsFeedback(section, `任务 #${jobId} 状态待核对,不能重复提交;请先在任务记录确认结果。`, 'warning');
unlockSettingsForm(section.querySelector('[data-instance-settings-form]'), true);
return;
}
setSettingsFeedback(section, `任务 #${jobId} ${jobStatus(status || 'queued')}${phase ? ` · ${phase}` : ''}…`, 'muted');
} catch (error) {
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
if (serial !== state.settingsSerial) return;
setSettingsFeedback(section, `${error.message},将继续等待任务结果。`, 'warning');
} finally {
if (state.settingsPollRequest === controller) state.settingsPollRequest = null;
}
if (!await waitForSettingsPoll(Math.min(10000, 2000 + attempt * 250), serial)) return;
}
setSettingsFeedback(section, `任务 #${jobId} 仍在执行,请稍后刷新任务记录;不要重复提交。`, 'warning');
}
function settingsEditor(vm) {
const template = byId('admin-instance-settings-controls');
const controls = template?.content?.cloneNode(true);
const section = controls?.querySelector('[data-instance-settings]');
if (!section) return el('section');
const form = section.querySelector('[data-instance-settings-form]');
const current = section.querySelector('[data-settings-current-hostname]');
if (current) current.textContent = `当前主机名:${text(vm.guest_hostname, vm.hostname, '未记录')}`;
if (!form) return section;
const activeJob = Boolean(vm.active_job && ['queued', 'running', 'uncertain'].includes(String(vm.active_job.status)));
if (activeJob) {
unlockSettingsForm(form, true);
setSettingsFeedback(section, `实例已有任务 #${vm.active_job.id}(${jobStatus(vm.active_job.status)}),完成前不能修改实例设置。`, 'warning');
}
const submit = async event => {
event.preventDefault();
if (state.settingsRequest || (activeJob && section.dataset.settingsRetry !== 'true')) return;
let body;
try {
body = settingsFormValues(form);
if (!form.elements.namedItem('confirm_restart')?.checked) {
throw new Error('请先确认实例会重启。');
}
} catch (error) {
setSettingsFeedback(section, error.message, 'danger');
return;
}
const controller = new AbortController();
state.settingsRequest = controller;
delete section.dataset.settingsRetry;
settingsSetBusy(form, true);
setSettingsFeedback(section, '正在创建实例设置任务,请勿重复提交…', 'muted');
try {
const result = await mutate(`/api/v1/admin/instances/${encodeURIComponent(vm.id)}/settings`, body, controller);
const jobId = result?.job_id ?? result?.job?.id;
const resultStatus = settingsJobState(result);
form.elements.namedItem('root_password').value = '';
form.elements.namedItem('root_password_confirmation').value = '';
form.elements.namedItem('ssh_public_key').value = '';
form.elements.namedItem('confirm_restart').checked = false;
if (!jobId && ['succeeded', 'completed', 'done'].includes(resultStatus)) {
setSettingsFeedback(section, '实例设置已应用,正在刷新详情…', 'success');
detailNotice('实例设置已应用,正在刷新详情。');
await refreshDetail(vm.id);
return;
}
if (!jobId) throw new Error('服务器未返回实例设置任务编号,请在任务记录中核对。');
setSettingsFeedback(section, `任务 #${jobId} 已创建,运行中的实例将在后台重启并应用设置…`, 'muted');
detailNotice(`实例设置任务 #${jobId} 已创建,正在等待执行结果。`);
void pollSettingsJob(vm, section, jobId, result?.status_url);
} catch (error) {
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
setSettingsFeedback(section, error.message, 'danger');
unlockSettingsForm(form);
} finally {
if (state.settingsRequest === controller) state.settingsRequest = null;
}
};
form.addEventListener('submit', submit);
form.addEventListener('reset', () => {
window.setTimeout(() => setSettingsFeedback(section, ''), 0);
});
for (const control of form.querySelectorAll('input, textarea')) {
control.addEventListener('input', () => {
const feedback = section.querySelector('[data-settings-feedback]');
if (feedback && feedback.classList.contains('text-danger')) setSettingsFeedback(section, '');
});
}
return section;
}
function networkJobState(job) {
return String(job?.status || job?.job?.status || '').toLowerCase();
}
@ -643,11 +848,12 @@ async function refreshDetail(id) {
state.detailRequest?.abort('refresh');
const controller = new AbortController();
state.detailRequest = controller;
detailNotice('正在刷新网络配置…');
detailNotice('正在刷新实例详情…');
try {
const payload = await api(`/api/v1/admin/instances/${encodeURIComponent(id)}`, controller);
if (controller.signal.aborted || state.detailId !== String(id)) return;
cancelNetworkActivity('detail-refresh');
cancelSettingsActivity('detail-refresh');
renderDetail(payload);
detailNotice('');
const vm = payload.instance;
@ -664,7 +870,7 @@ async function refreshDetail(id) {
}
} catch (error) {
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
if (state.detailId === String(id)) detailNotice(`${error.message} 当前网络任务结果请在任务记录中核对。`, true);
if (state.detailId === String(id)) detailNotice(`${error.message} 当前任务结果请在任务记录中核对。`, true);
} finally {
if (state.detailRequest === controller) state.detailRequest = null;
}
@ -883,7 +1089,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));
]), networkEditor(vm), settingsEditor(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)],
@ -944,6 +1150,7 @@ function closeDetail() {
state.detailRequest?.abort();
state.detailRequest = null;
cancelNetworkActivity('closed');
cancelSettingsActivity('closed');
state.detailId = null;
const dialog = byId('instance-detail');
if (dialog.open) dialog.close();
@ -961,6 +1168,7 @@ async function openDetail(id, opener) {
if (!/^[1-9][0-9]*$/.test(id)) return;
state.detailRequest?.abort();
cancelNetworkActivity('detail-switch');
cancelSettingsActivity('detail-switch');
state.detailId = id;
state.opener = opener;
const controller = new AbortController();
@ -1056,7 +1264,7 @@ if (root) {
// Native modal dialog traps focus; background scrolling is locked separately for iOS.
window.addEventListener('popstate', () => { closeDetail(); void loadPage(new URL(location.href), 'none'); });
document.addEventListener('visibilitychange', () => { if (document.hidden) stopStatuses(); else void refreshStatuses(); });
window.addEventListener('pagehide', () => { state.active = false; stopStatuses(); state.request?.abort(); state.detailRequest?.abort(); cancelNetworkActivity('pagehide'); });
window.addEventListener('pagehide', () => { state.active = false; stopStatuses(); state.request?.abort(); state.detailRequest?.abort(); cancelNetworkActivity('pagehide'); cancelSettingsActivity('pagehide'); });
window.addEventListener('pageshow', event => { state.active = true; if (event.persisted) { closeDetail(); void loadPage(new URL(location.href), 'none'); } });
if (bootstrapped) void refreshStatuses();
else void loadPage(new URL(location.href), 'none');

@ -432,6 +432,75 @@ html.admin-instance-detail-open body {
overflow-wrap: anywhere;
}
[data-admin-instance-drawer] .admin-instance-settings {
margin-top: 24px;
padding-top: 20px;
border-top: 1px solid var(--bs-border-color, #e8eef5);
}
[data-admin-instance-drawer] .admin-instance-settings-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
[data-admin-instance-drawer] .admin-instance-settings-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
}
[data-admin-instance-drawer] .admin-instance-settings-field {
display: grid;
gap: 6px;
min-width: 0;
margin: 0;
}
[data-admin-instance-drawer] .admin-instance-settings-field-wide {
grid-column: 1 / -1;
}
[data-admin-instance-drawer] .admin-instance-settings-field .form-label {
margin: 0;
color: #344054;
font-size: 13px;
font-weight: 700;
}
[data-admin-instance-drawer] .admin-instance-settings-current {
min-width: 0;
overflow-wrap: anywhere;
color: #7d8a9c;
font-size: 12px;
}
[data-admin-instance-drawer] .admin-instance-settings-field .form-text {
color: #7d8a9c;
font-size: 12px;
line-height: 1.5;
}
[data-admin-instance-drawer] .admin-instance-settings-confirm {
display: flex;
align-items: flex-start;
gap: 8px;
color: #344054;
font-size: 13px;
line-height: 1.5;
}
[data-admin-instance-drawer] .admin-instance-settings-confirm input {
flex: 0 0 auto;
margin-top: 3px;
}
[data-admin-instance-drawer] .admin-instance-settings-feedback {
min-height: 1.2em;
overflow-wrap: anywhere;
}
[data-admin-instance-drawer] [hidden] {
display: none !important;
}
@ -508,6 +577,22 @@ html.admin-instance-detail-open body {
[data-admin-instance-drawer] .admin-instance-network-options {
grid-template-columns: minmax(76px, 0.4fr) minmax(0, 1fr);
}
[data-admin-instance-drawer] .admin-instance-settings-grid {
grid-template-columns: minmax(0, 1fr);
}
[data-admin-instance-drawer] .admin-instance-settings-field-wide {
grid-column: auto;
}
[data-admin-instance-drawer] .admin-instance-settings-form .d-flex {
flex-direction: column;
}
[data-admin-instance-drawer] .admin-instance-settings-form .btn {
width: 100%;
}
}
.admin-stat-card h3 {

@ -70,6 +70,56 @@
<p class="text-muted fs-12 mt-3 mb-0">当前管理员仅可查看,超级管理员才可以修改实例网络。</p>
{/if}
</template>
<template id="admin-instance-settings-controls">
{if $admin_can_manage|default:false}
<section class="admin-instance-settings" data-instance-settings>
<div class="admin-instance-settings-heading">
<div>
<h3 class="h6 fw-semibold mb-1">实例设置</h3>
<p class="text-muted fs-13 mb-0">运行中的实例会重启,已关机实例保持关机;配置会在后台应用,未填写的字段不会改变。</p>
</div>
</div>
<form class="admin-instance-settings-form mt-3" data-instance-settings-form novalidate>
<div class="admin-instance-settings-grid">
<label class="admin-instance-settings-field">
<span class="form-label">主机名</span>
<span class="admin-instance-settings-current" data-settings-current-hostname>当前主机名:未记录</span>
<input class="form-control" name="hostname" type="text" maxlength="253" autocomplete="off" spellcheck="false" placeholder="例如 vm-prod-01" aria-describedby="settings-hostname-help">
<span class="form-text" id="settings-hostname-help">支持英文、数字、连字符和点,每段不能以连字符开头或结尾,最多 253 个字符。</span>
</label>
<label class="admin-instance-settings-field">
<span class="form-label">实例密码</span>
<input class="form-control" name="root_password" type="password" minlength="12" maxlength="128" autocomplete="new-password" spellcheck="false" placeholder="输入新的 root 密码" aria-describedby="settings-password-help">
<span class="form-text" id="settings-password-help">12–128 位可打印字符,须包含大写、小写、数字和符号。</span>
</label>
<label class="admin-instance-settings-field">
<span class="form-label">再次输入实例密码</span>
<input class="form-control" name="root_password_confirmation" type="password" minlength="12" maxlength="128" autocomplete="new-password" spellcheck="false" placeholder="再次输入以确认密码">
</label>
<label class="admin-instance-settings-field admin-instance-settings-field-wide">
<span class="form-label">替换 SSH 公钥</span>
<textarea class="form-control admin-mono" name="ssh_public_key" rows="3" maxlength="16384" autocomplete="off" spellcheck="false" placeholder="粘贴单行 OpenSSH 公钥,例如 ssh-ed25519 AAAA…"></textarea>
<span class="form-text">直接粘贴要写入实例的公钥,不会读取或展示用户已保存的 SSH 公钥。</span>
</label>
</div>
<label class="admin-instance-settings-confirm mt-3">
<input type="checkbox" name="confirm_restart" value="1" data-settings-confirm>
<span>我确认运行中的实例会重启,当前连接可能会短暂中断。</span>
</label>
<p class="admin-instance-settings-feedback text-muted fs-13 mb-2" data-settings-feedback role="status" aria-live="polite" hidden></p>
<div class="d-flex justify-content-end gap-2 flex-wrap">
<button class="btn btn-light btn-sm" type="reset" data-settings-reset>清空未提交内容</button>
<button class="btn btn-primary btn-sm" type="submit" data-settings-submit>提交实例设置</button>
</div>
</form>
</section>
{else}
<section class="admin-instance-settings" data-instance-settings>
<h3 class="h6 fw-semibold mb-1">实例设置</h3>
<p class="text-muted fs-13 mb-0">当前管理员仅可查看;仅超级管理员可以修改实例密码、主机名和 SSH 公钥。</p>
</section>
{/if}
</template>
<script id="admin-instances-bootstrap" type="application/json">{$instance_bootstrap_json nofilter}</script>
<script type="module" src="/cloud/admin-instances.js?v={$venix_asset_version}"></script>
{include file='admin/static_footer.tpl'}

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026100207' scope='global'}
{assign var=venix_asset_version value='2026100208' scope='global'}

Loading…
Cancel
Save