diff --git a/README.md b/README.md index f0613c0d..96a5801e 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ 项目提供面板程序、Python 依赖清单和可选的 [systemd service 文件](deploy/virsh-panel.service),没有安装器或反向代理配置。面板运行在管理服务器 A,默认只监听 `127.0.0.1:8000`;AlmaLinux 10 的 virsh 宿主机 B 通过已有的 root SSH 密钥连接。B 不需要安装面板、创建新账号或导入新公钥。面板使用 [libvirt 官方 SSH 连接方式](https://www.libvirt.org/uri.html)管理 `qemu:///system`,VNC 经 SSH 连接 B 的本机端口。 -这一版的持久化面板数据使用 **MariaDB**。首次打开网页会先配置数据库连接,再创建管理员和配置宿主机。数据库及有建表权限的专用账号需要你事先准备;面板不会安装 MariaDB 或自动创建数据库。旧版 `data/state.json`、`data/templates.json` 和本地宿主机配置**不会自动迁移**。虚拟机定义和虚拟磁盘仍由远端 libvirt/宿主机持有,数据库保存面板账户、登录会话、模板目录、宿主机连接资料、更新设置、更新任务及虚拟机性能历史等面板数据。 +这一版的持久化面板数据使用 **MariaDB**。首次打开网页会先配置数据库连接、创建初始账户;该账户的 `admin` 字段初始为 `0`,需由你手工在数据库升为管理员,之后才能在网页配置宿主机和 SMTP。数据库及有建表权限的专用账号需要你事先准备;面板不会安装 MariaDB 或自动创建数据库。旧版 `data/state.json`、`data/templates.json` 和本地宿主机配置**不会自动迁移**。虚拟机定义和虚拟磁盘仍由远端 libvirt/宿主机持有,数据库保存用户、邮箱验证码、虚拟机归属、登录会话、SMTP 设置、模板目录、宿主机连接资料、更新设置、更新任务及虚拟机性能历史等面板数据。 如果是在旧测试目录上替换代码,旧 `data/generations/` 中的明文 SSH 私钥不会被新版使用,也**不会自动删除**。为避免遗留敏感文件,建议先备份并核对后,在首次运行新版前使用全新的 `data/` 目录;不要未经核对直接删除仍需使用的资料。 @@ -26,11 +26,11 @@ python3 -m venv --system-site-packages .venv PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m uvicorn virsh_panel.app:create_app --factory --host 127.0.0.1 --port 8000 --workers 1 --proxy-headers --forwarded-allow-ips 127.0.0.1 ``` -上述命令保持在前台运行。出现 `Uvicorn running on http://127.0.0.1:8000` 表示已监听;可另开终端运行 `curl http://127.0.0.1:8000/api/v1/health` 检查。首次启动时,在启动终端输出中查找 `VIRSH_PANEL_SETUP_TOKEN=`,用它在网页先配置数据库,再创建管理员;管理员创建后令牌失效。停止面板用 `Ctrl+C`,再次启动只需执行最后一行启动命令。**不需要编辑面板配置文件,也不需要运行初始化命令。** +上述命令保持在前台运行。出现 `Uvicorn running on http://127.0.0.1:8000` 表示已监听;可另开终端运行 `curl http://127.0.0.1:8000/api/v1/health` 检查。首次启动时,在启动终端输出中查找 `VIRSH_PANEL_SETUP_TOKEN=`,用它在网页先配置数据库,再创建初始账户;账户创建后令牌失效。停止面板用 `Ctrl+C`,再次启动只需执行最后一行启动命令。**不需要编辑面板配置文件,也不需要运行初始化命令。** 手工更新版本时请同时替换 `static/index.html`、`static/app.js`、`static/styles.css` 和后端代码,不要只上传页面 HTML;保留原有 `data/` 和数据库。浏览器若出现“已选公网云镜像却仍要求 ISO”,先确认这三个静态文件均为同一版本,再重新打开页面。网页一键更新另有 Git 仓库和更新服务的要求,见下文。 -若初始化令牌意外公开、且尚未创建管理员,请先停止面板,只删除 `/home/virsh-panel/data/setup-token`,再启动面板生成新令牌。不要删除整个 `data/`;新令牌不要再次公开。 +若初始化令牌意外公开、且尚未创建初始账户,请先停止面板,只删除 `/home/virsh-panel/data/setup-token`,再启动面板生成新令牌。不要删除整个 `data/`;新令牌不要再次公开。 按当前需求从 A 的 root 终端运行面板;程序自动将 `data/` 目录及本地加密主密钥限制为 `0700`、`0600`。数据库中的敏感资料采用应用层认证加密,但运行中的 root 面板仍能解密 B 的 root SSH 私钥;只在可信网络和 HTTPS 反代后使用,妥善限制谁能访问 A。A 若启用 SELinux enforcing,还需在真实系统上验证 `/home/virsh-panel` 的访问标签。仓库保留可选 service 文件,但以上启动方式不依赖它。 @@ -41,15 +41,23 @@ PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m uvicorn virsh_panel.app:create_app ## 首次网页操作 1. 通过你的 HTTPS 域名打开面板,使用启动终端输出中的一次性令牌填写 MariaDB 的地址、端口、已有数据库名、专用账号和密码。数据库账号至少需要在该数据库中建表及读写权限;连接失败时不会保存配置。当前数据库连接尚未提供 TLS 参数,数据库请放在面板本机或可信内网,不要将其端口暴露公网。 -2. 使用同一个令牌创建面板管理员。创建完成后令牌失效,管理员密码只保存为密码哈希。 -3. 在网页填写 B 的 IP/DNS、SSH 端口、虚拟机地区、现有的 **root 客户端 SSH 私钥**、磁盘目录、ISO 目录和网络名称。地区是这台宿主机上虚拟机共用的展示标签,可留空;它不影响 SSH 连接或已导入的模板。私钥必须与 B 的 root 账号**已经授权的公钥**匹配;仅有 root 密码或 B 的 SSH 主机密钥不能代替它。加密私钥还需填写其口令。保存宿主机设置时,面板会将口令与私钥加密写入 MariaDB,以便面板重启后自动连接和无人登录时继续采样;设置 API 不回显口令,面板代码也不将其写入浏览器存储。**旧版本中只在内存解锁过的口令无法自动恢复**:升级后进入“宿主机设置”,不必重新粘贴原私钥,填写原口令并重新保存一次。只在“解锁宿主机 SSH 私钥”页面输入不会持久保存。 -4. 点击“扫描主机指纹”,再通过 B 的可信控制台运行 `ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub` 独立核对;确认后在网页测试、保存。保存前会重扫并测试 SSH 与 libvirt API,失败不会覆盖现有连接。 +2. 使用同一个令牌创建初始账户。密码只保存为密码哈希;此时 `users.admin=0`,账户虽可登录,但还不能管理宿主机。按照你的要求,面板**不会自动赋予管理员权限**。用有权访问该数据库的账号在 MariaDB 中核对用户名及 ID 后,手工执行下面 SQL;将示例 ID 和用户名换成查询到的初始账户: + + ```sql + SELECT id, username, admin, approved FROM users; + UPDATE users SET admin = 1 WHERE id = 1 AND username = '你的初始用户名'; + ``` + + 再刷新面板,权限会从数据库即时读取,不必重启。不要把 `admin=1` 给公开注册用户。 +3. 管理员在网页配置 SMTP 地址、端口、SSL/STARTTLS、发件邮箱及需要时的 SMTP 账号密码;设置加密保存在 MariaDB,页面不回显密码。完成后,访客可用邮箱验证码注册(10 分钟有效,重复发送与输错次数受限);邮箱验证成功即可登录,但须由管理员在“用户审核”批准后才能创建虚拟机。普通用户不能添加宿主机、导入云镜像模板、配置 SMTP 或更新面板,也看不到其他人的虚拟机和初始密码。面板外创建或管理员创建的未归属虚拟机仅管理员可见;当前没有从网页将旧 VM 分配给用户的功能。 +4. 在网页填写 B 的 IP/DNS、SSH 端口、虚拟机地区、现有的 **root 客户端 SSH 私钥**、磁盘目录、ISO 目录和网络名称。地区是这台宿主机上虚拟机共用的展示标签,可留空;它不影响 SSH 连接或已导入的模板。私钥必须与 B 的 root 账号**已经授权的公钥**匹配;仅有 root 密码或 B 的 SSH 主机密钥不能代替它。加密私钥还需填写其口令。保存宿主机设置时,面板会将口令与私钥加密写入 MariaDB,以便面板重启后自动连接和无人登录时继续采样;设置 API 不回显口令,面板代码也不将其写入浏览器存储。**旧版本中只在内存解锁过的口令无法自动恢复**:升级后进入“宿主机设置”,不必重新粘贴原私钥,填写原口令并重新保存一次。只在“解锁宿主机 SSH 私钥”页面输入不会持久保存。 +5. 点击“扫描主机指纹”,再通过 B 的可信控制台运行 `ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub` 独立核对;确认后在网页测试、保存。保存前会重扫并测试 SSH 与 libvirt API,失败不会覆盖现有连接。 宿主机私钥、已填写的私钥口令和配置加密保存在 MariaDB。数据库备份与 `data/master.key` 同时泄露时,这些凭据可以被解密,因此须分别严密保护;运行中的 root 面板进程同样能使用它们。OpenSSH 连接时需要读取私钥文件,Linux 上面板会将其临时还原到权限为 `0700` 的 `/dev/shm` 内存文件系统目录;面板关闭时清除。`data/runtime-wrappers/` 只包含不带密钥的启动包装器。若 SSH agent 异常退出,后台采样会限频尝试使用已保存口令恢复连接;若保存的口令错误,仍需管理员检查并重新保存。面板仅支持单个 Uvicorn worker。 虚拟机列表只展示状态、地区、系统或安装镜像、IP、规格和磁盘;点击虚拟机名称进入该机管理页,控制台、电源、重装和删除等操作都在管理页。地区取自当前宿主机设置。新建或重装的云镜像 VM 会记录所选模板名称及配置的公网 IP/CIDR;这个 IP 是**配置记录**,不是连通性探测。详情页的公网 IP 不显示 `/24` 等掩码后缀,可点击旁边的按钮复制;磁盘信息只显示总容量,不再显示磁盘块数。ISO 安装 VM 只记录安装镜像文件名,不能据此确认客体最终安装的系统;旧 VM 或面板外创建的 VM 若无可靠记录,会显示“未识别”或“未获取”,不会猜测客体系统与 IP。 -云镜像 VM 的详情页显示 SSH 登录名 `root`。面板保存了初始 root 密码时,默认以星号遮盖,管理员可按需点击“查看”或“复制”;不会在虚拟机列表或普通详情数据中直接返回密码。只有本版本以后由面板新建、或成功重装的密码模式云镜像 VM 才能查看其加密保存的初始密码;公钥模式不保存也不显示密码,ISO 安装和面板外创建的 VM 的客体密码则不由面板管理。旧 VM 曾使用但面板未保存的密码无法从密码哈希或虚拟机系统中还原。客体内修改 root 密码后,详情页保存的**初始**密码不会自动更新,可能已无法用于登录;请妥善保护数据库备份和面板主密钥。 +云镜像 VM 的详情页显示 SSH 登录名 `root`。面板保存了初始 root 密码时,默认以星号遮盖;管理员或该 VM 的所属用户可按需点击图标查看、复制,不会在虚拟机列表或普通详情数据中直接返回密码。只有本版本以后由面板新建、或成功重装的密码模式云镜像 VM 才能查看其加密保存的初始密码;公钥模式不保存也不显示密码,ISO 安装和面板外创建的 VM 的客体密码则不由面板管理。旧 VM 曾使用但面板未保存的密码无法从密码哈希或虚拟机系统中还原。客体内修改 root 密码后,详情页保存的**初始**密码不会自动更新,可能已无法用于登录;请妥善保护数据库备份和面板主密钥。 虚拟机详情页显示 CPU、客体内存、磁盘 I/O 和网络收发四张历史走势图,可切换最近 1 小时、24 小时、7 天和 30 天。面板后台定时从 [libvirt 域统计](https://libvirt.org/manpages/virsh.html#domstats)采样并写入 MariaDB,即使无人登录也会继续记录,前提是宿主机连接可用且加密私钥能自动解锁。旧配置若只在内存中解锁、没有重新保存口令,重启后后台采样会暂停,直到管理员解锁;按上述步骤保存口令后可避免这种中断。查询**只返回最近 30 天**的数据;运行中的面板会分批清理更早的数据库记录。面板停机或数据库不可用时物理清理会暂停,恢复后继续追赶,因此中断期间数据库中可能暂时留有超期记录。CPU 是按 vCPU 数归一化、最高显示 100% 的使用率,磁盘和网络显示每秒速率而不是累计量或网络带宽上限;网络收发方向以虚拟机为准。磁盘与网卡只汇总 libvirt 实际提供计数的设备,未提供计数的设备无法纳入统计。内存占用依赖客体内存气球统计,客户机不提供或统计过期时会显示无数据,不会把宿主机 QEMU 进程占用误当客体内存。初次采样、虚拟机停机、面板/宿主机不可达或计数器重置期间可能出现空白;面板停机期间不会补录历史。较长时间范围会聚合采样,短暂的停机或采样缺口可能不明显。 @@ -88,4 +96,4 @@ systemctl enable --now virsh-panel.service 独立的 `virsh-panel-update.service` 会先拉取私有仓库并安装目标版本 Python 依赖,再以快进方式切换代码、重启主面板并检查本机 HTTP 与数据库健康状态。更新任务绑定点击“检查更新”时看到的两个提交编号;若本地或远端版本变化,任务会拒绝切换并要求重新检查。更新任务状态加密存于 MariaDB,页面中断后可继续查询;独立服务异常退出或超时会尝试将未完成任务标为失败。更新前请备份 **MariaDB 数据和 `data/master.key`、`data/database-config.json`**;更新失败时不要重复点按钮,应先看 `journalctl -u virsh-panel-update.service -n 100`。依赖在代码切换前安装到当前 `.venv`,因此若依赖安装成功而代码切换失败,可能需要人工检查依赖版本。更新服务会保留更新前的 Git 回滚引用,但不会自动执行覆盖性的回滚。网页更新不负责安装系统 RPM、替换 `/etc/systemd/system` 中已安装的 unit 或修改反向代理配置;这些变化如后续版本需要,仍需人工处理。由于在线更新会运行私有仓库中的代码与依赖,必须保护 Gitea 仓库写入权限和访问令牌。 -功能范围:虚拟机列表和详情页四项性能走势图、从 ISO 创建、导入 AlmaLinux 10 云镜像模板并配置公网静态 IP 创建、云镜像重装、开机、关机、重启、强制断电/重置、删除和浏览器 VNC。当前为单管理员、单宿主机版本;不提供 ISO 上传、目录自动创建、虚拟网络创建、内网 IP 模板、异网段网关或多用户权限。真实 AlmaLinux 10 宿主机及 MariaDB 仍需现场联调。 +功能范围:邮箱验证注册、管理员审核及按虚拟机归属隔离用户,虚拟机列表和详情页四项性能走势图、从 ISO 创建、导入 AlmaLinux 10 云镜像模板并配置公网静态 IP 创建、云镜像重装、开机、关机、重启、强制断电/重置、删除和浏览器 VNC。当前仍是单宿主机版本;不提供 ISO 上传、目录自动创建、虚拟网络创建、内网 IP 模板或异网段网关。真实 AlmaLinux 10 宿主机、SMTP 服务及 MariaDB 仍需现场联调。 diff --git a/static/app.js b/static/app.js index 30720555..bee358fc 100644 --- a/static/app.js +++ b/static/app.js @@ -5,7 +5,11 @@ const UPDATE_BRANCH = "main"; const state = { csrfToken: "", + sessionEpoch: 0, username: "", + admin: false, + approved: false, + hostReady: false, vms: [], selectedVmId: null, credentialVmId: null, @@ -150,13 +154,25 @@ async function api(path, options = {}) { if (response.status !== 204) { try { payload = await response.json(); } catch { /* A failed HTTP response may not be JSON. */ } } - if (response.status === 401 && path !== "/api/v1/login" && path !== "/api/v1/session" && !path.startsWith("/api/v1/setup/") && !path.startsWith("/api/v1/database/")) { + if (response.status === 401 && path !== "/api/v1/login" && path !== "/api/v1/session" && !path.startsWith("/api/v1/register") && !path.startsWith("/api/v1/setup/") && !path.startsWith("/api/v1/database/")) { showLogin(); throw new Error("登录已过期,请重新登录。"); } if (response.status === 423 && payload?.error_code === "key_locked" && path !== "/api/v1/host/unlock") { - showUnlockView({ ...state.hostConfig, configured: true, key_locked: true }); - throw new Error("宿主机私钥已锁定,请输入私钥口令解锁。"); + if (state.admin) { + showUnlockView({ ...state.hostConfig, configured: true, key_locked: true }); + throw new Error("宿主机私钥已锁定,请输入私钥口令解锁。"); + } + showAccessWait("host"); + throw new Error("宿主机暂不可用,请联系管理员解锁私钥。"); + } + if (!state.admin && response.status === 409 && /宿主机/.test(errorMessage(payload, "")) && (path.startsWith("/api/v1/vms") || path === "/api/v1/resources")) { + showAccessWait("host"); + throw new Error("宿主机尚未就绪,请等待管理员完成配置。"); + } + if (!state.admin && response.status === 403 && /审核/.test(errorMessage(payload, ""))) { + showAccessWait("approval"); + throw new Error("账号正在等待管理员审核。"); } if (!response.ok) { const error = new Error(errorMessage(payload, `请求失败(HTTP ${response.status})`)); @@ -171,6 +187,18 @@ function stopPolling() { state.pollTimer = null; } +function clearAdminContent() { + for (const id of ["smtp-host", "smtp-username", "smtp-password", "smtp-from-address", "host-address", "host-region", "host-storage-pool", "host-iso-pool", "host-network"]) byId(id).value = ""; + byId("smtp-port").value = 465; + byId("smtp-tls-mode").value = "ssl"; + byId("smtp-status").hidden = true; + byId("pending-users-list").replaceChildren(); + showError("smtp-error", ""); + showError("pending-users-error", ""); + text("host-fingerprint", ""); + text("current-username", "用户"); +} + function showLogin() { stopPolling(); stopVmMetrics(); @@ -182,19 +210,72 @@ function showLogin() { state.updateCheck = null; state.updateSettings = null; state.updateReturnView = null; + state.sessionEpoch += 1; state.csrfToken = ""; + state.admin = false; + state.approved = false; + state.hostReady = false; state.vms = []; + state.resources = null; + state.hostConfig = null; + state.templateLoad = null; + state.templateImportJobId = null; state.selectedVmId = null; + clearAdminContent(); + renderVMs(); + clearVmMetrics("登录后加载监控数据。"); + fillSelect("vm-network", [], "network"); + fillSelect("vm-iso", [], "iso"); + fillTemplateSelect([]); + text("vm-detail-name", "虚拟机"); + text("vm-detail-header-ip", "未获取"); + text("vm-detail-header-region", "未设置"); + text("vm-detail-header-created-at", "未记录"); clearHostPrivateKey(); byId("unlock-passphrase").value = ""; byId("update-access-token").value = ""; + byId("smtp-password").value = ""; + byId("admin-menu").open = false; + byId("login-success").hidden = true; + byId("register-code-status").hidden = true; byId("boot-screen").hidden = true; byId("database-view").hidden = true; byId("setup-view").hidden = true; + byId("access-wait-view").hidden = true; byId("host-view").hidden = true; byId("unlock-view").hidden = true; byId("dashboard-view").hidden = true; byId("login-view").hidden = false; + byId("register-card").hidden = true; + byId("login-card").hidden = false; + byId("register-password").value = ""; + byId("register-password-confirm").value = ""; + byId("register-code").value = ""; +} + +function showRegister() { + showError("register-error", ""); + showError("login-error", ""); + byId("login-card").hidden = true; + byId("register-card").hidden = false; + byId("register-username").focus(); +} + +function showAccessWait(kind) { + stopPolling(); + stopVmMetrics(); + closeModal(); + clearVmCredential(); + const approval = kind === "approval"; + text("wait-current-user", state.username || "用户"); + text("wait-eyebrow", approval ? "ACCOUNT APPROVAL" : "HOST SETUP"); + text("wait-title", approval ? "等待管理员审核" : "等待管理员配置宿主机"); + text("wait-description", approval + ? "邮箱已验证,账号正在等待管理员审核。审核通过后才能创建和管理虚拟机。" + : "管理员尚未完成宿主机配置,暂时无法创建或管理虚拟机。请稍后点击“刷新状态”。"); + byId("boot-screen").hidden = true; + for (const id of ["database-view", "setup-view", "login-view", "host-view", "unlock-view", "dashboard-view"]) byId(id).hidden = true; + byId("access-wait-view").hidden = false; } function showDatabaseView() { @@ -205,6 +286,7 @@ function showDatabaseView() { byId("boot-screen").hidden = true; byId("setup-view").hidden = true; byId("login-view").hidden = true; + byId("access-wait-view").hidden = true; byId("host-view").hidden = true; byId("unlock-view").hidden = true; byId("dashboard-view").hidden = true; @@ -220,6 +302,7 @@ function showSetup() { byId("boot-screen").hidden = true; byId("database-view").hidden = true; byId("login-view").hidden = true; + byId("access-wait-view").hidden = true; byId("host-view").hidden = true; byId("unlock-view").hidden = true; byId("dashboard-view").hidden = true; @@ -249,6 +332,7 @@ function showUnlockView(hostConfig) { byId("database-view").hidden = true; byId("setup-view").hidden = true; byId("login-view").hidden = true; + byId("access-wait-view").hidden = true; byId("host-view").hidden = true; byId("dashboard-view").hidden = true; byId("unlock-view").hidden = false; @@ -271,6 +355,8 @@ function markHostTestStale() { } function showHostView(hostConfig = { configured: false }) { + if (!state.admin) return; + byId("admin-menu").open = false; stopPolling(); stopVmMetrics(); closeModal(); @@ -285,7 +371,7 @@ function showHostView(hostConfig = { configured: false }) { showError("host-error", ""); text("host-current-user", state.username || "管理员"); const configured = Boolean(hostConfig.configured); - text("host-step-label", configured ? "HOST SETTINGS" : "步骤 03 / 03"); + text("host-step-label", configured ? "HOST SETTINGS" : "管理员操作"); text("host-page-title", configured ? "宿主机设置" : "连接 libvirt 宿主机"); text("host-save-button", configured ? "保存修改" : "保存并进入面板"); byId("host-back-button").hidden = !configured; @@ -315,17 +401,21 @@ function showHostView(hostConfig = { configured: false }) { byId("database-view").hidden = true; byId("setup-view").hidden = true; byId("login-view").hidden = true; + byId("access-wait-view").hidden = true; byId("unlock-view").hidden = true; byId("dashboard-view").hidden = true; byId("host-view").hidden = false; } async function showDashboard(session) { + if (!state.admin && !state.approved) { showAccessWait("approval"); return; } + if (!state.admin && !state.hostReady) { showAccessWait("host"); return; } state.updateReturnView = null; state.csrfToken = session.csrf_token || ""; - state.username = session.username || "管理员"; + state.username = session.username || "用户"; text("current-username", state.username); byId("login-view").hidden = true; + byId("access-wait-view").hidden = true; byId("database-view").hidden = true; byId("setup-view").hidden = true; byId("host-view").hidden = true; @@ -342,9 +432,32 @@ async function showDashboard(session) { }, 15000); } -async function continueAfterLogin(session) { +function applySession(session) { + state.sessionEpoch += 1; state.csrfToken = session.csrf_token || ""; - state.username = session.username || "管理员"; + state.username = session.username || "用户"; + state.admin = session.admin === true; + state.approved = session.approved === true; + state.hostReady = session.host_ready === true; + if (!state.admin) clearAdminContent(); + for (const id of ["host-settings-button", "host-settings-mobile-button", "update-settings-button", "update-settings-mobile-button", "smtp-settings-button", "smtp-settings-mobile-button", "host-update-button", "unlock-update-button", "unlock-settings-button"]) { + byId(id).hidden = !state.admin; + } + byId("admin-menu").hidden = !state.admin; + byId("admin-menu").open = false; + byId("template-import").hidden = !state.admin; + text("current-username", state.username); +} + +async function continueAfterLogin(session) { + applySession(session); + if (!state.admin) { + state.hostConfig = null; + if (!state.approved) { showAccessWait("approval"); return; } + if (!state.hostReady) { showAccessWait("host"); return; } + await showDashboard(session); + return; + } const hostConfig = await api("/api/v1/host"); state.hostConfig = hostConfig || { configured: false }; if (hostConfig?.configured && hostConfig?.key_locked) showUnlockView(hostConfig); @@ -368,6 +481,7 @@ async function initialize() { } function showVmWorkspace() { + byId("admin-menu").open = false; stopVmMetrics(); clearVmCredential(); state.selectedVmId = null; @@ -375,14 +489,19 @@ function showVmWorkspace() { byId("vm-list-view").hidden = false; byId("vm-detail-view").hidden = true; byId("update-workspace").hidden = true; + byId("smtp-workspace").hidden = true; + byId("smtp-password").value = ""; byId("vm-navigation-button").classList.add("active"); byId("vm-navigation-button").setAttribute("aria-current", "page"); byId("update-settings-button").classList.remove("active"); byId("update-settings-button").removeAttribute("aria-current"); + byId("smtp-settings-button").classList.remove("active"); + byId("smtp-settings-button").removeAttribute("aria-current"); text("breadcrumb-current", "虚拟机"); } function openUpdateFromGate(returnView) { + if (!state.admin) return; if (returnView === "host") { const hasKeyInput = Boolean(byId("host-private-key").value || state.uploadedPrivateKey || byId("host-private-key-passphrase").value); if (hasKeyInput && !window.confirm("切换到网站更新会清空尚未保存的 SSH 私钥与口令输入。确定继续吗?")) return; @@ -412,14 +531,20 @@ function leaveUpdateWorkspace() { } async function showUpdateWorkspace() { + if (!state.admin) return; + byId("admin-menu").open = false; stopVmMetrics(); clearVmCredential(); byId("vm-workspace").hidden = true; + byId("smtp-workspace").hidden = true; + byId("smtp-password").value = ""; byId("update-workspace").hidden = false; byId("vm-navigation-button").classList.remove("active"); byId("vm-navigation-button").removeAttribute("aria-current"); byId("update-settings-button").classList.add("active"); byId("update-settings-button").setAttribute("aria-current", "page"); + byId("smtp-settings-button").classList.remove("active"); + byId("smtp-settings-button").removeAttribute("aria-current"); text("breadcrumb-current", "网站更新"); showError("update-settings-error", ""); if (!state.updateLastShownJobId && !state.updateJobId) showError("update-action-error", ""); @@ -430,6 +555,91 @@ async function showUpdateWorkspace() { } } +async function loadSmtpSettings() { + const epoch = state.sessionEpoch; + const settings = await api("/api/v1/smtp/settings"); + if (epoch !== state.sessionEpoch || !state.admin) return; + byId("smtp-host").value = settings?.host || ""; + byId("smtp-port").value = settings?.port || 465; + byId("smtp-tls-mode").value = settings?.tls_mode || "ssl"; + byId("smtp-username").value = settings?.username || ""; + byId("smtp-from-address").value = settings?.from_address || ""; + byId("smtp-password").value = ""; + byId("smtp-password").placeholder = settings?.password_configured ? "留空沿用已保存的密码" : "填写 SMTP 密码或应用专用密码"; + text("smtp-password-hint", settings?.password_configured + ? "密码已加密保存;留空沿用现有密码。已保存密码不会回显,也不会写入浏览器存储。" + : "保存后不会回显,也不会写入浏览器存储。"); + text("smtp-status", settings?.configured ? "邮件服务已配置,可发送注册验证码。" : "尚未配置邮件服务;注册验证码暂不可发送。"); + byId("smtp-status").hidden = false; +} + +async function loadPendingUsers() { + const epoch = state.sessionEpoch; + const result = await api("/api/v1/users/pending"); + if (epoch !== state.sessionEpoch || !state.admin) return; + const list = byId("pending-users-list"); + list.replaceChildren(); + const users = Array.isArray(result?.items) ? result.items : []; + if (!users.length) { + list.append(makeElement("p", "muted", "暂无待审核用户。")); + return; + } + for (const user of users) { + const id = Number(user?.id); + if (!Number.isSafeInteger(id) || id <= 0) continue; + const row = makeElement("div", "pending-user-row"); + const details = makeElement("div", "pending-user-details"); + details.append(makeElement("strong", "", user.username || `用户 ${id}`)); + details.append(makeElement("span", "", user.email || "")); + const createdAt = Number(user.created_at); + const createdDate = Number.isSafeInteger(createdAt) && createdAt > 0 ? new Date(createdAt * 1000) : null; + const created = createdDate && Number.isFinite(createdDate.getTime()) + ? vmCreatedAt({ created_at: createdDate.toISOString() }) : "未记录"; + details.append(makeElement("small", "", `注册时间:${created}`)); + const button = makeElement("button", "button button-outline small", "审核通过"); + button.type = "button"; + button.addEventListener("click", async () => { + if (!window.confirm(`确认通过用户 ${String(user.username || id)} 的审核?通过后该用户可创建并管理自己的虚拟机。`)) return; + setButtonBusy(button, true, "正在审核…"); + showError("pending-users-error", ""); + try { + const approved = await api(`/api/v1/users/${encodeURIComponent(String(id))}/approve`, { method: "POST" }); + if (approved?.approved !== true) throw new Error("无法确认审核结果,请刷新待审核列表。"); + toast("用户审核通过。", "success"); + await loadPendingUsers(); + } catch (error) { + showError("pending-users-error", error.message); + } finally { + setButtonBusy(button, false); + } + }); + row.append(details, button); + list.append(row); + } +} + +async function showSmtpWorkspace() { + if (!state.admin) return; + byId("admin-menu").open = false; + stopVmMetrics(); + clearVmCredential(); + byId("vm-workspace").hidden = true; + byId("update-workspace").hidden = true; + byId("smtp-workspace").hidden = false; + byId("vm-navigation-button").classList.remove("active"); + byId("vm-navigation-button").removeAttribute("aria-current"); + byId("update-settings-button").classList.remove("active"); + byId("update-settings-button").removeAttribute("aria-current"); + byId("smtp-settings-button").classList.add("active"); + byId("smtp-settings-button").setAttribute("aria-current", "page"); + text("breadcrumb-current", "邮件与用户审核"); + showError("smtp-error", ""); + showError("pending-users-error", ""); + const [settingsResult, usersResult] = await Promise.allSettled([loadSmtpSettings(), loadPendingUsers()]); + if (settingsResult.status === "rejected") showError("smtp-error", `无法读取邮件设置:${settingsResult.reason.message}`); + if (usersResult.status === "rejected") showError("pending-users-error", `无法读取待审核用户:${usersResult.reason.message}`); +} + async function loadUpdateSettings() { const settings = await api("/api/v1/update/settings"); state.updateCheck = null; @@ -698,17 +908,20 @@ async function submitUnlock() { async function loadVMs(silent = false) { if (state.loadingVMs || byId("dashboard-view").hidden) return; state.loadingVMs = true; + const epoch = state.sessionEpoch; const refreshButton = byId("refresh-button"); const detailRefreshButton = byId("vm-detail-refresh-button"); refreshButton.disabled = true; detailRefreshButton.disabled = true; try { const result = await api("/api/v1/vms"); + if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; state.vms = Array.isArray(result?.items) ? result.items : []; setConnection(true); renderVMs(); syncVmDetailAfterRefresh(); } catch (error) { + if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; setConnection(false); if (!silent && !byId("dashboard-view").hidden) toast(error.message, "error"); if (!state.vms.length) renderVMs(true); @@ -1313,19 +1526,24 @@ function fillSelect(id, items, kind) { } async function loadResources() { + const epoch = state.sessionEpoch; try { const result = await api("/api/v1/resources"); + if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; state.resources = result || {}; fillSelect("vm-network", Array.isArray(result?.networks) ? result.networks : [], "network"); fillSelect("vm-iso", Array.isArray(result?.isos) ? result.isos : [], "iso"); updateCreateSource(); showResourceWarning(""); } catch (error) { + if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; state.resources = null; fillSelect("vm-network", [], "network"); fillSelect("vm-iso", [], "iso"); updateCreateSource(); - showResourceWarning(`宿主机资源尚未就绪:${error.message}。请检查存储池和网络或网桥设置。`); + showResourceWarning(state.admin + ? `宿主机资源尚未就绪:${error.message}。请检查存储池和网络或网桥设置。` + : `宿主机资源尚未就绪:${error.message}。请联系管理员检查宿主机。`); throw error; } } @@ -1348,7 +1566,7 @@ function fillTemplateSelect(items, preferredId = "") { } if (previous && Array.from(select.options).some((option) => option.value === previous)) select.value = previous; select.disabled = selectedCreateSource() !== "cloud" || select.options.length <= 1; - if (!items.length) byId("template-import").open = true; + if (!items.length && state.admin) byId("template-import").open = true; const reinstallSelect = byId("reinstall-template"); const reinstallPrevious = reinstallSelect.value; @@ -1373,10 +1591,12 @@ function fillTemplateSelect(items, preferredId = "") { async function loadTemplates(preferredId = "") { if (state.templateLoad) await state.templateLoad; + const epoch = state.sessionEpoch; const request = api("/api/v1/vm-templates"); state.templateLoad = request; try { const result = await request; + if (epoch !== state.sessionEpoch || byId("dashboard-view").hidden) return; fillTemplateSelect(Array.isArray(result?.templates) ? result.templates : [], preferredId); } finally { if (state.templateLoad === request) state.templateLoad = null; @@ -1502,6 +1722,7 @@ function closeModal() { } function openCreate() { + if (!state.admin && (!state.approved || !state.hostReady)) return; byId("create-form").reset(); byId("vm-root-password").value = ""; byId("template-import").open = !!state.templateImportJobId; @@ -1842,6 +2063,7 @@ byId("setup-form").addEventListener("submit", async (event) => { byId("login-form").addEventListener("submit", async (event) => { event.preventDefault(); showError("login-error", ""); + byId("login-success").hidden = true; const button = byId("login-submit"); setButtonBusy(button, true, "正在登录…"); try { @@ -1860,6 +2082,111 @@ byId("login-form").addEventListener("submit", async (event) => { } }); +byId("show-register-button").addEventListener("click", showRegister); +byId("show-login-button").addEventListener("click", () => { + showLogin(); + byId("login-username").focus(); +}); + +byId("register-code-send").addEventListener("click", async () => { + showError("register-error", ""); + const emailInput = byId("register-email"); + if (!emailInput.checkValidity()) { + showError("register-error", "请先填写有效的邮箱地址。"); + emailInput.focus(); + return; + } + const button = byId("register-code-send"); + setButtonBusy(button, true, "正在发送…"); + try { + requireSecureCredentialTransport(); + const result = await api("/api/v1/register/code", { method: "POST", csrf: false, body: { email: emailInput.value.trim() } }); + if (result?.sent !== true) throw new Error("面板未确认验证码已发送,请稍后重试。"); + text("register-code-status", "如邮箱可注册且邮件服务可用,验证码将发送至该邮箱。请检查收件箱和垃圾邮件。"); + byId("register-code-status").hidden = false; + } catch (error) { + showError("register-error", error.message); + } finally { + setButtonBusy(button, false); + } +}); + +byId("register-form").addEventListener("submit", async (event) => { + event.preventDefault(); + showError("register-error", ""); + const password = byId("register-password").value; + if (password !== byId("register-password-confirm").value) { + showError("register-error", "两次输入的密码不一致。"); + return; + } + const button = byId("register-submit"); + setButtonBusy(button, true, "正在注册…"); + try { + requireSecureCredentialTransport(); + const username = byId("register-username").value.trim(); + const result = await api("/api/v1/register", { method: "POST", csrf: false, body: { + username, + email: byId("register-email").value.trim(), + password, + code: byId("register-code").value.trim(), + } }); + if (result?.registered !== true) throw new Error("面板未确认注册结果,请勿重复提交,稍后尝试登录。"); + byId("register-form").reset(); + showLogin(); + byId("login-username").value = username; + text("login-success", "邮箱已验证,注册成功。账号需等待管理员审核通过后才能创建虚拟机;你可以先登录查看审核状态。"); + byId("login-success").hidden = false; + } catch (error) { + showError("register-error", error.message); + } finally { + byId("register-password").value = ""; + byId("register-password-confirm").value = ""; + setButtonBusy(button, false); + } +}); + +byId("wait-refresh-button").addEventListener("click", async () => { + const button = byId("wait-refresh-button"); + setButtonBusy(button, true, "正在检查…"); + try { + const session = await api("/api/v1/session"); + if (!session?.authenticated) { showLogin(); return; } + await continueAfterLogin(session); + } catch (error) { + toast(`状态检查失败:${error.message}`, "error"); + } finally { + setButtonBusy(button, false); + } +}); + +byId("smtp-settings-form").addEventListener("submit", async (event) => { + event.preventDefault(); + if (!state.admin) return; + showError("smtp-error", ""); + const button = byId("smtp-save-button"); + const body = { + host: byId("smtp-host").value.trim(), + port: Number(byId("smtp-port").value), + tls_mode: byId("smtp-tls-mode").value, + username: byId("smtp-username").value.trim(), + password: byId("smtp-password").value, + from_address: byId("smtp-from-address").value.trim(), + }; + setButtonBusy(button, true, "正在保存…"); + try { + requireSecureCredentialTransport(); + await api("/api/v1/smtp/settings", { method: "PUT", body }); + await loadSmtpSettings(); + toast("邮件设置已保存。", "success"); + } catch (error) { + showError("smtp-error", error.message); + } finally { + delete body.password; + byId("smtp-password").value = ""; + setButtonBusy(button, false); + } +}); + async function logout(button) { setButtonBusy(button, true, "退出中…"); try { @@ -1873,6 +2200,7 @@ async function logout(button) { } byId("logout-button").addEventListener("click", () => void logout(byId("logout-button"))); +byId("wait-logout-button").addEventListener("click", () => void logout(byId("wait-logout-button"))); byId("host-logout-button").addEventListener("click", () => void logout(byId("host-logout-button"))); byId("unlock-logout-button").addEventListener("click", () => void logout(byId("unlock-logout-button"))); byId("host-settings-button").addEventListener("click", () => showHostView(state.hostConfig || { configured: true })); @@ -1882,6 +2210,9 @@ byId("unlock-update-button").addEventListener("click", () => openUpdateFromGate( byId("vm-navigation-button").addEventListener("click", leaveUpdateWorkspace); byId("update-settings-button").addEventListener("click", () => void showUpdateWorkspace()); byId("update-settings-mobile-button").addEventListener("click", () => void showUpdateWorkspace()); +byId("smtp-settings-button").addEventListener("click", () => void showSmtpWorkspace()); +byId("smtp-settings-mobile-button").addEventListener("click", () => void showSmtpWorkspace()); +byId("smtp-back-button").addEventListener("click", showVmWorkspace); byId("update-back-button").addEventListener("click", leaveUpdateWorkspace); byId("unlock-settings-button").addEventListener("click", () => showHostView(state.hostConfig || { configured: true })); byId("host-back-button").addEventListener("click", () => { @@ -2139,6 +2470,7 @@ document.querySelectorAll('input[name="source"]').forEach((radio) => radio.addEv })); byId("template-import-button").addEventListener("click", async () => { + if (!state.admin) return; showError("template-import-error", ""); const existingJobId = state.templateImportJobId; const name = byId("template-name").value.trim(); diff --git a/static/index.html b/static/index.html index fffbbe5c..f64e3454 100644 --- a/static/index.html +++ b/static/index.html @@ -5,8 +5,8 @@ VirtPilot · 虚拟机管理 - - + +
@@ -20,7 +20,7 @@ FIRST RUN SETUP

先连接数据库,
再开始管理。

面板业务数据保存在 MariaDB 中。只需在首次启用时填写连接信息,无需预先编辑面板配置文件。

-
01 · 配置数据库02 · 创建管理员03 · 连接宿主机
+
01 · 配置数据库02 · 创建初始用户03 · 授予管理员权限
@@ -44,7 +44,7 @@ -

数据库需由你预先创建并授权;面板不会自动安装 MariaDB。初始化令牌完成管理员创建后失效。

+

数据库需由你预先创建并授权;面板不会自动安装 MariaDB。初始化令牌完成初始用户创建后失效。

@@ -54,28 +54,28 @@
VirtPilot
FIRST RUN SETUP

欢迎使用
VirtPilot

-

完成数据库连接后,即可创建管理员并接入远端 libvirt 宿主机。

-
01 · 配置数据库02 · 创建管理员03 · 连接宿主机
+

完成数据库连接后先创建初始用户,再由你在数据库中将其 admin 字段改为管理员权限。

+
01 · 配置数据库02 · 创建初始用户03 · 授予管理员权限
步骤 02 / 03 -

创建面板管理员

+

创建初始用户

使用面板首次启动时在终端输出的一次性初始化令牌。完成后令牌将失效。

安全检查:请先完成你自己的 HTTPS 反向代理,并确认浏览器连接的是你信任的证书和域名,再输入令牌、密码或宿主机私钥。

- + - + - +
-

请通过启动终端输出获取令牌,不要向其他人提供。面板账号与宿主机 root 账号相互独立。

+

初始用户默认没有管理员权限。创建后请由你在数据库中将该用户 admin 字段设为 1,再重新登录配置 SMTP 和宿主机。面板账号与宿主机 root 账号相互独立。

@@ -97,24 +97,54 @@
-
+ +
+
+
VirtPilot
+
ACCOUNT STATUS

等待管理员审核

邮箱已验证,账号正在等待管理员审核。审核通过后才能创建和管理虚拟机。

+
+
VirtPilot
@@ -191,6 +221,7 @@ + +
diff --git a/static/styles.css b/static/styles.css index 2eb38b03..e777a34a 100644 --- a/static/styles.css +++ b/static/styles.css @@ -56,6 +56,7 @@ input:focus,select:focus,button:focus-visible{outline:3px solid rgba(18,166,176, .login-submit{height:48px;justify-content:space-between;padding:0 17px;margin-top:6px;font-size:14px} .login-submit span{font-size:20px;font-weight:400} .login-hint{margin:27px 0 0;color:#9aa5b2;font-size:12px;line-height:1.7} +.auth-switch{display:flex;align-items:center;gap:5px;margin:20px 0 0;color:#708093;font-size:12px}.auth-switch button{padding:2px 0;border:0;background:transparent;color:#0f8f9a;font-size:12px;font-weight:800}.auth-switch button:hover{text-decoration:underline}.register-code-row{display:flex;align-items:flex-start;gap:9px;margin-bottom:19px}.register-code-row input{min-width:0;flex:1;margin:0}.register-code-row .button{flex:none;height:46px}.register-code-status,.smtp-status{margin:0 0 16px;padding:10px 12px;border-radius:8px;background:#ecf8f7;color:#267d78;font-size:12px;line-height:1.6}.smtp-status{margin:0}.smtp-card{max-width:780px;margin-bottom:18px}.smtp-card .form-error{margin:0}.pending-users-list{display:grid;gap:10px}.pending-users-list>.muted{margin:0}.pending-user-row{display:flex;align-items:center;justify-content:space-between;gap:15px;border:1px solid #e2ebef;border-radius:9px;padding:13px 15px}.pending-user-details{min-width:0;display:grid;gap:4px;overflow-wrap:anywhere}.pending-user-details strong{font-size:13px;color:#2f455a}.pending-user-details span{font-size:12px;color:#5b7285}.pending-user-details small{font-size:11px;color:#9aabba} .setup-layout{display:grid;grid-template-columns:minmax(330px,40%) 1fr;min-height:100vh;background:#fff} .setup-intro{min-height:640px;background:radial-gradient(circle at 90% 95%,#1b5d68,#122d44 40%,#0e1e31 85%);color:#fff;padding:clamp(35px,5vw,75px);display:flex;flex-direction:column;align-items:flex-start} .setup-brand,.host-brand{display:flex;align-items:center;gap:11px;font-size:22px;font-weight:800;letter-spacing:-.5px}.setup-brand{margin-bottom:auto} @@ -92,6 +93,7 @@ input:focus,select:focus,button:focus-visible{outline:3px solid rgba(18,166,176, .breadcrumb{font-size:12px;color:#8c9bac}.breadcrumb span{padding:0 11px;color:#bbc5d0}.breadcrumb strong{color:#344961;font-weight:700} .topbar-right{display:flex;align-items:center;gap:19px}.topbar-user{display:flex;align-items:center;gap:9px;color:#34455b;font-size:12px;font-weight:700} .host-settings-mobile{display:none} +.admin-menu{display:none;position:relative;z-index:11}.admin-menu summary{list-style:none;display:flex;align-items:center;gap:5px;min-height:32px;padding:5px 9px;border-radius:7px;color:#536b7e;font-size:11px;font-weight:700;cursor:pointer;white-space:nowrap}.admin-menu summary::-webkit-details-marker{display:none}.admin-menu summary:hover,.admin-menu[open] summary{background:#edf6f6;color:#117f88}.admin-menu-options{position:absolute;right:0;top:calc(100% + 5px);display:grid;gap:3px;min-width:148px;padding:6px;border:1px solid #dde7ed;border-radius:9px;background:#fff;box-shadow:0 12px 30px rgba(17,42,59,.14)}.admin-menu-options .button{width:100%;justify-content:flex-start} .avatar{display:inline-flex;align-items:center;justify-content:center;border-radius:50%;height:30px;width:30px;background:#e9f8f7;color:#118e9a;font-size:12px;font-weight:800} .content{max-width:1600px;margin:0 auto;padding:37px clamp(24px,3.3vw,55px) 24px} .page-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:24px;margin-bottom:32px} @@ -149,7 +151,7 @@ tbody tr:hover{background:#fcfefe} .console-backdrop{padding:24px}.console-modal{width:min(100%,1200px);max-height:95vh;display:flex;flex-direction:column;overflow:hidden;background:#101820}.console-toolbar{display:flex;align-items:center;justify-content:space-between;gap:20px;background:#fff;padding:15px 20px}.console-toolbar h2{margin:4px 0 1px;font-size:16px}.console-toolbar p{margin:0;font-size:11px;color:#93a1af}.console-tools{display:flex;align-items:center;gap:8px}.console-stage{position:relative;min-height:280px;height:min(70vh,720px);background:#101820;display:flex;align-items:center;justify-content:center;overflow:hidden}.console-stage canvas{max-width:100%;max-height:100%}.console-placeholder{display:flex;align-items:center;gap:13px;color:#a9b9c5;font-size:12px}.console-spinner{height:20px;width:20px;border-radius:50%;border:2px solid #4f6673;border-top-color:#40ccd0;animation:spin .8s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}.console-password{display:flex;align-items:center;gap:10px;background:#fff;padding:13px 20px}.console-password label{margin:0;white-space:nowrap}.console-password input{width:220px;height:35px} .toast-region{position:fixed;right:23px;bottom:22px;display:flex;flex-direction:column;gap:9px;z-index:80;pointer-events:none}.toast{max-width:min(430px,calc(100vw - 36px));padding:12px 16px;border-radius:9px;color:#fff;background:#20364a;box-shadow:0 10px 24px rgba(15,30,44,.2);font-size:12px;line-height:1.5;pointer-events:auto}.toast.error{background:#ae3c49}.toast.success{background:#157e75} @media(max-width:1150px){th,td{padding-left:15px;padding-right:15px}.row-button{padding:6px}.content{padding-left:28px;padding-right:28px}} -@media(max-width:960px){.dashboard{display:block}.sidebar{position:relative;width:100%;height:65px;min-height:65px;padding:12px 24px}.sidebar-brand{padding:0}.sidebar-section-label,.sidebar-link,.sidebar-bottom{display:none}.host-settings-mobile{display:inline-flex}.topbar{height:60px;padding:0 24px}.content{padding:30px 24px}.page-heading{margin-bottom:24px}} +@media(max-width:960px){.dashboard{display:block}.sidebar{position:relative;width:100%;height:65px;min-height:65px;padding:12px 24px}.sidebar-brand{padding:0}.sidebar-section-label,.sidebar-link,.sidebar-bottom{display:none}.admin-menu{display:block}.topbar{height:60px;padding:0 24px}.content{padding:30px 24px}.page-heading{margin-bottom:24px}} @media(max-width:960px){.host-columns{grid-template-columns:1fr}.host-side-stack{grid-template-columns:repeat(2,minmax(0,1fr));align-items:start}.setup-layout{grid-template-columns:minmax(280px,36%) 1fr}} @media(max-width:960px){.update-grid{grid-template-columns:1fr}} @media(max-width:960px){.vm-detail-grid{grid-template-columns:1fr}} @@ -158,6 +160,7 @@ tbody tr:hover{background:#fcfefe} @media(max-width:740px){.vm-table{min-width:0}.vm-table thead{display:none}.vm-table tbody{display:grid;gap:12px;padding:12px}.vm-table tr{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));border:1px solid #e4ebf0;border-radius:10px;overflow:hidden}.vm-table td{display:block;min-width:0;height:auto;border:0;padding:12px 14px}.vm-table td:first-child{grid-column:1/-1;border-bottom:1px solid #edf1f5}.vm-table td:not(:first-child):before{content:attr(data-label);display:block;color:#9ba8b7;font-size:10px;font-weight:800;margin-bottom:7px}.vm-table .vm-metadata{max-width:none}.vm-table .vm-ip{white-space:normal}.vm-detail-facts{padding:4px 17px 12px}.vm-detail-actions{padding:16px 19px 19px}} @media(max-width:740px){.setup-layout{display:block}.setup-intro{min-height:0;padding:28px 25px}.setup-brand{margin:0 0 38px}.setup-intro h1{font-size:31px;margin:11px 0}.setup-intro p{font-size:12px;margin-bottom:24px}.setup-steps{margin-top:0}.setup-form-side{padding:36px 25px 55px}.setup-card h2{font-size:27px}.host-side-stack{grid-template-columns:1fr}.host-heading{align-items:flex-start;flex-direction:column}.host-topbar{height:65px}.host-content{padding-top:27px}.host-card{padding:20px}} @media(max-width:510px){.topbar{padding:0 17px}.content{padding:25px 14px}.page-heading{padding:0 3px}.overview-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.stat-card{padding:13px 11px;min-height:112px}.stat-card>strong{font-size:23px}.stat-icon{display:none}.topbar-right{gap:4px}.topbar-user{font-size:11px}.breadcrumb{font-size:11px}.modal-backdrop{padding:10px}.modal-header,.modal-body{padding-left:19px;padding-right:19px}.modal-footer{padding:14px 19px}.form-grid{gap:15px 10px}.console-backdrop{padding:0}.console-modal{height:100vh;max-height:100vh;border-radius:0}.console-stage{flex:1;height:auto}.console-tools .button{display:none}.console-password{flex-wrap:wrap}.console-password input{flex:1;min-width:130px}} -@media(max-width:510px){.topbar-right{flex-wrap:wrap;justify-content:flex-end;gap:2px}.host-settings-mobile{font-size:10px!important;padding:5px!important;min-height:28px!important}.topbar-user .avatar{display:none}.update-versions{grid-template-columns:1fr}} +@media(max-width:510px){.topbar-right{flex-wrap:nowrap;justify-content:flex-end;gap:5px;min-width:0}.topbar-user{min-width:0}.topbar-user #current-username{display:block;max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.topbar-user .avatar{display:none}.topbar-right #logout-button{font-size:10px;padding:5px;min-height:28px}.breadcrumb{white-space:nowrap}.breadcrumb span{padding:0 5px}.update-versions{grid-template-columns:1fr}} @media(max-width:510px){.create-source-picker,.cloud-fields>.form-grid{grid-template-columns:1fr}} +@media(max-width:510px){.register-code-row{flex-wrap:wrap}.register-code-row input{flex-basis:100%}.register-code-row .button{width:100%}.pending-user-row{align-items:flex-start;flex-direction:column}.pending-user-row .button{width:100%}.smtp-card .form-grid{grid-template-columns:1fr}} @media(max-width:510px){.vm-detail-heading .heading-actions{justify-content:space-between}.vm-detail-heading .heading-actions .button{flex:0 0 auto}.vm-detail-facts{grid-template-columns:1fr}.vm-detail-facts>div{padding:12px 0}.vm-detail-actions .row-button{flex:1 1 135px}.vm-table td{padding:10px 11px}.vm-identity{min-width:0}.vm-name-link{max-width:calc(100vw - 130px)}} diff --git a/tests/test_auth_sessions.py b/tests/test_auth_sessions.py new file mode 100644 index 00000000..c3869c9a --- /dev/null +++ b/tests/test_auth_sessions.py @@ -0,0 +1,79 @@ +"""Database sessions bind to immutable user IDs, not reusable usernames.""" + +from __future__ import annotations + +import json +import time + +import pytest + +from virsh_panel.auth import DatabaseSessionStore, SessionStore + + +class _Records: + def __init__(self): + self.values = {} + + def get(self, record_type, record_key): + return self.values.get((record_type, record_key)) + + def set(self, record_type, record_key, value): + self.values[(record_type, record_key)] = value + + def delete(self, record_type, record_key): + self.values.pop((record_type, record_key), None) + + +def test_database_session_round_trips_immutable_user_id(): + records = _Records() + sessions = DatabaseSessionStore(records) + created = sessions.issue("operator", user_id=47) + assert created.user_id == 47 + key = sessions._key(created.token) + payload = json.loads(records.get("session", key)) + assert payload["user_id"] == 47 + assert created.token not in records.get("session", key) + restored = DatabaseSessionStore(records).get(created.token) + assert restored == created + + +@pytest.mark.parametrize("invalid_id", [None, 0, -1, True, "47", 47.0]) +def test_database_session_issue_refuses_missing_or_invalid_user_id(invalid_id): + sessions = DatabaseSessionStore(_Records()) + with pytest.raises(ValueError, match="positive user ID"): + sessions.issue("operator", user_id=invalid_id) + + +@pytest.mark.parametrize("invalid_id", [None, 0, -1, True, "47", 47.0]) +def test_database_session_get_rejects_legacy_or_invalid_id(invalid_id): + records = _Records() + sessions = DatabaseSessionStore(records) + token = "legacy-token" + payload = { + "username": "operator", "csrf_token": "csrf-token", + "expires_at": time.time() + 100, + } + if invalid_id is not None: + payload["user_id"] = invalid_id + records.set("session", sessions._key(token), json.dumps(payload)) + assert sessions.get(token) is None + + +def test_database_session_expired_token_is_removed(): + records = _Records() + sessions = DatabaseSessionStore(records) + token = "expired-token" + key = sessions._key(token) + records.set("session", key, json.dumps({ + "username": "operator", "user_id": 47, + "csrf_token": "csrf-token", "expires_at": time.time() - 1, + })) + assert sessions.get(token) is None + assert records.get("session", key) is None + + +def test_injected_memory_sessions_keep_username_only_compatibility(): + sessions = SessionStore() + created = sessions.issue("test-admin") + assert created.user_id is None + assert sessions.get(created.token) == created diff --git a/tests/test_database.py b/tests/test_database.py index d49f183b..9ba8125d 100644 --- a/tests/test_database.py +++ b/tests/test_database.py @@ -14,7 +14,7 @@ from types import SimpleNamespace import pytest from cryptography.hazmat.primitives.ciphers.aead import AESGCM -from virsh_panel.auth import verify_password +from virsh_panel.auth import hash_password, verify_password from virsh_panel.cloud_templates import TemplateError from virsh_panel.database import ( DatabasePanelState, @@ -53,6 +53,26 @@ class MemoryStore: if record_type == kind} +class MemoryUsers: + def __init__(self, store: MemoryStore) -> None: + self.store = store + + def has_users(self) -> bool: + return self.store.get("test_user", "initial") is not None + + def create_initial_user(self, username: str, password: str, email=None): + self.store.set("test_user", "initial", json.dumps({ + "id": 1, "username": username, "email": email, + "password_hash": hash_password(password), "admin": False, + "approved": True, "email_verified": True, "created_at": 100, + })) + + def get_by_username(self, username: str): + record = self.store.get("test_user", "initial") + user = json.loads(record) if record else None + return user if user and user["username"] == username else None + + class EncryptedMemoryStore(MemoryStore): """Exercise the production record envelope without a MariaDB server.""" @@ -103,20 +123,20 @@ def test_non_linux_rejects_disk_backed_private_key_fallback(tmp_path, monkeypatc assert not list(data_dir.rglob("id_private")) -def test_admin_hash_is_database_only_and_bootstrap_token_is_consumed(tmp_path: Path): +def test_initial_user_hash_is_database_only_and_bootstrap_token_is_consumed(tmp_path: Path): store = MemoryStore() data_dir = tmp_path / "panel" - state = DatabasePanelState(data_dir, store) + state = DatabasePanelState(data_dir, store, MemoryUsers(store)) token = state.initialize_setup_token() assert token state.create_admin(token, "admin", "a-valid-very-long-password") assert not (data_dir / "state.json").exists() assert not (data_dir / "setup-token").exists() assert stat.S_IMODE(data_dir.stat().st_mode) == 0o700 - reopened = DatabasePanelState(data_dir, store) - username, hashed = reopened.admin() - assert username == "admin" - assert verify_password("a-valid-very-long-password", hashed) + reopened = DatabasePanelState(data_dir, store, MemoryUsers(store)) + user = reopened.users.get_by_username("admin") + assert user["admin"] is False and user["approved"] is True + assert verify_password("a-valid-very-long-password", user["password_hash"]) assert reopened.initialize_setup_token() is None diff --git a/tests/test_database_http.py b/tests/test_database_http.py index b76202d7..d7b4fb5e 100644 --- a/tests/test_database_http.py +++ b/tests/test_database_http.py @@ -23,13 +23,116 @@ except ModuleNotFoundError: sys.modules["libvirt"] = stub from virsh_panel import app as app_module +from virsh_panel.auth import hash_password from virsh_panel.config import Settings from virsh_panel.database import DatabasePanelState, DatabaseTemplateStore +from virsh_panel.users import UserError + + +class MemoryUsers: + """Only the SQL user-store boundary is replaced in isolated HTTP tests.""" + + def __init__(self, store): + self.store = store + + def has_users(self): + return any(kind == "test_user" for kind, _key in self.store.records) + + def get_by_username(self, username): + raw = self.store.get("test_user", username) + return json.loads(raw) if raw else None + + def get_by_id(self, user_id): + for (kind, _key), raw in self.store.records.items(): + if kind == "test_user": + user = json.loads(raw) + if user["id"] == user_id: + return user + return None + + def create_initial_user(self, username, password, email=None): + account = { + "id": 1, "username": username, "email": email, + "password_hash": hash_password(password), "admin": False, + "approved": True, "email_verified": True, "created_at": 100, + } + self.store.set("test_user", username, json.dumps(account)) + return account + + def promote(self, username): + account = self.get_by_username(username) + account["admin"] = True + self.store.set("test_user", username, json.dumps(account)) + + def owns_vm(self, host_scope, vm_id, user_id): + return self.store.get("test_vm_owner", f"{host_scope}:{vm_id}") == str(user_id) + + def assign_vm(self, host_scope, vm_id, user_id): + self.store.set("test_vm_owner", f"{host_scope}:{vm_id}", str(user_id)) + + def delete_vm_owner(self, host_scope, vm_id): + self.store.delete("test_vm_owner", f"{host_scope}:{vm_id}") + + def list_owned_vm_ids(self, host_scope, user_id): + prefix = f"{host_scope}:" + return {key[len(prefix):] for key, owner in self.store.list("test_vm_owner").items() + if key.startswith(prefix) and owner == str(user_id)} + + def list_pending_users(self): + pending = [] + for (kind, _key), raw in self.store.records.items(): + if kind == "test_user": + account = json.loads(raw) + if not account["approved"]: + pending.append({key: value for key, value in account.items() + if key != "password_hash"}) + return pending + + def approve_user(self, user_id): + account = self.get_by_id(user_id) + if account is None: + return None + account["approved"] = True + self.store.set("test_user", account["username"], json.dumps(account)) + return account + + @staticmethod + def generate_code(): + return "123456" + + def issue_registration_code(self, email, code): + if any(json.loads(raw)["email"] == email for (kind, _key), raw in self.store.records.items() + if kind == "test_user"): + return False + self.store.set("test_code", email, code) + return True + + def revoke_registration_code(self, email, code): + if self.store.get("test_code", email) != code: + return False + self.store.delete("test_code", email) + return True + + def register_with_code(self, username, email, password, code): + if self.store.get("test_code", email) != code: + raise UserError("验证码无效或已过期") + if self.get_by_username(username) is not None: + raise UserError("用户名或邮箱已存在", 409) + account = { + "id": 1 + sum(kind == "test_user" for kind, _key in self.store.records), + "username": username, "email": email, + "password_hash": hash_password(password), "admin": False, + "approved": False, "email_verified": True, "created_at": 101, + } + self.store.set("test_user", username, json.dumps(account)) + self.store.delete("test_code", email) + return account class MemoryStore: def __init__(self) -> None: self.records = {} + self.users = MemoryUsers(self) def get(self, kind, key): return self.records.get((kind, key)) @@ -83,7 +186,7 @@ def test_first_run_requires_database_then_admin_and_ignores_old_json(monkeypatch def make_components(directory, config, key, _ssh_binary): calls.append((config, key)) - return (DatabasePanelState(directory, store), FakeManager(), + return (DatabasePanelState(directory, store, store.users), FakeManager(), DatabaseTemplateStore(store), store) monkeypatch.setattr(app_module, "make_components", make_components) @@ -118,7 +221,8 @@ def test_first_run_requires_database_then_admin_and_ignores_old_json(monkeypatch assert created.status_code == 200 assert client.get("/api/v1/setup/status").json() == {"setup_required": False} session_cookie = client.cookies.get("virsh_panel_session") - assert ("admin", "singleton") in store.records + assert ("test_user", "admin") in store.records + assert store.users.get_by_username("admin")["admin"] is False assert not (data_dir / "setup-token").exists() encrypted = (data_dir / "database-config.json").read_bytes() assert b"test-database-password" not in encrypted @@ -137,7 +241,7 @@ def test_update_routes_require_auth_and_never_return_token(monkeypatch, tmp_path data_dir = tmp_path / "data" store = MemoryStore() monkeypatch.setattr(app_module, "make_components", lambda directory, *_: ( - DatabasePanelState(directory, store), FakeManager(), + DatabasePanelState(directory, store, store.users), FakeManager(), DatabaseTemplateStore(store), store, )) settings = Settings(data_dir=data_dir, @@ -194,6 +298,7 @@ def test_update_routes_require_auth_and_never_return_token(monkeypatch, tmp_path "password": "correct-horse-battery-staple", }) assert response.status_code == 200 + store.users.promote("admin") csrf = response.json()["csrf_token"] assert client.put("/api/v1/update/settings", json={ "access_token": "some-very-private-gitea-token", @@ -233,10 +338,10 @@ def test_vm_creation_finishes_before_update_is_queued(monkeypatch, tmp_path): return {"key_locked": False} class BlockingVMService: - def create_vm(self, _spec): + def create_vm(self, spec): vm_started.set() assert release_vm.wait(timeout=5), "test did not release VM creation" - return {"uuid": "00000000-0000-4000-8000-000000000001"} + return {"uuid": spec["vm_uuid"]} class FakeUpdater: def __init__(self, _repo_dir, data_store): @@ -256,7 +361,7 @@ def test_vm_creation_finishes_before_update_is_queued(monkeypatch, tmp_path): raise AssertionError("the mocked update service must start") monkeypatch.setattr(app_module, "make_components", lambda directory, *_: ( - DatabasePanelState(directory, store), ConfiguredManager(), + DatabasePanelState(directory, store, store.users), ConfiguredManager(), DatabaseTemplateStore(store), store, )) monkeypatch.setattr(app_module, "Updater", FakeUpdater) @@ -290,6 +395,7 @@ def test_vm_creation_finishes_before_update_is_queued(monkeypatch, tmp_path): "password": "correct-horse-battery-staple", }) assert admin.status_code == 200 + store.users.promote("admin") headers = {"X-CSRF-Token": admin.json()["csrf_token"]} with ThreadPoolExecutor(max_workers=2) as executor: creating = executor.submit(client.post, "/api/v1/vms", json={ diff --git a/tests/test_libvirt_service.py b/tests/test_libvirt_service.py index d74a8a01..262cc55e 100644 --- a/tests/test_libvirt_service.py +++ b/tests/test_libvirt_service.py @@ -633,6 +633,14 @@ class VMServiceTests(unittest.TestCase): self.assertEqual(len(self.backend.define_xmls), 1) self.assertEqual(self.backend.opened, self.backend.closed) + def test_iso_create_accepts_preassigned_uuid_for_user_ownership(self): + requested_uuid = "14d9bb2f-65cd-4406-a377-90685c0690e4" + created = self.service.create_vm(self.spec(vm_uuid=requested_uuid)) + self.assertEqual(created["uuid"], requested_uuid) + self.assertEqual(self.backend.domains[0].root.findtext("uuid"), requested_uuid) + with self.assertRaisesRegex(self.error_type, "UUID"): + self.service.create_vm(self.spec(name="invalid-uuid", vm_uuid="not-a-uuid")) + def test_unmanaged_vm_does_not_claim_an_os_or_ip(self): vm = self.service.create_vm(self.spec()) domain = self.backend.domains[0] diff --git a/tests/test_metrics.py b/tests/test_metrics.py index e2a170b5..ce474ed2 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -217,14 +217,17 @@ class FakeConnection: self.closed = True -def test_metric_table_created_with_record_table(): +def test_metric_and_user_tables_created_with_record_table(): connection = FakeConnection() store = DatabaseStore.__new__(DatabaseStore) store._connect = lambda: connection store._initialize_schema() - assert len(connection.fake_cursor.commands) == 2 + assert len(connection.fake_cursor.commands) == 5 assert "vm_metric_samples" in connection.fake_cursor.commands[1][0] assert "vm_metric_retention" in connection.fake_cursor.commands[1][0] + assert "CREATE TABLE IF NOT EXISTS users" in connection.fake_cursor.commands[2][0] + assert "CREATE TABLE IF NOT EXISTS registration_codes" in connection.fake_cursor.commands[3][0] + assert "CREATE TABLE IF NOT EXISTS vm_ownership" in connection.fake_cursor.commands[4][0] assert connection.commits == 1 and connection.closed diff --git a/tests/test_registration_http.py b/tests/test_registration_http.py new file mode 100644 index 00000000..c11e0b91 --- /dev/null +++ b/tests/test_registration_http.py @@ -0,0 +1,305 @@ +"""Production database-mode registration and authorization HTTP boundary.""" + +from __future__ import annotations + +import asyncio +import json +import sys +import types +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient +from starlette.websockets import WebSocketDisconnect + + +try: + import libvirt # noqa: F401 +except ModuleNotFoundError: + stub = types.ModuleType("libvirt") + stub.libvirtError = type("libvirtError", (Exception,), {}) + sys.modules["libvirt"] = stub + +from tests.test_database_http import MemoryStore # noqa: E402 +from virsh_panel import app as app_module # noqa: E402 +from virsh_panel.config import Settings # noqa: E402 +from virsh_panel.database import DatabasePanelState, DatabaseTemplateStore # noqa: E402 +from virsh_panel.libvirt_service import VMError # noqa: E402 +from virsh_panel.metrics import host_scope # noqa: E402 + + +ORIGIN = "https://panel.example.test" +PASSWORD = "correct-horse-battery-staple" +CREATE_VM = { + "name": "tenant-vm", "vcpu": 2, "memory_mib": 2048, + "disk_gib": 20, "network": "bridge:br0", "iso": "AlmaLinux-10.iso", +} + + +class _Manager: + profile = { + "host": "vmhost.example.test", "port": 22, + "fingerprint": "SHA256:configured-host", "key_locked": False, + "region": "东京", "storage_pool": "/home/kvm", "iso_pool": "/home/iso", + "default_network": "bridge:br0", "ssh_target": "vp-managed", + "ssh_config_file": "/fake/config", "ssh_known_hosts_file": "/fake/known_hosts", + } + + def current(self): + return self.profile + + def close(self): + pass + + +class _Service: + def __init__(self): + self.vms = {} + self.console_calls = [] + + def create_vm(self, spec): + vm = { + "uuid": spec["vm_uuid"], "name": spec["name"], "state": "running", + "vcpu": spec["vcpu"], "memory_mib": spec["memory_mib"], + "disks": [], "autostart": True, + } + self.vms[vm["uuid"]] = vm + return vm + + def list_vms(self): + return list(self.vms.values()) + + def get_vm(self, vm_id): + if vm_id not in self.vms: + raise VMError("虚拟机不存在", 404) + return self.vms[vm_id] + + def action(self, vm_id, _action): + return self.get_vm(vm_id) + + def delete_vm(self, vm_id, _delete_disks): + self.get_vm(vm_id) + del self.vms[vm_id] + return {"uuid": vm_id, "deleted": True, "deleted_disks": []} + + def console_port(self, vm_id): + self.console_calls.append(vm_id) + self.get_vm(vm_id) + return 5907 + + +class _NoMetrics: + def __init__(self, *_args, **_kwargs): + pass + + def start(self): + pass + + def close(self): + pass + + +def _login(client: TestClient, username: str): + response = client.post("/api/v1/login", json={ + "username": username, "password": PASSWORD, + }) + assert response.status_code == 200 + return {"X-CSRF-Token": response.json()["csrf_token"]} + + +def _register(client: TestClient, address: str, username: str): + code = client.post("/api/v1/register/code", json={"email": address}) + assert code.status_code == 200 and code.json() == {"sent": True} + response = client.post("/api/v1/register", json={ + "username": username, "email": address, + "password": PASSWORD, "code": "123456", + }) + assert response.status_code == 201 + assert response.json() == {"registered": True, "approved": False} + + +def test_registration_smtp_approval_and_per_user_vm_isolation(monkeypatch, tmp_path): + store = MemoryStore() + service = _Service() + sent = [] + monkeypatch.setattr(app_module, "make_components", lambda directory, *_: ( + DatabasePanelState(directory, store, store.users), _Manager(), + DatabaseTemplateStore(store), store, + )) + monkeypatch.setattr(app_module, "MetricsCollector", _NoMetrics) + monkeypatch.setattr( + app_module, "send_verification_code", + lambda config, email, code: sent.append((config.host, email, code)), + ) + settings = Settings( + data_dir=tmp_path / "data", + static_dir=Path(__file__).resolve().parents[1] / "static", + ) + app = app_module.create_app(settings, service_factory=lambda _profile: service) + token = (settings.data_dir / "setup-token").read_text(encoding="ascii").strip() + + with TestClient(app, base_url=ORIGIN) as admin: + configured = admin.post("/api/v1/database/setup", json={ + "host": "127.0.0.1", "port": 3306, "database": "virsh_panel", + "username": "panel", "password": "database-password", "setup_token": token, + }) + assert configured.status_code == 200 + initial = admin.post("/api/v1/setup/admin", json={ + "token": token, "username": "firstuser", "password": PASSWORD, + }) + assert initial.status_code == 200 + admin_headers = {"X-CSRF-Token": initial.json()["csrf_token"]} + assert admin.get("/api/v1/session").json()["admin"] is False + assert admin.get("/api/v1/smtp/settings").status_code == 403 + # The operator promotes the initial account manually in MariaDB. + store.users.promote("firstuser") + assert admin.get("/api/v1/session").json()["admin"] is True + smtp = admin.put("/api/v1/smtp/settings", json={ + "host": "smtp.example.test", "port": 587, "tls_mode": "starttls", + "from_address": "panel@example.test", "username": "mailer", + "password": "smtp-secret-password", + }, headers=admin_headers) + assert smtp.status_code == 200 + assert "smtp-secret-password" not in smtp.text + + original_sender = app_module.send_verification_code + + def fail_delivery(_config, _email, _code): + raise app_module.SMTPError("模拟 SMTP 发送失败", 502) + + monkeypatch.setattr(app_module, "send_verification_code", fail_delivery) + with TestClient(app, base_url=ORIGIN) as visitor: + failed_send = visitor.post("/api/v1/register/code", json={ + "email": "delivery-fail@example.test", + }) + assert failed_send.status_code == 200 + assert failed_send.json() == {"sent": True} + # A failed background delivery must remove the challenge so the + # user is not trapped behind the resend cooldown. + assert store.get("test_code", "delivery-fail@example.test") is None + monkeypatch.setattr(app_module, "send_verification_code", original_sender) + with TestClient(app, base_url=ORIGIN) as visitor: + retried = visitor.post("/api/v1/register/code", json={ + "email": "delivery-fail@example.test", + }) + assert retried.status_code == failed_send.status_code + assert retried.json() == failed_send.json() + assert store.get("test_code", "delivery-fail@example.test") == "123456" + sent.clear() + + with TestClient(app, base_url=ORIGIN) as first: + _register(first, "one@example.test", "tenantone") + assert sent == [("smtp.example.test", "one@example.test", "123456")] + first_headers = _login(first, "tenantone") + assert first.get("/api/v1/session").json()["approved"] is False + assert first.post("/api/v1/vms", json=CREATE_VM, + headers=first_headers).status_code == 403 + for protected in ( + "/api/v1/host", "/api/v1/update/settings", + "/api/v1/smtp/settings", "/api/v1/users/pending", + ): + assert first.get(protected).status_code == 403 + pending = admin.get("/api/v1/users/pending") + assert pending.status_code == 200 + items = pending.json()["items"] + assert len(items) == 1 and items[0]["username"] == "tenantone" + assert "password_hash" not in items[0] + approve = admin.post(f"/api/v1/users/{items[0]['id']}/approve", + headers=admin_headers) + assert approve.status_code == 200 + assert first.get("/api/v1/session").json()["approved"] is True + own = first.post("/api/v1/vms", json=CREATE_VM, headers=first_headers) + assert own.status_code == 201 + own_id = own.json()["uuid"] + + with TestClient(app, base_url=ORIGIN) as second: + _register(second, "two@example.test", "tenanttwo") + second_headers = _login(second, "tenanttwo") + second_id = store.users.get_by_username("tenanttwo")["id"] + assert admin.post(f"/api/v1/users/{second_id}/approve", + headers=admin_headers).status_code == 200 + other = second.post("/api/v1/vms", json={**CREATE_VM, "name": "other-vm"}, + headers=second_headers) + assert other.status_code == 201 + other_id = other.json()["uuid"] + + assert [vm["uuid"] for vm in first.get("/api/v1/vms").json()["items"]] == [own_id] + assert [vm["uuid"] for vm in second.get("/api/v1/vms").json()["items"]] == [other_id] + assert len(admin.get("/api/v1/vms").json()["items"]) == 2 + assert first.get(f"/api/v1/vms/{other_id}").status_code == 404 + assert first.post(f"/api/v1/vms/{other_id}/credential", + headers=first_headers).status_code == 404 + assert first.get(f"/api/v1/vms/{other_id}/metrics").status_code == 404 + assert first.post(f"/api/v1/vms/{other_id}/actions", json={ + "action": "reboot", + }, headers=first_headers).status_code == 404 + assert first.delete(f"/api/v1/vms/{other_id}", + headers=first_headers).status_code == 404 + assert first.get(f"/api/v1/vms/{own_id}").status_code == 200 + assert first.get("/api/v1/host").status_code == 403 + assert first.put("/api/v1/update/settings", json={ + "repository_url": "https://g.luoli.live/root/virt.git", "branch": "main", + "access_token": "forbidden", + }, headers=first_headers).status_code == 403 + assert first.put("/api/v1/smtp/settings", json={ + "host": "evil.example.test", "port": 587, "tls_mode": "starttls", + "from_address": "evil@example.test", + }, headers=first_headers).status_code == 403 + assert first.post(f"/api/v1/users/{second_id}/approve", + headers=first_headers).status_code == 403 + + cookie = first.cookies.get("virsh_panel_session") + with pytest.raises(WebSocketDisconnect) as denied: + with first.websocket_connect( + f"wss://panel.example.test/api/v1/vms/{other_id}/console", + headers={ + "host": "panel.example.test", "origin": ORIGIN, + "cookie": f"virsh_panel_session={cookie}", + }, + ): + pass + assert denied.value.code == 4404 + assert service.console_calls == [] + + monkeypatch.setattr(app_module, "CONSOLE_ACCESS_CHECK_SECONDS", 0.05) + + async def held_console(_websocket, **_kwargs): + # If the watchdog fails to close promptly, the relay + # closes with 1011 after a bounded fallback delay. + await asyncio.sleep(1) + raise app_module.ConsoleRelayError("test relay timeout") + + monkeypatch.setattr(app_module, "relay_console", held_console) + own_console = f"wss://panel.example.test/api/v1/vms/{own_id}/console" + own_cookie = first.cookies.get("virsh_panel_session") + with first.websocket_connect(own_console, headers={ + "host": "panel.example.test", "origin": ORIGIN, + "cookie": f"virsh_panel_session={own_cookie}", + }) as console: + assert first.post("/api/v1/logout", headers=first_headers).status_code == 200 + with pytest.raises(WebSocketDisconnect) as revoked: + console.receive_text() + assert revoked.value.code == 4403 + + first_headers = _login(first, "tenantone") + own_cookie = first.cookies.get("virsh_panel_session") + with first.websocket_connect(own_console, headers={ + "host": "panel.example.test", "origin": ORIGIN, + "cookie": f"virsh_panel_session={own_cookie}", + }) as console: + store.users.delete_vm_owner(host_scope(_Manager.profile), own_id) + with pytest.raises(WebSocketDisconnect) as ownership_revoked: + console.receive_text() + assert ownership_revoked.value.code == 4403 + + # A deleted username may later be reused. Its old bearer + # cookie must not acquire the replacement account's role. + old_account = store.users.get_by_username("tenantone") + store.delete("test_user", "tenantone") + replacement = {**old_account, "id": old_account["id"] + 1000, + "admin": True} + store.set("test_user", "tenantone", json.dumps(replacement)) + assert first.get("/api/v1/session").json()["authenticated"] is False + assert first.get("/api/v1/smtp/settings").status_code == 401 + assert first.post("/api/v1/vms", json=CREATE_VM, + headers=first_headers).status_code == 401 diff --git a/tests/test_smtp_service.py b/tests/test_smtp_service.py new file mode 100644 index 00000000..d2906a3c --- /dev/null +++ b/tests/test_smtp_service.py @@ -0,0 +1,201 @@ +"""SMTP settings safety and registration mail transport tests.""" + +from __future__ import annotations + +import smtplib + +import pytest +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +from virsh_panel.database import DatabaseStore +from virsh_panel.smtp_service import ( + SMTPConfig, SMTPError, SMTPSettingsStore, send_verification_code, validate_email, +) + + +def _settings(**overrides): + values = { + "host": "smtp.example.com", "port": 587, "tls_mode": "starttls", + "from_address": "no-reply@example.com", "username": "account@example.com", + "password": "app-password-secret", + } + values.update(overrides) + return values + + +class EncryptedRecords: + def __init__(self): + self.cipher = DatabaseStore.__new__(DatabaseStore) + self.cipher._cipher = AESGCM(b"s" * 32) + self.data = {} + + def get(self, kind, key): + encrypted = self.data.get((kind, key)) + return None if encrypted is None else self.cipher._decrypt(kind, key, encrypted) + + def set(self, kind, key, value): + self.data[(kind, key)] = self.cipher._encrypt(kind, key, value) + + +def test_smtp_settings_are_encrypted_and_password_never_returns_in_status(): + records = EncryptedRecords() + settings = SMTPSettingsStore(records) + assert settings.public_status() == {"configured": False} + + config = settings.save(_settings()) + assert config.password == "app-password-secret" + ciphertext = records.data[("smtp", "current")] + assert b"app-password-secret" not in ciphertext + assert b"smtp.example.com" not in ciphertext + + status = settings.public_status() + assert status == { + "configured": True, "host": "smtp.example.com", "port": 587, + "tls_mode": "starttls", "from_address": "no-reply@example.com", + "username": "account@example.com", "password_configured": True, + } + assert "app-password-secret" not in repr(config) + assert "password" not in status + + +def test_smtp_update_keeps_existing_password_only_for_same_account(): + settings = SMTPSettingsStore(EncryptedRecords()) + settings.save(_settings()) + assert settings.save(_settings(host="new.example.com", password="")).password == "app-password-secret" + with pytest.raises(SMTPError, match="必须同时填写"): + settings.save(_settings(username="other@example.com", password="")) + assert settings.get().host == "new.example.com" + assert settings.get().username == "account@example.com" + + +@pytest.mark.parametrize("value", [ + _settings(host="smtp.example.com\r\nX-Injected: yes"), + _settings(port=True), + _settings(port=0), + _settings(tls_mode="invalid"), + _settings(tls_mode=[]), + _settings(from_address="Sender "), + _settings(username="x", password="", tls_mode="starttls"), + _settings(tls_mode="none"), +]) +def test_invalid_smtp_settings_are_rejected(value): + with pytest.raises(SMTPError): + SMTPConfig.from_mapping(value) + + +@pytest.mark.parametrize("address", [ + "user@example.com\r\nBcc: victim@example.com", "Name ", + "user..name@example.com", "user@", "@example.com", " user@example.com", +]) +def test_invalid_mailbox_is_rejected(address): + with pytest.raises(SMTPError, match="邮箱地址格式无效"): + validate_email(address) + + +def test_address_keeps_local_part_and_canonicalizes_domain(): + assert validate_email("User+tag@EXAMPLE.COM") == "User+tag@example.com" + + +class FakeSMTP: + events = [] + sent = None + refused = {} + + def __init__(self, host, port, **kwargs): + self.events.append(("connect", host, port, kwargs)) + + def __enter__(self): + return self + + def __exit__(self, *_args): + self.events.append("quit") + + def ehlo(self): + self.events.append("ehlo") + + def starttls(self, **kwargs): + assert "context" in kwargs + self.events.append("starttls") + + def login(self, username, password): + self.events.append(("login", username, password)) + + def send_message(self, message): + self.events.append("send") + self.sent = message + return self.refused + + +def test_starttls_happens_before_login_and_sends_six_digit_code(monkeypatch): + FakeSMTP.events = [] + FakeSMTP.refused = {} + instances = [] + + def make_client(*args, **kwargs): + client = FakeSMTP(*args, **kwargs) + instances.append(client) + return client + + monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", make_client) + send_verification_code(SMTPConfig.from_mapping(_settings()), "user@example.com", "012345") + + assert FakeSMTP.events[0][0:3] == ("connect", "smtp.example.com", 587) + assert FakeSMTP.events[0][3]["timeout"] == 10 + assert FakeSMTP.events[1:] == [ + "ehlo", "starttls", "ehlo", + ("login", "account@example.com", "app-password-secret"), "send", "quit", + ] + message = instances[0].sent + assert message["To"] == "user@example.com" + assert message["From"] == "no-reply@example.com" + assert "012345" in message.get_content() + + +def test_ssl_and_unauthenticated_local_relay(monkeypatch): + FakeSMTP.events = [] + FakeSMTP.refused = {} + monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP_SSL", FakeSMTP) + send_verification_code( + SMTPConfig.from_mapping(_settings(port=465, tls_mode="ssl")), + "user@example.com", "123456", + ) + assert FakeSMTP.events[0][0:3] == ("connect", "smtp.example.com", 465) + assert "context" in FakeSMTP.events[0][3] + assert "starttls" not in FakeSMTP.events + + FakeSMTP.events = [] + monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", FakeSMTP) + send_verification_code( + SMTPConfig.from_mapping(_settings(port=25, tls_mode="none", username="", password="")), + "user@example.com", "123456", + ) + assert not any(isinstance(event, tuple) and event[0] == "login" + for event in FakeSMTP.events) + + +def test_smtp_transport_failure_is_redacted(monkeypatch): + class FailingSMTP(FakeSMTP): + def login(self, *_args): + raise smtplib.SMTPAuthenticationError(535, b"secret server reply") + + monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", FailingSMTP) + with pytest.raises(SMTPError) as failure: + send_verification_code( + SMTPConfig.from_mapping(_settings()), "user@example.com", "123456", + ) + assert failure.value.status == 502 + assert "secret" not in str(failure.value) + assert "app-password" not in str(failure.value) + + +def test_refused_recipient_and_bad_code_do_not_leak_details(monkeypatch): + FakeSMTP.events = [] + FakeSMTP.refused = {"user@example.com": (550, "mailbox secret")} + monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", FakeSMTP) + config = SMTPConfig.from_mapping(_settings()) + with pytest.raises(SMTPError) as failure: + send_verification_code(config, "user@example.com", "123456") + assert failure.value.status == 502 + assert "secret" not in str(failure.value) + with pytest.raises(SMTPError, match="验证码格式无效"): + send_verification_code(config, "user@example.com", "00000\n") diff --git a/tests/test_users.py b/tests/test_users.py new file mode 100644 index 00000000..edaf3da5 --- /dev/null +++ b/tests/test_users.py @@ -0,0 +1,240 @@ +"""Exercise SQL-backed registration and ownership without a MariaDB daemon.""" + +from __future__ import annotations + +import sqlite3 +import uuid + +import pytest + +from virsh_panel.auth import verify_password +from virsh_panel.users import DatabaseUserStore, UserError, normalize_email + + +class _Cursor: + def __init__(self, connection: sqlite3.Connection) -> None: + self._cursor = connection.cursor() + + def __enter__(self): + return self + + def __exit__(self, *_exc): + self._cursor.close() + + def execute(self, statement, parameters=()): + sql = statement.replace("%s", "?").replace(" FOR UPDATE", "") + try: + self._cursor.execute(sql, parameters) + except sqlite3.IntegrityError as exc: + import pymysql + + raise pymysql.err.IntegrityError(1062, str(exc)) from exc + return self + + def fetchone(self): + row = self._cursor.fetchone() + return None if row is None else dict(row) + + def fetchall(self): + return [dict(row) for row in self._cursor.fetchall()] + + @property + def lastrowid(self): + return self._cursor.lastrowid + + @property + def rowcount(self): + return self._cursor.rowcount + + +class _Connection: + def __init__(self): + self.raw = sqlite3.connect(":memory:") + self.raw.row_factory = sqlite3.Row + self.raw.execute("PRAGMA foreign_keys=ON") + self.raw.executescript(""" + CREATE TABLE users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL UNIQUE, + email TEXT UNIQUE, + password_hash TEXT NOT NULL, + admin INTEGER NOT NULL DEFAULT 0, + approved INTEGER NOT NULL DEFAULT 0, + email_verified INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL + ); + CREATE TABLE registration_codes ( + email TEXT PRIMARY KEY, + code_hash TEXT NOT NULL, + sent_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + failed_attempts INTEGER NOT NULL DEFAULT 0 + ); + CREATE TABLE vm_ownership ( + host_scope TEXT NOT NULL, + vm_uuid TEXT NOT NULL, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + created_at INTEGER NOT NULL, + PRIMARY KEY (host_scope, vm_uuid) + ); + """) + + def cursor(self): + return _Cursor(self.raw) + + def commit(self): + self.raw.commit() + + def rollback(self): + self.raw.rollback() + + def close(self): + # DatabaseUserStore opens a new wrapper per method. This one fake + # keeps a shared in-memory database alive across the test. + pass + + +class _Store: + def __init__(self): + self.connection = _Connection() + + def _connect(self): + return self.connection + + +@pytest.fixture +def users(): + store = _Store() + yield DatabaseUserStore(store, b"x" * 32), store.connection.raw + store.connection.raw.close() + + +def test_initial_user_is_not_admin_but_is_approved(users): + repository, _database = users + assert repository.has_users() is False + first = repository.create_initial_user("first", "initial-long-password", now=100) + assert first["admin"] is False + assert first["approved"] is True + assert first["email_verified"] is True + assert first["email"] is None + assert verify_password("initial-long-password", first["password_hash"]) + assert repository.has_users() is True + assert repository.get_by_username("first") == first + assert repository.get_by_id(first["id"]) == first + with pytest.raises(UserError) as repeated: + repository.create_initial_user("second", "another-long-password", now=101) + assert repeated.value.status == 409 + + +def test_registration_code_is_keyed_rate_limited_and_one_time(users): + repository, database = users + assert repository.issue_registration_code("User@Example.COM", "123456", now=100) + code_hash = database.execute( + "SELECT code_hash FROM registration_codes WHERE email=?", ("user@example.com",) + ).fetchone()[0] + assert len(code_hash) == 64 + assert code_hash != "123456" + with pytest.raises(UserError) as cooldown: + repository.issue_registration_code("user@example.com", "654321", now=120) + assert cooldown.value.status == 429 + with pytest.raises(UserError): + repository.register_with_code("registered", "user@example.com", "long-user-password", "000000", now=130) + assert database.execute( + "SELECT failed_attempts FROM registration_codes WHERE email=?", ("user@example.com",) + ).fetchone()[0] == 1 + created = repository.register_with_code( + "registered", "USER@EXAMPLE.COM", "long-user-password", "123456", now=140, + ) + assert created["email"] == "user@example.com" + assert created["email_verified"] is True + assert created["admin"] is False + assert created["approved"] is False + assert verify_password("long-user-password", created["password_hash"]) + assert repository.issue_registration_code("user@example.com", "222222", now=300) is False + with pytest.raises(UserError): + repository.register_with_code( + "duplicate", "user@example.com", "long-user-password", "123456", now=145, + ) + + +def test_code_expires_and_five_failures_consume_challenge(users): + repository, database = users + repository.issue_registration_code("fail@example.com", "999999", now=100) + for attempt in range(5): + with pytest.raises(UserError): + repository.register_with_code( + "wrong", "fail@example.com", "long-user-password", "000000", now=110 + attempt, + ) + assert database.execute("SELECT COUNT(*) FROM registration_codes").fetchone()[0] == 0 + with pytest.raises(UserError): + repository.register_with_code( + "wrong", "fail@example.com", "long-user-password", "999999", now=116, + ) + repository.issue_registration_code("expired@example.com", "111111", now=200) + with pytest.raises(UserError): + repository.register_with_code( + "expired", "expired@example.com", "long-user-password", "111111", now=800, + ) + assert database.execute( + "SELECT COUNT(*) FROM registration_codes WHERE email='expired@example.com'" + ).fetchone()[0] == 0 + + +def test_failed_smtp_delivery_can_revoke_only_matching_code(users): + repository, database = users + repository.issue_registration_code("retry@example.com", "111111", now=100) + assert repository.revoke_registration_code("retry@example.com", "222222") is False + assert repository.revoke_registration_code("retry@example.com", "111111") is True + assert database.execute("SELECT COUNT(*) FROM registration_codes").fetchone()[0] == 0 + assert repository.issue_registration_code("retry@example.com", "333333", now=101) + + +def test_approval_and_manual_admin_flag_are_distinct(users): + repository, database = users + repository.issue_registration_code("awaiting@example.com", "123456", now=100) + account = repository.register_with_code( + "awaiting", "awaiting@example.com", "long-user-password", "123456", now=120, + ) + pending = repository.list_pending_users() + assert len(pending) == 1 and pending[0]["username"] == "awaiting" + assert "password_hash" not in pending[0] + approved = repository.approve_user(account["id"]) + assert approved["approved"] is True and approved["admin"] is False + assert repository.list_pending_users() == [] + database.execute("UPDATE users SET admin=1 WHERE id=?", (account["id"],)) + database.commit() + assert repository.get_by_username("awaiting")["admin"] is True + assert repository.approve_user(999999) is None + + +def test_vm_ownership_is_scoped_to_host_and_user(users): + repository, _database = users + first = repository.create_initial_user("first", "initial-long-password", now=100) + repository.issue_registration_code("other@example.com", "123456", now=101) + other = repository.register_with_code( + "other", "other@example.com", "long-user-password", "123456", now=102, + ) + host = "a" * 64 + second_host = "b" * 64 + vm_id = str(uuid.uuid4()) + assert repository.owner_of_vm(host, vm_id) is None + repository.assign_vm(host, vm_id, first["id"], now=103) + repository.assign_vm(host, vm_id, first["id"], now=103) + assert repository.owns_vm(host, vm_id, first["id"]) is True + assert repository.owns_vm(host, vm_id, other["id"]) is False + assert repository.list_owned_vm_ids(host, first["id"]) == {vm_id} + assert repository.list_owned_vm_ids(second_host, first["id"]) == set() + with pytest.raises(UserError) as conflict: + repository.assign_vm(host, vm_id, other["id"], now=104) + assert conflict.value.status == 409 + repository.delete_vm_owner(host, vm_id) + assert repository.owner_of_vm(host, vm_id) is None + + +@pytest.mark.parametrize("address", [ + "evil@example.com\r\nBcc: victim@example.com", "not-an-email", "x@localhost", + "a..b@example.com", "x@example..com", "ñ@example.com", +]) +def test_email_validation_rejects_unsafe_addresses(address): + with pytest.raises(UserError): + normalize_email(address) diff --git a/virsh_panel/app.py b/virsh_panel/app.py index aca88c5a..f74816db 100644 --- a/virsh_panel/app.py +++ b/virsh_panel/app.py @@ -17,7 +17,7 @@ from contextlib import asynccontextmanager, suppress from typing import Any, Callable, Literal from urllib.parse import urlsplit -from fastapi import Depends, FastAPI, HTTPException, Query, Request, WebSocket +from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException, Query, Request, WebSocket from fastapi.responses import FileResponse, JSONResponse from fastapi.staticfiles import StaticFiles from pydantic import BaseModel, ConfigDict, Field, SecretStr @@ -37,10 +37,13 @@ from .metrics import (MAX_QUERY_POINTS, RETENTION_SECONDS, RANGES, MetricsCollec host_scope, query_interval_seconds) from .panel_state import PanelState, SetupError from .remote_host import HostProfile, RemoteHostError, RemoteHostManager +from .smtp_service import SMTPError, SMTPSettingsStore, send_verification_code from .updater import BRANCH, REPOSITORY_URL, UpdateError, Updater +from .users import UserError, normalize_email COOKIE_NAME = "virsh_panel_session" +CONSOLE_ACCESS_CHECK_SECONDS = 15 LOG = logging.getLogger(__name__) STARTUP_LOG = logging.getLogger("uvicorn.error") @@ -86,6 +89,29 @@ class LoginBody(BaseModel): password: str = Field(min_length=1, max_length=1024) +class RegistrationCodeBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + email: str = Field(min_length=3, max_length=254) + + +class RegistrationBody(RegistrationCodeBody): + username: str = Field(min_length=3, max_length=32) + password: str = Field(min_length=12, max_length=1024) + code: str = Field(pattern=r"^[0-9]{6}$") + + +class SMTPSettingsBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + host: str = Field(min_length=1, max_length=253) + port: int = Field(ge=1, le=65535) + tls_mode: Literal["ssl", "starttls", "none"] + username: str = Field(default="", max_length=256) + password: SecretStr | None = None + from_address: str = Field(min_length=3, max_length=254) + + class UnlockBody(BaseModel): model_config = ConfigDict(extra="forbid") @@ -389,6 +415,8 @@ def create_app( restore_jobs() sessions = DatabaseSessionStore(data_store) if data_store is not None else SessionStore() login_limiter = LoginLimiter() + registration_limiter = LoginLimiter() + code_send_limiter = LoginLimiter() setup_limiter = LoginLimiter() unlock_limiter = LoginLimiter() def metric_profile(): @@ -480,10 +508,42 @@ def create_app( async def handle_template_error(_request: Request, exc: TemplateError): return JSONResponse(status_code=exc.status, content={"error": str(exc)}) + @app.exception_handler(UserError) + async def handle_user_error(_request: Request, exc: UserError): + return JSONResponse(status_code=exc.status, content={"error": str(exc)}) + + @app.exception_handler(SMTPError) + async def handle_smtp_error(_request: Request, exc: SMTPError): + return JSONResponse(status_code=exc.status, content={"error": str(exc)}) + + def account_for_session(session: Session) -> dict: + if database_mode: + if state is None: + raise HTTPException(status_code=401, detail="请先登录") + user_id = getattr(session, "user_id", None) + if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: + raise HTTPException(status_code=401, detail="账号不可用,请重新登录") + account = state.users.get_by_id(user_id) + if (account is None or account["username"] != session.username + or not account["email_verified"]): + raise HTTPException(status_code=401, detail="账号不可用,请重新登录") + return account + # The injected JSON state is retained solely for the isolated HTTP + # test harness; production authorization always uses the users table. + return {"id": 0, "username": session.username, "admin": True, + "approved": True, "email_verified": True} + + def host_ready() -> bool: + if manager is None: + return False + profile = manager.current() + return profile is not None and not profile.get("key_locked", False) + def require_session(request: Request) -> Session: session = sessions.get(request.cookies.get(COOKIE_NAME)) if session is None: raise HTTPException(status_code=401, detail="请先登录") + account_for_session(session) return session def require_write(request: Request) -> Session: @@ -493,6 +553,50 @@ def create_app( raise HTTPException(status_code=403, detail="请求验证失败") return session + def require_admin(request: Request) -> Session: + session = require_session(request) + if not account_for_session(session)["admin"]: + raise HTTPException(status_code=403, detail="仅管理员可以执行此操作") + return session + + def require_admin_write(request: Request) -> Session: + session = require_write(request) + if not account_for_session(session)["admin"]: + raise HTTPException(status_code=403, detail="仅管理员可以执行此操作") + return session + + def require_approved(request: Request) -> Session: + session = require_session(request) + account = account_for_session(session) + if not account["admin"] and not account["approved"]: + raise HTTPException(status_code=403, detail="账号等待管理员批准") + return session + + def require_approved_write(request: Request) -> Session: + session = require_write(request) + account = account_for_session(session) + if not account["admin"] and not account["approved"]: + raise HTTPException(status_code=403, detail="账号等待管理员批准") + return session + + def require_vm_access(session: Session, profile: dict, vm_id: str) -> str: + if not database_mode: + return vm_id + try: + canonical_id = str(uuid.UUID(vm_id)) + except (TypeError, ValueError, AttributeError) as exc: + raise VMError("虚拟机 UUID 无效", 400) from exc + account = account_for_session(session) + if not account["admin"] and not state.users.owns_vm( + host_scope(profile), canonical_id, account["id"]): + raise VMError("虚拟机不存在", 404) + return canonical_id + + def smtp_store() -> SMTPSettingsStore: + if data_store is None: + raise SMTPError("请先完成数据库配置", 409) + return SMTPSettingsStore(data_store) + def current_updater() -> Updater: nonlocal updater if data_store is None: @@ -528,6 +632,22 @@ def create_app( profile["default_network"], ) + def verified_created_vm(profile: dict, result: dict, requested_uuid: str) -> dict: + if result.get("uuid") == requested_uuid: + return result + # Keep the preallocated owner/credential records if libvirt may have + # created the requested guest. Never delete a returned, mismatched UUID: + # it may refer to a different existing VM. + LOG.error("VM create returned a mismatched UUID: expected=%s", requested_uuid) + try: + verified = new_service(profile).get_vm(requested_uuid) + except VMError: + verified = None + if verified is not None and verified.get("uuid") == requested_uuid: + LOG.warning("Recovered VM result by querying the requested UUID: %s", requested_uuid) + return verified + raise VMError("虚拟机创建结果与预分配 UUID 不一致;请由管理员核查宿主机及归属记录", 502) + def current_service() -> VMService: return new_service(current_profile()) @@ -552,11 +672,21 @@ def create_app( return None, str(exc) def session_response(username: str) -> JSONResponse: - session = sessions.issue(username) + if database_mode: + account = state.users.get_by_username(username) + if account is None: + raise HTTPException(status_code=401, detail="账号不可用,请重新登录") + session = sessions.issue(username, user_id=account["id"]) + else: + session = sessions.issue(username) + account = account_for_session(session) response = JSONResponse({ "authenticated": True, "username": session.username, "csrf_token": session.csrf_token, + "admin": account["admin"], + "approved": account["approved"], + "host_ready": host_ready(), }) response.set_cookie( COOKIE_NAME, @@ -578,7 +708,10 @@ def create_app( if data_store is not None: # A running HTTP listener alone is not a usable post-update panel. # The updater treats this endpoint as readiness for the configured DB. - data_store.get("admin", "singleton") + if database_mode: + state.users.has_users() + else: + data_store.get("admin", "singleton") return {"status": "ok"} @app.get("/api/v1/database/status") @@ -646,7 +779,7 @@ def create_app( setup_limiter.failed(peer) raise setup_limiter.succeeded(peer) - LOG.info("panel administrator created: username=%s", username) + LOG.info("panel initial user created: username=%s", username) return session_response(username) @app.get("/api/v1/session") @@ -654,10 +787,17 @@ def create_app( session = sessions.get(request.cookies.get(COOKIE_NAME)) if session is None: return {"authenticated": False, "username": None, "csrf_token": None} + try: + account = account_for_session(session) + except HTTPException: + return {"authenticated": False, "username": None, "csrf_token": None} return { "authenticated": True, "username": session.username, "csrf_token": session.csrf_token, + "admin": account["admin"], + "approved": account["approved"], + "host_ready": host_ready(), } @app.post("/api/v1/login") @@ -667,18 +807,83 @@ def create_app( peer = _peer(request) if not login_limiter.allowed(peer): raise HTTPException(status_code=429, detail="登录尝试过多,请稍后再试") - admin = state.admin() - if admin is None: - raise HTTPException(status_code=409, detail="请先完成初始化") - username, encoded = admin - password_ok = verify_password(body.password, encoded) + if database_mode: + if not state.users.has_users(): + raise HTTPException(status_code=409, detail="请先完成初始化") + account = state.users.get_by_username(body.username) + encoded = account["password_hash"] if account else None + username = account["username"] if account else body.username + else: + legacy_admin = state.admin() + if legacy_admin is None: + raise HTTPException(status_code=409, detail="请先完成初始化") + username, encoded = legacy_admin + account = {"email_verified": True} + password_ok = verify_password(body.password, encoded) if encoded else False username_ok = hmac.compare_digest(body.username, username) - if not password_ok or not username_ok: + if not password_ok or not username_ok or not account["email_verified"]: login_limiter.failed(peer) raise HTTPException(status_code=401, detail="用户名或密码错误") login_limiter.succeeded(peer) return session_response(username) + def deliver_registration_code(config, email: str, code: str, users) -> None: + try: + send_verification_code(config, email, code) + except Exception as exc: + # Background delivery must not expose whether an email exists or + # relay SMTP server diagnostics to an unauthenticated client. + LOG.warning("Registration email delivery failed: %s", type(exc).__name__) + try: + users.revoke_registration_code(email, code) + except DatabaseError: + LOG.exception("Could not revoke undelivered registration code") + + @app.post("/api/v1/register/code") + def send_registration_code(body: RegistrationCodeBody, request: Request, + background_tasks: BackgroundTasks): + if not database_mode or state is None or not state.users.has_users(): + raise HTTPException(status_code=409, detail="请先完成面板初始化") + peer = _peer(request) + if not code_send_limiter.allowed(peer): + raise HTTPException(status_code=429, detail="验证码请求过多,请稍后再试") + email = normalize_email(body.email) + config = smtp_store().get() + if config is None: + raise SMTPError("管理员尚未配置 SMTP,暂不能注册", 503) + code = state.users.generate_code() + try: + should_send = state.users.issue_registration_code(email, code) + except UserError as exc: + if exc.status != 429: + raise + should_send = False + code_send_limiter.failed(peer) + if should_send: + # Sending after the HTTP response avoids exposing whether an + # address is registered via SMTP latency or transport failures. + background_tasks.add_task( + deliver_registration_code, config, email, code, state.users, + ) + # Identical public response for existing addresses and cooldowns. + return {"sent": True} + + @app.post("/api/v1/register", status_code=201) + def register(body: RegistrationBody, request: Request): + if not database_mode or state is None or not state.users.has_users(): + raise HTTPException(status_code=409, detail="请先完成面板初始化") + peer = _peer(request) + if not registration_limiter.allowed(peer): + raise HTTPException(status_code=429, detail="注册尝试过多,请稍后再试") + try: + state.users.register_with_code(body.username, body.email, + body.password, body.code) + except UserError: + registration_limiter.failed(peer) + raise + registration_limiter.succeeded(peer) + return {"registered": True, "approved": False} + @app.post("/api/v1/logout") def logout(request: Request, _session: Session = Depends(require_write)): sessions.revoke(request.cookies.get(COOKIE_NAME)) @@ -686,6 +891,36 @@ def create_app( response.delete_cookie(COOKIE_NAME, path="/") return response + @app.get("/api/v1/smtp/settings") + def get_smtp_settings(_session: Session = Depends(require_admin)): + return smtp_store().public_status() + + @app.put("/api/v1/smtp/settings") + def save_smtp_settings(body: SMTPSettingsBody, + _session: Session = Depends(require_admin_write)): + settings_data = body.model_dump(exclude={"password"}) + settings_data["password"] = (body.password.get_secret_value() + if body.password is not None else "") + config = smtp_store().save(settings_data) + LOG.info("SMTP settings changed: admin=%s", _session.username) + return config.public_status() + + @app.get("/api/v1/users/pending") + def pending_users(_session: Session = Depends(require_admin)): + if not database_mode: + return {"items": []} + return {"items": state.users.list_pending_users()} + + @app.post("/api/v1/users/{user_id}/approve") + def approve_user(user_id: int, _session: Session = Depends(require_admin_write)): + if not database_mode: + raise HTTPException(status_code=409, detail="数据库用户功能不可用") + account = state.users.approve_user(user_id) + if account is None: + raise HTTPException(status_code=404, detail="用户不存在") + LOG.info("user approved: id=%s admin=%s", user_id, _session.username) + return {"approved": True} + def public_update_settings() -> dict: info = current_updater().settings() return { @@ -701,12 +936,12 @@ def create_app( } @app.get("/api/v1/update/settings") - def update_settings(_session: Session = Depends(require_session)): + def update_settings(_session: Session = Depends(require_admin)): return public_update_settings() @app.put("/api/v1/update/settings") def save_update_settings(body: UpdateSettingsBody, - _session: Session = Depends(require_write)): + _session: Session = Depends(require_admin_write)): if body.repository_url != REPOSITORY_URL or body.branch != BRANCH: raise UpdateError("更新仓库和分支固定为面板指定的 Gitea main 分支", 422) service = current_updater() @@ -720,7 +955,7 @@ def create_app( return public_update_settings() @app.post("/api/v1/update/check") - def check_update(_session: Session = Depends(require_write)): + def check_update(_session: Session = Depends(require_admin_write)): result = current_updater().check() return { "repository_url": result["repository"], @@ -731,7 +966,7 @@ def create_app( } @app.post("/api/v1/update/apply", status_code=202) - def apply_update(body: UpdateApplyBody, _session: Session = Depends(require_write)): + def apply_update(body: UpdateApplyBody, _session: Session = Depends(require_admin_write)): with import_lock, reinstall_lock: if pending_templates or pending_reinstalls: raise UpdateError("云镜像导入或虚拟机重装正在执行,请等待完成后再更新面板", 409) @@ -768,22 +1003,22 @@ def create_app( return {"job_id": job["job_id"], "status": "queued"} @app.get("/api/v1/update/jobs/{job_id}") - def update_job(job_id: str, _session: Session = Depends(require_session)): + def update_job(job_id: str, _session: Session = Depends(require_admin)): job = current_updater().get_job(job_id) if job is None: raise UpdateError("更新任务不存在", 404) return job @app.get("/api/v1/host") - def host(_session: Session = Depends(require_session)): + def host(_session: Session = Depends(require_admin)): return _public_host(manager.current()) @app.post("/api/v1/host/scan") - def scan_host(body: HostScanBody, _session: Session = Depends(require_write)): + def scan_host(body: HostScanBody, _session: Session = Depends(require_admin_write)): return manager.scan(body.host, body.port) @app.post("/api/v1/host/unlock") - def unlock_host(body: UnlockBody, request: Request, _session: Session = Depends(require_write)): + def unlock_host(body: UnlockBody, request: Request, _session: Session = Depends(require_admin_write)): peer = _peer(request) if not unlock_limiter.allowed(peer): raise HTTPException(status_code=429, detail="私钥口令尝试过多,请稍后再试") @@ -798,7 +1033,7 @@ def create_app( return _public_host(profile) @app.post("/api/v1/host/test") - def test_host(body: HostBody, _session: Session = Depends(require_write)): + def test_host(body: HostBody, _session: Session = Depends(require_admin_write)): staged = manager.stage(body.profile(), confirmed_fingerprint=body.confirmed_fingerprint) try: result = manager.test(staged) @@ -812,7 +1047,7 @@ def create_app( manager.abort(staged) @app.put("/api/v1/host") - def save_host(body: HostBody, _session: Session = Depends(require_write)): + def save_host(body: HostBody, _session: Session = Depends(require_admin_write)): # A running reinstall uses the saved SSH host identity and paths. Do # not replace them while its libvirt operation is in flight. with reinstall_lock: @@ -838,11 +1073,11 @@ def create_app( } @app.get("/api/v1/resources") - def resources(_session: Session = Depends(require_session)): + def resources(_session: Session = Depends(require_approved)): return current_service().resources() @app.get("/api/v1/vm-templates") - def list_templates(_session: Session = Depends(require_session)): + def list_templates(_session: Session = Depends(require_approved)): profile = current_profile() return {"templates": templates.list(template_scope(profile))} @@ -887,7 +1122,7 @@ def create_app( pending_templates.discard((scope, template_id)) @app.post("/api/v1/vm-templates/import", status_code=202) - def import_template(body: ImportTemplateBody, _session: Session = Depends(require_write)): + def import_template(body: ImportTemplateBody, _session: Session = Depends(require_admin_write)): profile = current_profile() validate_image_url(body.url) name = validate_template_name(body.name) @@ -920,7 +1155,7 @@ def create_app( return {"job_id": job_id, "status": "running"} @app.get("/api/v1/vm-templates/import-jobs/{job_id}") - def import_job(job_id: str, _session: Session = Depends(require_session)): + def import_job(job_id: str, _session: Session = Depends(require_admin)): scope = template_scope(current_profile()) with import_lock: job = import_jobs.get(job_id) @@ -929,9 +1164,14 @@ def create_app( return {key: value for key, value in job.items() if key != "scope"} @app.get("/api/v1/vms") - def list_vms(_session: Session = Depends(require_session)): + def list_vms(_session: Session = Depends(require_approved)): profile = current_profile() vms = new_service(profile).list_vms() + if database_mode: + account = account_for_session(_session) + if not account["admin"]: + owned_ids = state.users.list_owned_vm_ids(host_scope(profile), account["id"]) + vms = [vm for vm in vms if vm["uuid"] in owned_ids] records = (data_store.list("vm_credential") if data_store is not None else test_credentials.copy()) return {"items": [decorate_vm( @@ -939,14 +1179,16 @@ def create_app( ) for vm in vms]} @app.get("/api/v1/vms/{vm_id}") - def get_vm(vm_id: str, _session: Session = Depends(require_session)): + def get_vm(vm_id: str, _session: Session = Depends(require_approved)): profile = current_profile() + require_vm_access(_session, profile, vm_id) vm = new_service(profile).get_vm(vm_id) return decorate_vm(vm, get_credential(profile, vm["uuid"]), profile) @app.post("/api/v1/vms/{vm_id}/credential") - def reveal_vm_credential(vm_id: str, _session: Session = Depends(require_write)): + def reveal_vm_credential(vm_id: str, _session: Session = Depends(require_approved_write)): profile = current_profile() + require_vm_access(_session, profile, vm_id) vm = new_service(profile).get_vm(vm_id) credential = get_credential(profile, vm["uuid"]) decorated = decorate_vm(vm, credential, profile) @@ -961,13 +1203,14 @@ def create_app( def get_vm_metrics( vm_id: str, range_: Literal["1h", "24h", "7d", "30d"] = Query("1h", alias="range"), - _session: Session = Depends(require_session), + _session: Session = Depends(require_approved), ): try: canonical_id = str(uuid.UUID(vm_id)) except (TypeError, ValueError, AttributeError) as exc: raise VMError("虚拟机 UUID 无效", 400) from exc profile = current_profile() + require_vm_access(_session, profile, canonical_id) # Never reveal another host's retained samples for a reused UUID. new_service(profile).get_vm(canonical_id) backend = metric_store if metric_store is not None else data_store @@ -990,12 +1233,14 @@ def create_app( @app.post("/api/v1/vms", status_code=201) def create_vm(body: CreateISOBody | CreateCloudBody, - _session: Session = Depends(require_write)): + _session: Session = Depends(require_approved_write)): # Keep the update submission lock until libvirt has finished creating # the VM. Otherwise an update can restart the web process mid-create. with reinstall_lock: forbid_long_job_during_update() profile = current_profile() + account = account_for_session(_session) + owner_id = account["id"] if database_mode and not account["admin"] else None if isinstance(body, CreateCloudBody): public_key = body.guest_ssh_public_key.strip() root_password = (body.root_password.get_secret_value() @@ -1021,11 +1266,13 @@ def create_app( spec["root_password_hash"] = password_hash requested_uuid = str(uuid.uuid4()) spec["vm_uuid"] = requested_uuid - save_credential(profile, requested_uuid, - "ssh_key" if public_key else "password", - f"panel-seed-{requested_uuid}.iso", - root_password or None) + if owner_id is not None: + state.users.assign_vm(host_scope(profile), requested_uuid, owner_id) try: + save_credential(profile, requested_uuid, + "ssh_key" if public_key else "password", + f"panel-seed-{requested_uuid}.iso", + root_password or None) vm = new_service(profile).create_cloud_vm(spec, record["volume_name"]) except Exception as exc: # An incomplete libvirt rollback may have left the guest @@ -1038,14 +1285,27 @@ def create_app( delete_credential(profile, requested_uuid) except DatabaseError: LOG.exception("Could not remove unused VM credential for %s", requested_uuid) + if owner_id is not None: + state.users.delete_vm_owner(host_scope(profile), requested_uuid) raise - if vm.get("uuid") != requested_uuid: - # A mismatched UUID would bind a root password to the - # wrong guest; do not silently claim the credential works. - LOG.error("Created VM UUID does not match requested UUID: %s", requested_uuid) - raise VMError("虚拟机已创建,但凭据绑定异常;请检查宿主机后再操作", 502) + vm = verified_created_vm(profile, vm, requested_uuid) else: - vm = new_service(profile).create_vm(body.model_dump(exclude={"source"})) + spec = body.model_dump(exclude={"source"}) + if database_mode: + requested_uuid = str(uuid.uuid4()) + spec["vm_uuid"] = requested_uuid + if owner_id is not None: + state.users.assign_vm(host_scope(profile), requested_uuid, owner_id) + try: + vm = new_service(profile).create_vm(spec) + except Exception as exc: + rollback_incomplete = (isinstance(exc, VMError) + and "回滚不完整" in str(exc)) + if owner_id is not None and not rollback_incomplete: + state.users.delete_vm_owner(host_scope(profile), requested_uuid) + raise + if database_mode: + vm = verified_created_vm(profile, vm, requested_uuid) LOG.info("vm created: uuid=%s admin=%s", vm.get("uuid"), _session.username) credential = get_credential(profile, vm["uuid"]) if isinstance(body, CreateCloudBody) else None return decorate_vm(vm, credential, profile) @@ -1125,7 +1385,7 @@ def create_app( @app.post("/api/v1/vms/{vm_id}/reinstall", status_code=202) def reinstall_vm(vm_id: str, body: ReinstallBody, - _session: Session = Depends(require_write)): + _session: Session = Depends(require_approved_write)): ssh_public_key = body.ssh_public_key.strip() supplied_password = (body.root_password.get_secret_value() if body.root_password is not None else "") @@ -1152,6 +1412,7 @@ def create_app( with reinstall_lock: forbid_long_job_during_update() profile = current_profile() + require_vm_access(_session, profile, vm_id) scope = template_scope(profile) record = templates.get(scope, body.template_id) vm = new_service(profile).get_vm(vm_id) @@ -1190,7 +1451,7 @@ def create_app( return {"job_id": job_id, "status": "queued"} @app.get("/api/v1/reinstall-jobs/{job_id}") - def reinstall_job(job_id: str, _session: Session = Depends(require_write)): + def reinstall_job(job_id: str, _session: Session = Depends(require_approved_write)): scope = template_scope(current_profile()) with reinstall_lock: job = reinstall_jobs.get(job_id) @@ -1205,7 +1466,7 @@ def create_app( @app.post("/api/v1/reinstall-jobs/{job_id}/ack-password") def acknowledge_reinstall_password(job_id: str, - _session: Session = Depends(require_write)): + _session: Session = Depends(require_approved_write)): scope = template_scope(current_profile()) with reinstall_lock: job = reinstall_jobs.get(job_id) @@ -1219,10 +1480,11 @@ def create_app( return {"acknowledged": True} @app.post("/api/v1/vms/{vm_id}/actions") - def action(vm_id: str, body: ActionBody, _session: Session = Depends(require_write)): + def action(vm_id: str, body: ActionBody, _session: Session = Depends(require_approved_write)): with reinstall_lock: forbid_long_job_during_update() profile = current_profile() + require_vm_access(_session, profile, vm_id) try: normalized_id = str(uuid.UUID(vm_id)) except ValueError: @@ -1237,11 +1499,12 @@ def create_app( def delete_vm( vm_id: str, delete_disks: bool = False, - _session: Session = Depends(require_write), + _session: Session = Depends(require_approved_write), ): with reinstall_lock: forbid_long_job_during_update() profile = current_profile() + require_vm_access(_session, profile, vm_id) try: normalized_id = str(uuid.UUID(vm_id)) except ValueError: @@ -1249,11 +1512,17 @@ def create_app( if (template_scope(profile), normalized_id) in pending_reinstalls: raise VMError("虚拟机正在重装系统,暂时不能删除", 409) result = new_service(profile).delete_vm(vm_id, delete_disks) + if database_mode: + try: + state.users.delete_vm_owner(host_scope(profile), result["uuid"]) + except DatabaseError: + LOG.exception("Could not remove owner for deleted VM %s", result["uuid"]) + result = {**result, "warning": "虚拟机已删除,但数据库中的归属记录未能清理"} try: delete_credential(profile, result["uuid"]) except DatabaseError: LOG.exception("Could not remove credential for deleted VM %s", result["uuid"]) - result = {**result, "warning": "虚拟机已删除,但数据库中的登录凭据未能清理;请检查数据库状态"} + result = {**result, "warning": "虚拟机已删除,但数据库中的登录凭据或归属记录未能完全清理;请检查数据库状态"} LOG.info( "vm deleted: uuid=%s delete_disks=%s admin=%s", result.get("uuid"), delete_disks, _session.username, @@ -1269,9 +1538,18 @@ def create_app( if not _origin_matches_host(websocket.headers.get("origin"), host): await websocket.close(code=4403) return - if await asyncio.to_thread(sessions.get, websocket.cookies.get(COOKIE_NAME)) is None: + session = await asyncio.to_thread(sessions.get, websocket.cookies.get(COOKIE_NAME)) + if session is None: await websocket.close(code=4401) return + try: + account = await asyncio.to_thread(account_for_session, session) + except HTTPException: + await websocket.close(code=4401) + return + if not account["admin"] and not account["approved"]: + await websocket.close(code=4403) + return profile = manager.current() if profile is None: await websocket.close(code=4409) @@ -1280,23 +1558,56 @@ def create_app( if profile.get("key_locked"): await websocket.close(code=4423) return + await asyncio.to_thread(require_vm_access, session, profile, vm_id) port = await asyncio.to_thread(new_service(profile).console_port, vm_id) except VMError: await websocket.close(code=4404) return await websocket.accept() + async def watch_console_access() -> None: + while True: + await asyncio.sleep(CONSOLE_ACCESS_CHECK_SECONDS) + try: + refreshed = await asyncio.to_thread(sessions.get, session.token) + if refreshed is None or refreshed.username != session.username: + return + account = await asyncio.to_thread(account_for_session, refreshed) + if not account["admin"] and not account["approved"]: + return + current = manager.current() + if (current is None or current.get("key_locked") + or host_scope(current) != host_scope(profile)): + return + await asyncio.to_thread(require_vm_access, refreshed, current, vm_id) + except (HTTPException, VMError, DatabaseError, RemoteHostError, + KeyError, TypeError, ValueError): + return + + relay_task = asyncio.create_task(relay_console( + websocket, + port=port, + ssh_target=profile["ssh_target"], + ssh_binary=settings.ssh_binary, + known_hosts_file=profile["ssh_known_hosts_file"], + ssh_config_file=profile["ssh_config_file"], + )) + access_task = asyncio.create_task(watch_console_access()) try: - await relay_console( - websocket, - port=port, - ssh_target=profile["ssh_target"], - ssh_binary=settings.ssh_binary, - known_hosts_file=profile["ssh_known_hosts_file"], - ssh_config_file=profile["ssh_config_file"], - ) + done, _pending = await asyncio.wait( + {relay_task, access_task}, return_when=asyncio.FIRST_COMPLETED) + if access_task in done: + relay_task.cancel() + await asyncio.gather(relay_task, return_exceptions=True) + with suppress(RuntimeError, OSError): + await websocket.close(code=4403) + return + await relay_task except ConsoleRelayError as exc: LOG.warning("VNC relay failed for vm %r: %s", vm_id, exc) with suppress(RuntimeError, OSError): await websocket.close(code=1011) + finally: + access_task.cancel() + await asyncio.gather(access_task, return_exceptions=True) return app diff --git a/virsh_panel/auth.py b/virsh_panel/auth.py index 4a95d083..9ba1fb55 100644 --- a/virsh_panel/auth.py +++ b/virsh_panel/auth.py @@ -1,4 +1,4 @@ -"""Password verification and short-lived, server-side administrator sessions.""" +"""Password verification and short-lived, server-side account sessions.""" from __future__ import annotations @@ -48,6 +48,9 @@ class Session: username: str csrf_token: str expires_at: float + # Immutable database primary key. The optional form is only for the + # injected, database-free HTTP test harness. + user_id: int | None = None class SessionStore: @@ -55,12 +58,13 @@ class SessionStore: self._sessions: dict[str, Session] = {} self._lock = threading.Lock() - def issue(self, username: str) -> Session: + def issue(self, username: str, user_id: int | None = None) -> Session: session = Session( token=secrets.token_urlsafe(32), username=username, csrf_token=secrets.token_urlsafe(32), expires_at=time.time() + SESSION_LIFETIME_SECONDS, + user_id=user_id, ) with self._lock: self._sessions[session.token] = session @@ -94,8 +98,8 @@ class DatabaseSessionStore: """Server-side sessions that survive a web-process restart. Only a SHA-256 fingerprint of the bearer token is used as the database - record key. The username, CSRF token and expiry are encrypted by the - database store; the raw bearer token is never persisted. + record key. The immutable user ID, username, CSRF token and expiry are + encrypted by the database store; the raw bearer token is never persisted. """ def __init__(self, database: _SessionDatabase) -> None: @@ -105,15 +109,19 @@ class DatabaseSessionStore: def _key(token: str) -> str: return hashlib.sha256(token.encode("ascii")).hexdigest() - def issue(self, username: str) -> Session: + def issue(self, username: str, user_id: int | None = None) -> Session: + if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: + raise ValueError("Database sessions require a positive user ID") session = Session( token=secrets.token_urlsafe(32), username=username, csrf_token=secrets.token_urlsafe(32), expires_at=time.time() + SESSION_LIFETIME_SECONDS, + user_id=user_id, ) payload = json.dumps({ "username": session.username, + "user_id": session.user_id, "csrf_token": session.csrf_token, "expires_at": session.expires_at, }, separators=(",", ":")) @@ -133,17 +141,19 @@ class DatabaseSessionStore: try: data = json.loads(raw) username = data["username"] + user_id = data["user_id"] csrf_token = data["csrf_token"] expires_at = data["expires_at"] except (TypeError, ValueError, KeyError): return None if (not isinstance(username, str) or not isinstance(csrf_token, str) - or not isinstance(expires_at, (int, float))): + or isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1 + or isinstance(expires_at, bool) or not isinstance(expires_at, (int, float))): return None if expires_at <= time.time(): self._database.delete("session", key) return None - return Session(token, username, csrf_token, float(expires_at)) + return Session(token, username, csrf_token, float(expires_at), user_id) def revoke(self, token: str | None) -> None: if not isinstance(token, str) or not token or len(token) > 256: diff --git a/virsh_panel/database.py b/virsh_panel/database.py index 14aade7f..75ab4243 100644 --- a/virsh_panel/database.py +++ b/virsh_panel/database.py @@ -33,7 +33,6 @@ try: except ImportError: # Allows package tooling to import without optional DB extras. pymysql = None -from .auth import hash_password from .cloud_templates import TemplateError from .panel_state import PanelState, SetupError, _USERNAME from .remote_host import ( @@ -84,6 +83,44 @@ CREATE TABLE IF NOT EXISTS vm_metric_samples ( KEY vm_metric_retention (sampled_at) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 """ +_USERS_SCHEMA = """ +CREATE TABLE IF NOT EXISTS users ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + username VARCHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + email VARCHAR(254) CHARACTER SET ascii COLLATE ascii_bin NULL, + password_hash VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + admin TINYINT(1) NOT NULL DEFAULT 0, + approved TINYINT(1) NOT NULL DEFAULT 0, + email_verified TINYINT(1) NOT NULL DEFAULT 0, + created_at BIGINT UNSIGNED NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY user_username (username), + UNIQUE KEY user_email (email) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 +""" +_REGISTRATION_CODE_SCHEMA = """ +CREATE TABLE IF NOT EXISTS registration_codes ( + email VARCHAR(254) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + code_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + sent_at BIGINT UNSIGNED NOT NULL, + expires_at BIGINT UNSIGNED NOT NULL, + failed_attempts TINYINT UNSIGNED NOT NULL DEFAULT 0, + PRIMARY KEY (email), + KEY code_expiry (expires_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 +""" +_VM_OWNERSHIP_SCHEMA = """ +CREATE TABLE IF NOT EXISTS vm_ownership ( + host_scope CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + vm_uuid CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + user_id BIGINT UNSIGNED NOT NULL, + created_at BIGINT UNSIGNED NOT NULL, + PRIMARY KEY (host_scope, vm_uuid), + KEY vm_owner_user (user_id, host_scope), + CONSTRAINT vm_owner_user_fk FOREIGN KEY (user_id) REFERENCES users(id) + ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 +""" _METRIC_COLUMNS = ( "cpu_percent", "memory_used_mib", "memory_total_mib", "disk_read_bps", "disk_write_bps", "network_rx_bps", "network_tx_bps", @@ -169,6 +206,9 @@ class DatabaseStore: with connection.cursor() as cursor: cursor.execute(_SCHEMA) cursor.execute(_METRIC_SCHEMA) + cursor.execute(_USERS_SCHEMA) + cursor.execute(_REGISTRATION_CODE_SCHEMA) + cursor.execute(_VM_OWNERSHIP_SCHEMA) connection.commit() except pymysql.MySQLError as exc: connection.rollback() @@ -419,45 +459,35 @@ class DatabaseStore: class DatabasePanelState(PanelState): - """Admin in MariaDB; the one-time bootstrap token remains a local file.""" + """Initial user in MariaDB; the one-time token remains a local file.""" - def __init__(self, data_dir: Path, store: DatabaseStore) -> None: + def __init__(self, data_dir: Path, store: DatabaseStore, users: Any) -> None: super().__init__(data_dir) self.store = store + self.users = users def admin(self) -> tuple[str, str] | None: - raw = self.store.get("admin", "singleton") - if raw is None: - return None - try: - record = json.loads(raw) - except (TypeError, ValueError) as exc: - raise DatabaseError("数据库管理员记录格式无效") from exc - if (not isinstance(record, dict) or not isinstance(record.get("username"), str) - or not isinstance(record.get("password_hash"), str)): - raise DatabaseError("数据库管理员记录格式无效") - return record["username"], record["password_hash"] + raise RuntimeError("Database-backed authentication must use state.users") + + def setup_required(self) -> bool: + return not self.users.has_users() - def create_admin(self, token: str, username: str, password: str) -> str: + def create_admin(self, token: str, username: str, password: str, + email: str | None = None) -> str: if not isinstance(username, str) or not _USERNAME.fullmatch(username): raise SetupError("用户名应为 3 至 32 位字母、数字、点、下划线或连字符") if not isinstance(password, str) or len(password) < 12 or len(password) > 1024: - raise SetupError("管理员密码长度须在 12 至 1024 位之间") + raise SetupError("密码长度须在 12 至 1024 位之间") with self._setup_lock(): - if self.admin() is not None: - raise SetupError("管理员已创建", 409) + if not self.setup_required(): + raise SetupError("初始用户已创建", 409) try: expected = self._read_token() except FileNotFoundError as exc: raise SetupError("初始化口令不可用,请重新启动面板并查看启动终端输出", 503) from exc if not isinstance(token, str) or not hmac.compare_digest(token, expected): raise SetupError("初始化口令无效", 403) - record = json.dumps( - {"username": username, "password_hash": hash_password(password)}, - ensure_ascii=False, separators=(",", ":"), - ) - if not self.store.insert("admin", "singleton", record): - raise SetupError("管理员已创建", 409) + self.users.create_initial_user(username, password, email) self.token_file.unlink(missing_ok=True) self._fsync_directory() return username @@ -904,8 +934,10 @@ def make_components( ssh_binary: str = "ssh", ) -> tuple[DatabasePanelState, DatabaseRemoteHostManager, DatabaseTemplateStore, DatabaseStore]: """Create ready-to-use DB-backed application components.""" + from .users import DatabaseUserStore + store = DatabaseStore(db_config, master_key) - state = DatabasePanelState(data_dir, store) + state = DatabasePanelState(data_dir, store, DatabaseUserStore(store, master_key)) manager = DatabaseRemoteHostManager(store, data_dir, ssh_binary=ssh_binary) templates = DatabaseTemplateStore(store) return state, manager, templates, store diff --git a/virsh_panel/libvirt_service.py b/virsh_panel/libvirt_service.py index 3a2cfd76..b18a7ae6 100644 --- a/virsh_panel/libvirt_service.py +++ b/virsh_panel/libvirt_service.py @@ -1098,6 +1098,12 @@ class VMService: def create_vm(self, spec: dict[str, Any]) -> dict[str, Any]: validated = self._validate_create(spec) validated["created_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") + requested_uuid = spec.get("vm_uuid") + if requested_uuid is not None: + try: + requested_uuid = str(uuidlib.UUID(requested_uuid)) + except (TypeError, ValueError, AttributeError) as exc: + raise VMError("虚拟机 UUID 无效") from exc with self._connect() as conn: if any(domain.name() == validated["name"] for domain in conn.listAllDomains(0)): raise VMError("虚拟机名称已存在", 409) @@ -1117,7 +1123,7 @@ class VMService: if not network.isActive(): raise VMError("配置的虚拟网络未启动", 409) - vm_uuid = str(uuidlib.uuid4()) + vm_uuid = requested_uuid or str(uuidlib.uuid4()) disk_name = f"{validated['name']}.qcow2" if disk_name in disk_pool.listVolumes(): raise VMError(f"磁盘文件 {disk_name} 已存在,不会覆盖现有数据", 409) diff --git a/virsh_panel/panel_state.py b/virsh_panel/panel_state.py index 60ab5ef8..92bab3eb 100644 --- a/virsh_panel/panel_state.py +++ b/virsh_panel/panel_state.py @@ -138,7 +138,7 @@ class PanelState: rotate a secret that may already have been shown to the operator. """ with self._setup_lock(): - if self.admin() is not None: + if not self.setup_required(): # Recover from a crash after state.json was committed but # before the now-obsolete token could be removed. if self.token_file.exists(): diff --git a/virsh_panel/smtp_service.py b/virsh_panel/smtp_service.py new file mode 100644 index 00000000..d5f74178 --- /dev/null +++ b/virsh_panel/smtp_service.py @@ -0,0 +1,215 @@ +"""Validated SMTP settings and registration verification mail delivery. + +The settings store deliberately uses the panel's encrypted record store. The +module never logs SMTP server responses because those can contain addresses or +authentication details supplied by a remote server. +""" + +from __future__ import annotations + +import ipaddress +import json +import re +import smtplib +import ssl +from dataclasses import dataclass, field +from email.message import EmailMessage +from typing import Any, Mapping, Protocol + + +_DNS_LABEL = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\Z") +_LOCAL_PART = re.compile(r"[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*\Z") +_SIX_DIGITS = re.compile(r"[0-9]{6}\Z") +_SMTP_RECORD_TYPE = "smtp" +_SMTP_RECORD_KEY = "current" + + +class SMTPError(Exception): + """Safe user-facing SMTP configuration or delivery failure.""" + + def __init__(self, message: str, status: int = 422) -> None: + super().__init__(message) + self.status = status + + +def _validate_host(host: str) -> str: + if (not isinstance(host, str) or not host or len(host) > 253 + or host != host.strip()): + raise SMTPError("SMTP 服务器地址格式无效") + try: + ipaddress.ip_address(host) + return host + except ValueError: + pass + if not all(_DNS_LABEL.fullmatch(label) for label in host.split(".")): + raise SMTPError("SMTP 服务器地址必须是 IP 或 DNS 名称") + return host.lower() + + +def validate_email(address: str) -> str: + """Accept a bare ASCII mailbox address, never a display name or header.""" + + if (not isinstance(address, str) or len(address) > 254 + or address != address.strip() or address.count("@") != 1): + raise SMTPError("邮箱地址格式无效") + local, domain = address.rsplit("@", 1) + if (not local or len(local) > 64 or not _LOCAL_PART.fullmatch(local) + or not domain or len(domain) > 253 + or not all(_DNS_LABEL.fullmatch(label) for label in domain.split("."))): + raise SMTPError("邮箱地址格式无效") + return f"{local}@{domain.lower()}" + + +@dataclass(frozen=True) +class SMTPConfig: + host: str + port: int + tls_mode: str + from_address: str + username: str = "" + password: str = field(default="", repr=False) + + def __post_init__(self) -> None: + object.__setattr__(self, "host", _validate_host(self.host)) + if (isinstance(self.port, bool) or not isinstance(self.port, int) + or not 1 <= self.port <= 65535): + raise SMTPError("SMTP 端口必须介于 1 到 65535") + if (not isinstance(self.tls_mode, str) + or self.tls_mode not in {"ssl", "starttls", "none"}): + raise SMTPError("SMTP 加密方式无效") + object.__setattr__(self, "from_address", validate_email(self.from_address)) + if (not isinstance(self.username, str) or len(self.username) > 256 + or self.username != self.username.strip() + or any(ord(char) < 32 or ord(char) == 127 for char in self.username)): + raise SMTPError("SMTP 用户名格式无效") + if not isinstance(self.password, str) or len(self.password) > 2048: + raise SMTPError("SMTP 密码格式无效") + if bool(self.username) != bool(self.password): + raise SMTPError("SMTP 用户名和密码必须同时填写") + if self.username and self.tls_mode == "none": + raise SMTPError("SMTP 账号认证必须启用 SSL 或 STARTTLS") + + @classmethod + def from_mapping(cls, values: Mapping[str, Any]) -> SMTPConfig: + if not isinstance(values, Mapping): + raise SMTPError("SMTP 配置格式无效") + return cls( + host=values.get("host"), + port=values.get("port"), + tls_mode=values.get("tls_mode"), + from_address=values.get("from_address"), + username=values.get("username", ""), + password=values.get("password", ""), + ) + + def as_record(self) -> dict[str, str | int]: + """Full value for the *encrypted* database record only.""" + + return { + "host": self.host, + "port": self.port, + "tls_mode": self.tls_mode, + "from_address": self.from_address, + "username": self.username, + "password": self.password, + } + + def public_status(self) -> dict[str, str | int | bool]: + """Admin-only status; intentionally never includes the SMTP password.""" + + return { + "configured": True, + "host": self.host, + "port": self.port, + "tls_mode": self.tls_mode, + "from_address": self.from_address, + "username": self.username, + "password_configured": bool(self.password), + } + + +class _RecordStore(Protocol): + def get(self, record_type: str, record_key: str) -> str | None: ... + def set(self, record_type: str, record_key: str, value: str) -> None: ... + + +class SMTPSettingsStore: + """One SMTP configuration in the panel's AES-GCM-encrypted record table.""" + + def __init__(self, records: _RecordStore) -> None: + self._records = records + + def get(self) -> SMTPConfig | None: + raw = self._records.get(_SMTP_RECORD_TYPE, _SMTP_RECORD_KEY) + if raw is None: + return None + try: + payload = json.loads(raw) + return SMTPConfig.from_mapping(payload) + except (ValueError, TypeError, SMTPError): + raise SMTPError("已保存的 SMTP 配置无效,请重新保存", status=503) from None + + def save(self, values: Mapping[str, Any]) -> SMTPConfig: + if not isinstance(values, Mapping): + raise SMTPError("SMTP 配置格式无效") + candidate = dict(values) + if candidate.get("password") in (None, ""): + current = self.get() + if current is not None and candidate.get("username", "") == current.username: + candidate["password"] = current.password + else: + candidate["password"] = "" + config = SMTPConfig.from_mapping(candidate) + self._records.set( + _SMTP_RECORD_TYPE, _SMTP_RECORD_KEY, + json.dumps(config.as_record(), ensure_ascii=False, separators=(",", ":")), + ) + return config + + def public_status(self) -> dict[str, str | int | bool]: + config = self.get() + return {"configured": False} if config is None else config.public_status() + + +def send_verification_code(config: SMTPConfig, recipient_email: str, code: str, *, + timeout: int | float = 10) -> None: + """Send one six-digit registration code; all transport errors are redacted.""" + + recipient = validate_email(recipient_email) + if not isinstance(code, str) or not _SIX_DIGITS.fullmatch(code): + raise SMTPError("验证码格式无效") + if (isinstance(timeout, bool) or not isinstance(timeout, (int, float)) + or not 0 < timeout <= 30): + raise SMTPError("SMTP 连接超时设置无效") + + message = EmailMessage() + message["From"] = config.from_address + message["To"] = recipient + message["Subject"] = "Virsh Panel 注册验证码" + message["Auto-Submitted"] = "auto-generated" + message.set_content( + f"您的注册验证码是:{code}\n\n验证码在 10 分钟内有效,请勿转发给他人。\n" + "如果不是您本人操作,请忽略这封邮件。\n", + charset="utf-8", + ) + + try: + context = ssl.create_default_context() + if config.tls_mode == "ssl": + client = smtplib.SMTP_SSL( + config.host, config.port, timeout=timeout, context=context, + ) + else: + client = smtplib.SMTP(config.host, config.port, timeout=timeout) + with client: + client.ehlo() + if config.tls_mode == "starttls": + client.starttls(context=context) + client.ehlo() + if config.username: + client.login(config.username, config.password) + refused = client.send_message(message) + if refused: + raise SMTPError("验证码发送失败,请检查 SMTP 配置后重试", status=502) + except (smtplib.SMTPException, OSError): + raise SMTPError("验证码发送失败,请检查 SMTP 配置后重试", status=502) from None diff --git a/virsh_panel/users.py b/virsh_panel/users.py new file mode 100644 index 00000000..cd23fa4f --- /dev/null +++ b/virsh_panel/users.py @@ -0,0 +1,478 @@ +"""MariaDB user accounts, registration codes, and VM ownership. + +The panel's public registration code is only six digits, so its stored +fingerprint is keyed with the database master key. A stolen database alone +cannot check guesses offline. Every SQL value is passed as a parameter. +""" + +from __future__ import annotations + +import hashlib +import hmac +import re +import secrets +import time +import uuid +from typing import Any + +from .auth import hash_password +from .database import DatabaseError, DatabaseStore, pymysql +from .panel_state import _USERNAME + + +_DOMAIN_LABEL = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\Z") +_LOCAL_PART = re.compile(r"[A-Za-z0-9_+%-](?:[A-Za-z0-9._+%-]{0,62}[A-Za-z0-9_+%-])?\Z") +_CODE = re.compile(r"[0-9]{6}\Z") +_HOST_SCOPE = re.compile(r"[0-9a-f]{64}\Z") +_MAX_CODE_ATTEMPTS = 5 + + +class UserError(Exception): + def __init__(self, message: str, status: int = 400) -> None: + super().__init__(message) + self.status = status + + +def normalize_email(email: str) -> str: + """Reject addresses that cannot be safely used in SMTP headers.""" + if not isinstance(email, str) or not 3 <= len(email) <= 254 or email != email.strip(): + raise UserError("邮箱地址格式无效") + try: + email.encode("ascii") + except UnicodeEncodeError as exc: + raise UserError("邮箱地址格式无效") from exc + if email.count("@") != 1: + raise UserError("邮箱地址格式无效") + local, domain = email.split("@") + if (len(local) > 64 or len(domain) > 253 or ".." in email + or not _LOCAL_PART.fullmatch(local) + or not all(_DOMAIN_LABEL.fullmatch(label) for label in domain.split(".")) + or "." not in domain): + raise UserError("邮箱地址格式无效") + return email.lower() + + +def _validate_username(username: str) -> str: + if not isinstance(username, str) or not _USERNAME.fullmatch(username): + raise UserError("用户名应为 3 至 32 位字母、数字、点、下划线或连字符") + return username + + +def _validate_password(password: str) -> str: + if not isinstance(password, str) or not 12 <= len(password) <= 1024: + raise UserError("密码长度须在 12 至 1024 位之间") + return password + + +def _validate_clock(now: int | None) -> int: + value = int(time.time()) if now is None else now + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise ValueError("Invalid registration time") + return value + + +def _vm_identity(host_scope: str, vm_uuid: str) -> tuple[str, str]: + if not isinstance(host_scope, str) or not _HOST_SCOPE.fullmatch(host_scope): + raise ValueError("Invalid host scope") + try: + canonical_uuid = str(uuid.UUID(vm_uuid)) + except (ValueError, TypeError, AttributeError) as exc: + raise ValueError("Invalid VM UUID") from exc + return host_scope, canonical_uuid + + +def _user_row(row: dict[str, Any] | None) -> dict[str, Any] | None: + if row is None: + return None + return { + "id": int(row["id"]), + "username": row["username"], + "email": row["email"], + "password_hash": row["password_hash"], + "admin": bool(row["admin"]), + "approved": bool(row["approved"]), + "email_verified": bool(row["email_verified"]), + "created_at": int(row["created_at"]), + } + + +class DatabaseUserStore: + """Users are plain SQL rows; password hashes and code digests are one-way.""" + + def __init__(self, store: DatabaseStore, code_key: bytes) -> None: + if not isinstance(code_key, bytes) or len(code_key) != 32: + raise ValueError("Registration code key must be 32 bytes") + self._store = store + self._code_key = code_key + + def _connect(self): + return self._store._connect() + + def _code_digest(self, email: str, code: str) -> str: + message = b"virsh-panel-registration-v1\x00" + email.encode("ascii") + b"\x00" + code.encode("ascii") + return hmac.new(self._code_key, message, hashlib.sha256).hexdigest() + + @staticmethod + def generate_code() -> str: + return f"{secrets.randbelow(1_000_000):06d}" + + def has_users(self) -> bool: + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute("SELECT id FROM users LIMIT 1") + return cursor.fetchone() is not None + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取用户数据") from exc + finally: + connection.close() + + def get_by_username(self, username: str) -> dict[str, Any] | None: + if not isinstance(username, str) or not _USERNAME.fullmatch(username): + return None + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT id, username, email, password_hash, admin, approved, " + "email_verified, created_at " + "FROM users WHERE username=%s", (username,), + ) + return _user_row(cursor.fetchone()) + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取用户数据") from exc + finally: + connection.close() + + def get_by_id(self, user_id: int) -> dict[str, Any] | None: + if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: + return None + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT id, username, email, password_hash, admin, approved, " + "email_verified, created_at " + "FROM users WHERE id=%s", (user_id,), + ) + return _user_row(cursor.fetchone()) + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取用户数据") from exc + finally: + connection.close() + + def create_initial_user(self, username: str, password: str, + email: str | None = None, *, now: int | None = None) -> dict[str, Any]: + """Insert the first account as a regular user, never as admin. + + The setup-token file lock held by DatabasePanelState serializes this + check/insert across web workers on the same panel server. + """ + username = _validate_username(username) + password_hash = hash_password(_validate_password(password)) + email = normalize_email(email) if email is not None else None + timestamp = _validate_clock(now) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute("SELECT id FROM users LIMIT 1 FOR UPDATE") + if cursor.fetchone() is not None: + raise UserError("初始用户已创建", 409) + cursor.execute( + "INSERT INTO users (username, email, password_hash, admin, " + "approved, email_verified, created_at) VALUES (%s, %s, %s, 0, 1, 1, %s)", + (username, email, password_hash, timestamp), + ) + user_id = cursor.lastrowid + connection.commit() + return { + "id": user_id, "username": username, "email": email, + "password_hash": password_hash, "admin": False, "approved": True, + "email_verified": True, "created_at": timestamp, + } + except UserError: + connection.rollback() + raise + except pymysql.err.IntegrityError as exc: + connection.rollback() + if exc.args and exc.args[0] == 1062: + raise UserError("用户名或邮箱已存在", 409) from exc + raise DatabaseError("无法创建初始用户") from exc + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法创建初始用户") from exc + finally: + connection.close() + + def issue_registration_code(self, email: str, code: str, *, now: int | None = None, + ttl_seconds: int = 600, + cooldown_seconds: int = 60) -> bool: + """Store a code and enforce resend cooldown; False means email already used. + + The caller should return the same public response for existing and new + email addresses, and send email only when this method returns True. + """ + email = normalize_email(email) + if not isinstance(code, str) or not _CODE.fullmatch(code): + raise ValueError("Invalid registration code") + if (isinstance(ttl_seconds, bool) or not isinstance(ttl_seconds, int) + or not 60 <= ttl_seconds <= 3600 + or isinstance(cooldown_seconds, bool) or not isinstance(cooldown_seconds, int) + or not 1 <= cooldown_seconds <= ttl_seconds): + raise ValueError("Invalid code lifetime or cooldown") + timestamp = _validate_clock(now) + digest = self._code_digest(email, code) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute("SELECT id FROM users WHERE email=%s", (email,)) + if cursor.fetchone() is not None: + connection.rollback() + return False + cursor.execute( + "SELECT sent_at FROM registration_codes WHERE email=%s FOR UPDATE", + (email,), + ) + existing = cursor.fetchone() + if existing is not None and timestamp - int(existing["sent_at"]) < cooldown_seconds: + raise UserError("验证码发送过于频繁,请稍后重试", 429) + if existing is None: + cursor.execute( + "INSERT INTO registration_codes " + "(email, code_hash, sent_at, expires_at, failed_attempts) " + "VALUES (%s, %s, %s, %s, 0)", + (email, digest, timestamp, timestamp + ttl_seconds), + ) + else: + cursor.execute( + "UPDATE registration_codes SET code_hash=%s, sent_at=%s, " + "expires_at=%s, failed_attempts=0 WHERE email=%s", + (digest, timestamp, timestamp + ttl_seconds, email), + ) + connection.commit() + return True + except UserError: + connection.rollback() + raise + except pymysql.err.IntegrityError as exc: + connection.rollback() + if exc.args and exc.args[0] == 1062: + raise UserError("验证码发送过于频繁,请稍后重试", 429) from exc + raise DatabaseError("无法保存注册验证码") from exc + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法保存注册验证码") from exc + finally: + connection.close() + + def revoke_registration_code(self, email: str, code: str) -> bool: + """Remove only the still-current challenge after SMTP delivery fails.""" + email = normalize_email(email) + if not isinstance(code, str) or not _CODE.fullmatch(code): + raise ValueError("Invalid registration code") + digest = self._code_digest(email, code) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT code_hash FROM registration_codes WHERE email=%s FOR UPDATE", + (email,), + ) + row = cursor.fetchone() + if row is None or not hmac.compare_digest(row["code_hash"], digest): + connection.rollback() + return False + cursor.execute( + "DELETE FROM registration_codes WHERE email=%s AND code_hash=%s", + (email, digest), + ) + connection.commit() + return True + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法撤销注册验证码") from exc + finally: + connection.close() + + def register_with_code(self, username: str, email: str, password: str, + code: str, *, now: int | None = None) -> dict[str, Any]: + username = _validate_username(username) + email = normalize_email(email) + password = _validate_password(password) + if not isinstance(code, str) or not _CODE.fullmatch(code): + raise UserError("验证码格式无效") + timestamp = _validate_clock(now) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT code_hash, expires_at, failed_attempts " + "FROM registration_codes WHERE email=%s FOR UPDATE", (email,), + ) + challenge = cursor.fetchone() + if challenge is None: + raise UserError("验证码无效或已过期") + if timestamp >= int(challenge["expires_at"]): + cursor.execute("DELETE FROM registration_codes WHERE email=%s", (email,)) + connection.commit() + raise UserError("验证码无效或已过期") + digest = self._code_digest(email, code) + if not hmac.compare_digest(digest, challenge["code_hash"]): + attempts = int(challenge["failed_attempts"]) + 1 + if attempts >= _MAX_CODE_ATTEMPTS: + cursor.execute("DELETE FROM registration_codes WHERE email=%s", (email,)) + else: + cursor.execute( + "UPDATE registration_codes SET failed_attempts=%s WHERE email=%s", + (attempts, email), + ) + connection.commit() + raise UserError("验证码无效或已过期") + password_hash = hash_password(password) + cursor.execute( + "INSERT INTO users (username, email, password_hash, admin, " + "approved, email_verified, created_at) VALUES (%s, %s, %s, 0, 0, 1, %s)", + (username, email, password_hash, timestamp), + ) + user_id = cursor.lastrowid + cursor.execute("DELETE FROM registration_codes WHERE email=%s", (email,)) + connection.commit() + return { + "id": user_id, "username": username, "email": email, + "password_hash": password_hash, "admin": False, "approved": False, + "email_verified": True, "created_at": timestamp, + } + except UserError: + connection.rollback() + raise + except pymysql.err.IntegrityError as exc: + connection.rollback() + if exc.args and exc.args[0] == 1062: + raise UserError("用户名或邮箱已存在", 409) from exc + raise DatabaseError("无法创建用户") from exc + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法创建用户") from exc + finally: + connection.close() + + def list_pending_users(self) -> list[dict[str, Any]]: + """Return registered accounts awaiting operator approval, no hashes.""" + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT id, username, email, admin, approved, email_verified, " + "created_at FROM users WHERE approved=0 ORDER BY created_at ASC, id ASC" + ) + rows = cursor.fetchall() + return [{ + "id": int(row["id"]), "username": row["username"], + "email": row["email"], "admin": bool(row["admin"]), + "approved": bool(row["approved"]), + "email_verified": bool(row["email_verified"]), + "created_at": int(row["created_at"]), + } for row in rows] + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取待审核用户") from exc + finally: + connection.close() + + def approve_user(self, user_id: int) -> dict[str, Any] | None: + """Approve an account; only the admin-authorized HTTP route may call this.""" + if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: + raise ValueError("Invalid user ID") + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute("UPDATE users SET approved=1 WHERE id=%s", (user_id,)) + connection.commit() + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法审核用户") from exc + finally: + connection.close() + return self.get_by_id(user_id) + + def assign_vm(self, host_scope: str, vm_uuid: str, user_id: int, + *, now: int | None = None) -> None: + host_scope, vm_uuid = _vm_identity(host_scope, vm_uuid) + if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: + raise ValueError("Invalid user ID") + timestamp = _validate_clock(now) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "INSERT INTO vm_ownership (host_scope, vm_uuid, user_id, created_at) " + "VALUES (%s, %s, %s, %s)", + (host_scope, vm_uuid, user_id, timestamp), + ) + connection.commit() + except pymysql.err.IntegrityError as exc: + connection.rollback() + if exc.args and exc.args[0] == 1062: + if self.owner_of_vm(host_scope, vm_uuid) == user_id: + return + raise UserError("此虚拟机已归属于其他用户", 409) from exc + raise DatabaseError("无法记录虚拟机归属") from exc + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法记录虚拟机归属") from exc + finally: + connection.close() + + def owner_of_vm(self, host_scope: str, vm_uuid: str) -> int | None: + host_scope, vm_uuid = _vm_identity(host_scope, vm_uuid) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT user_id FROM vm_ownership WHERE host_scope=%s AND vm_uuid=%s", + (host_scope, vm_uuid), + ) + row = cursor.fetchone() + return None if row is None else int(row["user_id"]) + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取虚拟机归属") from exc + finally: + connection.close() + + def owns_vm(self, host_scope: str, vm_uuid: str, user_id: int) -> bool: + if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: + return False + return self.owner_of_vm(host_scope, vm_uuid) == user_id + + def list_owned_vm_ids(self, host_scope: str, user_id: int) -> set[str]: + if not isinstance(host_scope, str) or not _HOST_SCOPE.fullmatch(host_scope): + raise ValueError("Invalid host scope") + if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1: + raise ValueError("Invalid user ID") + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "SELECT vm_uuid FROM vm_ownership WHERE host_scope=%s AND user_id=%s", + (host_scope, user_id), + ) + return {row["vm_uuid"] for row in cursor.fetchall()} + except pymysql.MySQLError as exc: + raise DatabaseError("无法读取虚拟机归属") from exc + finally: + connection.close() + + def delete_vm_owner(self, host_scope: str, vm_uuid: str) -> None: + host_scope, vm_uuid = _vm_identity(host_scope, vm_uuid) + connection = self._connect() + try: + with connection.cursor() as cursor: + cursor.execute( + "DELETE FROM vm_ownership WHERE host_scope=%s AND vm_uuid=%s", + (host_scope, vm_uuid), + ) + connection.commit() + except pymysql.MySQLError as exc: + connection.rollback() + raise DatabaseError("无法删除虚拟机归属") from exc + finally: + connection.close()