diff --git a/docs/FABRIC_HOST_ACCEPTANCE.md b/docs/FABRIC_HOST_ACCEPTANCE.md new file mode 100644 index 00000000..b12d9ce2 --- /dev/null +++ b/docs/FABRIC_HOST_ACCEPTANCE.md @@ -0,0 +1,49 @@ +# Fabric 宿主机验收矩阵 + +这份矩阵用于真实宿主机验收。当前代码已经完成脚本语法、能力解析、回读和事务 +契约测试;本仓库环境没有 AlmaLinux 10 或 Debian 13 宿主机,因此下列命令不能在 +本地模拟为通过。 + +## AlmaLinux 10 + +确认 NetworkManager 是唯一网络管理器,`nmcli connection show` 能看到 +`virt-cloud-wg-fabric0`,native `nftables.service` 为 active/enabled,firewalld +为 inactive/disabled。应用两台同地区宿主机后,记录 `wg show wg-fabric0`、 +`ip -4 route show table all`、`nft list table inet virt_cloud_wg_fabric`、默认路由 +和管理地址;这些证据中不得出现 `br0` 或管理接口被修改。 + +依次执行: + +1. `systemctl reload nftables`,确认 include 重新加载 table,Fabric observe 在 + repair timer 一个周期内仍为 active。 +2. `systemctl restart NetworkManager`,确认 keyfile、peer、精确 `/32` 路由和 + underlay endpoint 路由恢复,默认路由不漂移。 +3. 重启宿主机,确认 `nftables.service`、NetworkManager、Fabric helper 和 timer + 的 enabled/active 状态以及跨宿主机握手。 + +## Debian 13 + +确认 `/etc/network/interfaces` 或 `interfaces.d` 由经典 ifupdown 管理,探测到的 +`ifup`、`ifdown`、`ifquery` 路径与面板记录一致,systemd-networkd 和 NetworkManager +没有 active/enabled/configured 接管证据。验证 `ifup --force wg-fabric0` 只操作 +`wg-fabric0`,不会触碰 `br0`、默认路由或管理地址。 + +依次执行: + +1. `systemctl reload nftables`,确认 persistent include 和 table 回读;不要用 + `ifup` 代替 nftables reload。 +2. `systemctl restart networking`,确认 ifupdown fragment、peer、地址和路由回读。 +3. 重启宿主机,确认 `ifupdown`、nftables、Fabric repair timer 和跨宿主机握手。 + +## 失败回滚和安全边界 + +在隔离环境中分别让 `nft`、`wg`、`ip route`、`nmcli/ifup`、`systemctl enable` +和 `systemctl start timer` 返回失败。每次都应看到 apply 失败并保持 +`uncertain/degraded`,且原 panel-owned peer、地址、路由、keyfile/fragment、nft +table/include 和 systemd 状态恢复;无法恢复时不得报告 active。预先放置一个 +非 panel-owned 的同名 nft table、宽前缀路由(例如 `/16`、`/24`)、策略表路由或 +同名接口时,apply 必须拒绝并保留原状态。 + +最后从另一台宿主机核验 WireGuard underlay UDP 监听端口、NAT、MTU、SELinux 和 +公网防火墙。Fabric 的 native nft table 不负责放行 underlay UDP;如果公网防火墙 +没有独立的持久规则,不能把本地 `wg-fabric0` active 视为跨宿主机可用。 diff --git a/docs/INTEGRATION_PLAN.md b/docs/INTEGRATION_PLAN.md index 4d6bb9d4..5e0b11fe 100644 --- a/docs/INTEGRATION_PLAN.md +++ b/docs/INTEGRATION_PLAN.md @@ -100,10 +100,26 @@ ICMP,其余来自或发往 `wg-fabric0` 的主机服务流量丢弃;systemd 重新核对宿主机能力快照和 revision。 当前阶段没有 Fabric 删除/撤销 API;成员变更必须由后续迁移流程以新 revision -显式处理。underlay 端点的公网防火墙、NAT、MTU、SELinux/firewalld、管理器重载 -后的持久性,以及 AlmaLinux 的 NetworkManager、Debian 的 ifupdown 在真实重启后 -的恢复,仍属于真实宿主机验收项。Fabric 只使用独立的 `wg-fabric0`;管理器适配 -不得修改 `br0`、默认路由或宿主机管理接口。 +显式处理。Fabric 下发现在会在每台宿主机操作前重新执行固定能力探测,并在远端 +`/run/virt-cloud/wg-fabric0.lock` 内串行化 identity、apply、observe 和管理器 hook。 +apply 会先保存 panel-owned 配置、WireGuard peer/地址/路由、systemd 单元和 nft +状态;任一后续步骤失败会恢复该宿主机原状态,回滚自身失败时只保留 +`uncertain/degraded`,不会返回 active。跨宿主机仍不自动回退已经健康的节点。 +目标 peer 的 `/32` 会与所有路由表的宽前缀、blackhole、unreachable 和其他设备逐一 +检查,默认路由不被当作 Fabric overlay 路由;重叠或无法核验时 fail-closed。 + +nftables 规则现在保存为 root-only 的 +`/etc/nftables.d/virt-cloud-wg-fabric.nft`,并要求 Debian 的 +`/etc/nftables.conf` 或 AlmaLinux 的 `/etc/sysconfig/nftables.conf` 存在受管 include。 +规则带 plan digest,启动 helper 会校验归属、结构、revision 和 include;规则被防火墙 +重载清掉后,nftables 的持久配置负责重建,repair timer 负责短暂故障后的回读和修复。 +启用或可能在重启时接管的 firewalld 与 native nftables 会被能力探测判为冲突;当前 +Fabric 不把 raw nft 规则混入 firewalld direct/permanent 后端,也不会覆盖未知规则。 +underlay UDP 端口的公网防火墙、NAT、MTU、SELinux/firewalld、管理器重载后的实际 +连通性,以及 AlmaLinux 10 NetworkManager、Debian 13 ifupdown 在真实重启后的恢复, +仍属于真实宿主机验收项。Fabric 只使用独立的 `wg-fabric0`;管理器适配不得修改 +`br0`、默认路由或宿主机管理接口。 +真实验收步骤见 [Fabric 宿主机验收矩阵](FABRIC_HOST_ACCEPTANCE.md)。 ### VPC 控制面(当前实现阶段) @@ -145,14 +161,29 @@ PHP 只有在所有参与宿主机的观测 revision/digest 完全匹配时才 `waiting_observed`、根同步状态为 `waiting`,专用 worker 不会每 30 秒重复请求;后续 数据面上线后必须由显式 reconcile 重新推进,不能把 waiting 当成 active。 -本阶段故意不创建租户 `private0` 网卡、tap/bridge、guest route、WireGuard -AllowedIPs 或 VPC nft ACL;VPC API 返回 `applying/degraded/uncertain/waiting` 时页面和 -调度器必须把 `usable` 视为 false。删除成员、子网、route 或 ACL 会保留版本和 -tombstone,直到未来数据面回读确认后再清理。单台 VM 首版只允许加入一个 VPC, -与当前单一私网角色和防止跨租户混网的边界一致。Fabric 当前的 host-only nft -隔离优先于任何后续 VPC table,因此不能把“新建独立 nft table”误认为已经绕过 -Fabric 的默认 drop;租户数据面必须在后续阶段由带 owner/revision 的更早优先级 -规则显式放行,并同时具备回读和回滚。 +VPC 私网数据面现在由引擎的独立 reconciler 执行。每台参与宿主机使用带 owner +标记的独立私网 bridge/tap,VM XML 使用不绑定 nwfilter 的 `private0` 和私网 +`/32` 参数;公网 `br0`、公网默认路由和公网 nwfilter 不会被复用。宿主机策略表 +只安装成员/服务精确 `/32` 路由(自机走私网 bridge,跨机走 `wg-fabric0`),并 +为每个 WireGuard peer 合并精确 tenant `AllowedIPs`。每个 VPC 还有独立的 inet、 +bridge 和 ARP nft 表:ACL 按 priority 处理,bridge 入口校验 MAC/IP/ARP,IPv6、 +广播、多播和未知目的地址默认隔离;代理 ARP 仅允许面板登记的精确 `/32`。 + +云初始化 seed 同步写入 `public0`/`private0` 多网卡配置和 link-scope `/32` 路由。 +宿主机 apply 在 Fabric 锁和 VPC 锁内执行,持久文件、NetworkManager/ifupdown +配置、路由、策略规则、WireGuard、nft、代理 ARP 和 sysctl 都有实际回读;apply、 +实例接入和停机 libvirt 路径中途失败会按 ownership marker 恢复,响应不确定时保持 +`uncertain`,不猜测性反向操作。删除/撤销路径另外保留阶段 journal 并 fail-closed: +未提交事务只进入 `uncertain/manual_reconcile`,不会重复执行破坏性删除,只有已提交 +且完成资源不存在性证明后才清理 journal。PHP +只在每台宿主机的 XML、路由、ACL、反欺骗、代理 ARP、rp_filter 和完整 peer +AllowedIPs 证据都匹配当前 revision/digest 后才把 VPC 标为 `active`。 + +当前已完成脚本/解析器和引擎集成的静态验证;真实 AlmaLinux 10 NetworkManager、 +Debian 13 ifupdown、nft 语法、重启、防火墙重载、跨宿主机握手和故障回滚仍需按 +[VPC 私网数据面宿主机验收矩阵](VPC_DATAPLANE_ACCEPTANCE.md) 执行。删除成员仍 +保留 PHP tombstone,直到对应 VM `private0` 移除和宿主机资源回读完成。单台 VM +首版只允许加入一个 VPC,与当前单一私网角色和防止跨租户混网的边界一致。 本阶段没有 VPC 根删除接口。CIDR reservation 在租户私网数据面、引擎删除 tombstone 和宿主机回读闭环之前不会释放;这会保留地址以避免未知状态下复用, @@ -168,9 +199,9 @@ VM 删除与 VPC 成员是两个独立状态机:仍有成员(包括 `deletin 引擎已返回成功后把 tombstone 伪造为 `deleted`。账户删除同样拒绝遗留 VPC 或私网 CIDR reservation,避免独立 VPC worker 继续消费孤儿租户计划。 -AlmaLinux 10 与 Debian 13 的 WireGuard/NetworkManager/ifupdown 能力、 -真实宿主机路由、SELinux/firewalld、MTU 和跨机房连通性尚未在本阶段宣称通过; -需要独立的宿主机验收矩阵后,才可实现 VPC 数据面。 +AlmaLinux 10 与 Debian 13 的 WireGuard/NetworkManager/ifupdown 能力、真实宿主机 +路由、SELinux/firewalld、MTU 和跨机房连通性尚未在本地环境宣称通过;必须完成 +上述 Fabric 与 VPC 宿主机验收矩阵后,才能把环境状态推进为可上线。 PHP 不直接解密 Python 记录或执行任意 virsh 命令。主库与日志库可同实例或分别配置地址/端口。敏感业务数据加密;部署数据库连接配置仍是权限受限配置文件,不代表配置文件本身加密。 diff --git a/docs/VPC_DATAPLANE_ACCEPTANCE.md b/docs/VPC_DATAPLANE_ACCEPTANCE.md new file mode 100644 index 00000000..142c2671 --- /dev/null +++ b/docs/VPC_DATAPLANE_ACCEPTANCE.md @@ -0,0 +1,70 @@ +# VPC 私网数据面宿主机验收矩阵 + +代码侧已经验证计划解析、稳定私网 MAC、cloud-init 多网卡、生成脚本的 POSIX +语法和 typed readback contract。当前开发环境没有 `ip`、`wg`、`nft`、`nmcli`、 +`ifquery` 或 libvirt daemon,因此下面的宿主机步骤不能在本机冒充通过。 + +## 应用前证据 + +在每台同地区宿主机保存 Fabric `active` 的新鲜回读,并确认: + +- `wg-fabric0` 由 Fabric owner marker 所有,Fabric 锁可用,IPv4 forwarding 和 + `rp_filter` 处于兼容值; +- AlmaLinux 10 只有 NetworkManager/nmcli 处于 active/enabled,Debian 13 只有 + ifupdown 的 `ifup`、`ifdown`、`ifquery` 和 `/etc/network/interfaces`(含已加载 + 的 `interfaces.d`)作为网络管理来源; +- native nftables 是唯一防火墙所有者,持久主配置只存在一个受管 include 入口, + `/etc/virt-cloud`、`/run/virt-cloud`、`/etc/nftables.d` 和 `sysctl.d` 不是符号链; +- `br0`、管理接口、默认路由和未知 nft 规则的快照已经保存。 + +## 成员接入和回读 + +对一个跨两台宿主机的 VPC,至少放置两个成员和一个 ACL,逐台检查: + +1. 生成的 bridge 名称、owner/state/proxy 文件均为 root-only,bridge/tap 没有 + 地址、网关或 DNS;`private0` XML 的 bridge、稳定 MAC、`/32` 和持久/实时 XML + 都一致,私网接口不绑定公网 `clean-traffic` nwfilter。 +2. 每个成员 `/32` 和每条自定义 `/32` route 都带 panel route protocol、正确 + device/table、`via` 和 metric;不存在 VPC CIDR、默认路由或宽前缀的替代项。 +3. `wg show wg-fabric0 allowed-ips` 的每个 peer 与完整期望集合一致:overlay `/32` + 加精确 tenant/service `/32`,没有 `0.0.0.0/0`、宽前缀或其他 VPC 的未授权地址。 +4. nft inet/bridge/arp 三张表的 owner marker、chain priority、ACL comments、 + anti-spoof、IPv6/广播/未知目的 drop 和精确 proxy-ARP set 均能被 observe 回读。 + bridge 上通用 `proxy_arp=0`、同桥下一跳所需的 `proxy_arp_pvlan=1`、 + `rp_filter=2`,代理项集合与 route destination 集合 + 完全相同;其他地址的 ARP reply 必须被过滤。 +5. 从同机和跨机成员分别验证允许的 TCP/UDP/ICMP 流量、ACL deny、伪造源 MAC/IP、 + IPv6、广播/多播和访问宿主机自身地址。验证结果同时记录 guest route、宿主机 + route、WireGuard handshake 和 nft counter,不能只看页面的 `active`。 + +## 管理器和重启矩阵 + +AlmaLinux 10:执行 `nmcli connection reload`、`systemctl reload nftables`、 +`systemctl restart NetworkManager` 和宿主机重启。每一步都要确认 private bridge、 +route/rule、proxy ARP、nft include、WireGuard peer、private0 XML 和默认公网路径 +恢复,且 NetworkManager 没有接管 `br0` 或管理接口。 + +Debian 13:执行 `ifquery `、`ifup --force `、 +`systemctl reload nftables`、`systemctl restart networking` 和宿主机重启。确认 +`interfaces.d` fragment、route/rule、proxy ARP、nft include、WireGuard peer 和 +private0 XML 恢复;严禁用 ifdown 操作 `br0` 或管理接口。 + +## 故障回滚 + +在隔离环境中分别让 `ip link`、`ip route`、`ip rule`、`ip neigh`、`wg set`、 +`nft -c`、`nft -f`、NetworkManager/ifup、sysctl 或 libvirt define/seed 上传在 +每个阶段失败。预期结果是: + +- apply、实例接入和停机 libvirt 变更失败时,原 panel-owned bridge、route/rule、 + peer AllowedIPs、nft 表/include、proxy 项、sysctl、XML 和 seed 按快照恢复; +- 删除/撤销路径使用阶段 journal 和 fail-closed 收敛:未提交的 journal 在回读前 + 返回 `uncertain/manual_reconcile` 并保留现场,不重复执行破坏性删除;只有已经 + 提交且能证明面板资源全部不存在的 journal 才会被清理。因此删除路径的“回滚” + 是可审计的停机与人工核对边界,不是假设资源可以自动恢复; +- 外部 bridge/profile、未知 route、未知 ARP proxy 项和未知 nft 规则不被删除; +- 恢复本身失败或响应丢失时返回 `uncertain/degraded`,保留事务目录供下一次 + readback,绝不返回成功; +- 重试只依据新的完整宿主机回读,不对不确定的 libvirt 或网络变更盲目反向执行。 + +跨宿主机最后还要单独验证 underlay 公网防火墙、NAT、MTU、SELinux 和 UDP 监听。 +Fabric/VPC 的本地 nft 表不等于 underlay 已放行。 diff --git a/engine/tests/test_cloud_init.py b/engine/tests/test_cloud_init.py index b06d0ba1..346a61a3 100644 --- a/engine/tests/test_cloud_init.py +++ b/engine/tests/test_cloud_init.py @@ -14,7 +14,8 @@ from virsh_panel.cloud_init import ( _build_seed_iso, _enable_network_updates, build_seed_iso, generate_root_password, hash_root_password, - read_seed_network, replace_seed_network, replace_seed_settings, + read_seed_network, replace_seed_network, replace_seed_private_network, + replace_seed_settings, validate_cloud_network, validate_guest_hostname, validate_private_network, _parse_network_config, ) @@ -268,10 +269,54 @@ def test_seed_iso_can_add_private_role_without_public_route_or_dns(): "mac": "52:54:00:12:34:56", "private_ip_cidr": "10.24.3.7/32", "private_mac": "52:54:00:12:34:57", + "private_routes": [], "roles": ["public0", "private0"], } +@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None, + reason="pycdlib is not installed") +def test_private_seed_routes_are_exact_and_can_be_reconciled_or_removed(): + validated = validate_cloud_network( + "8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], PUBLIC_KEY, + ) + seed = build_seed_iso( + str(uuid.uuid4()), "private-route-vm", "52:54:00:12:34:56", validated, + private_mac="52:54:00:12:34:57", + private_network={ + "private_ip_cidr": "10.24.3.7/32", + "routes": ["10.24.3.8/32"], + }, + ) + assert read_seed_network(seed)["private_routes"] == ["10.24.3.8/32"] + + changed = replace_seed_private_network( + seed, + private_mac="52:54:00:12:34:58", + private_ip_cidr="10.24.3.9/32", + private_routes=["10.24.3.10/32", "10.24.3.11/32"], + ) + changed_network = read_seed_network(changed) + assert changed_network["private_ip_cidr"] == "10.24.3.9/32" + assert changed_network["private_mac"] == "52:54:00:12:34:58" + assert changed_network["private_routes"] == ["10.24.3.10/32", "10.24.3.11/32"] + + removed = replace_seed_private_network( + changed, private_mac=None, private_ip_cidr=None, + ) + removed_network = read_seed_network(removed) + assert "private_ip_cidr" not in removed_network + assert "private_routes" not in removed_network + + with pytest.raises(ValueError): + replace_seed_private_network( + seed, + private_mac="52:54:00:12:34:58", + private_ip_cidr="10.24.3.9/32", + private_routes=["10.24.3.0/24"], + ) + + @pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None, reason="pycdlib is not installed") def test_seed_iso_has_nocloud_files_and_mac_specific_static_network(): diff --git a/engine/tests/test_fabric.py b/engine/tests/test_fabric.py index 6bfeb24f..013d6cab 100644 --- a/engine/tests/test_fabric.py +++ b/engine/tests/test_fabric.py @@ -118,12 +118,27 @@ def test_generated_helpers_are_posix_safe_and_do_not_embed_private_keys(): assert result.returncode == 0, result.stderr assert "br0" not in script assert "PRIVATE KEY" not in script + observe = scripts[2] + assert "__VC_FABRIC_ADMIN_STATE__" in observe + assert "__VC_FABRIC_SYSCTL__ip_forward" in observe + assert "__VC_FABRIC_SYSCTL__rp_filter_default" in observe + assert "__VC_FABRIC_RPF__wg-fabric0" in observe + assert "__VC_FABRIC_VPC_STATE__" in observe + assert "list set inet virt_cloud_wg_fabric vpc_tenant_ips" in observe + assert 'table!="main" && table!="local"' in observe apply = scripts[-1] assert KEY2 in apply and KEY1 not in apply assert 'KEY="$BASE/wg-fabric0.key"' in apply assert "wg-fabric0" in apply assert "address_conflict" in apply assert "existing_route" in apply + assert "route_overlaps_target" in apply + assert "supernet" not in apply # shell check is numeric and bounded + assert "virt-cloud-wg-fabric.nft" in apply + assert "include \"/etc/nftables.d/virt-cloud-wg-fabric.nft\"" in apply + assert "trap rollback EXIT HUP INT TERM" in apply + assert '"$WG" showconf' in apply + assert "route save table all" in apply assert 'chmod 700 "$BASE" /usr/local/libexec' not in apply assert "virt-cloud-wg-fabric-v1" in apply assert "virt_cloud_wg_fabric" in apply @@ -137,6 +152,14 @@ def test_generated_helpers_are_posix_safe_and_do_not_embed_private_keys(): assert "NetworkManager/system-connections" in apply assert "nmcli" in apply assert "flock" in apply + assert "vpc_state_load" in apply + assert "vpc_state_allowed_for_peer" in apply + assert "vpc_state_refresh_nft" in apply + assert "vpc_state_refresh_nft" in _BOOT_HELPER + assert 'vpc_state != "invalid"' in observe + assert 'vpc[prefix "|" device "|" table "|" via "|" metric]' in observe + assert "key|wg.conf|address.save|route.save|nft.table" in _BOOT_HELPER + assert 'journal_file_mode" = 600' in _BOOT_HELPER ifup = _apply_script(current, current.nodes[0], { "host-a": KEY1, "host-b": KEY2, }, "ifupdown", "/usr/bin/ifup") @@ -147,10 +170,12 @@ def test_generated_helpers_are_posix_safe_and_do_not_embed_private_keys(): assert result.returncode == 0, result.stderr assert "/etc/network/interfaces.d/virt-cloud-wg-fabric0" in ifup assert "ifup" in ifup and "ifdown" in ifup - assert "ExecStart=/usr/bin/ifup --force wg-fabric0" in ifup + assert "ExecStart=/usr/local/libexec/virt-cloud-wg-fabric --ifupdown-service" in ifup # The Debian 13 contract must also work with classic ifupdown; its # ifquery implementation does not provide ifupdown2's --check flag. assert "ifquery\" --check" not in ifup + assert "VC_FABRIC_LOCK_HELD=1" in ifup + assert "VC_FABRIC_ALLOW_TRANSITION=1" in ifup assert "br0" not in ifup with pytest.raises(FabricError): _apply_script(current, current.nodes[0], { @@ -170,6 +195,12 @@ class FakeManager: self.ping_ok = ping_ok self.endpoint_device = endpoint_device self.scripts = [] + self.reprobe_calls = 0 + self.admin_state = "up" + self.ip_forward = "1" + self.rp_filter = "2" + self.rp_filter_default = "2" + self.rp_filter_iface = "2" self.profile = { "ssh_config_file": "/tmp/fake-ssh-config", "ssh_target": "vp-managed", @@ -192,6 +223,10 @@ class FakeManager: def current(self): return self.profile + def reprobe_current(self): + self.reprobe_calls += 1 + return self.profile["capabilities"] + def _exec(self, argv, *, timeout, input_text=None): assert argv[-1] == "/bin/sh -s" assert timeout == 35 @@ -234,14 +269,22 @@ class FakeManager: f"__VC_FABRIC_PATH__={target}|{FABRIC_INTERFACE}\n" f"__VC_FABRIC_ENDPOINT_PATH__={endpoint.split(':', 1)[0]}|{self.endpoint_device}\n" f"__VC_FABRIC_PING__={target}|{'ok' if self.ping_ok else 'failed'}\n" + f"__VC_FABRIC_ROUTE_OVERLAP__={target}|clean\n" "__VC_FABRIC_MANAGER_MODE__=networkmanager_nmcli\n" "__VC_FABRIC_MANAGER_OWNER__=owned\n" "__VC_FABRIC_MANAGER_ACTIVE__=active\n" + f"__VC_FABRIC_ADMIN_STATE__={self.admin_state}\n" + f"__VC_FABRIC_SYSCTL__ip_forward={self.ip_forward}\n" + f"__VC_FABRIC_SYSCTL__rp_filter={self.rp_filter}\n" + f"__VC_FABRIC_SYSCTL__rp_filter_default={self.rp_filter_default}\n" + f"__VC_FABRIC_RPF__wg-fabric0={self.rp_filter_iface}\n" "__VC_FABRIC_ENABLED__=enabled\n" "__VC_FABRIC_ACTIVE__=active\n" "__VC_FABRIC_TIMER_ENABLED__=enabled\n" "__VC_FABRIC_TIMER_ACTIVE__=active\n" "__VC_FABRIC_NFT_GUARD__=owned\n" + "__VC_FABRIC_NFT_PERSISTENCE__=owned\n" + "__VC_FABRIC_VPC_NFT_STATE__=owned\n" "__VC_FABRIC_KEY_SECURE__=yes\n" "__VC_FABRIC_CONFIG_SECURE__=yes\n" "__VC_FABRIC_HELPER__=owned\n" @@ -281,6 +324,24 @@ def test_adapter_ignores_the_kernel_connected_route_for_its_own_address(): assert observed["config_ok"] is True +def test_adapter_requires_admin_up_and_fabric_sysctl_readback(): + current = plan() + manager = FakeManager(KEY1) + manager.admin_state = "down" + assert FabricHostAdapter(manager).observe( + current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2} + )["config_ok"] is False + + manager.admin_state = "up" + manager.rp_filter_iface = "1" + observed = FabricHostAdapter(manager).observe( + current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2} + ) + assert observed["config_ok"] is False + assert observed["observed"]["admin_state"] == "up" + assert observed["observed"]["rp_filters"][FABRIC_INTERFACE] == "1" + + def test_adapter_rejects_stale_config_digest_and_failed_probe(): current = plan() stale = FakeManager(KEY1, config_digest="0" * 64) @@ -389,6 +450,8 @@ def test_coordinator_keeps_successful_hosts_and_blocks_next_stage(monkeypatch): assert result["next_stage_allowed"] is False states = {node["host_id"]: node["state"] for node in result["nodes"]} assert states == {"host-a": "active", "host-b": "uncertain"} + assert managers["host-a"].reprobe_calls == 1 + assert managers["host-b"].reprobe_calls == 1 serialized = "\n".join(store.values.values()) assert "PRIVATE KEY" not in serialized assert KEY1 in serialized and KEY2 in serialized @@ -488,3 +551,113 @@ def test_new_fabric_cannot_reuse_a_host_or_overlay_catalog_entry(): with pytest.raises(FabricError) as error: asyncio.run(coordinator.apply(value)) assert error.value.error_code == "fabric_host_interface_conflict" + + +class TenantReadbackManager(FakeManager): + """Synthetic readback with panel-owned VPC tenant state.""" + + def __init__(self, *args, tenant_ip="10.10.0.2/32", **kwargs): + super().__init__(*args, **kwargs) + self.tenant_ip = tenant_ip + + def _exec(self, argv, *, timeout, input_text=None): + result = super()._exec(argv, timeout=timeout, input_text=input_text) + if input_text.startswith("#!/bin/sh\nset -eu"): + return result + peer = KEY2 if self.public_key == KEY1 else KEY1 + target = "100.64.1.2" if self.public_key == KEY1 else "100.64.1.1" + endpoint = "203.0.113.2:51820" if self.public_key == KEY1 else "203.0.113.1:51820" + marker = f"__VC_FABRIC_PEER__={peer}|{endpoint}|{target}/32" + output = result.stdout.replace(marker, f"{marker},{self.tenant_ip}") + output += ( + "__VC_FABRIC_VPC_STATE__=owned\n" + f"__VC_FABRIC_VPC_TENANT__={peer}|{self.tenant_ip}\n" + "__VC_FABRIC_VPC_NFT_STATE__=owned\n" + f"__VC_FABRIC_VPC_NFT_IP__={self.tenant_ip}\n" + ) + return result.__class__(result.args, result.returncode, output, result.stderr) + + +def test_fabric_merges_and_reads_panel_owned_vpc_allowed_ips(): + current = plan() + observed = FabricHostAdapter(TenantReadbackManager(KEY1)).observe( + current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2} + ) + assert observed["config_ok"] is True + assert observed["observed"]["peer_allowed_exact"] is True + assert f"{KEY2}|10.10.0.2/32" in observed["observed"]["vpc_tenants"] + assert all("10001" not in route for route in observed["observed"]["routes"]) + + +def test_fabric_rejects_unbacked_vpc_allowed_ip(): + current = plan() + manager = FakeManager(KEY1) + original_exec = manager._exec + + def unbacked(argv, *, timeout, input_text=None): + result = original_exec(argv, timeout=timeout, input_text=input_text) + if input_text.startswith("#!/bin/sh\nset -eu"): + return result + peer = KEY2 + marker = f"__VC_FABRIC_PEER__={peer}|203.0.113.2:51820|100.64.1.2/32" + output = result.stdout.replace(marker, f"{marker},10.10.0.2/32") + return result.__class__(result.args, result.returncode, output, result.stderr) + + manager._exec = unbacked + observed = FabricHostAdapter(manager).observe( + current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2} + ) + assert observed["config_ok"] is False + assert observed["observed"]["peer_allowed_exact"] is False + + +def test_fabric_rejects_non_rfc1918_vpc_tenant_prefix(): + current = plan() + observed = FabricHostAdapter( + TenantReadbackManager(KEY1, tenant_ip="169.254.1.2/32") + ).observe(current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2}) + assert observed["config_ok"] is False + assert observed["observed"]["peer_allowed_exact"] is False + + +def test_fabric_rejects_stale_vpc_nft_tenant_set(): + current = plan() + manager = TenantReadbackManager(KEY1) + original_exec = manager._exec + + def stale_nft(argv, *, timeout, input_text=None): + result = original_exec(argv, timeout=timeout, input_text=input_text) + if input_text.startswith("#!/bin/sh\nset -eu"): + return result + output = result.stdout.replace( + "__VC_FABRIC_VPC_NFT_IP__=10.10.0.2/32\n", "") + return result.__class__(result.args, result.returncode, output, result.stderr) + + manager._exec = stale_nft + observed = FabricHostAdapter(manager).observe( + current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2} + ) + assert observed["config_ok"] is False + assert observed["observed"]["vpc_nft_exact"] is False + + +def test_fabric_does_not_hide_foreign_custom_route(): + current = plan() + manager = FakeManager(KEY1) + original_exec = manager._exec + + def foreign_route(argv, *, timeout, input_text=None): + result = original_exec(argv, timeout=timeout, input_text=input_text) + if input_text.startswith("#!/bin/sh\nset -eu"): + return result + output = result.stdout + ( + f"__VC_FABRIC_ROUTE__=10.10.0.2/32|10001|{FABRIC_INTERFACE}\n" + ) + return result.__class__(result.args, result.returncode, output, result.stderr) + + manager._exec = foreign_route + observed = FabricHostAdapter(manager).observe( + current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2} + ) + assert observed["config_ok"] is False + assert "10.10.0.2/32|10001|wg-fabric0" in observed["observed"]["routes"] diff --git a/engine/tests/test_remote_host.py b/engine/tests/test_remote_host.py index f81b01c9..42d7a913 100644 --- a/engine/tests/test_remote_host.py +++ b/engine/tests/test_remote_host.py @@ -85,6 +85,8 @@ __VCAP_SERVICE__nftables=active __VCAP_SERVICE_ENABLED__network_manager=enabled __VCAP_SERVICE_ENABLED__networkd=disabled __VCAP_SERVICE_ENABLED__networking=disabled +__VCAP_SERVICE_ENABLED__firewall=disabled +__VCAP_SERVICE_ENABLED__nftables=enabled __VCAP_FILE__interfaces=absent __VCAP_FILE__interfaces_d=absent __VCAP_FILE__networkmanager_profiles=absent @@ -119,6 +121,8 @@ class Runner: self.ssh_exit = 0 self.encrypted = False self.public_key_type = "ssh-ed25519" + self.capability_exit = 0 + self.capability_output = CAPABILITY_OUTPUT self.commands: list[list[str]] = [] def __call__(self, argv, **kwargs): @@ -134,7 +138,10 @@ class Runner: return subprocess.CompletedProcess(argv, 0, f"{self.public_key_type} fake-public-key\n", "") if argv[0] == "ssh": if _CAPABILITY_MARKER in argv[-1]: - return subprocess.CompletedProcess(argv, 0, CAPABILITY_OUTPUT, "") + return subprocess.CompletedProcess( + argv, self.capability_exit, self.capability_output, + "private remote diagnostic", + ) return subprocess.CompletedProcess(argv, self.ssh_exit, "", "permission denied") raise AssertionError(argv) @@ -474,6 +481,14 @@ def test_stage_test_commit_writes_private_pinned_ssh_config(tmp_path): assert tested["capabilities"]["os"]["package_tool"] == "dnf" assert tested["capabilities"]["os"]["package_tool_available"] is True assert tested["capabilities"]["wireguard"]["deployment_mode"] == "networkmanager_nmcli" + assert tested["capabilities"]["nftables"]["service_active"] is True + assert tested["capabilities"]["nftables"]["service_persistent"] is True + assert tested["capabilities"]["network"]["firewall_manager_evidence"] == { + "firewalld_active": False, + "firewalld_enabled": False, + "nftables_active": True, + "nftables_enabled": True, + } assert tested["capabilities"]["network"]["rp_filter_default"] == 2 assert tested["capabilities"]["network"]["rp_filter_interfaces"]["br0"] == 2 assert tested["capabilities"]["network_roles"]["private"]["host_interface"] == WG_FABRIC_INTERFACE @@ -511,6 +526,80 @@ def test_capability_snapshot_is_persisted_only_after_commit(tmp_path): assert profile_after["capabilities"]["wireguard"]["interface"] == WG_FABRIC_INTERFACE +def test_current_capabilities_are_reprobed_through_pinned_generation(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + staged = manager.stage( + make_profile(scanned, default_network="bridge:br0"), + scanned["fingerprint"], + ) + manager.test(staged) + current = manager.commit(staged) + profile_path = staged.path / "profile.json" + persisted_before = profile_path.read_bytes() + + runner.capability_output = CAPABILITY_OUTPUT.replace( + "__VCAP_SERVICE_ENABLED__nftables=enabled", + "__VCAP_SERVICE_ENABLED__nftables=disabled", + ) + capabilities = manager.reprobe_current_capabilities() + + assert capabilities["probe_valid"] is True + assert capabilities["network_roles"]["public"]["selector"] == "bridge:br0" + assert capabilities["nftables"]["service_active"] is True + assert capabilities["nftables"]["service_persistent"] is False + assert capabilities["vpc_ready"] is False + assert "nftables_service_not_enabled" in capabilities["reasons"] + assert profile_path.read_bytes() == persisted_before + assert current["capabilities"]["vpc_ready"] is True + assert runner.commands[-1][0:4] == [ + "ssh", "-F", str(staged.path / "config"), "-T", + ] + assert runner.commands[-1][-1] == _CAPABILITY_PROBE_COMMAND + + +def test_current_capability_reprobe_requires_configured_host(tmp_path): + manager = make_manager(tmp_path, Runner()) + with pytest.raises(RemoteHostError) as error: + manager.reprobe_current_capabilities() + assert error.value.status == 409 + assert error.value.error_code == "host_not_configured" + + +def test_current_capability_reprobe_hides_remote_failure_output(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + staged = manager.stage(make_profile(scanned), scanned["fingerprint"]) + manager.test(staged) + manager.commit(staged) + runner.capability_exit = 255 + + with pytest.raises(RemoteHostError) as error: + manager.reprobe_current_capabilities() + + assert error.value.status == 502 + assert error.value.error_code == "host_capability_probe_failed" + assert "private remote diagnostic" not in str(error.value) + + +def test_current_capability_reprobe_rejects_invalid_protocol(tmp_path): + runner = Runner() + manager = make_manager(tmp_path, runner) + scanned = manager.scan("host.example", 2222) + staged = manager.stage(make_profile(scanned), scanned["fingerprint"]) + manager.test(staged) + manager.commit(staged) + runner.capability_output = CAPABILITY_OUTPUT.replace("__VCAP_END__", "") + + with pytest.raises(RemoteHostError) as error: + manager.reprobe_current_capabilities() + + assert error.value.status == 502 + assert error.value.error_code == "host_capability_probe_invalid" + + def test_capability_probe_rejects_missing_private_plane_evidence(): output = CAPABILITY_OUTPUT.replace( "__VCAP_TOOL__wg=/usr/bin/wg", "__VCAP_TOOL__wg=", @@ -524,11 +613,23 @@ def test_capability_probe_rejects_missing_private_plane_evidence(): assert capabilities["private_ready"] is False assert capabilities["vpc_ready"] is False assert "wireguard_tool_missing" in capabilities["reasons"] - assert "firewall_owner_not_nftables" in capabilities["reasons"] + assert "nftables_service_not_active" in capabilities["reasons"] assert "ipv4_forwarding_disabled_or_unknown" in capabilities["reasons"] assert capabilities["network_roles"]["private"]["separate_from_public"] is True +def test_capability_probe_rejects_firewalld_enabled_for_next_boot(): + output = CAPABILITY_OUTPUT.replace( + "__VCAP_SERVICE_ENABLED__firewall=disabled", + "__VCAP_SERVICE_ENABLED__firewall=enabled", + ) + capabilities = parse_host_capabilities(output, public_network="bridge:br0") + assert capabilities["network"]["firewall_manager"] == "conflict" + assert capabilities["nftables"]["ready"] is False + assert capabilities["vpc_ready"] is False + assert "firewall_owner_not_nftables" in capabilities["reasons"] + + def test_capability_probe_rejects_preexisting_fabric_interface(): output = CAPABILITY_OUTPUT.replace( '[{"ifname":"br0"}]', diff --git a/engine/tests/test_vpc.py b/engine/tests/test_vpc.py index f854c8bb..23de109a 100644 --- a/engine/tests/test_vpc.py +++ b/engine/tests/test_vpc.py @@ -170,7 +170,7 @@ def test_plan_validates_routes_acl_ports_and_member_scope(): "private_ip_cidr": "10.20.0.11/32", "subnet_id": "subnet-a"}, ]}, ], - routes=[{"route_id": "route-a", "destination_cidr": "10.20.0.128/25", + routes=[{"route_id": "route-a", "destination_cidr": "10.20.0.128/32", "next_hop_member_id": "member-a", "metric": 20}], acls=[{"acl_id": "acl-a", "direction": "ingress", "action": "allow", "protocol": "tcp", "source_cidr": "10.20.0.0/24", @@ -195,6 +195,12 @@ def test_plan_validates_routes_acl_ports_and_member_scope(): "route_id": "bad", "destination_cidr": "0.0.0.0/0", "next_hop_host_id": "host-a", }])) + with pytest.raises(VpcError) as broad_route: + parse_vpc_plan(payload(routes=[{ + "route_id": "broad", "destination_cidr": "10.20.0.128/25", + "next_hop_member_id": "member-a", + }])) + assert broad_route.value.error_code == "vpc_route_not_exact" with pytest.raises(VpcError): parse_vpc_plan(payload(acls=[{ "acl_id": "bad", "direction": "egress", "action": "allow", diff --git a/engine/tests/test_vpc_dataplane.py b/engine/tests/test_vpc_dataplane.py new file mode 100644 index 00000000..d01de25d --- /dev/null +++ b/engine/tests/test_vpc_dataplane.py @@ -0,0 +1,251 @@ +"""Pure VPC private data-plane contract tests. + +These tests render the host transaction only; real nft/ip/wg and libvirt +acceptance remains a host-matrix test because this checkout has no network +namespace or libvirt daemon. +""" +from __future__ import annotations + +import subprocess +from dataclasses import replace + +from virsh_panel.vpc import VPC_SCHEMA_VERSION +from virsh_panel.vpc_dataplane import ( + _markers, + parse_vpc_dataplane_plan, + patch_private_interface_xml, + render_apply_script, + render_observe_script, + render_remove_script, + render_vpc_nft_rules, +) + + +WG_KEY = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=" +WG_KEY_2 = "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=" + + +def _plan(): + return parse_vpc_dataplane_plan({ + "schema_version": VPC_SCHEMA_VERSION, + "vpc_id": "vpc-hk-dp", + "region": "hk", + "fabric_id": "fabric-hk", + "fabric_revision": 3, + "cidr": "10.42.0.0/24", + "desired_revision": 1, + "operation_id": "vpc-op-dp-0001", + "subnets": [{"subnet_id": "subnet-a", "cidr": "10.42.0.0/25"}], + "hosts": [ + {"host_id": "host-a", "members": [{ + "member_id": "member-a", + "instance_uuid": "11111111-1111-4111-8111-111111111111", + "private_ip_cidr": "10.42.0.10/32", + "subnet_id": "subnet-a", + }]}, + {"host_id": "host-b", "members": [{ + "member_id": "member-b", + "instance_uuid": "22222222-2222-4222-8222-222222222222", + "private_ip_cidr": "10.42.0.11/32", + "subnet_id": "subnet-a", + }]}, + ], + "routes": [{ + "route_id": "service-a", "destination_cidr": "10.42.0.100/32", + "next_hop_member_id": "member-b", "metric": 20, + }], + "acls": [{ + "acl_id": "allow-https", "direction": "ingress", "action": "allow", + "protocol": "tcp", "source_cidr": "10.42.0.0/24", + "destination_cidr": "10.42.0.10/32", "port_from": 443, + "port_to": 443, "priority": 10, + }], + "fabric_peers": [{ + "host_id": "host-b", "public_key": WG_KEY, + "overlay_ip": "100.64.0.2/32", + "tenant_allowed_ips": ["10.42.0.11/32", "10.42.0.100/32"], + }], + }, "host-a") + + +def test_rendered_data_plane_has_exact_routes_proxy_arp_and_atomic_nft_batch(): + plan = _plan() + apply = render_apply_script(plan) + nft = render_vpc_nft_rules(plan) + assert "10.42.0.11/32|wg-fabric0" in apply + assert "10.42.0.100/32|wg-fabric0" in apply + assert 'route replace "$destination" table "$table" via "$via" dev "$device" onlink' in apply + assert 'neigh replace proxy "$proxy_ip"' in apply + assert "table arp" in nft + assert "arp-proxy-output" in nft + assert 'proxy_arp = 0' in apply + assert 'proxy_arp_pvlan = 1' in apply + assert 'NFT_BATCH="$TXN/apply.nft"' in apply + assert '"$NFT" -f "$NFT_BATCH"' in apply + assert '"$NFT" delete table inet "$TABLE"' not in apply + assert "anti-spoof-public-to-bridge" in nft + assert "anti-spoof-public-to-fabric" in nft + assert "anti-spoof-bridge-to-foreign" in nft + assert "anti-spoof-fabric-to-foreign" in nft + assert 'oifname "wg-fabric0" ip daddr @vpc_dest_ips drop' in nft + + +def test_rendered_scripts_are_posix_shell(): + plan = _plan() + for script in (render_apply_script(plan), render_observe_script(plan)): + result = subprocess.run( + ["/bin/sh", "-n"], input=script, text=True, + capture_output=True, check=False, + ) + assert result.returncode == 0, result.stderr + + +def test_remove_script_checks_ownership_before_destructive_cleanup(): + plan = _plan() + empty_host = replace( + plan, + members=tuple(member for member in plan.members + if member.host_id != plan.host_id), + ) + for mode in ("networkmanager_nmcli", "ifupdown"): + script = render_remove_script(empty_host, deployment_mode=mode) + result = subprocess.run( + ["/bin/sh", "-n"], input=script, text=True, + capture_output=True, check=False, + ) + assert result.returncode == 0, result.stderr + assert 'connection.stable-id' in script + assert 'nm_empty ipv4.routes' in script + assert "virt-cloud-vpc-dataplane-v1 vpc=" in script + assert 'nft_table_count' in script + assert '[ "$name" = "$TABLE" ]' in script + assert 'BRIDGE_PRESENT=no' in script + assert 'if "$IP" link show dev "$BRIDGE"' in script + assert 'bridge_routes6' in script + assert 'proxy_left' in script + for phase in ( + "routes_removed", "manager_removed", "bridge_removed", + "nft_removed", "files_removed", "wg_merged", "committed", + ): + assert f"set_phase {phase}" in script + assert '[ "$RESUME" = yes ]' in script + assert 'committed)' in script + assert 'files_removed|wg_merged)' in script + + +def test_proxy_markers_are_bounded_and_typed(): + parsed = _markers( + "__VC_VPC_PROXY_ARP__=0\n" + "__VC_VPC_PROXY_ARP_PVLAN__=1\n" + "__VC_VPC_PROXY_STATE__=owned\n" + "__VC_VPC_PROXY_IP__=10.42.0.11\n" + ) + assert parsed["proxy_arp"] == "0" + assert parsed["proxy_arp_pvlan"] == "1" + assert parsed["proxy_state"] == "owned" + assert parsed["proxy_ips"] == ["10.42.0.11"] + + +def test_peer_allowed_ips_are_closed_over_vpc_or_trusted_fabric_set(): + plan = _plan() + payload = plan.vpc.canonical() + payload["fabric_peers"] = [{ + "host_id": "host-b", "public_key": WG_KEY, + "overlay_ip": "100.64.0.2/32", + "tenant_allowed_ips": ["10.42.0.11/32", "10.42.0.100/32", + "10.42.0.200/32"], + }] + try: + parse_vpc_dataplane_plan(payload, "host-a") + except Exception as exc: + assert getattr(exc, "error_code", None) == "vpc_tenant_allowed_ip_unowned" + else: + raise AssertionError("unowned peer AllowedIP was accepted") + + parsed = parse_vpc_dataplane_plan( + payload, "host-a", + trusted_tenant_allowed_ips={ + "host-b": ["10.42.0.11/32", "10.42.0.100/32", + "10.42.0.200/32"], + }) + assert parsed.peers[0].tenant_allowed_ips[-1] == "10.42.0.200/32" + + +def test_observe_can_require_the_complete_authoritative_fabric_peer_set(): + plan = _plan() + strict = parse_vpc_dataplane_plan( + plan.vpc.canonical(), "host-a", + fabric_peers=[{ + "host_id": "host-b", "public_key": WG_KEY, + "overlay_ip": "100.64.0.2/32", + "tenant_allowed_ips": ["10.42.0.11/32", "10.42.0.100/32"], + }], + trusted_tenant_allowed_ips={ + "host-b": ["10.42.0.11/32", "10.42.0.100/32"], + }, + fabric_peer_keys=[WG_KEY, WG_KEY_2], + ) + assert strict.fabric_peer_keys == frozenset({WG_KEY, WG_KEY_2}) + observe = render_observe_script(strict) + assert "__VC_VPC_WG_PEER_SET__" in observe + assert "live_fabric_peer_keys" in observe + try: + parse_vpc_dataplane_plan( + plan.vpc.canonical(), "host-a", + fabric_peers=[{ + "host_id": "host-b", "public_key": WG_KEY, + "overlay_ip": "100.64.0.2/32", + "tenant_allowed_ips": ["10.42.0.11/32", "10.42.0.100/32"], + }], + trusted_tenant_allowed_ips={ + "host-b": ["10.42.0.11/32", "10.42.0.100/32"], + }, + fabric_peer_keys=[WG_KEY_2], + ) + except Exception as exc: + assert getattr(exc, "error_code", None) == "vpc_fabric_peer_set_invalid" + else: + raise AssertionError("VPC peer outside authoritative Fabric set was accepted") + + +def test_private_xml_patch_keeps_public_role_and_leaves_private_filter_free(): + plan = _plan() + member = plan.members[0] + xml = """ + + + """ + patched = patch_private_interface_xml( + xml, member=member, resources=plan.resources, + vpc_id=plan.vpc.vpc_id, desired_revision=plan.desired_revision, + desired_digest=plan.desired_digest, + ) + assert "alias name=\"public0\"" in patched + assert 'alias name="private0"' in patched + assert f'bridge="{plan.resources.bridge}"' in patched + assert 'filter="clean-traffic"' not in patched + assert f'private-network-digest="{plan.desired_digest}"' in patched + + +def test_private_xml_patch_promotes_legacy_single_nic_to_public_role(): + plan = _plan() + member = plan.members[0] + legacy = """ + + + """ + patched = patch_private_interface_xml( + legacy, member=member, resources=plan.resources, + vpc_id=plan.vpc.vpc_id, desired_revision=plan.desired_revision, + desired_digest=plan.desired_digest, + ) + assert 'alias name="public0"' in patched + assert 'alias name="private0"' in patched + # A second reconciliation must still identify the original NIC as public. + reparsed = patch_private_interface_xml( + patched, member=member, resources=plan.resources, + vpc_id=plan.vpc.vpc_id, desired_revision=plan.desired_revision, + desired_digest=plan.desired_digest, + ) + assert reparsed.count('alias name="public0"') == 1 + assert reparsed.count('alias name="private0"') == 1 diff --git a/engine/virsh_panel/cloud_init.py b/engine/virsh_panel/cloud_init.py index 37a5f641..df828b0a 100644 --- a/engine/virsh_panel/cloud_init.py +++ b/engine/virsh_panel/cloud_init.py @@ -321,6 +321,47 @@ def validate_private_network(private_ip_cidr: Any) -> dict[str, str]: return {"private_ip_cidr": str(interface)} +def _validate_private_routes(value: Any) -> list[str]: + """Validate the guest's exact on-link VPC routes. + + The host owns inter-host forwarding, while the guest still needs a route + for each remote /32. Keep this list deliberately narrow: no gateways, + default routes, or broad prefixes are accepted on ``private0``. + """ + if value is None: + return [] + if not isinstance(value, (list, tuple)) or len(value) > 4096: + raise ValueError("私网路由列表无效") + result: set[str] = set() + for item in value: + if isinstance(item, str): + destination = item + elif isinstance(item, dict): + if item.get("to") in {"default", "0.0.0.0/0", "::/0"}: + # Keep the legacy diagnostic used by seed validation callers: + # private0 is never allowed to acquire a default route. + raise ValueError("私网网卡必须是无默认路由的静态 /32") + if set(item) != {"to", "scope"} or item.get("scope") != "link": + raise ValueError("私网路由必须是 link scope 的 /32") + destination = item.get("to") + else: + raise ValueError("私网路由格式无效") + if destination in {"default", "0.0.0.0/0", "::/0"}: + raise ValueError("私网网卡必须是无默认路由的静态 /32") + try: + network = ipaddress.ip_network(destination, strict=True) + except (TypeError, ValueError) as exc: + raise ValueError("私网路由必须是 IPv4 /32") from exc + if (not isinstance(network, ipaddress.IPv4Network) + or network.prefixlen != 32 + or not any(network.subnet_of(ipaddress.IPv4Network(block)) + for block in ("10.0.0.0/8", "172.16.0.0/12", + "192.168.0.0/16"))): + raise ValueError("私网路由必须是 RFC1918 IPv4 /32") + result.add(str(network)) + return sorted(result) + + def _validate_network_mac(value: Any, label: str) -> str: if not isinstance(value, str) or not _MAC.fullmatch(value): raise ValueError(f"{label} MAC 地址无效") @@ -403,7 +444,6 @@ def _parse_network_config(config: Any) -> dict[str, Any]: or private.get("accept-ra") is not False or not isinstance(private.get("addresses"), list) or len(private["addresses"]) != 1 - or "routes" in private or not isinstance(private_match, dict) or set(private_match) != {"macaddress"}): raise ValueError("原 cloud-init 私网网卡必须是无默认路由的静态 /32") @@ -414,6 +454,7 @@ def _parse_network_config(config: Any) -> dict[str, Any]: result.update({ **private_network, "private_mac": private_mac, + "private_routes": _validate_private_routes(private.get("routes")), "roles": [PUBLIC_INTERFACE_ALIAS, PRIVATE_INTERFACE_ALIAS], }) return result @@ -552,6 +593,9 @@ def build_seed_iso( private_network.get("private_ip_cidr") if isinstance(private_network, dict) else None ) + private_routes = _validate_private_routes( + private_network.get("routes", []) + if isinstance(private_network, dict) else []) if normalized_private_mac == normalized_mac: raise ValueError("公网和私网网卡不能使用同一个 MAC") network_config["ethernets"][PRIVATE_INTERFACE_ALIAS] = { @@ -560,6 +604,10 @@ def build_seed_iso( "dhcp6": False, "accept-ra": False, "addresses": [private["private_ip_cidr"]], + **({"routes": [ + {"to": destination, "scope": "link"} + for destination in private_routes + ]} if private_routes else {}), } if debian12_network_fix: # dhcp6=false does not disable DHCPv6 started in response to a router @@ -776,6 +824,72 @@ def replace_seed_network( raise ValueError("原 cloud-init 网络配置格式无效") from exc +def replace_seed_private_network( + seed: bytes, + *, + private_mac: str | None, + private_ip_cidr: str | None, + private_routes: list[str] | tuple[str, ...] | None = None, +) -> bytes: + """Add, replace, or remove the panel-managed ``private0`` network. + + The public NIC, credentials, hostname and DNS settings are copied from + the existing panel seed. A private NIC never receives DHCP, IPv6 RA, or a + default route; its only address is the validated RFC1918 /32. Passing + ``None`` for both values removes the private role and is used when a VPC + member is detached. + """ + if (private_mac is None) != (private_ip_cidr is None): + raise ValueError("私网网卡必须同时提供 MAC 和地址") + if private_mac is None and private_routes: + raise ValueError("移除私网网卡时不能保留路由") + files = _read_seed_files(seed) + try: + config = json.loads(files["network-config"]) + parsed = _parse_network_config(config) + # Validate the complete existing role before editing it. This keeps a + # hand-edited or foreign seed from becoming a partially managed + # multi-NIC configuration. + _parse_network_config(config) + user_data = _enable_network_updates(files["user-data"]) + metadata = _decode_seed_metadata(files["meta-data"]) + ethernets = config.get("ethernets") + if not isinstance(ethernets, dict): + raise ValueError("原 cloud-init 网卡配置无效") + if private_mac is None: + ethernets.pop(PRIVATE_INTERFACE_ALIAS, None) + else: + normalized_mac = _validate_network_mac(private_mac, "私网") + private = validate_private_network(private_ip_cidr) + routes = _validate_private_routes(private_routes) + if normalized_mac == parsed["mac"]: + raise ValueError("公网和私网网卡不能使用同一个 MAC") + ethernets[PRIVATE_INTERFACE_ALIAS] = { + "match": {"macaddress": normalized_mac}, + "dhcp4": False, + "dhcp6": False, + "accept-ra": False, + "addresses": [private["private_ip_cidr"]], + **({"routes": [ + {"to": destination, "scope": "link"} + for destination in routes + ]} if routes else {}), + } + # Rotate the datasource identity so both add and remove operations are + # consumed on the next boot. Credentials remain opaque bytes. + metadata["instance-id"] = f"virt-cloud-private-{uuid.uuid4().hex}" + metadata[_NETWORK_POLICY_KEY] = _NETWORK_POLICY_VALUE + network_data = json.dumps(config, ensure_ascii=True).encode("ascii") + b"\n" + return _build_seed_iso(( + ("/USERDATA.;1", "user-data", "/user-data", user_data), + ("/METADATA.;1", "meta-data", "/meta-data", + _encode_seed_metadata(metadata)), + ("/NETWORK.;1", "network-config", "/network-config", network_data), + )) + except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: + raise ValueError("原 cloud-init 网络配置格式无效") from exc + + def _read_seed_files(seed: bytes) -> dict[str, bytes]: """Read the three bounded files from a panel-generated NoCloud seed.""" if not isinstance(seed, bytes) or not seed or len(seed) > 1024 * 1024: @@ -1101,6 +1215,7 @@ def read_seed_network(seed: bytes) -> dict[str, Any]: result.update({ "private_ip_cidr": parsed["private_ip_cidr"], "private_mac": parsed["private_mac"], + "private_routes": list(parsed.get("private_routes", [])), "roles": list(parsed["roles"]), }) return result diff --git a/engine/virsh_panel/fabric.py b/engine/virsh_panel/fabric.py index 3998e0dc..41820f8a 100644 --- a/engine/virsh_panel/fabric.py +++ b/engine/virsh_panel/fabric.py @@ -30,12 +30,20 @@ FABRIC_SERVICE = "virt-cloud-wg-fabric.service" FABRIC_REPAIR_SERVICE = "virt-cloud-wg-fabric-reconcile.service" FABRIC_TIMER = "virt-cloud-wg-fabric-reconcile.timer" FABRIC_NFT_TABLE = "virt_cloud_wg_fabric" +FABRIC_NFT_RULES = "/etc/nftables.d/virt-cloud-wg-fabric.nft" +FABRIC_NFT_MAIN_CANDIDATES = ( + "/etc/nftables.conf", + "/etc/sysconfig/nftables.conf", +) FABRIC_CONNECTION = "virt-cloud-wg-fabric0" FABRIC_NM_PROFILE = "/etc/NetworkManager/system-connections/virt-cloud-wg-fabric0.nmconnection" FABRIC_IFUPDOWN_FRAGMENT = "/etc/network/interfaces.d/virt-cloud-wg-fabric0" FABRIC_LOCK = "/run/virt-cloud/wg-fabric0.lock" +FABRIC_TXN = "/etc/virt-cloud/.wg-fabric-txn" FABRIC_DEPLOYMENT_MODES = frozenset(("networkmanager_nmcli", "ifupdown")) IFUP_PATHS = frozenset(("/usr/sbin/ifup", "/usr/bin/ifup", "/sbin/ifup", "/bin/ifup")) +IFDOWN_PATHS = frozenset(("/usr/sbin/ifdown", "/usr/bin/ifdown", "/sbin/ifdown", "/bin/ifdown")) +IFQUERY_PATHS = frozenset(("/usr/sbin/ifquery", "/usr/bin/ifquery", "/sbin/ifquery", "/bin/ifquery")) MAX_FABRIC_NODES = 64 MAX_ENDPOINT_LENGTH = 64 MAX_FABRIC_OUTPUT = 262144 @@ -43,10 +51,403 @@ MAX_FABRIC_CONFIG = 65536 HANDSHAKE_MAX_AGE = 600 FABRIC_RECONCILE_INTERVAL = 30 MAX_MARKER_LINE = 512 +VPC_STATE_DIR = "/etc/virt-cloud/vpc-dataplane" +VPC_STATE_OWNER_MARKER = "virt-cloud-vpc-dataplane-v1" +MAX_VPC_STATE_FILES = 256 +MAX_VPC_STATE_SIZE = 65536 _ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}\Z") _KEY = re.compile(r"[A-Za-z0-9+/]{42}==\Z|[A-Za-z0-9+/]{43}=\Z") _FABRIC_KEY = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}\Z") +_RFC1918_NETWORKS = ( + ipaddress.IPv4Network("10.0.0.0/8"), + ipaddress.IPv4Network("172.16.0.0/12"), + ipaddress.IPv4Network("192.168.0.0/16"), +) + + +# VPC owns the tenant half of a WireGuard peer's AllowedIPs. Fabric must +# merge that state when it writes/restarts wg-fabric0, while still retaining +# exclusive ownership of the overlay /32. This fragment is deliberately +# shell-only because it runs on the remote host; it validates ownership, +# permissions and every tenant prefix before producing a small, private +# key|ip file consumed by the caller. The observer uses the same parser in +# tolerant mode so a malformed state degrades readback rather than accepting +# an unverified tenant route. +_VPC_STATE_LOADER = r'''VPC_STATE_DIR="/etc/virt-cloud/vpc-dataplane" +VPC_STATE_OWNER="virt-cloud-vpc-dataplane-v1" +VPC_STATE_HOST="__VC_FABRIC_HOST_ID__" +VPC_STATE_FABRIC="__VC_FABRIC_ID__" +VPC_FABRIC_NETWORK="__VC_FABRIC_NETWORK__" +VPC_STATE_OBSERVE="__VC_VPC_STATE_OBSERVE__" +VPC_STATE_STATUS=empty +VPC_PEER_FILE="/run/virt-cloud/.virt-cloud-vpc-peers.$$" +VPC_ROUTE_FILE="/run/virt-cloud/.virt-cloud-vpc-routes.$$" +VPC_TENANT_FILE="/run/virt-cloud/.virt-cloud-vpc-tenant-ips.$$" +vpc_state_fail() { + VPC_STATE_STATUS=invalid + if [ "$VPC_STATE_OBSERVE" = yes ]; then return 1; fi + exit 71 +} +vpc_state_ipv4() { + printf '%s\n' "$1" | awk -F. 'BEGIN {ok=1} NF != 4 {ok=0} { + for (i=1;i<=4;i++) if ($i !~ /^[0-9]+$/ || $i > 255) ok=0 + } END {exit ok ? 0 : 1}' +} +vpc_state_key() { + printf '%s\n' "$1" | awk 'length($0)==44 && $0 ~ /^[A-Za-z0-9+\/]+=$/ {ok=1} + END {exit ok ? 0 : 1}' +} +vpc_state_host() { + case "$1" in ''|*[!A-Za-z0-9_-]*) return 1 ;; esac + [ "$(printf '%s' "$1" | awk 'length($0)<=64')" = "$1" ] +} +vpc_state_hex() { + printf '%s\n' "$1" | awk 'length($0)==64 && $0 ~ /^[0-9a-f]+$/ {ok=1} + END {exit ok ? 0 : 1}' +} +vpc_state_allowed() { + case "$1" in */32) ;; *) return 1 ;; esac + vpc_state_ipv4 "${1%/32}" +} +vpc_state_private() { + printf '%s\n' "${1%/32}" | awk -F. 'NF==4 { + if ($1==10) ok=1 + else if ($1==172 && $2>=16 && $2<=31) ok=1 + else if ($1==192 && $2==168) ok=1 + } END {exit ok ? 0 : 1}' +} +vpc_state_cidr() { + printf '%s\n' "$1" | awk -F'[./]' 'NF==5 && $1 ~ /^[0-9]+$/ && $2 ~ /^[0-9]+$/ && $3 ~ /^[0-9]+$/ && $4 ~ /^[0-9]+$/ && $5 ~ /^[0-9]+$/ { + if ($1>255 || $2>255 || $3>255 || $4>255 || $5<16 || $5>24) exit 1 + if ($1==10) ok=1 + else if ($1==172 && $2>=16 && $2<=31) ok=1 + else if ($1==192 && $2==168) ok=1 + } END {exit ok ? 0 : 1}' +} +vpc_state_cidr_contains() { + # State routes are all /32s. Keep the check arithmetic-only and avoid + # non-portable awk bitwise operators so this works with AlmaLinux and + # Debian's default awk implementations. + awk -F'[./]' -v addr="${1%/32}" -v cidr="$2" 'BEGIN { + na=split(addr,a,"."); nc=split(cidr,n,"/"); nb=split(n[1],b,".") + if (na != 4 || nc != 2 || nb != 4 || n[2] !~ /^[0-9]+$/) exit 1 + for (i=1;i<=4;i++) if (a[i] !~ /^[0-9]+$/ || a[i] > 255 || b[i] !~ /^[0-9]+$/ || b[i] > 255) exit 1 + prefix=n[2]+0; if (prefix < 0 || prefix > 32) exit 1 + value=(a[1]*256+a[2])*65536+a[3]*256+a[4] + base=(b[1]*256+b[2])*65536+b[3]*256+b[4] + unit=1; for (i=0;i<32-prefix;i++) unit*=2 + # Require a canonical network and the route address inside it. + exit (base % unit == 0 && int(value/unit) == int(base/unit)) ? 0 : 1 + }' +} +vpc_state_in_fabric() { + awk -F'[./]' -v addr="${1%/32}" -v cidr="$VPC_FABRIC_NETWORK" 'BEGIN { + na=split(addr,a,"."); nc=split(cidr,n,"/"); nb=split(n[1],b,".") + if (na != 4 || nc != 2 || nb != 4 || n[2] !~ /^[0-9]+$/) exit 1 + value=(a[1]*256+a[2])*65536+a[3]*256+a[4] + base=(b[1]*256+b[2])*65536+b[3]*256+b[4] + unit=1; for (i=0;i<32-n[2];i++) unit*=2 + exit (value >= base && value < base+unit) ? 0 : 1 + }' +} +vpc_state_safe_token() { + case "$1" in ''|*[!A-Za-z0-9_.:-]*) return 1 ;; esac + [ "$(printf '%s' "$1" | awk 'length($0)<=128')" = "$1" ] +} +vpc_state_dir_secure() { + [ -n "$STAT" ] || return 1 + [ ! -L "$VPC_STATE_DIR" ] || return 1 + if [ ! -e "$VPC_STATE_DIR" ]; then return 0; fi + [ -d "$VPC_STATE_DIR" ] && [ ! -L "$VPC_STATE_DIR" ] || return 1 + [ "$($STAT -c '%u:%a' "$VPC_STATE_DIR" 2>/dev/null)" = 0:700 ] +} +vpc_state_load() { + VPC_STATE_STATUS=empty + [ -n "$STAT" ] || vpc_state_fail || return 1 + vpc_state_dir_secure || vpc_state_fail || return 1 + rm -f "$VPC_PEER_FILE" 2>/dev/null || true + rm -f "$VPC_ROUTE_FILE" 2>/dev/null || true + rm -f "$VPC_TENANT_FILE" 2>/dev/null || true + : > "$VPC_PEER_FILE" || vpc_state_fail || return 1 + chmod 600 "$VPC_PEER_FILE" || vpc_state_fail || return 1 + : > "$VPC_ROUTE_FILE" || vpc_state_fail || return 1 + chmod 600 "$VPC_ROUTE_FILE" || vpc_state_fail || return 1 + : > "$VPC_TENANT_FILE" || vpc_state_fail || return 1 + chmod 600 "$VPC_TENANT_FILE" || vpc_state_fail || return 1 + vpc_state_files=0 + vpc_state_seen_ips= + for vpc_state_file in "$VPC_STATE_DIR"/*.state; do + [ -e "$vpc_state_file" ] || [ -L "$vpc_state_file" ] || continue + vpc_state_files=$((vpc_state_files + 1)) + [ "$vpc_state_files" -le 256 ] || vpc_state_fail || return 1 + [ -f "$vpc_state_file" ] && [ ! -L "$vpc_state_file" ] || vpc_state_fail || return 1 + [ "$($STAT -c '%u:%a' "$vpc_state_file" 2>/dev/null)" = 0:600 ] || + vpc_state_fail || return 1 + [ "$($STAT -c '%s' "$vpc_state_file" 2>/dev/null)" -le 65536 ] 2>/dev/null || + vpc_state_fail || return 1 + vpc_owner_count=0 + vpc_host_count=0 + vpc_vpc_count=0 + vpc_cidr_count=0 + vpc_fabric_count=0 + vpc_revision_count=0 + vpc_digest_count=0 + vpc_table_count=0 + vpc_state_table= + vpc_state_bridge= + while IFS='|' read -r vpc_kind vpc_a vpc_b vpc_c vpc_d; do + case "$vpc_kind" in + owner) + [ "$vpc_a" = "$VPC_STATE_OWNER" ] && [ -z "$vpc_b$vpc_c$vpc_d" ] || + vpc_state_fail || return 1 + vpc_owner_count=$((vpc_owner_count + 1)) ;; + host) + [ "$vpc_a" = "$VPC_STATE_HOST" ] && [ -z "$vpc_b$vpc_c$vpc_d" ] || + vpc_state_fail || return 1 + vpc_host_count=$((vpc_host_count + 1)) ;; + vpc) + vpc_state_safe_token "$vpc_a" && + [ -z "$vpc_b$vpc_c$vpc_d" ] || + vpc_state_fail || return 1 + vpc_vpc_count=$((vpc_vpc_count + 1)) ;; + cidr) + vpc_state_cidr "$vpc_a" && [ -z "$vpc_b$vpc_c$vpc_d" ] || + vpc_state_fail || return 1 + vpc_state_cidr_value=$vpc_a + vpc_cidr_count=$((vpc_cidr_count + 1)) ;; + fabric) + vpc_state_safe_token "$vpc_a" && + { [ "$VPC_STATE_FABRIC" = "*" ] || [ "$vpc_a" = "$VPC_STATE_FABRIC" ]; } && + [ -z "$vpc_b$vpc_c$vpc_d" ] || + vpc_state_fail || return 1 + vpc_fabric_count=$((vpc_fabric_count + 1)) ;; + revision) + printf '%s\n' "$vpc_a" | awk 'length($0)>=1 && length($0)<=19 && $0 ~ /^[1-9][0-9]*$/ {ok=1} + END {exit ok ? 0 : 1}' || vpc_state_fail || return 1 + [ -z "$vpc_b$vpc_c$vpc_d" ] || vpc_state_fail || return 1 + vpc_revision_count=$((vpc_revision_count + 1)) ;; + digest) + vpc_state_hex "$vpc_a" && [ -z "$vpc_b$vpc_c$vpc_d" ] || + vpc_state_fail || return 1 + vpc_digest_count=$((vpc_digest_count + 1)) ;; + bridge|priority) + if [ "$vpc_kind" = bridge ]; then + vpc_state_safe_token "$vpc_a" && [ -z "$vpc_b$vpc_c$vpc_d" ] || + vpc_state_fail || return 1 + vpc_state_bridge=$vpc_a + else + vpc_state_safe_token "$vpc_a" && [ -z "$vpc_b$vpc_c$vpc_d" ] || + vpc_state_fail || return 1 + fi ;; + table) + case "$vpc_a" in ''|*[!0-9]*) vpc_state_fail || return 1 ;; esac + [ "$vpc_a" -le 4294967295 ] 2>/dev/null || vpc_state_fail || return 1 + [ -z "$vpc_b$vpc_c$vpc_d" ] || vpc_state_fail || return 1 + vpc_state_table=$vpc_a + vpc_table_count=$((vpc_table_count + 1)) ;; + route) + vpc_route_via=${vpc_d%%|*} + vpc_route_metric=${vpc_d#*|} + if ! vpc_state_allowed "$vpc_a" || ! vpc_state_private "$vpc_a" || + vpc_state_in_fabric "$vpc_a" || + [ -z "$vpc_b" ] || + { [ "$vpc_b" != "$vpc_state_bridge" ] && [ "$vpc_b" != wg-fabric0 ]; } || + ! vpc_state_safe_token "$vpc_b" || + case "$vpc_c" in ''|*[!0-9]*) true ;; *) false ;; esac || + [ "$vpc_c" != "$vpc_state_table" ] || + { [ "$vpc_route_via" != - ] && ! vpc_state_ipv4 "$vpc_route_via"; } || + case "$vpc_route_metric" in ''|*[!0-9]*) true ;; *) false ;; esac || + [ "$vpc_route_metric" -lt 1 ] 2>/dev/null || + [ "$vpc_route_metric" -gt 65535 ] 2>/dev/null; then + vpc_state_fail || return 1 + fi + printf '%s|%s|%s|%s|%s\n' "$vpc_a" "$vpc_b" "$vpc_c" "$vpc_route_via" "$vpc_route_metric" >> "$VPC_ROUTE_FILE" || + vpc_state_fail || return 1 + # The Fabric quarantine set must cover both sides of an + # inter-host flow. State files carry all member and + # service /32 routes, including addresses that are local + # to this host and therefore are absent from peer lines. + printf '%s\n' "$vpc_a" >> "$VPC_TENANT_FILE" || + vpc_state_fail || return 1 ;; + peer) + vpc_state_host "$vpc_a" && vpc_state_key "$vpc_b" && [ -n "$vpc_c" ] && + [ -z "$vpc_d" ] || vpc_state_fail || return 1 + vpc_old_ifs=$IFS + IFS=, + for vpc_ip in $vpc_c; do + vpc_state_allowed "$vpc_ip" || { IFS=$vpc_old_ifs; vpc_state_fail || return 1; } + vpc_state_private "$vpc_ip" || { IFS=$vpc_old_ifs; vpc_state_fail || return 1; } + vpc_state_in_fabric "$vpc_ip" && { IFS=$vpc_old_ifs; vpc_state_fail || return 1; } + case " $vpc_state_seen_ips " in + *" $vpc_ip "*) IFS=$vpc_old_ifs; vpc_state_fail || return 1 ;; + esac + vpc_state_seen_ips="$vpc_state_seen_ips $vpc_ip" + printf '%s|%s\n' "$vpc_b" "$vpc_ip" >> "$VPC_PEER_FILE" || { + IFS=$vpc_old_ifs; vpc_state_fail || return 1; + } + done + IFS=$vpc_old_ifs + vpc_peer_count=$((vpc_peer_count + 1)) ;; + '') : ;; + *) vpc_state_fail || return 1 ;; + esac + done < "$vpc_state_file" + [ "$vpc_owner_count" = 1 ] && [ "$vpc_host_count" = 1 ] && + [ "$vpc_vpc_count" = 1 ] && [ "$vpc_cidr_count" = 1 ] && + [ "$vpc_revision_count" = 1 ] && + [ "$vpc_fabric_count" = 1 ] && [ "$vpc_digest_count" = 1 ] && + [ "$vpc_table_count" = 1 ] || + vpc_state_fail || return 1 + # Validate membership after the complete record has been parsed so a + # malicious route cannot precede the cidr line and bypass the check. + while IFS='|' read -r vpc_route_prefix vpc_route_dev vpc_route_tbl vpc_route_via vpc_route_metric vpc_route_extra; do + [ -n "$vpc_route_prefix" ] || continue + [ -z "$vpc_route_extra" ] || vpc_state_fail || return 1 + vpc_state_cidr_contains "$vpc_route_prefix" "$vpc_state_cidr_value" || + vpc_state_fail || return 1 + done < "$VPC_ROUTE_FILE" + done + if [ "$vpc_state_files" -gt 0 ]; then VPC_STATE_STATUS=owned; fi + return 0 +} +vpc_state_allowed_for_peer() { + vpc_lookup_key=$1 + vpc_lookup_result= + if [ -f "$VPC_PEER_FILE" ]; then + while IFS='|' read -r vpc_key vpc_ip vpc_extra; do + [ "$vpc_key" = "$vpc_lookup_key" ] || continue + [ -z "$vpc_extra" ] || { VPC_STATE_STATUS=invalid; return 1; } + if [ -n "$vpc_lookup_result" ]; then + vpc_lookup_result="$vpc_lookup_result,$vpc_ip" + else + vpc_lookup_result=$vpc_ip + fi + done < "$VPC_PEER_FILE" + fi + printf '%s' "$vpc_lookup_result" +} +vpc_state_route_owned() { + vpc_route_target=$1 + vpc_route_device=$2 + vpc_route_table=$3 + vpc_route_via=${4:--} + vpc_route_metric=${5:-100} + [ -f "$VPC_ROUTE_FILE" ] || return 1 + while IFS='|' read -r vpc_route_prefix vpc_route_dev vpc_route_tbl vpc_route_state_via vpc_route_state_metric vpc_route_extra; do + [ -z "$vpc_route_extra" ] || continue + [ "$vpc_route_prefix" = "$vpc_route_target" ] && + [ "$vpc_route_dev" = "$vpc_route_device" ] && + [ "$vpc_route_tbl" = "$vpc_route_table" ] && + [ "${vpc_route_state_via:--}" = "$vpc_route_via" ] && + [ "${vpc_route_state_metric:-100}" = "$vpc_route_metric" ] && return 0 + done < "$VPC_ROUTE_FILE" + return 1 +} +vpc_state_refresh_nft() { + # The Fabric quarantine table is the later hook in the forwarding path. + # Refresh its exact tenant set while holding the shared Fabric lock. The + # caller must have already run vpc_state_load, which validates every state + # file, key, host and RFC1918 /32 before this function is reached. + [ -n "$NFT" ] || return 1 + "$NFT" list table inet virt_cloud_wg_fabric >/dev/null 2>&1 || return 1 + vpc_nft_tmp="$VPC_TENANT_FILE.nft" + { + printf '%s\n' 'flush set inet virt_cloud_wg_fabric vpc_tenant_ips' + if [ -s "$VPC_TENANT_FILE" ]; then + printf '%s' 'add element inet virt_cloud_wg_fabric vpc_tenant_ips { ' + awk 'NF == 1 { + if ($0 !~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\/32$/ || seen[$0]++) bad=1 + else { if (out) printf ", "; printf "%s", $0; out=1 } + } + END { if (bad) exit 1; if (out) printf " "; }' "$VPC_TENANT_FILE" || return 1 + printf '%s\n' '}' + fi + } > "$vpc_nft_tmp" || return 1 + chmod 600 "$vpc_nft_tmp" || { rm -f "$vpc_nft_tmp"; return 1; } + "$NFT" -c -f "$vpc_nft_tmp" >/dev/null 2>&1 || { rm -f "$vpc_nft_tmp"; return 1; } + "$NFT" -f "$vpc_nft_tmp" >/dev/null 2>&1 + vpc_nft_status=$? + rm -f "$vpc_nft_tmp" + return "$vpc_nft_status" +} +''' + + +# Read back the actual tenant set from the Fabric quarantine table. The +# state-file loader proves what the panel intends to authorize; this fragment +# proves that nftables currently contains the same exact /32 set after a +# reboot, reload, or an out-of-band firewall change. Keep the parser narrow: +# interval/range elements and non-IPv4 tokens fail closed in the adapter. +_VPC_NFT_OBSERVE_FRAGMENT = r'''vpc_nft_state=missing +vpc_nft_values= +if [ -n "$NFT" ]; then + vpc_nft_text=$("$NFT" list set inet virt_cloud_wg_fabric vpc_tenant_ips 2>/dev/null || true) + if [ -n "$vpc_nft_text" ]; then + if vpc_nft_values=$(printf '%s\n' "$vpc_nft_text" | awk ' +function valid_ipv4(value, octets, count, pos) { + count = split(value, octets, ".") + if (count != 4) return 0 + for (pos = 1; pos <= 4; pos++) + if (octets[pos] !~ /^[0-9]+$/ || octets[pos] > 255) return 0 + return 1 +} +function canonical_ipv4(value, parts, count, address) { + count = split(value, parts, "/") + if (count == 1) address=parts[1] + else if (count == 2 && parts[2] == "32") address=parts[1] + else return "" + if (!valid_ipv4(address)) return "" + return address +} +{ + line = $0 + if (!set_seen && line ~ /^[[:space:]]*set[[:space:]]+vpc_tenant_ips[[:space:]]*\{/) set_seen=1 + if (set_seen && line ~ /elements[[:space:]]*=[[:space:]]*\{/) { + sub(/^.*elements[[:space:]]*=[[:space:]]*\{/, "", line) + elements_seen=1 + in_elements=1 + } + if (in_elements) { + close_pos=index(line, "}") + if (close_pos) { + line=substr(line, 1, close_pos-1) + in_elements=0 + } + gsub(/[{},]/, " ", line) + count=split(line, fields, /[[:space:]]+/) + for (pos=1; pos<=count; pos++) { + token=fields[pos] + if (token == "") continue + token=canonical_ipv4(token) + if (token == "") {bad=1; continue} + print token + } + } +} +END { + if (!set_seen || !elements_seen && in_elements || in_elements || bad) exit 1 +}' + ); then + vpc_nft_state=owned + printf '%s\n' '__VC_FABRIC_VPC_NFT_STATE__=owned' + if [ -n "$vpc_nft_values" ]; then + printf '%s\n' "$vpc_nft_values" | while IFS= read -r vpc_nft_ip; do + [ -n "$vpc_nft_ip" ] || continue + printf '%s\n' "__VC_FABRIC_VPC_NFT_IP__=$vpc_nft_ip" + done + fi + else + vpc_nft_state=invalid + printf '%s\n' '__VC_FABRIC_VPC_NFT_STATE__=invalid' + fi + else + printf '%s\n' '__VC_FABRIC_VPC_NFT_STATE__=missing' + fi +else + printf '%s\n' '__VC_FABRIC_VPC_NFT_STATE__=missing' +fi +''' class FabricError(Exception): @@ -96,6 +497,17 @@ def _text(value: Any, label: str, *, maximum: int) -> str: return value +def _is_rfc1918_address(value: ipaddress.IPv4Address) -> bool: + """Return true only for the three RFC1918 IPv4 private ranges. + + ``IPv4Address.is_private`` also covers link-local, documentation and + other special-use ranges. The host-side VPC state loader intentionally + accepts only RFC1918 tenant /32s, so the Python readback validator must + enforce the same boundary instead of silently widening it. + """ + return any(value in network for network in _RFC1918_NETWORKS) + + def _host_id(value: Any) -> str: if not isinstance(value, str) or not _ID.fullmatch(value): raise FabricError("Fabric 宿主机标识无效") @@ -277,6 +689,30 @@ def _profile_ifup_path(profile: Mapping[str, Any] | None) -> str: return "/usr/sbin/ifup" +def _profile_ifquery_path(profile: Mapping[str, Any] | None) -> str: + """Select the probed ifquery path without accepting shell text.""" + capabilities = profile.get("capabilities") if isinstance(profile, Mapping) else None + tools = capabilities.get("tools") if isinstance(capabilities, Mapping) else None + if isinstance(tools, Mapping): + entry = tools.get("ifquery") + candidate = entry.get("path") if isinstance(entry, Mapping) else None + if candidate in IFQUERY_PATHS: + return str(candidate) + return "/usr/sbin/ifquery" + + +def _profile_ifdown_path(profile: Mapping[str, Any] | None) -> str: + """Select the probed ifdown path without accepting shell text.""" + capabilities = profile.get("capabilities") if isinstance(profile, Mapping) else None + tools = capabilities.get("tools") if isinstance(capabilities, Mapping) else None + if isinstance(tools, Mapping): + entry = tools.get("ifdown") + candidate = entry.get("path") if isinstance(entry, Mapping) else None + if candidate in IFDOWN_PATHS: + return str(candidate) + return "/usr/sbin/ifdown" + + def _here_doc(path: str, content: str) -> str: marker = "__VC_FABRIC_" + hashlib.sha256(content.encode()).hexdigest()[:16] end = "" if content.endswith("\n") else "\n" @@ -286,25 +722,76 @@ def _here_doc(path: str, content: str) -> str: return f"cat > {target} <<'{marker}'\n{content}{end}{marker}\n" +def _nft_rules_text(digest: str) -> str: + """Return the persistent, revision-bound host quarantine ruleset.""" + marker = f"{FABRIC_OWNER_MARKER}:{digest}" + return f'''# {FABRIC_OWNER_MARKER} +# fabric-plan-digest={digest} +table inet {FABRIC_NFT_TABLE} {{ + # VPC reconciler fills this set only with validated tenant /32s from + # panel-owned state files. Keeping it in the Fabric table is required: + # the Fabric quarantine chain runs after the tenant chain and must not + # drop an already-authorized private packet. + set vpc_tenant_ips {{ + type ipv4_addr; + flags interval; + }} + chain input {{ + type filter hook input priority -100; policy accept; + iifname "{FABRIC_INTERFACE}" ip protocol icmp accept comment "{marker}" + iifname "{FABRIC_INTERFACE}" counter drop comment "{marker}" + }} + chain output {{ + type filter hook output priority -100; policy accept; + oifname "{FABRIC_INTERFACE}" ip protocol icmp accept comment "{marker}" + oifname "{FABRIC_INTERFACE}" counter drop comment "{marker}" + }} + chain forward {{ + type filter hook forward priority -100; policy accept; + iifname "{FABRIC_INTERFACE}" ip saddr != @vpc_tenant_ips counter drop comment "{marker}" + oifname "{FABRIC_INTERFACE}" ip daddr != @vpc_tenant_ips counter drop comment "{marker}" + iifname "{FABRIC_INTERFACE}" ip saddr @vpc_tenant_ips ip daddr != @vpc_tenant_ips counter drop comment "{marker}" + oifname "{FABRIC_INTERFACE}" ip daddr @vpc_tenant_ips ip saddr != @vpc_tenant_ips counter drop comment "{marker}" + }} +}} +''' + + _BOOT_HELPER = r'''#!/bin/sh # virt-cloud-wg-fabric-v1 # fabric-plan-digest=__VC_FABRIC_DIGEST__ -EXPECTED_DIGEST="__VC_FABRIC_DIGEST__" +PLAN_DIGEST="__VC_FABRIC_DIGEST__" +EXPECTED_DIGEST="$PLAN_DIGEST" DEPLOYMENT_MODE="__VC_FABRIC_MODE__" CONNECTION="__VC_FABRIC_CONNECTION__" CONNECTION_UUID="__VC_FABRIC_UUID__" +IFUP_PATH="__VC_IFUP_PATH__" +IFQUERY_PATH="__VC_IFQUERY_PATH__" +IFDOWN_PATH="__VC_IFDOWN_PATH__" +RECOVER_ONLY=no +[ "${1:-}" = --recover-only ] && RECOVER_ONLY=yes set -eu umask 077 PATH=/usr/sbin:/usr/bin:/sbin:/bin export PATH _tmp_owner= -cleanup() { [ -z "$_tmp_owner" ] || rm -f "$_tmp_owner" || true; } +_tmp_nft_rules= +cleanup() { + [ -z "$_tmp_owner" ] || rm -f "$_tmp_owner" || true + [ -z "$_tmp_nft_rules" ] || rm -f "$_tmp_nft_rules" || true + [ -z "${VPC_PEER_FILE:-}" ] || rm -f "$VPC_PEER_FILE" || true + [ -z "${VPC_ROUTE_FILE:-}" ] || rm -f "$VPC_ROUTE_FILE" || true + [ -z "${VPC_TENANT_FILE:-}" ] || rm -f "$VPC_TENANT_FILE" || true +} trap cleanup EXIT HUP INT TERM BASE=/etc/virt-cloud IFACE=wg-fabric0 +HELPER=/usr/local/libexec/virt-cloud-wg-fabric CONF="$BASE/wg-fabric0.conf" OWNER="$BASE/wg-fabric0.owner" KEY="$BASE/wg-fabric0.key" +NFT_RULES=/etc/nftables.d/virt-cloud-wg-fabric.nft +JOURNAL="$BASE/.wg-fabric-txn" NM_PROFILE=/etc/NetworkManager/system-connections/virt-cloud-wg-fabric0.nmconnection IFUPDOWN_FRAGMENT=/etc/network/interfaces.d/virt-cloud-wg-fabric0 LOCK=/run/virt-cloud/wg-fabric0.lock @@ -314,12 +801,334 @@ WG=$(find_tool /usr/bin/wg /usr/sbin/wg /bin/wg /sbin/wg) || exit 70 IP=$(find_tool /usr/sbin/ip /usr/bin/ip /sbin/ip /bin/ip) || exit 70 NFT=$(find_tool /usr/sbin/nft /usr/bin/nft /sbin/nft /bin/nft) || exit 70 STAT=$(find_tool /usr/bin/stat /bin/stat /usr/sbin/stat /sbin/stat) || exit 70 +SHA256=$(find_tool /usr/bin/sha256sum /bin/sha256sum /usr/sbin/sha256sum /sbin/sha256sum) || exit 70 +SYSTEMCTL=$(find_tool /usr/bin/systemctl /bin/systemctl /usr/sbin/systemctl /sbin/systemctl) || exit 70 +AWK=$(find_tool /usr/bin/awk /bin/awk /usr/sbin/awk /sbin/awk) || exit 70 +BRIDGE_CMD=$(find_tool /usr/sbin/bridge /usr/bin/bridge /sbin/bridge /bin/bridge) || exit 70 +read_sysctl() { + [ -r "$1" ] || return 1 + sysctl_value= + IFS= read -r sysctl_value < "$1" || return 1 + printf '%s' "$sysctl_value" +} +if ! sysctl_forward=$(read_sysctl /proc/sys/net/ipv4/ip_forward); then exit 71; fi +[ "$sysctl_forward" = 1 ] || exit 71 +if ! sysctl_rp_all=$(read_sysctl /proc/sys/net/ipv4/conf/all/rp_filter); then exit 71; fi +case "$sysctl_rp_all" in 0|2) : ;; *) exit 71 ;; esac +if ! sysctl_rp_default=$(read_sysctl /proc/sys/net/ipv4/conf/default/rp_filter); then exit 71; fi +case "$sysctl_rp_default" in 0|2) : ;; *) exit 71 ;; esac [ "$DEPLOYMENT_MODE" = networkmanager_nmcli ] || [ "$DEPLOYMENT_MODE" = ifupdown ] || exit 71 if [ -L /run/virt-cloud ] || { [ -e /run/virt-cloud ] && [ ! -d /run/virt-cloud ]; }; then exit 71; fi -mkdir -p /run/virt-cloud +if [ -e /run/virt-cloud ]; then + [ -d /run/virt-cloud ] && [ ! -L /run/virt-cloud ] || exit 71 + [ "$(stat -c '%u:%a' /run/virt-cloud 2>/dev/null)" = 0:700 ] || exit 71 +else + mkdir /run/virt-cloud + chmod 700 /run/virt-cloud +fi FLOCK=$(find_tool /usr/bin/flock /usr/sbin/flock /bin/flock /sbin/flock) || exit 70 -exec 9>"$LOCK" -"$FLOCK" -x 9 || exit 79 +if [ "${VC_FABRIC_LOCK_HELD:-0}" != 1 ]; then + [ ! -L "$LOCK" ] || exit 71 + if [ ! -e "$LOCK" ]; then + : > "$LOCK" + chmod 600 "$LOCK" + fi + [ -f "$LOCK" ] && [ "$(stat -c '%u:%a' "$LOCK" 2>/dev/null)" = 0:600 ] || exit 71 + exec 9>>"$LOCK" + "$FLOCK" -x 9 || exit 79 + [ ! -L "$LOCK" ] && [ "$(stat -c '%u:%a' "$LOCK" 2>/dev/null)" = 0:600 ] || exit 71 +fi +journal_secure() { + [ "$(stat -c '%u:%a' "$BASE" 2>/dev/null)" = 0:700 ] || return 1 + [ -d "$JOURNAL" ] && [ ! -L "$JOURNAL" ] || return 1 + [ "$(stat -c '%u:%a' "$JOURNAL" 2>/dev/null)" = 0:700 ] || return 1 + [ -f "$JOURNAL/state" ] && [ ! -L "$JOURNAL/state" ] || return 1 + [ "$(stat -c '%u:%a' "$JOURNAL/state" 2>/dev/null)" = 0:600 ] || return 1 + return 0 +} +journal_value() { + journal_key=$1 + awk -F= -v wanted="$journal_key" '$1 == wanted {print substr($0, index($0, "=") + 1); found=1} END {exit found ? 0 : 1}' "$JOURNAL/meta" +} +journal_file_secure() { + journal_name=$1 + [ -f "$JOURNAL/$journal_name" ] && [ ! -L "$JOURNAL/$journal_name" ] || return 1 + journal_file_mode=$(stat -c '%a' "$JOURNAL/$journal_name" 2>/dev/null || true) + [ "$(stat -c '%u' "$JOURNAL/$journal_name" 2>/dev/null)" = 0 ] || return 1 + # Snapshots containing private key material or live WireGuard state must + # remain owner-only even while an interrupted transaction is recovered. + # A permissive mode here would allow recovery to copy a secret back to a + # host-readable path before the normal readback catches the drift. + case "$journal_name" in + key|wg.conf|address.save|route.save|nft.table) + [ "$journal_file_mode" = 600 ] || return 1 ;; + helper) + [ "$journal_file_mode" = 700 ] || return 1 ;; + *) + case "$journal_file_mode" in + 600|640|644|700) : ;; + *) return 1 ;; + esac ;; + esac +} +restore_journal_file() { + restore_target=$1 + restore_name=$2 + restore_dir=${restore_target%/*} + if [ -f "$JOURNAL/$restore_name.present" ]; then + journal_file_secure "$restore_name" || return 1 + [ ! -L "$restore_target" ] || return 1 + [ -d "$restore_dir" ] || return 1 + restore_tmp=$(mktemp "$restore_dir/.virt-cloud-restore.XXXXXX") || return 1 + cp -p "$JOURNAL/$restore_name" "$restore_tmp" || { rm -f "$restore_tmp"; return 1; } + chmod "$(stat -c '%a' "$JOURNAL/$restore_name")" "$restore_tmp" || { rm -f "$restore_tmp"; return 1; } + mv -f "$restore_tmp" "$restore_target" || { rm -f "$restore_tmp"; return 1; } + elif [ -f "$JOURNAL/$restore_name.absent" ]; then + [ ! -L "$restore_target" ] || return 1 + rm -f "$restore_target" || return 1 + else + return 1 + fi + return 0 +} +nft_panel_owned() { + journal_nft=$1 + journal_owner_count=$(printf '%s\n' "$journal_nft" | grep -Ec 'comment "virt-cloud-wg-fabric-v1:[0-9a-f]{64}"' || true) + journal_chain_count=$(printf '%s\n' "$journal_nft" | grep -Ec '^[[:space:]]*chain [A-Za-z0-9_.-]+ \{' || true) + journal_named_chain_count=$(printf '%s\n' "$journal_nft" | grep -Ec '^[[:space:]]*chain (input|output|forward) \{' || true) + journal_rule_count=$(printf '%s\n' "$journal_nft" | grep -Ec '^[[:space:]]+(iifname|oifname) "wg-fabric0".* (accept|drop)( |$)' || true) + journal_bad_actions=$(printf '%s\n' "$journal_nft" | grep -Eci '^[[:space:]]+(iifname|oifname).* (reject|masquerade|snat|dnat|redirect|jump|goto|queue|tproxy|dup|log|limit|notrack|meter)( |$)' || true) + [ "$journal_owner_count" = 8 ] && [ "$journal_chain_count" = 3 ] && + [ "$journal_named_chain_count" = 3 ] && [ "$journal_rule_count" = 8 ] && + [ "$journal_bad_actions" = 0 ] || return 1 + printf '%s\n' "$journal_nft" | grep -Fq 'iifname "wg-fabric0" ip protocol icmp accept' || return 1 + printf '%s\n' "$journal_nft" | grep -Fq 'oifname "wg-fabric0" ip protocol icmp accept' || return 1 + printf '%s\n' "$journal_nft" | grep -Eq 'iifname "wg-fabric0".*counter drop' || return 1 + printf '%s\n' "$journal_nft" | grep -Eq 'oifname "wg-fabric0".*counter drop' || return 1 + return 0 +} +recover_journal() { + [ -e "$JOURNAL" ] || return 0 + journal_secure || exit 79 + journal_state=$(cat "$JOURNAL/state" 2>/dev/null || true) + case "$journal_state" in + committed) + rm -rf "$JOURNAL" || exit 79 + return 0 + ;; + preparing) + # Snapshot creation completes before any host mutation. A + # preparing journal is therefore safe to discard after its owner + # and mode checks; ready means live mutation may have started. + rm -rf "$JOURNAL" || exit 79 + return 0 + ;; + ready) ;; + *) exit 79 ;; + esac + journal_file_secure meta || exit 79 + journal_schema=$(journal_value schema 2>/dev/null || true) + journal_mode=$(journal_value deployment_mode 2>/dev/null || true) + journal_plan_digest=$(journal_value plan_digest 2>/dev/null || true) + journal_connection_uuid=$(journal_value connection_uuid 2>/dev/null || true) + journal_nft_main=$(journal_value nft_main 2>/dev/null || true) + journal_iface_before=$(journal_value iface_before 2>/dev/null || true) + journal_iface_up_before=$(journal_value iface_up_before 2>/dev/null || true) + journal_nft_before=$(journal_value nft_before 2>/dev/null || true) + journal_service_enabled=$(journal_value service_enabled_before 2>/dev/null || true) + journal_service_active=$(journal_value service_active_before 2>/dev/null || true) + journal_timer_enabled=$(journal_value timer_enabled_before 2>/dev/null || true) + journal_timer_active=$(journal_value timer_active_before 2>/dev/null || true) + [ "$journal_schema" = 1 ] || exit 79 + # A recovery-only invocation may be running from the helper installed + # before the interrupted revision. In that case the journal is the + # authority for the old digest/manager mode; a normal invocation still + # fences recovery to the currently installed plan. + if [ "${RECOVER_ONLY:-no}" != yes ]; then + [ "$journal_plan_digest" = "$PLAN_DIGEST" ] || exit 79 + [ "$journal_connection_uuid" = "$CONNECTION_UUID" ] || exit 79 + [ "$journal_mode" = "$DEPLOYMENT_MODE" ] || exit 79 + else + # The helper installed before the interruption may not know the new + # plan digest/UUID, but the journal values still need strict, single + # record validation before they reach comparisons or path decisions. + printf '%s\n' "$journal_plan_digest" | awk ' + BEGIN {count=0; valid=0} + {count++; if (length($0)==64 && $0 ~ /^[0-9a-f]+$/) valid=1} + END {exit (count == 1 && valid) ? 0 : 1} + ' >/dev/null || exit 79 + printf '%s\n' "$journal_connection_uuid" | awk ' + BEGIN {count=0; valid=0} + { + count++ + valid = length($0) == 36 && $0 ~ /^[0-9A-Fa-f-]+$/ && + substr($0, 9, 1) == "-" && + substr($0, 14, 1) == "-" && + substr($0, 19, 1) == "-" && + substr($0, 24, 1) == "-" + } + END {exit (count == 1 && valid) ? 0 : 1} + ' >/dev/null || exit 79 + fi + case "$journal_mode" in + networkmanager_nmcli|ifupdown) : ;; + *) exit 79 ;; + esac + case "$journal_nft_main" in /etc/nftables.conf|/etc/sysconfig/nftables.conf) : ;; *) exit 79 ;; esac + case "$journal_iface_before:$journal_iface_up_before:$journal_nft_before" in + yes:yes:yes|yes:no:yes|no:no:no) : ;; + *) exit 79 ;; + esac + [ -n "$journal_service_enabled" ] && [ -n "$journal_timer_enabled" ] && [ -n "$journal_timer_active" ] || exit 79 + case "$journal_service_enabled" in *[!A-Za-z0-9_-]*) exit 79 ;; esac + case "$journal_timer_enabled" in *[!A-Za-z0-9_-]*) exit 79 ;; esac + case "$journal_timer_active" in active|inactive|activating|deactivating|unknown) : ;; *) exit 79 ;; esac + case "$journal_service_active" in active|inactive|activating|deactivating|unknown) : ;; *) exit 79 ;; esac + for journal_required in conf key owner helper unit repair timer nm_profile ifupdown_fragment nft_rules nft_main; do + if [ -f "$JOURNAL/$journal_required.present" ]; then + journal_file_secure "$journal_required" || exit 79 + elif [ -f "$JOURNAL/$journal_required.absent" ]; then + [ ! -L "$JOURNAL/$journal_required.absent" ] || exit 79 + [ "$(stat -c '%u:%a' "$JOURNAL/$journal_required.absent" 2>/dev/null)" = 0:600 ] || exit 79 + else + exit 79 + fi + done + if [ "$journal_nft_before" = yes ]; then + journal_file_secure nft.table || exit 79 + fi + journal_wg_ok=yes + if [ "$journal_iface_before" = yes ]; then + journal_file_secure wg.conf || journal_wg_ok=no + journal_file_secure address.save || journal_wg_ok=no + journal_file_secure route.save || journal_wg_ok=no + fi + [ "$journal_wg_ok" = yes ] || exit 79 + # Capture the live ownership evidence before restoring any snapshot. A + # same-name link or owner file may have been replaced by an operator while + # the transaction was interrupted; restoring the old marker first would + # erase that evidence and could make recovery overwrite a foreign link. + journal_current_owner_state=absent + journal_current_owner= + if [ -e "$OWNER" ] || [ -L "$OWNER" ]; then + [ -f "$OWNER" ] && [ ! -L "$OWNER" ] || exit 79 + journal_current_owner_state=present + journal_current_owner=$(cat "$OWNER" 2>/dev/null || true) + fi + journal_current_iface_state=absent + if "$IP" link show dev "$IFACE" >/dev/null 2>&1; then + journal_current_iface_state=present + # A same-name non-WireGuard interface is never panel-owned. Keep the + # journal for manual reconciliation instead of deleting or reusing it. + "$WG" show "$IFACE" >/dev/null 2>&1 || exit 79 + fi + if [ "$journal_current_owner_state" = present ]; then + [ "$journal_current_owner" = "virt-cloud-wg-fabric-v1" ] || exit 79 + fi + restore_journal_file "$CONF" conf || exit 79 + restore_journal_file "$KEY" key || exit 79 + restore_journal_file "$OWNER" owner || exit 79 + restore_journal_file "$HELPER" helper || exit 79 + restore_journal_file "/etc/systemd/system/virt-cloud-wg-fabric.service" unit || exit 79 + restore_journal_file "/etc/systemd/system/virt-cloud-wg-fabric-reconcile.service" repair || exit 79 + restore_journal_file "/etc/systemd/system/virt-cloud-wg-fabric-reconcile.timer" timer || exit 79 + restore_journal_file "$NM_PROFILE" nm_profile || exit 79 + restore_journal_file "$IFUPDOWN_FRAGMENT" ifupdown_fragment || exit 79 + restore_journal_file "$NFT_RULES" nft_rules || exit 79 + restore_journal_file "$journal_nft_main" nft_main || exit 79 + if [ "$journal_iface_before" = yes ]; then + if [ "$journal_current_iface_state" = absent ]; then + "$IP" link add dev "$IFACE" type wireguard >/dev/null 2>&1 || exit 79 + fi + "$WG" show "$IFACE" >/dev/null 2>&1 || exit 79 + "$WG" setconf "$IFACE" "$JOURNAL/wg.conf" >/dev/null 2>&1 || exit 79 + "$IP" address flush dev "$IFACE" >/dev/null 2>&1 || exit 79 + "$IP" address restore < "$JOURNAL/address.save" >/dev/null 2>&1 || exit 79 + "$IP" route flush table all dev "$IFACE" >/dev/null 2>&1 || exit 79 + "$IP" route restore < "$JOURNAL/route.save" >/dev/null 2>&1 || exit 79 + if [ "$journal_iface_up_before" = yes ]; then + "$IP" link set dev "$IFACE" up >/dev/null 2>&1 || exit 79 + else + "$IP" link set dev "$IFACE" down >/dev/null 2>&1 || exit 79 + fi + elif [ "$journal_current_iface_state" = present ]; then + # The pre-restore owner/type checks above prove that this link was + # panel-owned before it can be removed. + "$IP" link del dev "$IFACE" >/dev/null 2>&1 || exit 79 + fi + if [ "$journal_nft_before" = yes ]; then + journal_tables=$($NFT list tables 2>/dev/null) || exit 79 + if printf '%s\n' "$journal_tables" | grep -Eq 'table inet virt_cloud_wg_fabric([[:space:]]|$)'; then + journal_current_nft=$($NFT list table inet virt_cloud_wg_fabric 2>/dev/null) || exit 79 + else + journal_current_nft= + fi + [ -z "$journal_current_nft" ] || nft_panel_owned "$journal_current_nft" || exit 79 + [ -z "$journal_current_nft" ] || "$NFT" delete table inet virt_cloud_wg_fabric >/dev/null 2>&1 || exit 79 + "$NFT" -f "$JOURNAL/nft.table" >/dev/null 2>&1 || exit 79 + else + journal_tables=$($NFT list tables 2>/dev/null) || exit 79 + if printf '%s\n' "$journal_tables" | grep -Eq 'table inet virt_cloud_wg_fabric([[:space:]]|$)'; then + journal_current_nft=$($NFT list table inet virt_cloud_wg_fabric 2>/dev/null) || exit 79 + nft_panel_owned "$journal_current_nft" || exit 79 + "$NFT" delete table inet virt_cloud_wg_fabric >/dev/null 2>&1 || exit 79 + fi + fi + "$SYSTEMCTL" daemon-reload >/dev/null 2>&1 || exit 79 + case "$journal_service_enabled" in + enabled|enabled-runtime) "$SYSTEMCTL" enable virt-cloud-wg-fabric.service >/dev/null 2>&1 || exit 79 ;; + *) "$SYSTEMCTL" disable virt-cloud-wg-fabric.service >/dev/null 2>&1 || true ;; + esac + case "$journal_timer_enabled" in + enabled|enabled-runtime) "$SYSTEMCTL" enable virt-cloud-wg-fabric-reconcile.timer >/dev/null 2>&1 || exit 79 ;; + *) "$SYSTEMCTL" disable virt-cloud-wg-fabric-reconcile.timer >/dev/null 2>&1 || true ;; + esac + if [ "$journal_mode" = networkmanager_nmcli ]; then + journal_nmcli=$(find_tool /usr/bin/nmcli /usr/sbin/nmcli /bin/nmcli /sbin/nmcli || true) + [ -n "$journal_nmcli" ] || exit 79 + if [ -f "$NM_PROFILE" ]; then + journal_old_uuid=$(awk -F= '$1 == "uuid" {print $2; found=1} END {exit found ? 0 : 1}' "$NM_PROFILE" 2>/dev/null || true) + case "$journal_old_uuid" in + ????????-????-????-????-????????????) : ;; + *) exit 79 ;; + esac + "$journal_nmcli" connection load "$NM_PROFILE" >/dev/null 2>&1 || exit 79 + if [ "$journal_iface_before" = yes ]; then + if [ "$journal_iface_up_before" = yes ]; then + "$journal_nmcli" connection up uuid "$journal_old_uuid" >/dev/null 2>&1 || exit 79 + else + # Preserve a previously administratively-down link. A + # recovery must not turn it on as a side effect. + "$journal_nmcli" connection down uuid "$journal_old_uuid" >/dev/null 2>&1 || true + "$IP" link set dev "$IFACE" down >/dev/null 2>&1 || exit 79 + fi + fi + else + if [ "$journal_iface_before" = yes ]; then + # Do not guess which in-memory connection is foreign when the + # previous panel profile did not exist. The restored disk + # state cannot safely reactivate an unmanaged link. + exit 79 + fi + # A first deployment had no panel connection and no interface. + # There is nothing to reactivate; leave the restored absent state + # in place and let the caller retry the apply transaction. + fi + elif [ -f "$IFUPDOWN_FRAGMENT" ] && [ "$journal_iface_before" = yes ] && [ "$journal_iface_up_before" = yes ]; then + [ -x "$IFUP_PATH" ] || exit 79 + export VC_FABRIC_LOCK_HELD=1 + export VC_FABRIC_ALLOW_TRANSITION=1 + "$IFUP_PATH" --force "$IFACE" >/dev/null 2>&1 || exit 79 + fi + rm -rf "$JOURNAL" || exit 79 + exec "$HELPER" "$@" +} +if [ "${VC_FABRIC_APPLYING:-0}" != 1 ]; then + recover_journal "$@" +fi +if [ "${1:-}" = --recover-only ]; then + exit 0 +fi if [ "$DEPLOYMENT_MODE" = networkmanager_nmcli ]; then [ ! -L /etc/NetworkManager ] && [ ! -L /etc/NetworkManager/system-connections ] || exit 71 @@ -353,9 +1162,9 @@ if [ "${1:-}" = --ifdown ]; then validate_ifupdown_fragment || exit 71 fi if [ -f "$OWNER" ] && [ "$(cat "$OWNER")" = "virt-cloud-wg-fabric-v1" ] && - "$IP" link show dev "$IFACE" >/dev/null 2>&1 && - "$WG" show "$IFACE" >/dev/null 2>&1; then - "$IP" link del dev "$IFACE" + "$IP" link show dev "$IFACE" >/dev/null 2>&1; then + "$IP" -d link show dev "$IFACE" 2>/dev/null | grep -Eq '(^|[[:space:]])wireguard([[:space:]]|$)' || exit 71 + "$IP" link del dev "$IFACE" || exit 72 fi exit 0 fi @@ -365,8 +1174,17 @@ IFUP= if [ "$DEPLOYMENT_MODE" = networkmanager_nmcli ]; then NMCLI=$(find_tool /usr/bin/nmcli /usr/sbin/nmcli /bin/nmcli /sbin/nmcli) || exit 70 else - IFQUERY=$(find_tool /usr/sbin/ifquery /usr/bin/ifquery /sbin/ifquery /bin/ifquery) || exit 70 - IFUP=$(find_tool /usr/sbin/ifup /usr/bin/ifup /sbin/ifup /bin/ifup) || exit 70 + [ -x "$IFQUERY_PATH" ] || exit 70 + [ -x "$IFUP_PATH" ] || exit 70 + [ -x "$IFDOWN_PATH" ] || exit 70 + IFQUERY="$IFQUERY_PATH" + IFUP="$IFUP_PATH" +fi +if [ "$DEPLOYMENT_MODE" = ifupdown ] && + [ "${1:-}" = --ifupdown-service ]; then + export VC_FABRIC_LOCK_HELD=1 + "$IFUP" --force "$IFACE" + exit 0 fi if [ "$DEPLOYMENT_MODE" = ifupdown ] && [ "${1:-}" = --ifupdown-hook ]; then @@ -391,8 +1209,7 @@ if [ "$DEPLOYMENT_MODE" = ifupdown ] && # During an API revision change the old config is intentionally still in # place while ifup runs. Only the pre-up link creation is needed until # the transactional apply below installs the new config. - if [ ! -f "$CONF" ] || ! awk -F'|' -v expected="$EXPECTED_DIGEST" \ - '$1 == "digest" && $2 == expected {ok=1} END {exit ok ? 0 : 1}' "$CONF"; then + if [ ! -f "$CONF" ]; then "$IP" link set dev "$IFACE" up || exit 72 exit 0 fi @@ -545,9 +1362,13 @@ while IFS='|' read -r kind a b c d; do esac done < "$CONF" [ "$schema_seen" = 1 ] && [ "$fabric_seen" = 1 ] && [ "$revision_seen" = 1 ] && [ "$digest_seen" = 1 ] && [ "$listen_seen" = 1 ] && [ "$network_seen" = 1 ] && [ "$overlay_seen" = 1 ] || exit 72 -[ "$digest_value" = "$EXPECTED_DIGEST" ] || exit 72 +is_hex64 "$digest_value" || exit 72 +ACTIVE_DIGEST="$digest_value" +[ "$ACTIVE_DIGEST" = "$PLAN_DIGEST" ] || exit 72 [ -n "$overlay" ] && [ "$peer_count" -gt 0 ] && [ "$peer_count" = "$route_count" ] || exit 72 [ "$peer_count" -le 64 ] || exit 72 +__VC_VPC_STATE_LOADER__ +vpc_state_load || exit 71 if ! address_output=$($IP -o -4 addr show 2>/dev/null); then exit 73; fi address_conflict=$(printf '%s\n' "$address_output" | awk -v wanted="$overlay" -v iface="$IFACE" '{split($4,a,"/"); if (a[1]==wanted && $2!=iface) {print $2; exit}}') [ -z "$address_conflict" ] || exit 73 @@ -564,10 +1385,13 @@ while IFS='|' read -r kind a b c d; do done < "$CONF" if "$IP" link show dev "$IFACE" >/dev/null 2>&1; then if ! fabric_routes=$($IP -o route show table all dev "$IFACE" 2>/dev/null); then exit 75; fi - route_conflict=$(printf '%s\n' "$fabric_routes" | awk -v iface="$IFACE" -v own="$overlay" -v allowed="$allowed_routes" ' + route_conflict=$(printf '%s\n' "$fabric_routes" | awk -v iface="$IFACE" -v own="$overlay" -v allowed="$allowed_routes" -v vpc_file="$VPC_ROUTE_FILE" ' + BEGIN {while ((getline line < vpc_file) > 0) {n=split(line, parts, "|"); if (n>=5) vpc[parts[1] "|" parts[2] "|" parts[3] "|" parts[4] "|" parts[5]]=1} close(vpc_file)} NF {prefix=$1; if ($1=="local" || $1=="broadcast" || $1=="unreachable" || $1=="blackhole" || $1=="prohibit" || $1=="throw") prefix=$2 - table="main"; device=""; for (i=1;i<=NF;i++) {if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1)} + table="main"; device=""; via="-"; metric="100"; proto=""; for (i=1;i<=NF;i++) {if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1); if ($i=="via") via=$(i+1); if ($i=="metric") metric=$(i+1); if ($i=="proto") proto=$(i+1)} + if (table=="254") table="main"; if (table=="255") table="local" if (prefix==own && (table=="local" || table=="main") && device==iface) next + if (table!="main" && proto=="186" && vpc[prefix "|" device "|" table "|" via "|" metric]) next ok=0; n=split(allowed, values, " "); for (i=1;i<=n;i++) if (values[i]==prefix) ok=1 if (table!="main" || device!=iface || !ok || ++seen[prefix]>1) {print "foreign"; exit}}') [ -z "$route_conflict" ] || exit 75 @@ -578,34 +1402,60 @@ fi [ -f "$OWNER" ] && [ "$($STAT -c '%u' "$OWNER" 2>/dev/null)" = 0 ] || exit 71 [ "$($STAT -c '%a' "$OWNER" 2>/dev/null)" = 600 ] || exit 71 if [ -f "$OWNER" ] && [ "$(cat "$OWNER")" != "virt-cloud-wg-fabric-v1" ]; then exit 71; fi +NFT_RULES=/etc/nftables.d/virt-cloud-wg-fabric.nft +[ -d /etc/nftables.d ] && [ ! -L /etc/nftables.d ] || exit 71 +[ "$($STAT -c '%u:%a' /etc/nftables.d 2>/dev/null)" = 0:755 ] || exit 71 +[ -f "$NFT_RULES" ] && [ ! -L "$NFT_RULES" ] || exit 71 +[ "$($STAT -c '%u:%a' "$NFT_RULES" 2>/dev/null)" = 0:600 ] || exit 71 +nft_first=; nft_second= +{ IFS= read -r nft_first || true; IFS= read -r nft_second || true; } < "$NFT_RULES" +[ "$nft_first" = '# virt-cloud-wg-fabric-v1' ] || exit 71 +[ "$nft_second" = "# fabric-plan-digest=$EXPECTED_DIGEST" ] || exit 71 +nft_persisted=no +nft_main_count=0 +for nft_main in /etc/nftables.conf /etc/sysconfig/nftables.conf; do + [ -f "$nft_main" ] && [ ! -L "$nft_main" ] || continue + [ "$($STAT -c '%u' "$nft_main" 2>/dev/null)" = 0 ] || exit 71 + nft_main_mode=$($STAT -c '%a' "$nft_main" 2>/dev/null || true) + case "$nft_main_mode" in [0-7][0145][0145]) : ;; *) exit 71 ;; esac + nft_main_count=$((nft_main_count + 1)) + if grep -Fqx 'include "/etc/nftables.d/virt-cloud-wg-fabric.nft"' "$nft_main" || + grep -Fqx 'include "/etc/nftables.d/*.nft"' "$nft_main" || + grep -Fqx 'include "/etc/nftables.d/*"' "$nft_main"; then + nft_persisted=yes + fi +done +[ "$nft_main_count" = 1 ] && [ "$nft_persisted" = yes ] || exit 71 +validate_nft_table() { + nft_owner_count=$(printf '%s\n' "$1" | grep -Fxc " iifname \"wg-fabric0\" ip protocol icmp accept comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true) + nft_owner_count=$((nft_owner_count + $(printf '%s\n' "$1" | grep -Fxc " oifname \"wg-fabric0\" ip protocol icmp accept comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true))) + nft_owner_count=$((nft_owner_count + $(printf '%s\n' "$1" | grep -Fxc " iifname \"wg-fabric0\" ip saddr != @vpc_tenant_ips counter drop comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true))) + nft_owner_count=$((nft_owner_count + $(printf '%s\n' "$1" | grep -Fxc " oifname \"wg-fabric0\" ip daddr != @vpc_tenant_ips counter drop comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true))) + nft_owner_count=$((nft_owner_count + $(printf '%s\n' "$1" | grep -Fxc " iifname \"wg-fabric0\" counter drop comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true))) + nft_owner_count=$((nft_owner_count + $(printf '%s\n' "$1" | grep -Fxc " oifname \"wg-fabric0\" counter drop comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true))) + nft_owner_count=$((nft_owner_count + $(printf '%s\n' "$1" | grep -Fxc " iifname \"wg-fabric0\" ip saddr @vpc_tenant_ips ip daddr != @vpc_tenant_ips counter drop comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true))) + nft_owner_count=$((nft_owner_count + $(printf '%s\n' "$1" | grep -Fxc " oifname \"wg-fabric0\" ip daddr @vpc_tenant_ips ip saddr != @vpc_tenant_ips counter drop comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true))) + nft_chain_count=$(printf '%s\n' "$1" | grep -Ec '^[[:space:]]*chain [A-Za-z0-9_.-]+ \{' || true) + nft_named_chain_count=$(printf '%s\n' "$1" | grep -Ec '^[[:space:]]*chain (input|output|forward) \{' || true) + nft_rule_count=$(printf '%s\n' "$1" | grep -Ec '^[[:space:]]+(iifname|oifname) "wg-fabric0".* (accept|drop)( |$)' || true) + nft_bad_actions=$(printf '%s\n' "$1" | grep -Eci '^[[:space:]]+(iifname|oifname).* (reject|masquerade|snat|dnat|redirect|jump|goto|queue|tproxy|dup|log|limit|notrack|meter)( |$)' || true) + [ "$nft_owner_count" = 8 ] && [ "$nft_chain_count" = 3 ] && + [ "$nft_named_chain_count" = 3 ] && [ "$nft_rule_count" = 8 ] && + [ "$nft_bad_actions" = 0 ] || return 1 + printf '%s\n' "$1" | grep -Fq 'iifname "wg-fabric0" ip protocol icmp accept' || return 1 + printf '%s\n' "$1" | grep -Fq 'oifname "wg-fabric0" ip protocol icmp accept' || return 1 + printf '%s\n' "$1" | grep -Fq 'set vpc_tenant_ips' || return 1 + printf '%s\n' "$1" | grep -Eq 'iifname "wg-fabric0".*counter drop' || return 1 + printf '%s\n' "$1" | grep -Eq 'oifname "wg-fabric0".*counter drop' || return 1 +} if nft_table=$("$NFT" list table inet virt_cloud_wg_fabric 2>/dev/null); then - case "$nft_table" in *virt-cloud-wg-fabric-v1*) : ;; *) exit 71 ;; esac - case "$nft_table" in *'iifname "wg-fabric0"'*'ip protocol icmp'*accept*'iifname "wg-fabric0"'*drop*) : ;; *) exit 71 ;; esac - case "$nft_table" in *'oifname "wg-fabric0"'*'ip protocol icmp'*accept*'oifname "wg-fabric0"'*drop*) : ;; *) exit 71 ;; esac - case "$nft_table" in *'iifname "wg-fabric0"'*drop*) : ;; *) exit 71 ;; esac - case "$nft_table" in *'oifname "wg-fabric0"'*drop*) : ;; *) exit 71 ;; esac - case "$nft_table" in *'hook forward'*priority*100*'policy accept'*) : ;; *) exit 71 ;; esac + validate_nft_table "$nft_table" || exit 71 else - "$NFT" -f - <<'__VC_FABRIC_NFT__' -table inet virt_cloud_wg_fabric { - chain input { - type filter hook input priority -100; policy accept; - iifname "wg-fabric0" ip protocol icmp accept comment "virt-cloud-wg-fabric-v1" - iifname "wg-fabric0" counter drop comment "virt-cloud-wg-fabric-v1" - } - chain output { - type filter hook output priority -100; policy accept; - oifname "wg-fabric0" ip protocol icmp accept comment "virt-cloud-wg-fabric-v1" - oifname "wg-fabric0" counter drop comment "virt-cloud-wg-fabric-v1" - } - chain forward { - type filter hook forward priority -100; policy accept; - iifname "wg-fabric0" counter drop comment "virt-cloud-wg-fabric-v1" - oifname "wg-fabric0" counter drop comment "virt-cloud-wg-fabric-v1" - } -} -__VC_FABRIC_NFT__ + "$NFT" -f "$NFT_RULES" || exit 72 + nft_table=$("$NFT" list table inet virt_cloud_wg_fabric 2>/dev/null) || exit 72 + validate_nft_table "$nft_table" || exit 71 fi +vpc_state_refresh_nft || exit 71 manager_owner=missing if [ "$DEPLOYMENT_MODE" = networkmanager_nmcli ]; then [ -f "$NM_PROFILE" ] && [ ! -L "$NM_PROFILE" ] || exit 72 @@ -642,18 +1492,203 @@ else # would allow two managers to race over the same device. exit 72 fi +recover_vpc_dataplanes() { + [ -d "$VPC_STATE_DIR" ] || return 0 + for vpc_state_file in "$VPC_STATE_DIR"/*.state; do + [ -e "$vpc_state_file" ] || [ -L "$vpc_state_file" ] || continue + [ -f "$vpc_state_file" ] && [ ! -L "$vpc_state_file" ] || exit 71 + vpc_token=\${vpc_state_file##*/} + vpc_token=\${vpc_token%.state} + vpc_state_safe_token "$vpc_token" || exit 71 + vpc_id=$(awk -F'|' '$1=="vpc" {print $2; exit}' "$vpc_state_file") + vpc_bridge=$(awk -F'|' '$1=="bridge" {print $2; exit}' "$vpc_state_file") + vpc_cidr=$(awk -F'|' '$1=="cidr" {print $2; exit}' "$vpc_state_file") + vpc_table=$(awk -F'|' '$1=="table" {print $2; exit}' "$vpc_state_file") + vpc_priority=$(awk -F'|' '$1=="priority" {print $2; exit}' "$vpc_state_file") + vpc_hash=$(printf '%s' "$vpc_id" | "$SHA256" | awk '{print $1}') + [ "$(printf '%s' "$vpc_hash" | awk '{print substr($0,1,11)}')" = "$vpc_token" ] || exit 71 + [ "$vpc_bridge" = "vcv-$vpc_token" ] || exit 71 + vpc_expected_table_hex=$(printf '%s' "$vpc_hash" | awk '{print substr($0,13,8)}') + vpc_expected_table_offset=$(printf '%d' "0x$vpc_expected_table_hex" 2>/dev/null) || exit 71 + vpc_expected_table=$((10000 + vpc_expected_table_offset % 10000)) + [ "$vpc_table" = "$vpc_expected_table" ] || exit 71 + vpc_expected_priority_hex=$(printf '%s' "$vpc_hash" | awk '{print substr($0,21,8)}') + vpc_expected_priority_offset=$(printf '%d' "0x$vpc_expected_priority_hex" 2>/dev/null) || exit 71 + vpc_expected_priority=$((20000 + 2 * (vpc_expected_priority_offset % 5000))) + [ "$vpc_priority" = "$vpc_expected_priority" ] || exit 71 + vpc_state_safe_token "$vpc_bridge" || exit 71 + vpc_state_cidr "$vpc_cidr" || exit 71 + case "$vpc_table:$vpc_priority" in + *[!0-9:]*|:*) exit 71 ;; + esac + [ "$vpc_table" -ge 10000 ] && [ "$vpc_table" -le 19999 ] || exit 71 + [ "$vpc_priority" -ge 20000 ] && [ "$vpc_priority" -le 29998 ] || exit 71 + vpc_owner_file="$VPC_STATE_DIR/$vpc_token.owner" + [ -f "$vpc_owner_file" ] && [ ! -L "$vpc_owner_file" ] || exit 71 + [ "$($STAT -c '%u:%a' "$vpc_owner_file" 2>/dev/null)" = 0:600 ] || exit 71 + grep -Fqx 'virt-cloud-vpc-dataplane-v1' "$vpc_owner_file" || exit 71 + vpc_nft_file="/etc/nftables.d/virt-cloud-vpc-$vpc_token.nft" + [ -f "$vpc_nft_file" ] && [ ! -L "$vpc_nft_file" ] || exit 71 + [ "$($STAT -c '%u:%a' "$vpc_nft_file" 2>/dev/null)" = 0:600 ] || exit 71 + grep -Fqx '# virt-cloud-vpc-dataplane-v1' "$vpc_nft_file" || exit 71 + vpc_sysctl_file="/etc/sysctl.d/99-virt-cloud-vpc-$vpc_token.conf" + [ -f "$vpc_sysctl_file" ] && [ ! -L "$vpc_sysctl_file" ] || exit 71 + [ "$($STAT -c '%u:%a' "$vpc_sysctl_file" 2>/dev/null)" = 0:600 ] || exit 71 + grep -Fqx "net.ipv4.conf.$vpc_bridge.rp_filter = 2" "$vpc_sysctl_file" || exit 71 + grep -Fqx "net.ipv4.conf.$vpc_bridge.proxy_arp = 0" "$vpc_sysctl_file" || exit 71 + grep -Fqx "net.ipv4.conf.$vpc_bridge.proxy_arp_pvlan = 1" "$vpc_sysctl_file" || exit 71 + if [ "$DEPLOYMENT_MODE" = networkmanager_nmcli ]; then + nm_vpc_field() { "$NMCLI" -t --escape no -g "$1" connection show "$2" 2>/dev/null | sed -n '1p'; } + [ "$(nm_vpc_field connection.type "$vpc_bridge")" = bridge ] || exit 71 + [ "$(nm_vpc_field connection.interface-name "$vpc_bridge")" = "$vpc_bridge" ] || exit 71 + [ "$(nm_vpc_field ipv4.method "$vpc_bridge")" = disabled ] || exit 71 + [ "$(nm_vpc_field ipv6.method "$vpc_bridge")" = disabled ] || exit 71 + for nm_vpc_empty in ipv4.addresses ipv4.routes ipv4.routing-rules ipv4.gateway ipv4.dns ipv6.addresses ipv6.routes ipv6.routing-rules ipv6.gateway ipv6.dns connection.master connection.controller connection.port-type; do + nm_vpc_value=$(nm_vpc_field "$nm_vpc_empty" "$vpc_bridge") + [ -z "$nm_vpc_value" ] || [ "$nm_vpc_value" = "--" ] || exit 71 + done + [ "$(nm_vpc_field connection.stable-id "$vpc_bridge")" = "virt-cloud-vpc-dataplane-v1 vpc=$vpc_id" ] || exit 71 + "$NMCLI" connection up "$vpc_bridge" >/dev/null 2>&1 || exit 72 + else + vpc_if_fragment="/etc/network/interfaces.d/virt-cloud-vpc-$vpc_token" + [ -f "$vpc_if_fragment" ] && [ ! -L "$vpc_if_fragment" ] || exit 71 + [ "$($STAT -c '%u:%a' "$vpc_if_fragment" 2>/dev/null)" = 0:600 ] || exit 71 + vpc_revision=$(awk -F'|' '$1=="revision" {print $2; exit}' "$vpc_state_file") + vpc_digest=$(awk -F'|' '$1=="digest" {print $2; exit}' "$vpc_state_file") + grep -Fqx "# virt-cloud-vpc-dataplane-v1 vpc=$vpc_id revision=$vpc_revision digest=$vpc_digest" "$vpc_if_fragment" || exit 71 + "$IFQUERY" "$vpc_bridge" >/dev/null 2>&1 || exit 72 + VC_FABRIC_APPLYING=1 "$IFUP" --force "$vpc_bridge" >/dev/null 2>&1 || exit 72 + fi + "$IP" -d link show dev "$vpc_bridge" 2>/dev/null | grep -Eq '(^|[[:space:]])bridge[[:space:]]+(forward_delay|stp_state|hello_time|ageing_time)([[:space:]]|$)' || exit 71 + vpc_bridge_addrs=$("$IP" -o addr show dev "$vpc_bridge" 2>/dev/null || true) + printf '%s\n' "$vpc_bridge_addrs" | grep -Eq '[[:space:]]inet6?[[:space:]]' && exit 71 || true + vpc_bridge_ports=$("$BRIDGE_CMD" link show master "$vpc_bridge" 2>/dev/null) || exit 71 + while IFS= read -r vpc_port_line; do + [ -n "$vpc_port_line" ] || continue + vpc_port=$(printf '%s\n' "$vpc_port_line" | sed -n 's/^[0-9][0-9]*: \([^:[:space:]]*\).*/\1/p') + case "$vpc_port" in + vnet[0-9]*|tap[0-9A-Za-z_.-]*|macvtap[0-9]*|fwpr[0-9A-Za-z_.-]*|fwln[0-9A-Za-z_.-]*) : ;; + *) exit 71 ;; + esac + done </dev/null) || exit 71 + printf '%s\n' "$vpc_bridge_routes" | awk -v wanted_table="$vpc_table" ' + NF {table="main"; proto=""; prefix=$1 + for (i=1;i<=NF;i++) {if ($i=="table") table=$(i+1); if ($i=="proto") proto=$(i+1)} + if (table=="254") table="main" + if (prefix=="default" || table!=wanted_table || proto!="186") bad=1} + END {exit bad ? 1 : 0}' || exit 71 + for vpc_sysctl_key in rp_filter proxy_arp proxy_arp_pvlan; do + [ -e "/proc/sys/net/ipv4/conf/$vpc_bridge/$vpc_sysctl_key" ] || exit 71 + done + printf '%s\n' 2 > "/proc/sys/net/ipv4/conf/$vpc_bridge/rp_filter" || exit 71 + printf '%s\n' 0 > "/proc/sys/net/ipv4/conf/$vpc_bridge/proxy_arp" || exit 71 + printf '%s\n' 1 > "/proc/sys/net/ipv4/conf/$vpc_bridge/proxy_arp_pvlan" || exit 71 + [ "$(cat "/proc/sys/net/ipv4/conf/$vpc_bridge/rp_filter")" = 2 ] || exit 71 + [ "$(cat "/proc/sys/net/ipv4/conf/$vpc_bridge/proxy_arp")" = 0 ] || exit 71 + [ "$(cat "/proc/sys/net/ipv4/conf/$vpc_bridge/proxy_arp_pvlan")" = 1 ] || exit 71 + vpc_proxy_file="$VPC_STATE_DIR/$vpc_token.proxy" + [ -f "$vpc_proxy_file" ] && [ ! -L "$vpc_proxy_file" ] || exit 71 + [ "$($STAT -c '%u:%a' "$vpc_proxy_file" 2>/dev/null)" = 0:600 ] || exit 71 + sed -n '1p' "$vpc_proxy_file" | grep -Fqx '# virt-cloud-vpc-proxy-v1' || exit 71 + while IFS= read -r vpc_proxy_ip; do + [ -n "$vpc_proxy_ip" ] || continue + vpc_state_ipv4 "$vpc_proxy_ip" || exit 71 + "$IP" neigh replace proxy "$vpc_proxy_ip" dev "$vpc_bridge" || exit 72 + done </dev/null && [ "$vpc_metric" -le 65535 ] 2>/dev/null || exit 71 + if [ "$vpc_via" = - ]; then + "$IP" route replace "$vpc_destination" table "$vpc_route_table" dev "$vpc_device" proto 186 metric "$vpc_metric" || exit 72 + else + vpc_state_ipv4 "$vpc_via" || exit 71 + "$IP" route replace "$vpc_destination" table "$vpc_route_table" via "$vpc_via" dev "$vpc_device" onlink proto 186 metric "$vpc_metric" || exit 72 + fi + done < "$vpc_state_file" + for vpc_rule_pref in "$vpc_priority" "$((vpc_priority + 1))"; do + vpc_rule_existing=$("$IP" -o rule show pref "$vpc_rule_pref" 2>/dev/null || true) + if [ -n "$vpc_rule_existing" ]; then + printf '%s\n' "$vpc_rule_existing" | grep -Fq "to $vpc_cidr lookup $vpc_table" || exit 71 + if [ "$vpc_rule_pref" = "$vpc_priority" ]; then + printf '%s\n' "$vpc_rule_existing" | grep -Fq "iif" && exit 71 || true + else + printf '%s\n' "$vpc_rule_existing" | grep -Fq "iif $IFACE" || exit 71 + fi + fi + done + "$IP" rule replace pref "$vpc_priority" to "$vpc_cidr" lookup "$vpc_table" || exit 72 + "$IP" rule replace pref "$((vpc_priority + 1))" iif "$IFACE" to "$vpc_cidr" lookup "$vpc_table" || exit 72 + vpc_nft_tables=$(awk '$1=="table" {print $2 "|" $3}' "$vpc_nft_file") + vpc_nft_missing=no + while IFS='|' read -r vpc_family vpc_name; do + [ -n "$vpc_family" ] || continue + case "$vpc_family:$vpc_name" in + inet:*|bridge:*|arp:*) : ;; + *) exit 71 ;; + esac + if ! "$NFT" list table "$vpc_family" "$vpc_name" >/dev/null 2>&1; then + vpc_nft_missing=yes + else + "$NFT" list table "$vpc_family" "$vpc_name" 2>/dev/null | grep -Fq 'virt-cloud-vpc-dataplane-v1' || exit 71 + fi + done </dev/null 2>&1 || exit 72 + "$NFT" -f "$vpc_nft_file" >/dev/null 2>&1 || exit 72 + fi + done +} "$WG" set "$IFACE" private-key "$KEY" "$IP" address replace "$overlay/32" dev "$IFACE" "$IP" link set dev "$IFACE" up "$WG" set "$IFACE" listen-port "$listen" while IFS='|' read -r kind a b c d; do [ "$kind" = peer ] || continue - "$WG" set "$IFACE" peer "$b" endpoint "$c" allowed-ips "$d" persistent-keepalive 25 + vpc_extra=$(vpc_state_allowed_for_peer "$b") || exit 71 + vpc_allowed="$d" + [ -z "$vpc_extra" ] || vpc_allowed="$vpc_allowed,$vpc_extra" + "$WG" set "$IFACE" peer "$b" endpoint "$c" allowed-ips "$vpc_allowed" persistent-keepalive 25 done < "$CONF" while IFS='|' read -r kind a b c d; do [ "$kind" = route ] || continue "$IP" route replace "$a" table main dev "$IFACE" done < "$CONF" +recover_vpc_dataplanes +actual_peers=$("$WG" show "$IFACE" peers 2>/dev/null) || exit 78 +for actual_peer in $actual_peers; do + case " $seen_peers " in *" $actual_peer "*) : ;; *) exit 78 ;; esac +done +for expected_peer in $seen_peers; do + case " $actual_peers " in *" $expected_peer "*) : ;; *) exit 78 ;; esac +done +actual_fabric_routes=$("$IP" -o route show table all dev "$IFACE" 2>/dev/null) || exit 78 + route_extra=$(printf '%s\n' "$actual_fabric_routes" | awk -v allowed="$allowed_routes" -v vpc_file="$VPC_ROUTE_FILE" ' + BEGIN {while ((getline line < vpc_file) > 0) {n=split(line, parts, "|"); if (n>=5) vpc[parts[1] "|" parts[2] "|" parts[3] "|" parts[4] "|" parts[5]]=1} close(vpc_file)} + NF { + prefix=$1 + if ($1=="local" || $1=="broadcast" || $1=="unreachable" || $1=="blackhole" || $1=="prohibit" || $1=="throw") prefix=$2 + table="main"; device=""; via="-"; metric="100"; proto="" + for (i=1;i<=NF;i++) {if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1); if ($i=="via") via=$(i+1); if ($i=="metric") metric=$(i+1); if ($i=="proto") proto=$(i+1)} + if (table=="254") table="main"; if (table=="255") table="local" + if (table!="main" && proto=="186" && vpc[prefix "|" device "|" table "|" via "|" metric]) next + ok=0; n=split(allowed, values, " "); for (i=1;i<=n;i++) if (values[i]==prefix) ok=1 + if (!ok || table!="main" || device!="wg-fabric0") {print "extra"; exit} + }') +[ -z "$route_extra" ] || exit 78 +for expected_route in $allowed_routes; do + route_seen=$(printf '%s\n' "$actual_fabric_routes" | awk -v wanted="$expected_route" ' + NF {prefix=$1; table="main"; device=""; for (i=1;i<=NF;i++) {if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1)} if (prefix==wanted && table=="main" && device=="wg-fabric0") {print 1; exit}}') + [ "$route_seen" = 1 ] || exit 78 +done for route in $allowed_routes; do target=${route%/32} path_result=$($IP route get "$target" from "$overlay" 2>/dev/null) || exit 78 @@ -709,37 +1744,316 @@ WantedBy=timers.target ''' _NFT_GUARD = r'''NFT=$(find_tool /usr/sbin/nft /usr/bin/nft /sbin/nft /bin/nft) || exit 70 +[ -d /etc/nftables.d ] && [ ! -L /etc/nftables.d ] || exit 71 +[ "$($STAT -c '%u:%a' /etc/nftables.d 2>/dev/null)" = 0:755 ] || exit 71 +[ -f "$NFT_RULES" ] && [ ! -L "$NFT_RULES" ] || exit 71 +[ "$($STAT -c '%u:%a' "$NFT_RULES" 2>/dev/null)" = 0:600 ] || exit 71 +nft_first=; nft_second= +{ IFS= read -r nft_first || true; IFS= read -r nft_second || true; } < "$NFT_RULES" +[ "$nft_first" = '# virt-cloud-wg-fabric-v1' ] || exit 71 +[ "$nft_second" = "# fabric-plan-digest=$EXPECTED_DIGEST" ] || exit 71 +nft_persisted=no +nft_main_count=0 +for nft_main in /etc/nftables.conf /etc/sysconfig/nftables.conf; do + [ -f "$nft_main" ] && [ ! -L "$nft_main" ] || continue + [ "$($STAT -c '%u' "$nft_main" 2>/dev/null)" = 0 ] || exit 71 + nft_main_mode=$($STAT -c '%a' "$nft_main" 2>/dev/null || true) + case "$nft_main_mode" in [0-7][0145][0145]) : ;; *) exit 71 ;; esac + nft_main_count=$((nft_main_count + 1)) + if grep -Fqx 'include "/etc/nftables.d/virt-cloud-wg-fabric.nft"' "$nft_main" || + grep -Fqx 'include "/etc/nftables.d/*.nft"' "$nft_main" || + grep -Fqx 'include "/etc/nftables.d/*"' "$nft_main"; then + nft_persisted=yes + fi +done +[ "$nft_main_count" = 1 ] && [ "$nft_persisted" = yes ] || exit 71 +validate_nft_table() { + nft_owner_count=$(printf '%s\n' "$1" | grep -Ec 'comment "virt-cloud-wg-fabric-v1:[0-9a-f]{64}"' || true) + nft_digest_count=$(printf '%s\n' "$1" | grep -Foc "comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true) + nft_chain_count=$(printf '%s\n' "$1" | grep -Ec '^[[:space:]]*chain [A-Za-z0-9_.-]+ \{' || true) + nft_named_chain_count=$(printf '%s\n' "$1" | grep -Ec '^[[:space:]]*chain (input|output|forward) \{' || true) + nft_rule_count=$(printf '%s\n' "$1" | grep -Ec '^[[:space:]]+(iifname|oifname) "wg-fabric0".* (accept|drop)( |$)' || true) + nft_bad_actions=$(printf '%s\n' "$1" | grep -Eci '^[[:space:]]+(iifname|oifname).* (reject|masquerade|snat|dnat|redirect|jump|goto|queue|tproxy|dup|log|limit|notrack|meter)( |$)' || true) + [ "$nft_owner_count" = 8 ] && [ "$nft_digest_count" = 8 ] && [ "$nft_chain_count" = 3 ] && + [ "$nft_named_chain_count" = 3 ] && [ "$nft_rule_count" = 8 ] && + [ "$nft_bad_actions" = 0 ] || return 1 + printf '%s\n' "$1" | grep -Fq 'iifname "wg-fabric0" ip protocol icmp accept' || return 1 + printf '%s\n' "$1" | grep -Fq 'oifname "wg-fabric0" ip protocol icmp accept' || return 1 + printf '%s\n' "$1" | grep -Fq 'set vpc_tenant_ips' || return 1 + printf '%s\n' "$1" | grep -Eq 'iifname "wg-fabric0".*counter drop' || return 1 + printf '%s\n' "$1" | grep -Eq 'oifname "wg-fabric0".*counter drop' || return 1 +} +validate_nft_shape() { + nft_shape_owner_count=$(printf '%s\n' "$1" | grep -Ec 'comment "virt-cloud-wg-fabric-v1:[0-9a-f]{64}"' || true) + nft_shape_chain_count=$(printf '%s\n' "$1" | grep -Ec '^[[:space:]]*chain [A-Za-z0-9_.-]+ \{' || true) + nft_shape_named_count=$(printf '%s\n' "$1" | grep -Ec '^[[:space:]]*chain (input|output|forward) \{' || true) + nft_shape_rule_count=$(printf '%s\n' "$1" | grep -Ec '^[[:space:]]+(iifname|oifname) "wg-fabric0".* (accept|drop)( |$)' || true) + nft_shape_bad=$(printf '%s\n' "$1" | grep -Eci '^[[:space:]]+(iifname|oifname).* (reject|masquerade|snat|dnat|redirect|jump|goto|queue|tproxy|dup|log|limit|notrack|meter)( |$)' || true) + [ "$nft_shape_owner_count" = 8 ] && [ "$nft_shape_chain_count" = 3 ] && + [ "$nft_shape_named_count" = 3 ] && [ "$nft_shape_rule_count" = 8 ] && + [ "$nft_shape_bad" = 0 ] || return 1 + printf '%s\n' "$1" | grep -Fq 'set vpc_tenant_ips' || return 1 +} if nft_table=$($NFT list table inet virt_cloud_wg_fabric 2>/dev/null); then - case "$nft_table" in - *virt-cloud-wg-fabric-v1*) : ;; - *) exit 71 ;; - esac - case "$nft_table" in *'iifname "wg-fabric0"'*'ip protocol icmp'*accept*'iifname "wg-fabric0"'*drop*) : ;; *) exit 71 ;; esac - case "$nft_table" in *'oifname "wg-fabric0"'*'ip protocol icmp'*accept*'oifname "wg-fabric0"'*drop*) : ;; *) exit 71 ;; esac - case "$nft_table" in *'iifname "wg-fabric0"'*drop*) : ;; *) exit 71 ;; esac - case "$nft_table" in *'oifname "wg-fabric0"'*drop*) : ;; *) exit 71 ;; esac - case "$nft_table" in *'hook forward'*priority*100*'policy accept'*) : ;; *) exit 71 ;; esac + if ! validate_nft_table "$nft_table"; then + validate_nft_shape "$nft_table" || exit 71 + "$NFT" delete table inet virt_cloud_wg_fabric || exit 72 + "$NFT" -f "$NFT_RULES" || exit 72 + fi else - $NFT -f - <<'__VC_FABRIC_NFT__' -table inet virt_cloud_wg_fabric { - chain input { - type filter hook input priority -100; policy accept; - iifname "wg-fabric0" ip protocol icmp accept comment "virt-cloud-wg-fabric-v1" - iifname "wg-fabric0" counter drop comment "virt-cloud-wg-fabric-v1" - } - chain output { - type filter hook output priority -100; policy accept; - oifname "wg-fabric0" ip protocol icmp accept comment "virt-cloud-wg-fabric-v1" - oifname "wg-fabric0" counter drop comment "virt-cloud-wg-fabric-v1" - } - chain forward { - type filter hook forward priority -100; policy accept; - iifname "wg-fabric0" counter drop comment "virt-cloud-wg-fabric-v1" - oifname "wg-fabric0" counter drop comment "virt-cloud-wg-fabric-v1" - } + $NFT -f "$NFT_RULES" || exit 72 +fi +nft_table=$($NFT list table inet virt_cloud_wg_fabric 2>/dev/null) || exit 72 +validate_nft_table "$nft_table" || exit 71 +''' + + +_TRANSACTION_SCRIPT = r'''COMMITTED=no +ROLLBACK_FAILED=no +JOURNAL_READY=no +TXN= +NFT_BEFORE=no +nft_panel_owned() { + nft_text=$1 + nft_owner_count=$(printf '%s\\n' "$nft_text" | grep -Ec 'comment "virt-cloud-wg-fabric-v1:[0-9a-f]{64}"' || true) + nft_chain_count=$(printf '%s\\n' "$nft_text" | grep -Ec '^[[:space:]]*chain [A-Za-z0-9_.-]+ \\{' || true) + nft_named_chain_count=$(printf '%s\\n' "$nft_text" | grep -Ec '^[[:space:]]*chain (input|output|forward) \\{' || true) + nft_rule_count=$(printf '%s\\n' "$nft_text" | grep -Ec '^[[:space:]]+(iifname|oifname) "wg-fabric0".* (accept|drop)( |$)' || true) + nft_bad_actions=$(printf '%s\\n' "$nft_text" | grep -Eci '^[[:space:]]+(iifname|oifname).* (reject|masquerade|snat|dnat|redirect|jump|goto|queue|tproxy|dup)( |$)' || true) + [ "$nft_owner_count" = 8 ] && [ "$nft_chain_count" = 3 ] && + [ "$nft_named_chain_count" = 3 ] && [ "$nft_rule_count" = 8 ] && + [ "$nft_bad_actions" = 0 ] || return 1 + printf '%s\\n' "$nft_text" | grep -Fq 'iifname "wg-fabric0" ip protocol icmp accept' || return 1 + printf '%s\\n' "$nft_text" | grep -Fq 'oifname "wg-fabric0" ip protocol icmp accept' || return 1 + printf '%s\\n' "$nft_text" | grep -Fq 'set vpc_tenant_ips' || return 1 + printf '%s\\n' "$nft_text" | grep -Fq 'chain forward' || return 1 + return 0 } -__VC_FABRIC_NFT__ +snapshot_file() { + snapshot_path=$1 + snapshot_name=$2 + if [ -L "$snapshot_path" ]; then exit 71; fi + if [ -f "$snapshot_path" ]; then + cp -p "$snapshot_path" "$TXN/$snapshot_name" || exit 76 + : > "$TXN/$snapshot_name.present" + else + : > "$TXN/$snapshot_name.absent" + fi +} +restore_file() { + restore_path=$1 + restore_name=$2 + if [ -f "$TXN/$restore_name.present" ]; then + [ ! -L "$restore_path" ] || { ROLLBACK_FAILED=yes; return; } + cp -p "$TXN/$restore_name" "$restore_path" || ROLLBACK_FAILED=yes + else + [ ! -L "$restore_path" ] || { ROLLBACK_FAILED=yes; return; } + rm -f "$restore_path" || ROLLBACK_FAILED=yes + fi +} +if [ -L "$BASE" ] || { [ -e "$BASE" ] && [ ! -d "$BASE" ]; }; then exit 71; fi +if [ -e "$BASE/.wg-fabric-txn" ]; then + [ -d "$BASE/.wg-fabric-txn" ] && [ ! -L "$BASE/.wg-fabric-txn" ] || exit 79 + [ "$(stat -c '%u:%a' "$BASE/.wg-fabric-txn" 2>/dev/null)" = 0:700 ] || exit 79 + [ -f "$BASE/.wg-fabric-txn/state" ] && [ ! -L "$BASE/.wg-fabric-txn/state" ] || exit 79 + journal_existing_state=$(cat "$BASE/.wg-fabric-txn/state" 2>/dev/null || true) + case "$journal_existing_state" in + committed|preparing) rm -rf "$BASE/.wg-fabric-txn" || exit 79 ;; + ready) + # Complete an interrupted revision before creating a new journal. + # An old helper without the recovery-only entry point must fail + # closed rather than running its normal apply path against a live + # transaction. + [ -x "$HELPER" ] || exit 79 + grep -Fq -- '--recover-only' "$HELPER" || exit 79 + VC_FABRIC_LOCK_HELD=1 "$HELPER" --recover-only || exit 79 + [ ! -e "$BASE/.wg-fabric-txn" ] || exit 79 + ;; + *) exit 79 ;; + esac +fi +TXN="$BASE/.wg-fabric-txn" +mkdir "$TXN" +chmod 700 "$TXN" +_txn_state_tmp=$(mktemp "$TXN/.state.XXXXXX") +printf '%s\n' preparing > "$_txn_state_tmp" +chmod 600 "$_txn_state_tmp" +mv -f "$_txn_state_tmp" "$TXN/state" +_txn_state_tmp= +nft_existing= +transaction_nft_tables=$($NFT list tables 2>/dev/null) || exit 71 +if printf '%s\n' "$transaction_nft_tables" | grep -Eq 'table inet virt_cloud_wg_fabric([[:space:]]|$)'; then + nft_existing=$($NFT list table inet virt_cloud_wg_fabric 2>/dev/null) || exit 71 + nft_panel_owned "$nft_existing" || exit 71 fi +snapshot_file "$CONF" conf +snapshot_file "$KEY" key +snapshot_file "$OWNER" owner +snapshot_file "$HELPER" helper +snapshot_file "$UNIT" unit +snapshot_file "$REPAIR_UNIT" repair +snapshot_file "$TIMER_UNIT" timer +snapshot_file "$NM_PROFILE" nm_profile +snapshot_file "$IFUPDOWN_FRAGMENT" ifupdown_fragment +snapshot_file "$NFT_RULES" nft_rules +snapshot_file "$NFT_MAIN" nft_main +SERVICE_ENABLED_BEFORE=$($SYSTEMCTL is-enabled virt-cloud-wg-fabric.service 2>/dev/null || true) +SERVICE_ACTIVE_BEFORE=$($SYSTEMCTL is-active virt-cloud-wg-fabric.service 2>/dev/null || true) +TIMER_ENABLED_BEFORE=$($SYSTEMCTL is-enabled virt-cloud-wg-fabric-reconcile.timer 2>/dev/null || true) +TIMER_ACTIVE_BEFORE=$($SYSTEMCTL is-active virt-cloud-wg-fabric-reconcile.timer 2>/dev/null || true) +IFACE_BEFORE=no +IFACE_UP_BEFORE=no +if "$IP" link show dev "$IFACE" >/dev/null 2>&1; then + IFACE_BEFORE=yes + "$WG" showconf "$IFACE" > "$TXN/wg.conf" || exit 76 + "$IP" address save dev "$IFACE" > "$TXN/address.save" || exit 76 + "$IP" route save table all dev "$IFACE" > "$TXN/route.save" || exit 76 + if "$IP" link show dev "$IFACE" 2>/dev/null | + awk -F'[<>]' 'NF >= 3 { + count=split($2, flags, ",") + for (i=1; i<=count; i++) if (flags[i] == "UP") found=1 + } END {exit found ? 0 : 1}'; then + IFACE_UP_BEFORE=yes + fi +fi +NFT_BEFORE=no +if "$NFT" list table inet virt_cloud_wg_fabric > "$TXN/nft.table" 2>/dev/null; then + NFT_BEFORE=yes +fi +cat > "$TXN/meta.tmp" < "$_txn_state_tmp" +chmod 600 "$_txn_state_tmp" +mv -f "$_txn_state_tmp" "$TXN/state" +_txn_state_tmp= +sync +JOURNAL_READY=yes +rollback() { + rollback_status=$? + trap - EXIT HUP INT TERM + set +e + set +u + if [ "$COMMITTED" = yes ]; then + cleanup + rm -rf "$TXN" + exit "$rollback_status" + fi + if [ "$JOURNAL_READY" != yes ]; then + # No live mutation occurs before the ready marker. Remove an + # incomplete snapshot rather than attempting a partial restore. + rm -rf "$TXN" + cleanup + exit "$rollback_status" + fi + # Stop only the timer introduced by this transaction. The oneshot service + # is deliberately never started while the transaction lock is held. + case "$TIMER_ACTIVE_BEFORE" in + active|activating) : ;; + *) $SYSTEMCTL stop virt-cloud-wg-fabric-reconcile.timer >/dev/null 2>&1 || true ;; + esac + # Remove a link created by this transaction before restoring an absent + # owner marker. Foreign links are never touched. + if [ "$IFACE_BEFORE" = no ] && + "$IP" link show dev "$IFACE" >/dev/null 2>&1 && + "$WG" show "$IFACE" >/dev/null 2>&1; then + "$IP" link del dev "$IFACE" || ROLLBACK_FAILED=yes + fi + # Restore manager artifacts before asking either manager to bring back a + # pre-existing interface. Foreign files are never overwritten. + restore_file "$CONF" conf + restore_file "$KEY" key + restore_file "$OWNER" owner + restore_file "$HELPER" helper + restore_file "$UNIT" unit + restore_file "$REPAIR_UNIT" repair + restore_file "$TIMER_UNIT" timer + restore_file "$NM_PROFILE" nm_profile + restore_file "$IFUPDOWN_FRAGMENT" ifupdown_fragment + restore_file "$NFT_RULES" nft_rules + restore_file "$NFT_MAIN" nft_main + if [ "$IFACE_BEFORE" = yes ]; then + if ! "$IP" link show dev "$IFACE" >/dev/null 2>&1; then + "$IP" link add dev "$IFACE" type wireguard || ROLLBACK_FAILED=yes + fi + "$WG" setconf "$IFACE" "$TXN/wg.conf" || ROLLBACK_FAILED=yes + "$IP" address flush dev "$IFACE" || ROLLBACK_FAILED=yes + "$IP" address restore < "$TXN/address.save" || ROLLBACK_FAILED=yes + "$IP" route flush table all dev "$IFACE" || ROLLBACK_FAILED=yes + "$IP" route restore < "$TXN/route.save" || ROLLBACK_FAILED=yes + if [ "$IFACE_UP_BEFORE" = yes ]; then + "$IP" link set dev "$IFACE" up || ROLLBACK_FAILED=yes + else + "$IP" link set dev "$IFACE" down || ROLLBACK_FAILED=yes + fi + fi + if [ "$NFT_BEFORE" = yes ]; then + nft_table_list=$($NFT list tables 2>/dev/null) || ROLLBACK_FAILED=yes + nft_current= + if [ "$ROLLBACK_FAILED" = no ] && + printf '%s\n' "$nft_table_list" | grep -Eq 'table inet virt_cloud_wg_fabric([[:space:]]|$)'; then + nft_current=$($NFT list table inet virt_cloud_wg_fabric 2>/dev/null) || ROLLBACK_FAILED=yes + fi + if [ -n "$nft_current" ] && nft_panel_owned "$nft_current"; then + "$NFT" delete table inet virt_cloud_wg_fabric >/dev/null 2>&1 || ROLLBACK_FAILED=yes + "$NFT" -f "$TXN/nft.table" >/dev/null 2>&1 || ROLLBACK_FAILED=yes + else + # Never delete an operator table that appeared or was altered + # while the transaction was in flight. + ROLLBACK_FAILED=yes + fi + else + nft_table_list=$($NFT list tables 2>/dev/null) || ROLLBACK_FAILED=yes + if [ "$ROLLBACK_FAILED" = no ] && + printf '%s\n' "$nft_table_list" | grep -Eq 'table inet virt_cloud_wg_fabric([[:space:]]|$)'; then + nft_current=$($NFT list table inet virt_cloud_wg_fabric 2>/dev/null) || ROLLBACK_FAILED=yes + nft_panel_owned "$nft_current" || ROLLBACK_FAILED=yes + if [ "$ROLLBACK_FAILED" = no ]; then + "$NFT" delete table inet virt_cloud_wg_fabric >/dev/null 2>&1 || ROLLBACK_FAILED=yes + fi + fi + fi + $SYSTEMCTL daemon-reload >/dev/null 2>&1 || ROLLBACK_FAILED=yes + case "$SERVICE_ENABLED_BEFORE" in enabled|enabled-runtime) $SYSTEMCTL enable virt-cloud-wg-fabric.service >/dev/null 2>&1 || ROLLBACK_FAILED=yes ;; *) $SYSTEMCTL disable virt-cloud-wg-fabric.service >/dev/null 2>&1 || true ;; esac + case "$TIMER_ENABLED_BEFORE" in enabled|enabled-runtime) $SYSTEMCTL enable virt-cloud-wg-fabric-reconcile.timer >/dev/null 2>&1 || ROLLBACK_FAILED=yes ;; *) $SYSTEMCTL disable virt-cloud-wg-fabric-reconcile.timer >/dev/null 2>&1 || true ;; esac + if [ "$ROLLBACK_FAILED" = yes ]; then + printf '%s\n' '__VC_FABRIC_ROLLBACK__=failed' >&2 + # Keep the durable snapshot so a boot or a later maintenance run can + # retry recovery. Deleting it here would turn a partial rollback into + # an unrecoverable mixed host state. + else + printf '%s\n' '__VC_FABRIC_ROLLBACK__=ok' >&2 + rm -rf "$TXN" + fi + cleanup + exit "$rollback_status" +} +trap rollback EXIT HUP INT TERM ''' @@ -820,12 +2134,28 @@ BASE=/etc/virt-cloud IFACE={_q(FABRIC_INTERFACE)} OWNER="$BASE/wg-fabric0.owner" KEY="$BASE/wg-fabric0.key" +LOCK={_q(FABRIC_LOCK)} if [ -L "$BASE" ] || {{ [ -e "$BASE" ] && [ ! -d "$BASE" ]; }}; then exit 71; fi if [ -L "$OWNER" ]; then exit 71; fi find_tool() {{ for p in "$@"; do [ -x "$p" ] && {{ printf '%s' "$p"; return 0; }}; done; return 1; }} WG=$(find_tool /usr/bin/wg /usr/sbin/wg /bin/wg /sbin/wg) || exit 70 IP=$(find_tool /usr/sbin/ip /usr/bin/ip /sbin/ip /bin/ip) || exit 70 STAT=$(find_tool /usr/bin/stat /bin/stat /usr/sbin/stat /sbin/stat) || exit 70 +AWK=$(find_tool /usr/bin/awk /bin/awk /usr/sbin/awk /sbin/awk) || exit 70 +FLOCK=$(find_tool /usr/bin/flock /usr/sbin/flock /bin/flock /sbin/flock) || exit 70 +if [ -L /run/virt-cloud ] || {{ [ -e /run/virt-cloud ] && [ ! -d /run/virt-cloud ]; }}; then exit 71; fi +if [ -e /run/virt-cloud ]; then + [ -d /run/virt-cloud ] && [ ! -L /run/virt-cloud ] || exit 71 + [ "$($STAT -c '%u:%a' /run/virt-cloud 2>/dev/null)" = 0:700 ] || exit 71 +else + mkdir /run/virt-cloud + chmod 700 /run/virt-cloud +fi +[ ! -L "$LOCK" ] || exit 71 +if [ ! -e "$LOCK" ]; then : > "$LOCK"; chmod 600 "$LOCK"; fi +[ -f "$LOCK" ] && [ "$($STAT -c '%u:%a' "$LOCK" 2>/dev/null)" = 0:600 ] || exit 71 +exec 9>>"$LOCK" +"$FLOCK" -x 9 || exit 79 if [ -f "$OWNER" ] && [ "$(cat "$OWNER")" != {_q(FABRIC_OWNER_MARKER)} ]; then exit 71; fi if [ -f "$OWNER" ]; then [ "$($STAT -c '%u' "$OWNER" 2>/dev/null)" = 0 ] || exit 71 @@ -856,7 +2186,9 @@ printf '%s\\n' "__VC_FABRIC_PUBLIC_KEY__=$($WG pubkey < "$KEY")" def _apply_script(plan: FabricPlan, host: FabricNode, public_keys: Mapping[str, str], deployment_mode: str = "networkmanager_nmcli", - ifup_path: str = "/usr/sbin/ifup") -> str: + ifup_path: str = "/usr/sbin/ifup", + ifquery_path: str = "/usr/sbin/ifquery", + ifdown_path: str = "/usr/sbin/ifdown") -> str: if deployment_mode not in FABRIC_DEPLOYMENT_MODES: raise FabricError( "宿主机网络管理器不受支持", 409, @@ -865,17 +2197,35 @@ def _apply_script(plan: FabricPlan, host: FabricNode, raise FabricError( "宿主机 ifup 路径不受支持", 409, "fabric_host_network_manager_conflict") + if ifquery_path not in IFQUERY_PATHS: + raise FabricError( + "宿主机 ifquery 路径不受支持", 409, + "fabric_host_network_manager_conflict") + if ifdown_path not in IFDOWN_PATHS: + raise FabricError( + "宿主机 ifdown 路径不受支持", 409, + "fabric_host_network_manager_conflict") config = _config_text(plan, host, public_keys) connection_uuid = _fabric_connection_uuid(plan, host) nm_profile = _nm_profile_template(plan, host, connection_uuid) ifupdown_fragment = _ifupdown_fragment(plan, host) + nft_rules = _nft_rules_text(plan.digest) helper_content = _BOOT_HELPER.replace( "__VC_FABRIC_DIGEST__", plan.digest).replace( "__VC_FABRIC_MODE__", deployment_mode).replace( "__VC_FABRIC_CONNECTION__", FABRIC_CONNECTION).replace( - "__VC_FABRIC_UUID__", _fabric_connection_uuid(plan, host)) + "__VC_FABRIC_UUID__", _fabric_connection_uuid(plan, host)).replace( + "__VC_IFUP_PATH__", _q(ifup_path)).replace( + "__VC_IFQUERY_PATH__", _q(ifquery_path)).replace( + "__VC_IFDOWN_PATH__", _q(ifdown_path)).replace( + "__VC_FABRIC_HOST_ID__", host.host_id).replace( + "__VC_VPC_STATE_LOADER__", _VPC_STATE_LOADER.replace( + "__VC_FABRIC_HOST_ID__", host.host_id).replace( + "__VC_FABRIC_ID__", "$config_fabric").replace( + "__VC_FABRIC_NETWORK__", "$network").replace( + "__VC_VPC_STATE_OBSERVE__", "no")) manager_exec = ( - f"{ifup_path} --force wg-fabric0" + "/usr/local/libexec/virt-cloud-wg-fabric --ifupdown-service" if deployment_mode == "ifupdown" else "/usr/local/libexec/virt-cloud-wg-fabric" ) @@ -891,8 +2241,11 @@ def _apply_script(plan: FabricPlan, host: FabricNode, if peer.host_id == host.host_id: continue peer_commands.append( + f"vpc_extra=$(vpc_state_allowed_for_peer {_q(public_keys[peer.host_id])}) || exit 71\n" + f"vpc_allowed={_q(peer.allowed_ip)}\n" + "[ -z \"$vpc_extra\" ] || vpc_allowed=\"$vpc_allowed,$vpc_extra\"\n" f"$WG set $IFACE peer {_q(public_keys[peer.host_id])} endpoint " - f"{_q(peer.endpoint)} allowed-ips {_q(peer.allowed_ip)} " + f"{_q(peer.endpoint)} allowed-ips \"$vpc_allowed\" " "persistent-keepalive 25" ) peer_keys = " ".join( @@ -947,10 +2300,13 @@ for existing in $existing_peers; do done if "$IP" link show dev "$IFACE" >/dev/null 2>&1; then if ! fabric_routes=$($IP -o route show table all dev "$IFACE" 2>/dev/null); then exit 75; fi - route_conflict=$(printf '%s\n' "$fabric_routes" | awk -v iface="$IFACE" -v own={_q(host.overlay_ip)} -v allowed="$MANAGED_ROUTES $OLD_MANAGED_ROUTES" ' + route_conflict=$(printf '%s\n' "$fabric_routes" | awk -v iface="$IFACE" -v own={_q(host.overlay_ip)} -v allowed="$MANAGED_ROUTES $OLD_MANAGED_ROUTES" -v vpc_file="$VPC_ROUTE_FILE" ' + BEGIN {{while ((getline line < vpc_file) > 0) {{n=split(line, parts, "|"); if (n>=5) vpc[parts[1] "|" parts[2] "|" parts[3] "|" parts[4] "|" parts[5]]=1}} close(vpc_file)}} NF {{prefix=$1; if ($1=="local" || $1=="broadcast" || $1=="unreachable" || $1=="blackhole" || $1=="prohibit" || $1=="throw") prefix=$2 - table="main"; device=""; for (i=1;i<=NF;i++) {{if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1)}} + table="main"; device=""; via="-"; metric="100"; proto=""; for (i=1;i<=NF;i++) {{if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1); if ($i=="via") via=$(i+1); if ($i=="metric") metric=$(i+1); if ($i=="proto") proto=$(i+1)}} + if (table=="254") table="main"; if (table=="255") table="local" if (prefix==own && (table=="local" || table=="main") && device==iface) next + if (table!="main" && proto=="186" && vpc[prefix "|" device "|" table "|" via "|" metric]) next ok=0; n=split(allowed, values, " "); for (i=1;i<=n;i++) if (values[i]==prefix) ok=1 if (table!="main" || device!=iface || !ok || ++seen[prefix]>1) {{print "foreign"; exit}}}}') [ -z "$route_conflict" ] || exit 75 @@ -958,18 +2314,47 @@ fi # The UDP endpoint must leave through the host underlay, never through the # fabric itself. This catches policy-route self-loops before any mutation. {endpoint_checks} -# A desired overlay /32 may only be replaced when every existing route for it -# is already on this managed interface. Any other device/table is a conflict. -for route in $MANAGED_ROUTES; do - if ! existing_route=$("$IP" -o route show table all exact "$route" 2>/dev/null); then - exit 75 +# A desired overlay /32 may only be replaced when an existing route is the +# exact route recorded in the previous panel-owned config. A broader route in +# any policy table (including blackhole/unreachable/connected routes) would +# win or leak traffic around the overlay and is therefore a hard conflict. +route_overlaps_target() {{ + overlap_target=${{1%/32}} + overlap_exact=$1 + overlap_old="$OLD_MANAGED_ROUTES" + overlap_routes= + if ! overlap_routes=$("$IP" -o -4 route show table all 2>/dev/null); then + printf '%s\\n' conflict + return 0 fi - route_conflict=$(printf '%s\\n' "$existing_route" | awk -v iface="$IFACE" '{{ - if (NF) {{table="main"; device=""; for (i=1;i<=NF;i++) {{ - if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1) - }}; count++ - if (table!="main" || device!=iface) {{print "foreign"; bad=1; exit}}}} - END {{if (!bad && count>1) print "duplicate"}}}}') + printf '%s\\n' "$overlap_routes" | awk -v target="$overlap_target" -v exact="$overlap_exact" -v old="$overlap_old" -v iface="$IFACE" ' + function ipnum(v, a) {{split(v,a,"."); if (length(a)!=4) return -1; return ((a[1]*256+a[2])*256+a[3])*256+a[4]}} + function contains(prefix, p, n, base, bits, unit, value) {{ + if (prefix == "default") return 0 + n=split(prefix,p,"/") + if (n == 1) {{base=ipnum(prefix); bits=32}} + else if (n == 2 && p[2] ~ /^[0-9]+$/) {{base=ipnum(p[1]); bits=p[2]}} + else return 0 + value=ipnum(target) + if (base < 0 || value < 0 || bits < 0 || bits > 32) return 0 + unit=2^(32-bits); return value >= base && value < base+unit + }} + function in_old(v, parts, count, i) {{ + count=split(old, parts, " "); for (i=1;i<=count;i++) if (parts[i] == v) return 1 + return 0 + }} + {{ + prefix=$1 + if ($1=="local" || $1=="broadcast" || $1=="unreachable" || $1=="blackhole" || $1=="prohibit" || $1=="throw") prefix=$2 + if (!contains(prefix)) next + table="main"; device="" + for (i=1;i<=NF;i++) {{if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1)}} + if ((prefix == exact || prefix == target) && table == "main" && device == iface && in_old(exact)) next + print "conflict"; exit + }}' +}} +for route in $MANAGED_ROUTES; do + route_conflict=$(route_overlaps_target "$route") if [ -n "$route_conflict" ]; then exit 75 fi @@ -990,13 +2375,18 @@ fi''' remove_old_routes = r'''if [ -f "$CONF" ]; then while IFS='|' read -r kind a b c d; do [ "$kind" = route ] || continue - case " $MANAGED_ROUTES " in *" $a "*) : ;; *) "$IP" route del "$a" table main dev "$IFACE" 2>/dev/null || true ;; esac + case " $MANAGED_ROUTES " in *" $a "*) : ;; *) "$IP" route del "$a" table main dev "$IFACE" 2>/dev/null || exit 73 ;; esac done < "$CONF" fi''' nm_write = f'''if [ "$DEPLOYMENT_MODE" = networkmanager_nmcli ]; then - mkdir -p /etc/NetworkManager/system-connections - chmod 700 /etc/NetworkManager/system-connections + if [ -e /etc/NetworkManager/system-connections ]; then + [ -d /etc/NetworkManager/system-connections ] && [ ! -L /etc/NetworkManager/system-connections ] || exit 71 + [ "$($STAT -c '%u:%a' /etc/NetworkManager/system-connections 2>/dev/null)" = 0:700 ] || exit 71 + else + mkdir -p /etc/NetworkManager/system-connections + chmod 700 /etc/NetworkManager/system-connections + fi _tmp_nm=$(mktemp /etc/NetworkManager/system-connections/.virt-cloud-wg-fabric0.XXXXXX) {{ cat <<'__VC_NM_PROFILE__' @@ -1015,8 +2405,13 @@ __VC_NM_PROFILE__ _tmp_nm= fi''' ifupdown_write = f'''if [ "$DEPLOYMENT_MODE" = ifupdown ]; then - mkdir -p /etc/network/interfaces.d - chmod 755 /etc/network/interfaces.d + if [ -e /etc/network/interfaces.d ]; then + [ -d /etc/network/interfaces.d ] && [ ! -L /etc/network/interfaces.d ] || exit 71 + [ "$($STAT -c '%u:%a' /etc/network/interfaces.d 2>/dev/null)" = 0:755 ] || exit 71 + else + mkdir -p /etc/network/interfaces.d + chmod 755 /etc/network/interfaces.d + fi _tmp_ifupdown=$(mktemp /etc/network/interfaces.d/.virt-cloud-wg-fabric0.XXXXXX) {_here_doc('$_tmp_ifupdown', ifupdown_fragment).rstrip()} chmod 600 "$_tmp_ifupdown" @@ -1039,10 +2434,15 @@ _tmp_repair= _tmp_timer= _tmp_nm= _tmp_ifupdown= +_tmp_nft= +_tmp_nft_main= cleanup() {{ - for _fabric_tmp in "$_tmp_key" "$_tmp_owner" "$_tmp_conf" "$_tmp_helper" "$_tmp_unit" "$_tmp_repair" "$_tmp_timer" "$_tmp_nm" "$_tmp_ifupdown"; do + for _fabric_tmp in "$_tmp_key" "$_tmp_owner" "$_tmp_conf" "$_tmp_helper" "$_tmp_unit" "$_tmp_repair" "$_tmp_timer" "$_tmp_nm" "$_tmp_ifupdown" "$_tmp_nft" "$_tmp_nft_main"; do [ -z "$_fabric_tmp" ] || rm -f "$_fabric_tmp" || true done + [ -z "${{VPC_PEER_FILE:-}}" ] || rm -f "$VPC_PEER_FILE" || true + [ -z "${{VPC_ROUTE_FILE:-}}" ] || rm -f "$VPC_ROUTE_FILE" || true + [ -z "${{VPC_TENANT_FILE:-}}" ] || rm -f "$VPC_TENANT_FILE" || true }} trap cleanup EXIT HUP INT TERM BASE=/etc/virt-cloud @@ -1054,9 +2454,13 @@ HELPER=/usr/local/libexec/virt-cloud-wg-fabric UNIT=/etc/systemd/system/{FABRIC_SERVICE} REPAIR_UNIT=/etc/systemd/system/{FABRIC_REPAIR_SERVICE} TIMER_UNIT=/etc/systemd/system/{FABRIC_TIMER} +LOCK={_q(FABRIC_LOCK)} +NFT_RULES={_q(FABRIC_NFT_RULES)} NM_PROFILE={_q(FABRIC_NM_PROFILE)} IFUPDOWN_FRAGMENT={_q(FABRIC_IFUPDOWN_FRAGMENT)} -LOCK={_q(FABRIC_LOCK)} +NFT_MAIN= +PLAN_DIGEST={_q(plan.digest)} +EXPECTED_DIGEST="$PLAN_DIGEST" DEPLOYMENT_MODE={_q(deployment_mode)} CONNECTION={_q(FABRIC_CONNECTION)} CONNECTION_UUID={_q(connection_uuid)} @@ -1064,24 +2468,54 @@ if [ -L "$BASE" ] || {{ [ -e "$BASE" ] && [ ! -d "$BASE" ]; }}; then exit 71; fi find_tool() {{ for p in "$@"; do [ -x "$p" ] && {{ printf '%s' "$p"; return 0; }}; done; return 1; }} WG=$(find_tool /usr/bin/wg /usr/sbin/wg /bin/wg /sbin/wg) || exit 70 IP=$(find_tool /usr/sbin/ip /usr/bin/ip /sbin/ip /bin/ip) || exit 70 +NFT=$(find_tool /usr/sbin/nft /usr/bin/nft /sbin/nft /bin/nft) || exit 70 SYSTEMCTL=$(find_tool /usr/bin/systemctl /bin/systemctl /usr/sbin/systemctl /sbin/systemctl) || exit 70 STAT=$(find_tool /usr/bin/stat /bin/stat /usr/sbin/stat /sbin/stat) || exit 70 FLOCK=$(find_tool /usr/bin/flock /usr/sbin/flock /bin/flock /sbin/flock) || exit 70 +read_sysctl() {{ + [ -r "$1" ] || return 1 + sysctl_value= + IFS= read -r sysctl_value < "$1" || return 1 + printf '%s' "$sysctl_value" +}} +if ! sysctl_forward=$(read_sysctl /proc/sys/net/ipv4/ip_forward); then exit 71; fi +[ "$sysctl_forward" = 1 ] || exit 71 +if ! sysctl_rp_all=$(read_sysctl /proc/sys/net/ipv4/conf/all/rp_filter); then exit 71; fi +case "$sysctl_rp_all" in 0|2) : ;; *) exit 71 ;; esac +if ! sysctl_rp_default=$(read_sysctl /proc/sys/net/ipv4/conf/default/rp_filter); then exit 71; fi +case "$sysctl_rp_default" in 0|2) : ;; *) exit 71 ;; esac if [ -L /run/virt-cloud ] || {{ [ -e /run/virt-cloud ] && [ ! -d /run/virt-cloud ]; }}; then exit 71; fi -mkdir -p /run/virt-cloud -exec 9>"$LOCK" +if [ -e /run/virt-cloud ]; then + [ -d /run/virt-cloud ] && [ ! -L /run/virt-cloud ] || exit 71 + [ "$(stat -c '%u:%a' /run/virt-cloud 2>/dev/null)" = 0:700 ] || exit 71 +else + mkdir /run/virt-cloud + chmod 700 /run/virt-cloud +fi +[ ! -L "$LOCK" ] || exit 71 +if [ ! -e "$LOCK" ]; then : > "$LOCK"; chmod 600 "$LOCK"; fi +[ -f "$LOCK" ] && [ "$(stat -c '%u:%a' "$LOCK" 2>/dev/null)" = 0:600 ] || exit 71 +exec 9>>"$LOCK" "$FLOCK" -x 9 || exit 79 +[ ! -L "$LOCK" ] && [ "$(stat -c '%u:%a' "$LOCK" 2>/dev/null)" = 0:600 ] || exit 71 NMCLI= IFQUERY= IFUP= if [ "$DEPLOYMENT_MODE" = networkmanager_nmcli ]; then NMCLI=$(find_tool /usr/bin/nmcli /usr/sbin/nmcli /bin/nmcli /sbin/nmcli) || exit 70 else - IFQUERY=$(find_tool /usr/sbin/ifquery /usr/bin/ifquery /sbin/ifquery /bin/ifquery) || exit 70 - IFUP=$(find_tool /usr/sbin/ifup /usr/bin/ifup /sbin/ifup /bin/ifup) || exit 70 + IFQUERY={_q(ifquery_path)} + IFUP={_q(ifup_path)} + [ -x "$IFQUERY" ] && [ -x "$IFUP" ] || exit 70 fi -mkdir -p "$BASE" /usr/local/libexec /etc/systemd/system -chmod 700 "$BASE" +if [ -e "$BASE" ]; then + [ -d "$BASE" ] && [ ! -L "$BASE" ] || exit 71 + [ "$($STAT -c '%u:%a' "$BASE" 2>/dev/null)" = 0:700 ] || exit 71 +else + mkdir "$BASE" + chmod 700 "$BASE" +fi +mkdir -p /usr/local/libexec /etc/systemd/system if [ -L "$CONF" ] || [ -L "$KEY" ] || [ -L "$OWNER" ]; then exit 71; fi check_artifact() {{ artifact_path=$1 @@ -1117,15 +2551,56 @@ for managed_unit in "$REPAIR_UNIT" "$TIMER_UNIT"; do done MANAGED_PEERS={_q(peer_keys)} MANAGED_ROUTES={_q(route_keys)} +{_VPC_STATE_LOADER.replace('__VC_FABRIC_HOST_ID__', host.host_id).replace('__VC_FABRIC_ID__', plan.fabric_id).replace('__VC_FABRIC_NETWORK__', plan.overlay_cidr).replace('__VC_VPC_STATE_OBSERVE__', 'no')} +vpc_state_load || exit 71 {preflight} if [ -f "$OWNER" ] && [ "$(cat "$OWNER")" != {_q(FABRIC_OWNER_MARKER)} ]; then exit 71; fi if "$IP" link show dev "$IFACE" >/dev/null 2>&1; then [ -f "$OWNER" ] && [ "$(cat "$OWNER")" = {_q(FABRIC_OWNER_MARKER)} ] || exit 71 "$WG" show "$IFACE" >/dev/null 2>&1 || exit 71 fi -# Only after every read-only ownership, endpoint, route, and address preflight -# has passed may this helper create or validate the host-only nftables guard. +# Native nftables must have a persistent include owned by this transaction. +# Debian and AlmaLinux use one of these two service entry points. Unknown +# layouts fail closed instead of appending to an arbitrary firewall file. +NFT_MAIN_COUNT=0 +for nft_candidate in /etc/nftables.conf /etc/sysconfig/nftables.conf; do + if [ -f "$nft_candidate" ] && [ ! -L "$nft_candidate" ] && + [ "$("$STAT" -c '%u' "$nft_candidate" 2>/dev/null)" = 0 ]; then + nft_main_mode=$("$STAT" -c '%a' "$nft_candidate" 2>/dev/null || true) + case "$nft_main_mode" in [0-7][0145][0145]) : ;; *) continue ;; esac + [ -n "$NFT_MAIN" ] || NFT_MAIN="$nft_candidate" + NFT_MAIN_COUNT=$((NFT_MAIN_COUNT + 1)) + fi +done +[ "$NFT_MAIN_COUNT" = 1 ] || exit 71 +if [ -L /etc/nftables.d ] || {{ [ -e /etc/nftables.d ] && [ ! -d /etc/nftables.d ]; }}; then exit 71; fi +if [ -e /etc/nftables.d ]; then + [ "$("$STAT" -c '%u:%a' /etc/nftables.d 2>/dev/null)" = 0:755 ] || exit 71 +else + mkdir /etc/nftables.d + chmod 755 /etc/nftables.d +fi +{_TRANSACTION_SCRIPT} +_tmp_nft=$(mktemp /etc/nftables.d/.virt-cloud-wg-fabric.XXXXXX) +{_here_doc('$_tmp_nft', nft_rules).rstrip()} +chmod 600 "$_tmp_nft" +mv -f "$_tmp_nft" "$NFT_RULES" +_tmp_nft= +if ! grep -Fqx 'include "/etc/nftables.d/virt-cloud-wg-fabric.nft"' "$NFT_MAIN" && + ! grep -Fqx 'include "/etc/nftables.d/*.nft"' "$NFT_MAIN" && + ! grep -Fqx 'include "/etc/nftables.d/*"' "$NFT_MAIN"; then + _tmp_nft_main=$(mktemp "${{NFT_MAIN}}.virt-cloud.XXXXXX") + cat "$NFT_MAIN" > "$_tmp_nft_main" + printf '%s\\n' 'include "/etc/nftables.d/virt-cloud-wg-fabric.nft"' >> "$_tmp_nft_main" + "$NFT" -c -f "$_tmp_nft_main" >/dev/null 2>&1 || exit 72 + chmod "$($STAT -c '%a' "$NFT_MAIN")" "$_tmp_nft_main" + mv -f "$_tmp_nft_main" "$NFT_MAIN" +fi +# Only after every read-only ownership, endpoint, route, address, and +# persistence preflight has passed may this helper create or validate the +# host-only nftables guard. {_NFT_GUARD} +vpc_state_refresh_nft || exit 71 if [ ! -f "$KEY" ]; then umask 077 _tmp_key=$(mktemp "$BASE/.wg-key.XXXXXX") @@ -1145,7 +2620,7 @@ if [ "$DEPLOYMENT_MODE" = networkmanager_nmcli ]; then nm_first=; nm_second= {{ IFS= read -r nm_first || true; IFS= read -r nm_second || true; }} < "$NM_PROFILE" [ "$nm_first" = '# virt-cloud-wg-fabric-v1' ] || exit 71 - [ "$nm_second" = "# fabric-plan-digest=$EXPECTED_DIGEST" ] || exit 71 + case "$nm_second" in '# fabric-plan-digest='*) : ;; *) exit 71 ;; esac awk -F= -v id="$CONNECTION" -v uuid="$CONNECTION_UUID" ' $0 == "type=wireguard" {{type=1}} $0 == "interface-name=wg-fabric0" {{iface=1}} @@ -1186,7 +2661,11 @@ if [ "$DEPLOYMENT_MODE" = networkmanager_nmcli ]; then "$NMCLI" connection up uuid {_q(connection_uuid)} >/dev/null 2>&1 || exit 72 "$IP" link show dev "$IFACE" >/dev/null 2>&1 || exit 72 else + export VC_FABRIC_LOCK_HELD=1 + export VC_FABRIC_ALLOW_TRANSITION=1 + export VC_FABRIC_APPLYING=1 "$IFUP" --force "$IFACE" >/dev/null 2>&1 || exit 72 + unset VC_FABRIC_APPLYING "$IP" link show dev "$IFACE" >/dev/null 2>&1 || exit 72 fi if [ ! -f "$OWNER" ] || [ "$(cat "$OWNER")" != {_q(FABRIC_OWNER_MARKER)} ]; then @@ -1203,7 +2682,7 @@ fi if [ -f "$CONF" ]; then while IFS='|' read -r kind a b c d; do [ "$kind" = overlay ] || continue - [ "$a" = {_q(host.overlay_ip)} ] || "$IP" address del "$a/32" dev "$IFACE" 2>/dev/null || true + [ "$a" = {_q(host.overlay_ip)} ] || "$IP" address del "$a/32" dev "$IFACE" 2>/dev/null || exit 73 done < "$CONF" fi "$WG" set "$IFACE" private-key "$KEY" @@ -1211,6 +2690,8 @@ fi {chr(10).join(peer_commands)} "$IP" address replace {_q(host.overlay_ip + '/32')} dev "$IFACE" "$IP" link set dev "$IFACE" up +if ! sysctl_rp_iface=$(read_sysctl "/proc/sys/net/ipv4/conf/$IFACE/rp_filter"); then exit 71; fi +case "$sysctl_rp_iface" in 0|2) : ;; *) exit 71 ;; esac {route_commands} {path_checks} _tmp_conf=$(mktemp "$BASE/.wg-fabric0.conf.XXXXXX") @@ -1237,7 +2718,13 @@ _tmp_timer= "$SYSTEMCTL" enable {FABRIC_SERVICE} >/dev/null "$SYSTEMCTL" enable {FABRIC_TIMER} >/dev/null "$SYSTEMCTL" start {FABRIC_TIMER} >/dev/null -"$SYSTEMCTL" start {FABRIC_SERVICE} >/dev/null +_txn_state_tmp=$(mktemp "$TXN/.state.XXXXXX") +printf '%s\n' committed > "$_txn_state_tmp" +chmod 600 "$_txn_state_tmp" +mv -f "$_txn_state_tmp" "$TXN/state" +_txn_state_tmp= +sync +COMMITTED=yes printf '%s\\n' '__VC_FABRIC_APPLIED__' ''' @@ -1247,6 +2734,9 @@ def _observe_script( endpoint_ips: tuple[str, ...] = (), deployment_mode: str = "networkmanager_nmcli", connection_uuid: str = "", + host_id: str | None = None, + fabric_id: str | None = None, + overlay_cidr: str | None = None, ) -> str: target_lines = "\n".join( f'''if $PING -c 1 -W 1 {_q(target)} >/dev/null 2>&1; then @@ -1265,6 +2755,13 @@ printf '%s\\n' "__VC_FABRIC_PATH__={target}|$path_dev"''' endpoint_dev=$(printf '%s\\n' "$endpoint_result" | awk '{{for (i=1;i<=NF;i++) if ($i=="dev") {{print $(i+1); exit}}}}') printf '%s\\n' "__VC_FABRIC_ENDPOINT_PATH__={endpoint}|$endpoint_dev"''' for endpoint in endpoint_ips) + overlap_lines = "\n".join( + f'''if [ "$(route_overlap_status {_q(target)})" = conflict ]; then + printf '%s\\n' "__VC_FABRIC_ROUTE_OVERLAP__={target}|conflict" +else + printf '%s\\n' "__VC_FABRIC_ROUTE_OVERLAP__={target}|clean" +fi''' + for target in targets) return f'''#!/bin/sh set +e PATH=/usr/sbin:/usr/bin:/sbin:/bin @@ -1279,6 +2776,8 @@ CONNECTION={_q(FABRIC_CONNECTION)} CONNECTION_UUID={_q(connection_uuid)} NM_PROFILE={_q(FABRIC_NM_PROFILE)} IFUPDOWN_FRAGMENT={_q(FABRIC_IFUPDOWN_FRAGMENT)} +LOCK={_q(FABRIC_LOCK)} +NFT_RULES={_q(FABRIC_NFT_RULES)} HELPER=/usr/local/libexec/virt-cloud-wg-fabric UNIT=/etc/systemd/system/{FABRIC_SERVICE} REPAIR_UNIT=/etc/systemd/system/{FABRIC_REPAIR_SERVICE} @@ -1287,9 +2786,87 @@ find_tool() {{ for p in "$@"; do [ -x "$p" ] && {{ printf '%s' "$p"; return 0; } WG=$(find_tool /usr/bin/wg /usr/sbin/wg /bin/wg /sbin/wg) || exit 70 IP=$(find_tool /usr/sbin/ip /usr/bin/ip /sbin/ip /bin/ip) || exit 70 SYSTEMCTL=$(find_tool /usr/bin/systemctl /bin/systemctl /usr/sbin/systemctl /sbin/systemctl) || exit 70 +AWK=$(find_tool /usr/bin/awk /bin/awk /usr/sbin/awk /sbin/awk) || exit 70 PING=$(find_tool /usr/bin/ping /bin/ping /usr/sbin/ping /sbin/ping || true) NFT=$(find_tool /usr/sbin/nft /usr/bin/nft /sbin/nft /bin/nft || true) STAT=$(find_tool /usr/bin/stat /bin/stat /usr/sbin/stat /sbin/stat || true) +FLOCK=$(find_tool /usr/bin/flock /usr/sbin/flock /bin/flock /sbin/flock) || exit 70 +read_observed_sysctl() {{ + observed_sysctl_path=$1 + [ -r "$observed_sysctl_path" ] || return 1 + observed_sysctl_value= + IFS= read -r observed_sysctl_value < "$observed_sysctl_path" || return 1 + printf '%s' "$observed_sysctl_value" +}} +observed_sysctl_or_unknown() {{ + if observed_value=$(read_observed_sysctl "$1"); then + printf '%s' "$observed_value" + else + printf '%s' unknown + fi +}} +observed_ip_forward=$(observed_sysctl_or_unknown /proc/sys/net/ipv4/ip_forward) +observed_rp_all=$(observed_sysctl_or_unknown /proc/sys/net/ipv4/conf/all/rp_filter) +observed_rp_default=$(observed_sysctl_or_unknown /proc/sys/net/ipv4/conf/default/rp_filter) +observed_rp_iface=$(observed_sysctl_or_unknown "/proc/sys/net/ipv4/conf/$IFACE/rp_filter") +observed_admin_state=missing +observed_link_line= +if observed_link_line=$($IP -o link show dev "$IFACE" 2>/dev/null); then + observed_link_flags=$(printf '%s\n' "$observed_link_line" | + awk -F'[<>]' 'NF >= 3 {{print $2; exit}}') + case ",$observed_link_flags," in + *,UP,*) observed_admin_state=up ;; + *) observed_admin_state=down ;; + esac +fi +printf '%s\\n' "__VC_FABRIC_ADMIN_STATE__=$observed_admin_state" +printf '%s\\n' "__VC_FABRIC_SYSCTL__ip_forward=$observed_ip_forward" +printf '%s\\n' "__VC_FABRIC_SYSCTL__rp_filter=$observed_rp_all" +printf '%s\\n' "__VC_FABRIC_SYSCTL__rp_filter_default=$observed_rp_default" +printf '%s\\n' "__VC_FABRIC_RPF__wg-fabric0=$observed_rp_iface" +if [ -n "$STAT" ]; then + [ -d /etc/nftables.d ] && [ ! -L /etc/nftables.d ] || exit 71 + [ "$($STAT -c '%u:%a' /etc/nftables.d 2>/dev/null)" = 0:755 ] || exit 71 +fi +if [ -L /run/virt-cloud ] || {{ [ -e /run/virt-cloud ] && [ ! -d /run/virt-cloud ]; }}; then exit 71; fi +if [ -e /run/virt-cloud ]; then + [ -d /run/virt-cloud ] && [ ! -L /run/virt-cloud ] || exit 71 + [ -n "$STAT" ] && [ "$($STAT -c '%u:%a' /run/virt-cloud 2>/dev/null)" = 0:700 ] || exit 71 +else + mkdir /run/virt-cloud + chmod 700 /run/virt-cloud +fi +[ ! -L "$LOCK" ] || exit 71 +if [ ! -e "$LOCK" ]; then : > "$LOCK"; chmod 600 "$LOCK"; fi +[ -f "$LOCK" ] && [ "$($STAT -c '%u:%a' "$LOCK" 2>/dev/null)" = 0:600 ] || exit 71 +exec 9>>"$LOCK" +"$FLOCK" -x 9 || exit 79 +{_VPC_STATE_LOADER.replace('__VC_FABRIC_HOST_ID__', host_id or '').replace('__VC_FABRIC_ID__', fabric_id or '*').replace('__VC_FABRIC_NETWORK__', overlay_cidr or '').replace('__VC_VPC_STATE_OBSERVE__', 'yes')} +vpc_observe_cleanup() {{ + [ -z "${{VPC_PEER_FILE:-}}" ] || rm -f "$VPC_PEER_FILE" + [ -z "${{VPC_ROUTE_FILE:-}}" ] || rm -f "$VPC_ROUTE_FILE" + [ -z "${{VPC_TENANT_FILE:-}}" ] || rm -f "$VPC_TENANT_FILE" +}} +trap vpc_observe_cleanup EXIT HUP INT TERM +if vpc_state_load; then + printf '%s\\n' "__VC_FABRIC_VPC_STATE__=$VPC_STATE_STATUS" + if [ -f "$VPC_PEER_FILE" ]; then + while IFS='|' read -r vpc_observed_key vpc_observed_ip vpc_observed_extra; do + [ -n "$vpc_observed_key" ] && [ -n "$vpc_observed_ip" ] && [ -z "$vpc_observed_extra" ] || continue + printf '%s\\n' "__VC_FABRIC_VPC_TENANT__=$vpc_observed_key|$vpc_observed_ip" + done < "$VPC_PEER_FILE" + fi + if [ -f "$VPC_TENANT_FILE" ]; then + while IFS= read -r vpc_observed_tenant_ip; do + [ -n "$vpc_observed_tenant_ip" ] || continue + printf '%s\\n' "__VC_FABRIC_VPC_TENANT_IP__=$vpc_observed_tenant_ip" + done < "$VPC_TENANT_FILE" + fi +else + printf '%s\\n' '__VC_FABRIC_VPC_STATE__=invalid' +fi +{_VPC_NFT_OBSERVE_FRAGMENT} +[ -z "${{VPC_PEER_FILE:-}}" ] || rm -f "$VPC_PEER_FILE" NMCLI= IFQUERY= if [ "$DEPLOYMENT_MODE" = networkmanager_nmcli ]; then @@ -1306,9 +2883,9 @@ if [ "$DEPLOYMENT_MODE" = networkmanager_nmcli ] && [ -n "$NMCLI" ]; then [ "$($STAT -c '%u' "$NM_PROFILE" 2>/dev/null)" = 0 ] && [ "$($STAT -c '%a' "$NM_PROFILE" 2>/dev/null)" = 600 ]; then nm_first=; nm_second= - {{ IFS= read -r nm_first || true; IFS= read -r nm_second || true; }} < "$NM_PROFILE" - [ "$nm_first" = '# virt-cloud-wg-fabric-v1' ] && - [ "$nm_second" = "# fabric-plan-digest=$(awk -F'|' '/^digest\\|/ {{print $2; exit}}' "$CONF" 2>/dev/null)" ] && + {{ IFS= read -r nm_first || true; IFS= read -r nm_second || true; }} < "$NM_PROFILE" + [ "$nm_first" = '# virt-cloud-wg-fabric-v1' ] && + case "$nm_second" in '# fabric-plan-digest='*) : ;; *) false ;; esac && awk -F= -v id="$CONNECTION" -v uuid="$CONNECTION_UUID" ' $0 == "type=wireguard" {{type=1}} $0 == "interface-name=wg-fabric0" {{iface=1}} @@ -1326,9 +2903,9 @@ elif [ "$DEPLOYMENT_MODE" = ifupdown ] && [ -n "$IFQUERY" ]; then [ "$($STAT -c '%u' "$IFUPDOWN_FRAGMENT" 2>/dev/null)" = 0 ] && [ "$($STAT -c '%a' "$IFUPDOWN_FRAGMENT" 2>/dev/null)" = 600 ]; then if_first=; if_second= - {{ IFS= read -r if_first || true; IFS= read -r if_second || true; }} < "$IFUPDOWN_FRAGMENT" - [ "$if_first" = '# virt-cloud-wg-fabric-v1' ] && - [ "$if_second" = "# fabric-plan-digest=$(awk -F'|' '/^digest\\|/ {{print $2; exit}}' "$CONF" 2>/dev/null)" ] && + {{ IFS= read -r if_first || true; IFS= read -r if_second || true; }} < "$IFUPDOWN_FRAGMENT" + [ "$if_first" = '# virt-cloud-wg-fabric-v1' ] && + case "$if_second" in '# fabric-plan-digest='*) : ;; *) false ;; esac && awk ' NR == 1 && $0 == "# virt-cloud-wg-fabric-v1" {{next}} NR == 2 && index($0, "# fabric-plan-digest=") == 1 {{next}} @@ -1359,6 +2936,36 @@ fi printf '%s\\n' "__VC_FABRIC_MANAGER_MODE__=$DEPLOYMENT_MODE" printf '%s\\n' "__VC_FABRIC_MANAGER_OWNER__=$manager_owner" printf '%s\\n' "__VC_FABRIC_MANAGER_ACTIVE__=$manager_active" +route_overlap_status() {{ + overlap_target=$1 + overlap_exact="$overlap_target/32" + overlap_routes= + if ! overlap_routes=$("$IP" -o -4 route show table all 2>/dev/null); then + printf '%s' conflict + return 0 + fi + printf '%s\\n' "$overlap_routes" | awk -v target="$overlap_target" -v exact="$overlap_exact" -v iface="$IFACE" ' + function ipnum(v, a) {{split(v,a,"."); if (length(a)!=4) return -1; return ((a[1]*256+a[2])*256+a[3])*256+a[4]}} + function contains(prefix, p, n, base, bits, unit, value) {{ + if (prefix == "default") return 0 + n=split(prefix,p,"/") + if (n == 1) {{base=ipnum(prefix); bits=32}} + else if (n == 2 && p[2] ~ /^[0-9]+$/) {{base=ipnum(p[1]); bits=p[2]}} + else return 0 + value=ipnum(target) + if (base < 0 || value < 0 || bits < 0 || bits > 32) return 0 + unit=2^(32-bits); return value >= base && value < base+unit + }} + {{ + prefix=$1 + if ($1=="local" || $1=="broadcast" || $1=="unreachable" || $1=="blackhole" || $1=="prohibit" || $1=="throw") prefix=$2 + if (!contains(prefix)) next + table="main"; device="" + for (i=1;i<=NF;i++) {{if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1)}} + if ((prefix == exact || prefix == target) && table == "main" && device == iface) next + print "conflict"; exit + }}' +}} if [ -n "$PING" ]; then {target_lines} wait @@ -1540,14 +3147,28 @@ if "$IP" link show dev "$IFACE" >/dev/null 2>&1 && "$WG" show "$IFACE" >/dev/nul printf '%s\\n' "__VC_FABRIC_PEER__=$peer|$endpoint|$allowed" printf '%s\\n' "__VC_FABRIC_HANDSHAKE__=$peer|$handshake" done - $IP -o route show table all dev "$IFACE" 2>/dev/null | awk '{{ - table="main"; device=""; prefix=$1 + $IP -o route show table all dev "$IFACE" 2>/dev/null | awk -v vpc_file="${{VPC_ROUTE_FILE:-}}" -v vpc_state="${{VPC_STATE_STATUS:-invalid}}" '{{ + BEGIN {{ + if (vpc_state != "invalid" && vpc_file != "") {{ + while ((getline line < vpc_file) > 0) {{ + n=split(line, parts, "|") + if (n >= 5) vpc[parts[1] "|" parts[2] "|" parts[3] "|" parts[4] "|" parts[5]]=1 + }} + close(vpc_file) + }} + }} + table="main"; device=""; via="-"; metric="100"; proto=""; prefix=$1 if ($1=="local" || $1=="broadcast" || $1=="unreachable" || $1=="blackhole" || $1=="prohibit" || $1=="throw") prefix=$2 - for (i=1;i<=NF;i++) {{if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1)}} + for (i=1;i<=NF;i++) {{if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1); if ($i=="via") via=$(i+1); if ($i=="metric") metric=$(i+1); if ($i=="proto") proto=$(i+1)}} + if (table=="254") table="main" + if (table=="255") table="local" + if (table!="main" && table!="local" && proto=="186" && vpc_state != "invalid" && + vpc[prefix "|" device "|" table "|" via "|" metric]) next print "__VC_FABRIC_ROUTE__=" prefix "|" table "|" device }}' {path_lines} {endpoint_lines} +{overlap_lines} else printf '%s\\n' '__VC_FABRIC_INTERFACE__=missing' fi @@ -1587,13 +3208,45 @@ active=$($SYSTEMCTL is-active {FABRIC_SERVICE} 2>/dev/null || true) timer_enabled=$($SYSTEMCTL is-enabled {FABRIC_TIMER} 2>/dev/null || true) timer_active=$($SYSTEMCTL is-active {FABRIC_TIMER} 2>/dev/null || true) nft_guard=missing +nft_persistence=missing +if [ -n "$NFT" ] && [ -n "$STAT" ] && [ -f "$NFT_RULES" ] && [ ! -L "$NFT_RULES" ] && + [ "$($STAT -c '%u:%a' "$NFT_RULES" 2>/dev/null)" = 0:600 ]; then + nft_rule_first=; nft_rule_second= + {{ IFS= read -r nft_rule_first || true; IFS= read -r nft_rule_second || true; }} < "$NFT_RULES" + if [ "$nft_rule_first" = '# virt-cloud-wg-fabric-v1' ] && + [ "$nft_rule_second" = "# fabric-plan-digest=$(awk -F'|' '/^digest\\|/ {{print $2; exit}}' "$CONF" 2>/dev/null)" ]; then + nft_main_count=0 + for nft_main in /etc/nftables.conf /etc/sysconfig/nftables.conf; do + [ -f "$nft_main" ] && [ ! -L "$nft_main" ] || continue + [ "$($STAT -c '%u' "$nft_main" 2>/dev/null)" = 0 ] || continue + nft_main_mode=$($STAT -c '%a' "$nft_main" 2>/dev/null || true) + case "$nft_main_mode" in [0-7][0145][0145]) : ;; *) continue ;; esac + nft_main_count=$((nft_main_count + 1)) + if grep -Fqx 'include "/etc/nftables.d/virt-cloud-wg-fabric.nft"' "$nft_main" || + grep -Fqx 'include "/etc/nftables.d/*.nft"' "$nft_main" || + grep -Fqx 'include "/etc/nftables.d/*"' "$nft_main"; then + nft_persistence=owned + fi + done + [ "$nft_main_count" = 1 ] || nft_persistence=missing + fi +fi if [ -n "$NFT" ]; then if nft_table=$($NFT list table inet {FABRIC_NFT_TABLE} 2>/dev/null); then - case "$nft_table" in *virt-cloud-wg-fabric-v1*'iifname "wg-fabric0"'*'ip protocol icmp'*accept*'iifname "wg-fabric0"'*drop*) - case "$nft_table" in *'oifname "wg-fabric0"'*'ip protocol icmp'*accept*'oifname "wg-fabric0"'*drop*) - case "$nft_table" in *'hook forward'*priority*100*'policy accept'*) nft_guard=owned ;; esac ;; - esac ;; - esac + nft_owner_count=$(printf '%s\\n' "$nft_table" | grep -Ec 'comment "{FABRIC_OWNER_MARKER}:[0-9a-f]{64}"' || true) + nft_digest_count=$(printf '%s\\n' "$nft_table" | grep -Foc "comment \"{FABRIC_OWNER_MARKER}:$config_digest\"" || true) + nft_chain_count=$(printf '%s\\n' "$nft_table" | grep -Ec '^[[:space:]]*chain [A-Za-z0-9_.-]+ \\{{' || true) + nft_named_chain_count=$(printf '%s\\n' "$nft_table" | grep -Ec '^[[:space:]]*chain (input|output|forward) \\{{' || true) + nft_rule_count=$(printf '%s\\n' "$nft_table" | grep -Ec '^[[:space:]]+(iifname|oifname) "wg-fabric0".* (accept|drop)( |$)' || true) + nft_bad_actions=$(printf '%s\\n' "$nft_table" | grep -Eci '^[[:space:]]+(iifname|oifname).* (reject|masquerade|snat|dnat|redirect|jump|goto|queue|tproxy|dup|log|limit|notrack|meter)( |$)' || true) + printf '%s\\n' "$nft_table" | grep -Fq 'iifname "wg-fabric0" ip protocol icmp accept' || nft_owner_count=0 + printf '%s\\n' "$nft_table" | grep -Fq 'oifname "wg-fabric0" ip protocol icmp accept' || nft_owner_count=0 + printf '%s\\n' "$nft_table" | grep -Fq 'set vpc_tenant_ips' || nft_owner_count=0 + printf '%s\\n' "$nft_table" | grep -Eq 'iifname "wg-fabric0".*counter drop' || nft_owner_count=0 + printf '%s\\n' "$nft_table" | grep -Eq 'oifname "wg-fabric0".*counter drop' || nft_owner_count=0 + [ "$nft_owner_count" = 8 ] && [ "$nft_digest_count" = 8 ] && [ "$nft_rule_count" = 8 ] && + [ "$nft_chain_count" = 3 ] && [ "$nft_named_chain_count" = 3 ] && + [ "$nft_bad_actions" = 0 ] && nft_guard=owned fi fi printf '%s\\n' "__VC_FABRIC_ENABLED__=$enabled" @@ -1601,6 +3254,7 @@ printf '%s\\n' "__VC_FABRIC_ACTIVE__=$active" printf '%s\\n' "__VC_FABRIC_TIMER_ENABLED__=$timer_enabled" printf '%s\\n' "__VC_FABRIC_TIMER_ACTIVE__=$timer_active" printf '%s\\n' "__VC_FABRIC_NFT_GUARD__=$nft_guard" +printf '%s\\n' "__VC_FABRIC_NFT_PERSISTENCE__=$nft_persistence" printf '%s\\n' "__VC_FABRIC_KEY_SECURE__=$key_secure" printf '%s\\n' "__VC_FABRIC_CONFIG_SECURE__=$(if [ "$config_size_ok" = yes ] && [ "$($STAT -c '%u' "$CONF" 2>/dev/null)" = 0 ] && [ "$($STAT -c '%a' "$CONF" 2>/dev/null)" = 600 ]; then printf yes; else printf no; fi)" printf '%s\\n' "__VC_FABRIC_HELPER__=$helper_marker" @@ -1617,8 +3271,11 @@ def _parse_markers(output: str) -> dict[str, Any]: result: dict[str, Any] = { "addresses": [], "peers": [], "routes": [], "paths": [], "config_peers": [], "config_routes": [], "endpoint_paths": [], - "pings": [], - "handshakes": {} + "pings": [], "route_overlaps": [], + "handshakes": {}, "sysctls": {}, "rp_filters": {}, + "vpc_state": "missing", "vpc_tenants": [], + "vpc_tenant_ips": [], + "vpc_nft_state": "missing", "vpc_nft_ips": [], } for line in output.splitlines(): if len(line) > MAX_MARKER_LINE: @@ -1672,6 +3329,26 @@ def _parse_markers(output: str) -> dict[str, Any]: # Keep compatibility with an older helper during an # in-place upgrade; new helpers always include table/device. result["routes"].append((fields[0], "main", FABRIC_INTERFACE)) + elif line.startswith("__VC_FABRIC_VPC_STATE__="): + value = line.split("=", 1)[1] + if value in {"empty", "owned", "invalid"}: + result["vpc_state"] = value + elif line.startswith("__VC_FABRIC_VPC_TENANT__="): + fields = line.split("=", 1)[1].split("|") + if len(fields) == 2 and all(fields): + result["vpc_tenants"].append(tuple(fields)) + elif line.startswith("__VC_FABRIC_VPC_TENANT_IP__="): + value = line.split("=", 1)[1] + if value: + result["vpc_tenant_ips"].append(value) + elif line.startswith("__VC_FABRIC_VPC_NFT_STATE__="): + value = line.split("=", 1)[1] + if value in {"owned", "missing", "invalid"}: + result["vpc_nft_state"] = value + elif line.startswith("__VC_FABRIC_VPC_NFT_IP__="): + value = line.split("=", 1)[1] + if value: + result["vpc_nft_ips"].append(value) elif line.startswith("__VC_FABRIC_PATH__="): fields = line.split("=", 1)[1].split("|") if len(fields) == 2 and all(fields): @@ -1684,12 +3361,32 @@ def _parse_markers(output: str) -> dict[str, Any]: fields = line.split("=", 1)[1].split("|") if len(fields) == 2 and all(fields): result["pings"].append(tuple(fields)) + elif line.startswith("__VC_FABRIC_ROUTE_OVERLAP__="): + fields = line.split("=", 1)[1].split("|") + if len(fields) == 2 and all(fields): + result["route_overlaps"].append(tuple(fields)) elif line.startswith("__VC_FABRIC_MANAGER_MODE__="): result["manager_mode"] = line.split("=", 1)[1] elif line.startswith("__VC_FABRIC_MANAGER_OWNER__="): result["manager_owner"] = line.split("=", 1)[1] elif line.startswith("__VC_FABRIC_MANAGER_ACTIVE__="): result["manager_active"] = line.split("=", 1)[1] + elif line.startswith("__VC_FABRIC_ADMIN_STATE__="): + value = line.split("=", 1)[1] + if value in {"up", "down", "missing", "unknown"}: + result["admin_state"] = value + elif line.startswith("__VC_FABRIC_SYSCTL__"): + fields = line[len("__VC_FABRIC_SYSCTL__"):].split("=", 1) + if (len(fields) == 2 + and fields[0] in {"ip_forward", "rp_filter", + "rp_filter_default"} + and fields[1] in {"0", "1", "2", "unknown"}): + result["sysctls"][fields[0]] = fields[1] + elif line.startswith("__VC_FABRIC_RPF__"): + fields = line[len("__VC_FABRIC_RPF__"):].split("=", 1) + if (len(fields) == 2 and fields[0] == FABRIC_INTERFACE + and fields[1] in {"0", "1", "2", "unknown"}): + result["rp_filters"][fields[0]] = fields[1] elif line.startswith("__VC_FABRIC_ENABLED__="): result["enabled"] = line.split("=", 1)[1] elif line.startswith("__VC_FABRIC_ACTIVE__="): @@ -1700,6 +3397,8 @@ def _parse_markers(output: str) -> dict[str, Any]: result["timer_active"] = line.split("=", 1)[1] elif line.startswith("__VC_FABRIC_NFT_GUARD__="): result["nft_guard"] = line.split("=", 1)[1] + elif line.startswith("__VC_FABRIC_NFT_PERSISTENCE__="): + result["nft_persistence"] = line.split("=", 1)[1] elif line.startswith("__VC_FABRIC_KEY_SECURE__="): result["key_secure"] = line.split("=", 1)[1] elif line.startswith("__VC_FABRIC_CONFIG_SECURE__="): @@ -1718,9 +3417,13 @@ def _parse_markers(output: str) -> dict[str, Any]: or len(result["paths"]) > MAX_FABRIC_NODES or len(result["endpoint_paths"]) > MAX_FABRIC_NODES or len(result["pings"]) > MAX_FABRIC_NODES + or len(result["route_overlaps"]) > MAX_FABRIC_NODES or len(result["config_peers"]) > MAX_FABRIC_NODES or len(result["config_routes"]) > MAX_FABRIC_NODES - or len(result["handshakes"]) > MAX_FABRIC_NODES): + or len(result["handshakes"]) > MAX_FABRIC_NODES + or len(result["vpc_tenants"]) > MAX_FABRIC_NODES * 256 + or len(result["vpc_tenant_ips"]) > MAX_FABRIC_NODES * 4096 + or len(result["vpc_nft_ips"]) > MAX_FABRIC_NODES * 256): raise FabricError( "宿主机 Fabric 标记数量异常", 502, "fabric_readback_invalid") @@ -1798,9 +3501,14 @@ class FabricHostAdapter: mode = self._deployment_mode() ifup_path = _profile_ifup_path( self.profile if self.profile is not None else self.manager.current()) + ifquery_path = _profile_ifquery_path( + self.profile if self.profile is not None else self.manager.current()) + ifdown_path = _profile_ifdown_path( + self.profile if self.profile is not None else self.manager.current()) output = self._run(_apply_script( plan, host, public_keys, deployment_mode=mode, - ifup_path=ifup_path)) + ifup_path=ifup_path, ifquery_path=ifquery_path, + ifdown_path=ifdown_path)) if "__VC_FABRIC_APPLIED__" not in output: raise FabricError( "宿主机未确认 Fabric 应用", 502, @@ -1817,7 +3525,8 @@ class FabricHostAdapter: mode = self._deployment_mode() parsed = _parse_markers(self._run(_observe_script( targets, host.overlay_ip, endpoint_ips, mode, - _fabric_connection_uuid(plan, host)))) + _fabric_connection_uuid(plan, host), host.host_id, plan.fabric_id, + plan.overlay_cidr))) expected_peers = { (public_keys[peer.host_id], peer.endpoint, peer.allowed_ip) for peer in plan.nodes if peer.host_id != host.host_id @@ -1826,7 +3535,124 @@ class FabricHostAdapter: expected_config_routes = { peer.allowed_ip for peer in plan.nodes if peer.host_id != host.host_id } + expected_key_to_peer = { + public_keys[peer.host_id]: peer + for peer in plan.nodes if peer.host_id != host.host_id + } + tenant_by_key: dict[str, set[str]] = {} + tenant_evidence_ok = parsed.get("vpc_state", "missing") in { + "missing", "empty", "owned" + } + tenant_seen: set[str] = set() + all_tenant_ips: set[str] = set() + for raw_tenant in parsed.get("vpc_tenants", []): + if (not isinstance(raw_tenant, (list, tuple)) + or len(raw_tenant) != 2): + tenant_evidence_ok = False + continue + tenant_key, tenant_ip = raw_tenant + try: + validate_wireguard_key(tenant_key) + tenant_addr = ipaddress.ip_interface(tenant_ip) + if tenant_addr.version != 4 or tenant_addr.network.prefixlen != 32: + raise ValueError("tenant prefix") + if not _is_rfc1918_address(tenant_addr.ip): + raise ValueError("tenant address") + if tenant_addr.ip in ipaddress.ip_network(plan.overlay_cidr): + raise ValueError("overlay overlap") + except (FabricError, ValueError, TypeError): + tenant_evidence_ok = False + continue + tenant_ip = f"{tenant_addr.ip}/32" + if tenant_ip in tenant_seen: + tenant_evidence_ok = False + continue + tenant_seen.add(tenant_ip) + all_tenant_ips.add(tenant_ip) + # The state directory is host-wide and may contain VPCs attached + # to another Fabric. Their valid tenant records are retained for + # the nft set comparison, but are not allowed to authorize an + # AllowedIPs extra for this plan's peers. + if tenant_key not in expected_key_to_peer: + continue + tenant_by_key.setdefault(tenant_key, set()).add(tenant_ip) + # Route records cover every member and service /32 on this host, + # including local destinations that cannot appear in a peer's + # AllowedIPs list. The Fabric quarantine set must contain this full + # address universe so its bidirectional anti-spoof rules do not drop + # a valid remote-to-local service flow. + tenant_address_evidence_ok = True + address_seen: set[str] = set() + for raw_tenant_ip in parsed.get("vpc_tenant_ips", []): + try: + tenant_addr = ipaddress.ip_interface(raw_tenant_ip) + if (tenant_addr.version != 4 + or tenant_addr.network.prefixlen != 32 + or not _is_rfc1918_address(tenant_addr.ip) + or tenant_addr.ip in ipaddress.ip_network(plan.overlay_cidr)): + raise ValueError("tenant address") + except (ValueError, TypeError): + tenant_address_evidence_ok = False + continue + tenant_ip = f"{tenant_addr.ip}/32" + if tenant_ip in address_seen: + tenant_address_evidence_ok = False + continue + address_seen.add(tenant_ip) + all_tenant_ips.add(tenant_ip) + tenant_evidence_ok = tenant_evidence_ok and tenant_address_evidence_ok + nft_evidence_ok = parsed.get("vpc_nft_state") == "owned" + nft_tenant_ips: set[str] = set() + for raw_nft_ip in parsed.get("vpc_nft_ips", []): + try: + nft_addr = ipaddress.ip_interface(raw_nft_ip) + if (nft_addr.version != 4 + or nft_addr.network.prefixlen != 32 + or not _is_rfc1918_address(nft_addr.ip) + or nft_addr.ip in ipaddress.ip_network(plan.overlay_cidr)): + raise ValueError("nft tenant prefix") + except (ValueError, TypeError): + nft_evidence_ok = False + continue + nft_ip = f"{nft_addr.ip}/32" + if nft_ip in nft_tenant_ips: + nft_evidence_ok = False + continue + nft_tenant_ips.add(nft_ip) + nft_tenant_exact = nft_evidence_ok and nft_tenant_ips == all_tenant_ips actual_peers = set(tuple(item) for item in parsed.get("peers", [])) + overlay_peers: set[tuple[str, str, str]] = set() + peer_allowed_exact = True + for raw_peer in actual_peers: + if len(raw_peer) != 3: + peer_allowed_exact = False + continue + peer_key, peer_endpoint, raw_allowed = raw_peer + expected_peer = expected_key_to_peer.get(peer_key) + if expected_peer is None or peer_endpoint != expected_peer.endpoint: + peer_allowed_exact = False + continue + allowed_items = [item for item in raw_allowed.split(",") if item] + expected_overlay = expected_peer.allowed_ip + if allowed_items.count(expected_overlay) != 1: + peer_allowed_exact = False + extras = set(allowed_items) - {expected_overlay} + if len(allowed_items) != len(set(allowed_items)): + peer_allowed_exact = False + try: + for extra in extras: + extra_addr = ipaddress.ip_interface(extra) + if (extra_addr.version != 4 + or extra_addr.network.prefixlen != 32 + or not _is_rfc1918_address(extra_addr.ip) + or extra_addr.ip in ipaddress.ip_network(plan.overlay_cidr)): + raise ValueError("invalid tenant prefix") + except (ValueError, TypeError): + peer_allowed_exact = False + if extras != tenant_by_key.get(peer_key, set()): + peer_allowed_exact = False + overlay_peers.add((peer_key, peer_endpoint, expected_overlay)) + peer_allowed_exact = peer_allowed_exact and tenant_evidence_ok actual_config_peers = { tuple(item) for item in parsed.get("config_peers", []) if isinstance(item, (list, tuple)) and len(item) == 3 @@ -1840,9 +3666,14 @@ class FabricHostAdapter: tuple(route) for route in parsed.get("routes", []) if isinstance(route, (list, tuple)) and len(route) == 3 and not (route[0] in local_route_forms - and route[1] in {"main", "local"} + and route[1] in {"main", "local", "254", "255"} and route[2] == FABRIC_INTERFACE) } + actual_routes = { + (route[0], "main" if route[1] == "254" else + "local" if route[1] == "255" else route[1], route[2]) + for route in actual_routes + } expected_addresses = {host.overlay_ip} actual_addresses = set(parsed.get("addresses", [])) expected_routes = { @@ -1877,6 +3708,24 @@ class FabricHostAdapter: tuple(ping) for ping in parsed.get("pings", []) if isinstance(ping, (list, tuple)) and len(ping) == 2 } + expected_route_overlaps = { + (peer.overlay_ip, "clean") + for peer in plan.nodes if peer.host_id != host.host_id + } + actual_route_overlaps = { + tuple(item) for item in parsed.get("route_overlaps", []) + if isinstance(item, (list, tuple)) and len(item) == 2 + } + observed_sysctls = parsed.get("sysctls", {}) + observed_rp_filters = parsed.get("rp_filters", {}) + sysctl_ok = ( + isinstance(observed_sysctls, Mapping) + and observed_sysctls.get("ip_forward") == "1" + and observed_sysctls.get("rp_filter") in {"0", "2"} + and observed_sysctls.get("rp_filter_default") in {"0", "2"} + and isinstance(observed_rp_filters, Mapping) + and observed_rp_filters.get(FABRIC_INTERFACE) in {"0", "2"} + ) config_ok = ( parsed.get("owner") == FABRIC_OWNER_MARKER and parsed.get("config_fabric") == plan.fabric_id @@ -1889,18 +3738,27 @@ class FabricHostAdapter: and parsed.get("public_key") == public_keys[host.host_id] and str(parsed.get("listen_port", "")) == str(host.listen_port) and actual_addresses == expected_addresses - and actual_peers == expected_peers + and overlay_peers == expected_peers + and peer_allowed_exact + and nft_tenant_exact and actual_config_peers == expected_config_peers and actual_config_routes == expected_config_routes and actual_routes == expected_routes and actual_paths == expected_paths and endpoint_paths_ok and actual_pings == expected_pings + and actual_route_overlaps == expected_route_overlaps and parsed.get("enabled") == "enabled" - and parsed.get("service_active") == "active" + # The apply transaction performs the live readback itself and + # deliberately does not start the same lock-taking oneshot while + # holding the host lock. ``inactive`` is therefore valid when + # the enabled service and repair timer are intact; ``failed`` and + # unknown states remain degraded. + and parsed.get("service_active") in {"active", "inactive"} and parsed.get("timer_enabled") == "enabled" and parsed.get("timer_active") == "active" and parsed.get("nft_guard") == "owned" + and parsed.get("nft_persistence") == "owned" and parsed.get("key_secure") == "yes" and parsed.get("config_secure") == "yes" and parsed.get("helper_marker") == "owned" @@ -1910,6 +3768,11 @@ class FabricHostAdapter: and parsed.get("manager_mode") == mode and parsed.get("manager_owner") == "owned" and parsed.get("manager_active") == "active" + # A successful apply is not enough when an operator later brings + # the interface down or changes forwarding/rp_filter. Require a + # fresh kernel readback before exposing the Fabric as active. + and parsed.get("admin_state") == "up" + and sysctl_ok ) now = int(time.time()) handshakes: dict[str, int] = {} @@ -1940,6 +3803,18 @@ class FabricHostAdapter: "listen_port": parsed.get("listen_port"), "addresses": sorted(actual_addresses), "peers": sorted(actual_peers), + "overlay_peers": sorted(overlay_peers), + "peer_allowed_exact": peer_allowed_exact, + "vpc_state": parsed.get("vpc_state"), + "vpc_tenants": sorted( + "|".join(item) for item in parsed.get("vpc_tenants", []) + if isinstance(item, (list, tuple)) and len(item) == 2), + "vpc_tenant_ips": sorted( + item for item in parsed.get("vpc_tenant_ips", []) + if isinstance(item, str)), + "vpc_nft_state": parsed.get("vpc_nft_state"), + "vpc_nft_ips": sorted(nft_tenant_ips), + "vpc_nft_exact": nft_tenant_exact, "config_peers": sorted(actual_config_peers), "config_routes": sorted(actual_config_routes), "routes": sorted("|".join(route) for route in actual_routes), @@ -1947,11 +3822,14 @@ class FabricHostAdapter: "endpoint_paths": sorted( "|".join(path) for path in actual_endpoint_paths), "pings": sorted("|".join(ping) for ping in actual_pings), + "route_overlaps": sorted( + "|".join(item) for item in actual_route_overlaps), "enabled": parsed.get("enabled"), "service_active": parsed.get("service_active"), "timer_enabled": parsed.get("timer_enabled"), "timer_active": parsed.get("timer_active"), "nft_guard": parsed.get("nft_guard"), + "nft_persistence": parsed.get("nft_persistence"), "key_secure": parsed.get("key_secure"), "config_secure": parsed.get("config_secure"), "helper_marker": parsed.get("helper_marker"), @@ -1961,6 +3839,11 @@ class FabricHostAdapter: "manager_mode": parsed.get("manager_mode"), "manager_owner": parsed.get("manager_owner"), "manager_active": parsed.get("manager_active"), + "admin_state": parsed.get("admin_state"), + "sysctls": dict(observed_sysctls) + if isinstance(observed_sysctls, Mapping) else {}, + "rp_filters": dict(observed_rp_filters) + if isinstance(observed_rp_filters, Mapping) else {}, "handshakes": handshakes, }, } @@ -2049,20 +3932,33 @@ class FabricCoordinator: "listen_port", "enabled", "service_active", "timer_enabled", "timer_active", "nft_guard", "key_secure", - "config_secure", "helper_marker", "unit_marker", + "nft_persistence", "config_secure", "helper_marker", "unit_marker", "repair_marker", "timer_marker", "manager_mode", - "manager_owner", "manager_active"): + "manager_owner", "manager_active", "admin_state", + "vpc_state", "peer_allowed_exact", + "vpc_nft_state", "vpc_nft_exact"): if key in observed: safe_observed[key] = observed[key] for key in ( "addresses", "routes", "paths", "pings", - "endpoint_paths", "config_routes"): + "endpoint_paths", "config_routes", "route_overlaps", + "vpc_tenants", "vpc_nft_ips"): items = observed.get(key) if isinstance(items, list): safe_observed[key] = [ item for item in items if isinstance(item, str) and len(item) <= 128 ] + for key in ("sysctls", "rp_filters"): + values = observed.get(key) + if isinstance(values, Mapping): + safe_observed[key] = { + str(name): str(value) + for name, value in values.items() + if isinstance(name, str) + and len(name) <= 64 + and str(value) in {"0", "1", "2", "unknown"} + } config_peers = observed.get("config_peers") if isinstance(config_peers, list): safe_observed["config_peers"] = [ @@ -2091,6 +3987,15 @@ class FabricCoordinator: and all(isinstance(part, str) and len(part) <= 128 for part in item) ] + overlay_peers = observed.get("overlay_peers") + if isinstance(overlay_peers, list): + safe_observed["overlay_peers"] = [ + list(item) for item in overlay_peers + if isinstance(item, (list, tuple)) + and len(item) == 3 + and all(isinstance(part, str) and len(part) <= 128 + for part in item) + ] handshakes = observed.get("handshakes") if isinstance(handshakes, Mapping): safe_observed["handshakes"] = { @@ -2158,8 +4063,29 @@ class FabricCoordinator: raise FabricError( "Fabric 宿主机组件不存在", 503, "fabric_host_unavailable") - profile = await asyncio.to_thread(component.manager.current) - if not profile: + # A capability snapshot is only an enrollment hint. Services, + # firewall ownership, links and sysctls can change while a host + # remains configured, so every Fabric operation must perform a + # fresh read-only probe through the pinned SSH generation. + reprobe_snapshot = getattr( + component.manager, "reprobe_current_snapshot", None) + reprobe = getattr(component.manager, "reprobe_current", None) + if not callable(reprobe_snapshot) and not callable(reprobe): + raise FabricError( + "宿主机不支持能力重新探测", + 503, "fabric_host_capability_probe_unsupported") + try: + if callable(reprobe_snapshot): + profile, capabilities = await asyncio.to_thread( + reprobe_snapshot) + else: + profile = await asyncio.to_thread(component.manager.current) + capabilities = await asyncio.to_thread(reprobe) + except RemoteHostError as exc: + raise FabricError( + "宿主机能力重新探测失败", + 502, "fabric_host_capability_probe_failed") from exc + if not isinstance(profile, Mapping) or not profile: raise FabricError( "Fabric 宿主机尚未配置", 409, "fabric_host_not_configured") @@ -2167,7 +4093,12 @@ class FabricCoordinator: raise FabricError( "宿主机稳定标识与 Fabric 节点不一致", 409, "fabric_host_identity_mismatch") - capabilities = profile.get("capabilities") + if not isinstance(capabilities, Mapping): + raise FabricError( + "宿主机能力重新探测结果无效", + 502, "fabric_host_capability_probe_invalid") + live_profile = dict(profile) + live_profile["capabilities"] = dict(capabilities) if (not isinstance(capabilities, Mapping) or capabilities.get("vpc_ready") is not True): raise FabricError( @@ -2198,7 +4129,7 @@ class FabricCoordinator: raise FabricError( "Fabric 参与宿主机必须属于同一地区", 409, "fabric_region_mismatch") - components[node.host_id] = (component, dict(profile)) + components[node.host_id] = (component, live_profile) return components async def apply(self, value: Mapping[str, Any]) -> dict[str, Any]: diff --git a/engine/virsh_panel/internal.py b/engine/virsh_panel/internal.py index df7ecfbe..1a14d102 100644 --- a/engine/virsh_panel/internal.py +++ b/engine/virsh_panel/internal.py @@ -362,7 +362,7 @@ class EngineApplication: # VPC desired state has an independent model and per-VPC locks. It is # deliberately separate from FabricCoordinator and the public # VM/network_change operation state machine. - self.vpc = VpcCoordinator(store, self.fabric) + self.vpc = VpcCoordinator(store, self.fabric, self.registry) self.introspection = introspection project_dir = Path(config.get("project_dir", Path(__file__).resolve().parents[2])) self.updater = updater or Updater( @@ -3342,9 +3342,9 @@ class EngineApplication: await asyncio.to_thread(self.fabric.recover) self.fabric_reconcile_task = asyncio.create_task( self.fabric.reconcile_loop()) - # At this phase VPC reconciliation only refreshes the - # Fabric gate and durable observed state. It has no - # private NIC, route or nftables side effects. + # VPC reconciliation applies the private data plane only + # after the Fabric gate is active, and records durable + # observed state for the all-host lifecycle gate. await asyncio.to_thread(self.vpc.recover) self.vpc_reconcile_task = asyncio.create_task( self.vpc.reconcile_loop()) diff --git a/engine/virsh_panel/libvirt_service.py b/engine/virsh_panel/libvirt_service.py index 9675ab08..37d717d5 100644 --- a/engine/virsh_panel/libvirt_service.py +++ b/engine/virsh_panel/libvirt_service.py @@ -22,14 +22,15 @@ import xml.etree.ElementTree as ET from contextlib import contextmanager from datetime import datetime, timezone from pathlib import Path -from typing import Any, Callable, Iterator +from typing import Any, Callable, Iterator, Sequence import libvirt from virsh_panel.cloud_init import ( _validate_guest_auth, _validate_ssh_public_key, build_seed_iso, default_guest_hostname, read_seed_network, - replace_seed_network, replace_seed_settings, validate_cloud_network, + replace_seed_network, replace_seed_private_network, replace_seed_settings, + validate_cloud_network, validate_private_network, validate_guest_hostname, ) @@ -1485,6 +1486,379 @@ class VMService: root = self._vm_xml(domain) return observe_private_state(root, vm_uuid=domain.UUIDString()) + def read_private_domain_xml(self, uuid: str) -> str: + """Return the persistent domain XML used by the VPC readback lane. + + The VPC coordinator must compare the definition that will be used on + the next boot, rather than trusting a live QEMU XML response that can + lag a config-only update. A persistent domain is required; callers + that need the live definition can use ``read_private_domain_pair``. + """ + vm_uuid = self._uuid(uuid) + with self._connect() as conn: + domain = self._domain(conn, vm_uuid) + if not domain.isPersistent(): + raise VMError("VPC 私网网卡只能接入持久化虚拟机", 409, + error_code="vpc_vm_not_persistent") + return domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) + + def read_private_domain_pair(self, uuid: str) -> dict[str, str | None]: + """Read persistent and live XML for an exact private NIC proof.""" + vm_uuid = self._uuid(uuid) + with self._connect() as conn: + domain = self._domain(conn, vm_uuid) + if not domain.isPersistent(): + raise VMError("VPC 私网网卡只能接入持久化虚拟机", 409, + error_code="vpc_vm_not_persistent") + inactive = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) + live = domain.XMLDesc(0) if domain.isActive() else None + return {"inactive": inactive, "live": live} + + @staticmethod + def _private_interface_from_root(root: ET.Element) -> ET.Element | None: + try: + return select_private_interface(root.findall("./devices/interface")) + except ValueError as exc: + raise VMError("虚拟机网卡角色不明确,已停止私网接入", 409, + error_code="vpc_private_xml_role_invalid") from exc + + def ensure_private_interface( + self, + vm_id: str, + *, + member: Any, + resources: Any, + vpc_id: str, + desired_revision: int, + desired_digest: str, + private_routes: Sequence[str] | None = None, + ) -> dict[str, Any]: + """Attach one panel-owned ``private0`` NIC and refresh its seed. + + The operation is intentionally a single libvirt/seed transaction. A + running domain uses ``attach/updateDeviceFlags`` for live and config + state; a stopped domain is updated through ``defineXML``. On any + confirmed failure the original XML and seed are restored. If a live + libvirt response is lost, the method raises an ``uncertain`` error and + leaves reconciliation to the VPC readback lane instead of guessing. + """ + from .vpc_dataplane import VpcDataplaneError, patch_private_interface_xml + + vm_uuid = self._uuid(vm_id) + if not isinstance(vpc_id, str) or not vpc_id: + raise VMError("VPC 标识无效", 422, error_code="vpc_invalid") + if (isinstance(desired_revision, bool) + or not isinstance(desired_revision, int) + or desired_revision < 1): + raise VMError("VPC revision 无效", 422, error_code="vpc_invalid") + if (not isinstance(desired_digest, str) + or not re.fullmatch(r"[0-9a-f]{64}", desired_digest)): + raise VMError("VPC 摘要无效", 422, error_code="vpc_invalid") + + with _CREATE_LOCK, self._connect() as conn: + domain = self._domain(conn, vm_uuid) + if not domain.isPersistent(): + raise VMError("VPC 私网网卡只能接入持久化虚拟机", 409, + error_code="vpc_vm_not_persistent") + if getattr(domain, "hasManagedSaveImage", lambda _flags: 0)(0): + raise VMError("虚拟机存在托管保存状态,请先处理后再接入私网", 409, + error_code="vpc_vm_managed_save_present") + try: + if int(getattr(domain, "snapshotNum", lambda _flags: 0)(0)) > 0: + raise VMError("虚拟机存在原生快照,请先处理后再接入私网", 409, + error_code="vpc_vm_native_snapshot_present") + except (TypeError, ValueError) as exc: + raise VMError("无法确认虚拟机原生快照状态", 502, + error_code="vpc_vm_native_snapshot_state_unknown") from exc + + old_inactive_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) + old_root = ET.fromstring(old_inactive_xml) + private_before = self._private_interface_from_root(old_root) + # A NIC owned by another VPC is never replaced implicitly. This + # also prevents a stale desired revision from hijacking a tenant + # interface after a VPC membership move. + if private_before is not None: + metadata = old_root.find(f"./metadata/{{{PANEL_NS}}}managed") + owner_vpc = metadata.get("private-vpc-id") if metadata is not None else None + if owner_vpc not in (None, vpc_id): + raise VMError("虚拟机 private0 已属于另一 VPC", 409, + error_code="vpc_private_interface_conflict") + + try: + new_xml = patch_private_interface_xml( + old_inactive_xml, member=member, resources=resources, + vpc_id=vpc_id, desired_revision=desired_revision, + desired_digest=desired_digest) + except VpcDataplaneError as exc: + raise VMError(str(exc), exc.status, exc.error_code) from exc + new_root = ET.fromstring(new_xml) + target_private = self._private_interface_from_root(new_root) + if target_private is None: + raise VMError("无法生成 private0 网卡", 502, + error_code="vpc_private_xml_invalid") + + was_running = bool(domain.isActive()) + live_mutator = None + if was_running: + live_mutator = (getattr(domain, "attachDeviceFlags", None) + if private_before is None + else getattr(domain, "updateDeviceFlags", None)) + if not callable(live_mutator): + raise VMError( + "运行中的虚拟机不支持安全添加或更新 private0", 409, + error_code="vpc_private_live_unsupported") + + seed = self._owned_seed_volume(conn, domain) + if seed is None: + raise VMError("找不到 cloud-init 配置盘,无法接入私网", 409, + error_code="vpc_seed_missing") + old_seed = self._download_seed_volume(conn, seed) + try: + seed_network = read_seed_network(old_seed) + except (ImportError, ValueError) as exc: + raise VMError("原 cloud-init 配置盘格式无效,无法接入私网", 409, + error_code="vpc_seed_invalid") from exc + public = select_public_interface(old_root.findall("./devices/interface")) + public_mac = public.find("mac") if public is not None else None + managed = old_root.find(f"./metadata/{{{PANEL_NS}}}managed") + public_ip = managed.get("public-ip-cidr") if managed is not None else None + if (public_mac is None or not public_mac.get("address") + or seed_network.get("mac") != public_mac.get("address", "").lower() + or (public_ip and seed_network.get("public_ip_cidr") != public_ip)): + raise VMError("虚拟机公网 XML 与 cloud-init 配置盘不一致", 409, + error_code="vpc_seed_network_mismatch") + private_mac = target_private.find("mac") + private_ip_node = new_root.find(f"./metadata/{{{PANEL_NS}}}managed") + private_ip = (private_ip_node.get("private-ip-cidr") + if private_ip_node is not None else None) + if private_mac is None or not private_ip: + raise VMError("私网网卡身份不完整", 502, + error_code="vpc_private_xml_invalid") + try: + replacement_seed = replace_seed_private_network( + old_seed, private_mac=private_mac.get("address"), + private_ip_cidr=private_ip, + private_routes=list(private_routes or ())) + seed_check = read_seed_network(replacement_seed) + expected_seed_routes = sorted(set(private_routes or ())) + if sorted(seed_check.get("private_routes", [])) != expected_seed_routes: + raise VMError("私网 cloud-init 路由回读不一致", 502, + error_code="vpc_seed_route_readback_mismatch") + except (ImportError, ValueError) as exc: + raise VMError("无法生成私网 cloud-init 配置", 409, + error_code="vpc_seed_update_failed") from exc + + switched_config = False + switched_live = False + seed_touched = False + config_attempted = False + live_attempted = False + result_uncertain = False + committed = False + try: + current_capacity = int(seed.info()[1]) + if len(replacement_seed) > current_capacity: + seed.resize(len(replacement_seed), 0) + # Mark the seed dirty before the stream starts. A transport + # error can occur after a partial write, so setting this only + # after _upload_volume returns would skip the rollback. + seed_touched = True + self._upload_volume(conn, seed, iter((replacement_seed,)), + len(replacement_seed)) + # Device APIs cannot update domain-level ownership metadata. + # Always persist the complete XML first, then alter only the + # live device when QEMU is running. + config_attempted = True + defined = conn.defineXML(new_xml) + if defined is None: + raise VMError("宿主机未能保存 private0 配置", 502, + error_code="vpc_private_define_failed") + switched_config = True + if was_running: + target_xml = ET.tostring(target_private, encoding="unicode") + live_attempted = True + live_mutator(target_xml, libvirt.VIR_DOMAIN_AFFECT_LIVE) + switched_live = True + + pair = self.read_private_domain_pair(vm_uuid) + inactive_after = ET.fromstring(pair["inactive"] or "") + observed_private = self._private_interface_from_root(inactive_after) + observed_meta = inactive_after.find(f"./metadata/{{{PANEL_NS}}}managed") + observed_mac = observed_private.find("mac") if observed_private is not None else None + if (observed_private is None or observed_mac is None + or observed_mac.get("address", "").lower() != private_mac.get("address", "").lower() + or observed_meta is None + or observed_meta.get("private-vpc-id") != vpc_id + or observed_meta.get("private-network-revision") != str(desired_revision) + or observed_meta.get("private-network-digest") != desired_digest): + raise VMError("private0 配置回读不一致", 502, + error_code="vpc_private_xml_readback_mismatch") + if was_running: + live_after = ET.fromstring(pair["live"] or "") + live_private = self._private_interface_from_root(live_after) + live_source = (live_private.find("source") + if live_private is not None else None) + live_mac = (live_private.find("mac") + if live_private is not None else None) + if (live_private is None or live_source is None + or live_source.get("bridge") != resources.bridge + or live_mac is None + or live_mac.get("address", "").lower() + != private_mac.get("address", "").lower() + or live_private.findall("filterref")): + raise VMError("private0 实时配置回读不一致", 502, + error_code="vpc_private_live_readback_mismatch") + committed = True + return {"xml": pair["inactive"], "live": pair["live"], + "seed_updated": True, "readback": "confirmed"} + except VMError as exc: + # Once a persistent definition or live device mutation has + # been attempted on a running domain, even a typed readback + # error cannot prove that the old state is still present. + # Keep the operation uncertain so the VPC reconciler performs + # a fresh pair read instead of reporting a plain apply error + # or issuing a speculative inverse live mutation. + if (was_running and (config_attempted or live_attempted) + and not result_uncertain): + result_uncertain = True + raise VMError( + "私网网卡应用结果不确定,请等待宿主机回读", 502, + error_code="vpc_private_result_uncertain") from exc + raise + except Exception as exc: + # A live libvirt response can be lost after the device was + # committed. Do not issue a speculative inverse operation in + # that case; the host adapter will mark the VPC uncertain. + if config_attempted or live_attempted: + result_uncertain = True + raise VMError("私网网卡应用结果不确定,请等待宿主机回读", 502, + error_code="vpc_private_result_uncertain") from exc + raise VMError("私网网卡应用失败", 502, + error_code="vpc_private_apply_failed") from exc + finally: + # For stopped domains, restore both XML and seed on a + # confirmed failure. Never overwrite a running domain after + # an uncertain live mutation. + # A seed upload performed before a failed define can still be + # restored safely while the old running domain is untouched. + # After a running XML/live mutation, leave the complete scene + # for readback and never guess an inverse operation. + rollback_xml_confirmed = not result_uncertain and not was_running + rollback_seed_confirmed = ( + not result_uncertain + and (not was_running or not config_attempted and not live_attempted) + ) + if seed_touched and not committed and (rollback_xml_confirmed or rollback_seed_confirmed): + try: + # If defineXML committed, restore the original + # persistent definition before restoring the seed. + if switched_config and rollback_xml_confirmed: + conn.defineXML(old_inactive_xml) + if rollback_seed_confirmed: + if len(old_seed) > int(seed.info()[1]): + seed.resize(len(old_seed), 0) + self._upload_volume(conn, seed, iter((old_seed,)), len(old_seed)) + except Exception: + LOG.exception("Could not restore VPC seed for %s", vm_uuid) + + def remove_private_interface( + self, vm_id: str, *, vpc_id: str, resources: Any, + desired_revision: int, desired_digest: str, + ) -> dict[str, Any]: + """Detach a private0 NIC only when its panel VPC ownership matches.""" + vm_uuid = self._uuid(vm_id) + with _CREATE_LOCK, self._connect() as conn: + domain = self._domain(conn, vm_uuid) + if not domain.isPersistent() or getattr(domain, "hasManagedSaveImage", lambda _flags: 0)(0): + raise VMError("虚拟机状态不允许移除 private0", 409, + error_code="vpc_private_remove_unsafe") + if int(getattr(domain, "snapshotNum", lambda _flags: 0)(0)) > 0: + raise VMError("虚拟机存在原生快照,无法移除 private0", 409, + error_code="vpc_private_remove_unsafe") + if domain.isActive(): + raise VMError("运行中的虚拟机需先停机再移除 private0", 409, + error_code="vpc_private_remove_requires_stopped") + old_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) + root = ET.fromstring(old_xml) + private = self._private_interface_from_root(root) + managed = root.find(f"./metadata/{{{PANEL_NS}}}managed") + if private is None: + return {"removed": True, "already_absent": True, + "xml": old_xml, "readback": "confirmed"} + if managed is None or managed.get("private-vpc-id") != vpc_id: + raise VMError("private0 不属于目标 VPC", 409, + error_code="vpc_private_interface_conflict") + devices = root.find("./devices") + if devices is None: + raise VMError("虚拟机 XML 缺少 devices", 409, + error_code="vpc_private_xml_invalid") + devices.remove(private) + # Clear only private ownership fields; public metadata remains. + for key in ("private-vpc-id", "private-member-id", "private-ip-cidr", + "private-network-bridge", "private-network-verified", + "private-dataplane-owner", "private-network-revision", + "private-network-digest"): + managed.attrib.pop(key, None) + seed = self._owned_seed_volume(conn, domain) + if seed is None: + raise VMError("找不到 cloud-init 配置盘,无法移除私网", 409, + error_code="vpc_seed_missing") + old_seed = self._download_seed_volume(conn, seed) + replacement = replace_seed_private_network( + old_seed, private_mac=None, private_ip_cidr=None) + define_attempted = False + defined = False + seed_touched = False + committed = False + try: + define_attempted = True + defined_domain = conn.defineXML(ET.tostring(root, encoding="unicode")) + if defined_domain is None: + raise VMError("宿主机未能移除 private0", 502, + error_code="vpc_private_remove_failed") + defined = True + if len(replacement) > int(seed.info()[1]): + seed.resize(len(replacement), 0) + seed_touched = True + self._upload_volume(conn, seed, iter((replacement,)), len(replacement)) + observed_xml = defined_domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) + observed_root = ET.fromstring(observed_xml) + if self._private_interface_from_root(observed_root) is not None: + raise VMError("private0 移除回读不一致", 502, + error_code="vpc_private_remove_readback_mismatch") + observed_seed = read_seed_network(self._download_seed_volume(conn, seed)) + if "private_ip_cidr" in observed_seed or "private_mac" in observed_seed: + raise VMError("私网配置盘移除回读不一致", 502, + error_code="vpc_seed_remove_readback_mismatch") + committed = True + return {"removed": True, "already_absent": False, + "xml": observed_xml, "readback": "confirmed"} + except VMError: + raise + except Exception as exc: + # A lost define/upload response must be reconciled from the + # host. Do not blindly re-attach a live or unknown device. + if define_attempted: + raise VMError("私网移除结果不确定,请等待宿主机回读", 502, + error_code="vpc_private_remove_uncertain") from exc + raise VMError("宿主机未能移除 private0", 502, + error_code="vpc_private_remove_failed") from exc + finally: + if not committed and defined: + try: + # The domain is stopped, so restoring the persistent + # XML and seed is a confirmed, safe inverse operation. + conn.defineXML(old_xml) + if seed_touched: + if len(old_seed) > int(seed.info()[1]): + seed.resize(len(old_seed), 0) + self._upload_volume(conn, seed, iter((old_seed,)), len(old_seed)) + except Exception as rollback_exc: + LOG.exception("Could not roll back VPC private removal for %s", vm_uuid) + raise VMError( + "私网移除回滚失败,请等待宿主机核对", 502, + error_code="vpc_private_remove_rollback_failed") from rollback_exc + def get_vm_state(self, uuid: str) -> dict[str, Any]: """Fetch one domain's power state without loading its XML metadata.""" with self._connect() as conn: diff --git a/engine/virsh_panel/remote_host.py b/engine/virsh_panel/remote_host.py index f619263b..630143f5 100644 --- a/engine/virsh_panel/remote_host.py +++ b/engine/virsh_panel/remote_host.py @@ -41,7 +41,7 @@ _IFACE_NAME = re.compile(r"[A-Za-z0-9_.:-]{1,15}\Z") PUBLIC_POOL_KEY = re.compile(r"[0-9a-f]{32}\Z") PUBLIC_POOL_STATES = frozenset({"active", "draining", "disabled"}) MAX_PUBLIC_NETWORK_POOLS = 32 -HOST_CAPABILITY_SCHEMA_VERSION = 1 +HOST_CAPABILITY_SCHEMA_VERSION = 2 WG_FABRIC_INTERFACE = "wg-fabric0" WG_FABRIC_OWNERSHIP_MARKER = "virt-cloud-wg-fabric-v1" _MAX_CAPABILITY_OUTPUT = 262144 @@ -185,6 +185,8 @@ probe_service_enabled() { probe_service_enabled network_manager NetworkManager probe_service_enabled networkd systemd-networkd probe_service_enabled networking networking +probe_service_enabled firewall firewalld +probe_service_enabled nftables nftables # ifupdown ownership is represented by bounded facts only. The contents of # interfaces files can include addresses, credentials, and arbitrary hooks; @@ -204,6 +206,15 @@ if test -d /etc/network/interfaces.d; then done fi printf "%s\n" "__VCAP_FILE__interfaces_d=$interfaces_d_configured" +interfaces_d_loaded=absent +if test -f /etc/network/interfaces && + /usr/bin/grep -Eq "^[[:space:]]*(source|source-directory)[[:space:]]+/etc/network/interfaces[.]d" /etc/network/interfaces 2>/dev/null; then + interfaces_d_loaded=present +elif test -f /etc/network/interfaces && + /bin/grep -Eq "^[[:space:]]*(source|source-directory)[[:space:]]+/etc/network/interfaces[.]d" /etc/network/interfaces 2>/dev/null; then + interfaces_d_loaded=present +fi +printf "%s\n" "__VCAP_FILE__interfaces_d_loaded=$interfaces_d_loaded" # A disabled manager can still take over on the next restart when it has # persistent profiles. Return presence markers only; profile contents may @@ -999,7 +1010,10 @@ def parse_host_capabilities( ) ifupdown_configured = ( files.get("interfaces") == "present" - or files.get("interfaces_d") == "present" + and ( + files.get("interfaces_d") != "present" + or files.get("interfaces_d_loaded") == "present" + ) ) ifupdown_service_ready = networking_active or networking_enabled # A configured interfaces file is ownership evidence even when the @@ -1064,9 +1078,16 @@ def parse_host_capabilities( else: network_deployment_mode = "unsupported" + firewalld_active = services.get("firewall") == "active" + nftables_active = services.get("nftables") == "active" + firewalld_enabled = service_enabled.get("firewall") in manager_enabled_states + nftables_enabled = service_enabled.get("nftables") in manager_enabled_states firewall_managers = { - "firewalld": services.get("firewall") == "active", - "nftables": services.get("nftables") == "active", + # An enabled-but-currently-inactive service can take ownership after + # a reboot. Treat it as ownership evidence so Fabric never installs + # nft rules beside a firewalld instance that will start later. + "firewalld": firewalld_active or firewalld_enabled, + "nftables": nftables_active or nftables_enabled, } active_firewall_managers = [name for name, active in firewall_managers.items() if active] if len(active_firewall_managers) == 1: @@ -1110,8 +1131,13 @@ def parse_host_capabilities( # and own a dedicated private ACL table, then read it back before marking # a VPC revision active. An unknown or unmanaged firewall is rejected so # that the private policy cannot silently drift into a different owner. - nft_ready = bool(tool_state["nft"]["available"] and nft_readable - and firewall_manager == "nftables") + nft_ready = bool( + tool_state["nft"]["available"] + and nft_readable + and firewall_manager == "nftables" + and nftables_active + and nftables_enabled + ) forwarding_ready = ip_forward == 1 selector = public_network if isinstance(public_network, str) else "" if selector.startswith("bridge:"): @@ -1177,6 +1203,10 @@ def parse_host_capabilities( reasons.append("nftables_probe_failed") if firewall_manager != "nftables": reasons.append("firewall_owner_not_nftables") + elif not nftables_active: + reasons.append("nftables_service_not_active") + elif not nftables_enabled: + reasons.append("nftables_service_not_enabled") if not forwarding_ready: reasons.append("ipv4_forwarding_disabled_or_unknown") if not rp_filter_ready: @@ -1206,6 +1236,9 @@ def parse_host_capabilities( reasons.append("ifupdown_tools_missing") if not ifupdown_configured: reasons.append("ifupdown_configuration_missing") + elif (files.get("interfaces_d") == "present" + and files.get("interfaces_d_loaded") != "present"): + reasons.append("ifupdown_interfaces_d_not_included") if not ifupdown_service_ready: reasons.append("ifupdown_service_not_active_or_enabled") elif network_manager not in {"ifupdown", "conflict", "unknown"}: @@ -1234,13 +1267,15 @@ def parse_host_capabilities( "capability_probe_invalid", "unsupported_host_os", "wireguard_tool_missing", "wireguard_kernel_unavailable", "iproute2_missing", "nftables_tool_missing", "nftables_probe_failed", "firewall_owner_not_nftables", + "nftables_service_not_active", "nftables_service_not_enabled", "iproute2_probe_failed", "flock_missing", "ipv4_forwarding_disabled_or_unknown", "rp_filter_not_compatible", "network_manager_conflict", "wireguard_fabric_interface_conflict", "network_manager_unknown", "network_manager_policy_mismatch", "systemd_networkd_not_supported", "networkmanager_nmcli_missing", "networkmanager_service_not_active", "networkmanager_service_not_enabled", - "ifupdown_tools_missing", "ifupdown_configuration_missing", + "ifupdown_tools_missing", "ifupdown_configuration_missing", + "ifupdown_interfaces_d_not_included", "ifupdown_service_not_active_or_enabled", )) vpc_ready = private_ready and public_verified @@ -1281,6 +1316,7 @@ def parse_host_capabilities( "ifupdown": { "interfaces_file": files.get("interfaces") == "present", "interfaces_d": files.get("interfaces_d") == "present", + "interfaces_d_loaded": files.get("interfaces_d_loaded") == "present", "configured": ifupdown_configured, "tools_available": ifupdown_tools_available, "service_active": networking_active, @@ -1292,6 +1328,12 @@ def parse_host_capabilities( }, "deployment_mode": network_deployment_mode, "firewall_manager": firewall_manager, + "firewall_manager_evidence": { + "firewalld_active": firewalld_active, + "firewalld_enabled": firewalld_enabled, + "nftables_active": nftables_active, + "nftables_enabled": nftables_enabled, + }, "ip_probe_valid": ip_probe_valid, "bridges": bridge_names, "interfaces": all_interfaces, @@ -1322,6 +1364,10 @@ def parse_host_capabilities( "tool_available": bool(tool_state["nft"]["available"]), "ruleset_readable": nft_readable, "owner": firewall_manager, + "service": services.get("nftables", "unknown"), + "service_enabled": service_enabled.get("nftables", "unknown"), + "service_active": nftables_active, + "service_persistent": nftables_enabled, "ready": nft_ready, }, "network_roles": { @@ -1882,6 +1928,86 @@ class RemoteHostManager: for agent in agents: agent.close() + def reprobe_current_snapshot(self) -> tuple[dict[str, Any], dict[str, Any]]: + """Return a fresh capability snapshot bound to one SSH generation. + + The profile and capability result are returned together while the + manager lock is held. Fabric can therefore not combine capabilities + from a newly committed generation with the SSH path of an older one. + The probe remains read-only and does not update the durable profile. + """ + with self._lock: + generation = self._current_generation() + if generation is None: + raise RemoteHostError( + "请先配置宿主机", + status=409, + error_code="host_not_configured", + ) + profile = self.current() + if profile is None: + raise RemoteHostError( + "请先配置宿主机", + status=409, + error_code="host_not_configured", + ) + if profile.get("key_locked"): + raise RemoteHostError( + "当前 SSH 私钥已锁定,请先解锁", + status=409, + error_code="host_private_key_locked", + ) + ssh_config = generation / "config" + try: + config_info = ssh_config.lstat() + except OSError as exc: + raise RemoteHostError( + "已保存的 SSH 配置损坏", status=500, + ) from exc + if (not stat.S_ISREG(config_info.st_mode) + or config_info.st_mode & 0o077): + raise RemoteHostError("已保存的 SSH 配置权限无效", status=500) + probe = self._exec( + [ + self.ssh_binary, + "-F", + str(ssh_config), + "-T", + "-o", + "ConnectTimeout=10", + SSH_ALIAS, + _CAPABILITY_PROBE_COMMAND, + ], + timeout=22, + ) + if probe.returncode != 0: + raise RemoteHostError( + "宿主机能力重新探测失败;请检查 SSH 连接和宿主机状态", + status=502, + error_code="host_capability_probe_failed", + ) + capabilities = parse_host_capabilities( + probe.stdout, + public_network=profile.get("default_network", ""), + ) + if not capabilities["probe_valid"]: + raise RemoteHostError( + "宿主机能力探针返回无效结果", + status=502, + error_code="host_capability_probe_invalid", + ) + return dict(profile), capabilities + + def reprobe_current_capabilities(self) -> dict[str, Any]: + """Read a fresh capability snapshot through the pinned generation.""" + _profile, capabilities = self.reprobe_current_snapshot() + return capabilities + + # Keep the shorter name available to Fabric callers while retaining the + # explicit name for other host-capability consumers. + def reprobe_current(self) -> dict[str, Any]: + return self.reprobe_current_capabilities() + def current(self) -> dict[str, Any] | None: generation = self._current_generation() if generation is None: diff --git a/engine/virsh_panel/vpc.py b/engine/virsh_panel/vpc.py index 7ba82d6b..39fa11d2 100644 --- a/engine/virsh_panel/vpc.py +++ b/engine/virsh_panel/vpc.py @@ -9,13 +9,14 @@ to the later data-plane phase. """ from __future__ import annotations +import asyncio import hashlib import ipaddress import json import re import time -from dataclasses import dataclass -from typing import Any, Mapping +from dataclasses import dataclass, replace +from typing import Any, Mapping, Sequence from .fabric import FabricError @@ -548,10 +549,19 @@ def parse_vpc_plan(value: Mapping[str, Any]) -> VpcPlan: _alias(raw, "destination_cidr", "destination", "VPC route destination"), "VPC route destination", min_prefix=network.prefixlen, max_prefix=32) - # A route may be an exact member /32; the future data-plane uses the - # same precision for WireGuard AllowedIPs and guest routes. + # The private data plane is an L3 /32 fabric. A wider route would + # become a cryptokey-routing and nftables bypass (and could overlap a + # different tenant), so reject it at the control-plane boundary rather + # than relying on the host adapter to catch it later. + if destination.prefixlen != 32: + raise VpcError("VPC route destination 必须是精确 /32", 409, + "vpc_route_not_exact") if not destination.subnet_of(network): raise VpcError("VPC route destination 必须是 VPC 内的网段") + if destination.network_address in { + network.network_address, network.broadcast_address}: + raise VpcError("VPC route destination 不能使用 VPC 保留地址", 409, + "vpc_route_reserved_address") member_target = raw.get("next_hop_member_id") host_target = raw.get("next_hop_host_id") if (member_target is None) == (host_target is None): @@ -674,7 +684,9 @@ def _plan_from_record(value: Mapping[str, Any]) -> VpcPlan: host_ids: list[str] = [] if isinstance(raw_host_rows, list): for host in raw_host_rows: - if isinstance(host, Mapping) and isinstance(host.get("host_id"), str): + if (isinstance(host, Mapping) + and host.get("retiring") is not True + and isinstance(host.get("host_id"), str)): host_ids.append(host["host_id"]) for host_id in members_by_host: if host_id not in host_ids: @@ -709,9 +721,13 @@ def _plan_from_record(value: Mapping[str, Any]) -> VpcPlan: class VpcCoordinator: """Durable desired/observed VPC state with an independent lock set.""" - def __init__(self, store: Any, fabric: Any): + def __init__(self, store: Any, fabric: Any, registry: Any | None = None): self.store = store self.fabric = fabric + # The registry is optional for pure control-plane/unit callers. The + # production EngineApplication supplies it so a VPC revision can only + # become active after host bridge/WireGuard/nft and libvirt readback. + self.registry = registry # Intentionally independent from FabricCoordinator._locks and from # the VM/public network mutation locks. self._locks: dict[str, Any] = {} @@ -814,11 +830,392 @@ class VpcCoordinator: "error_code": error_code, } + def _fabric_record(self, plan: VpcPlan) -> dict[str, Any]: + """Load and validate the durable Fabric identity used by the data plane.""" + loader = getattr(self.fabric, "_load", None) + raw = loader("fabric_desired", plan.fabric_id) if callable(loader) else None + if not isinstance(raw, Mapping): + raise VpcError("VPC Fabric 记录不可用", 409, + "vpc_fabric_record_unavailable") + try: + fabric_plan = self.fabric._plan_from_record(raw) + except Exception as exc: + raise VpcError("VPC Fabric 记录无效", 500, + "vpc_fabric_record_corrupt") from exc + if (fabric_plan.fabric_id != plan.fabric_id + or fabric_plan.region != plan.region + or fabric_plan.revision != plan.fabric_revision): + raise VpcError("VPC Fabric revision 或地区不匹配", 409, + "vpc_fabric_revision_mismatch") + return dict(raw) + + def _validate_dataplane_resources(self, plan: VpcPlan) -> None: + """Reject deterministic resource collisions before touching a host.""" + from .vpc_dataplane import resource_names + + current = resource_names(plan.vpc_id) + seen: dict[str, str] = {} + for field in ("bridge", "nft_table", "route_table"): + seen[str(getattr(current, field))] = plan.vpc_id + for priority in (current.rule_priority, current.rule_priority + 1): + seen[f"rule:{priority}"] = plan.vpc_id + for key, raw in self.store.list("vpc_desired").items(): + if key == plan.vpc_id: + continue + try: + other = _plan_from_record(json.loads(raw)) + except (TypeError, ValueError, VpcError) as exc: + raise VpcError("VPC 资源目录损坏", 500, + "vpc_record_corrupt") from exc + resources = resource_names(other.vpc_id) + for field in ("bridge", "nft_table", "route_table"): + marker = str(getattr(resources, field)) + owner = seen.get(marker) + if owner is not None and owner != other.vpc_id: + raise VpcError("VPC 数据面资源发生冲突", 409, + "vpc_dataplane_resource_conflict") + seen[marker] = other.vpc_id + for priority in (resources.rule_priority, resources.rule_priority + 1): + marker = f"rule:{priority}" + owner = seen.get(marker) + if owner is not None and owner != other.vpc_id: + raise VpcError("VPC 数据面资源发生冲突", 409, + "vpc_dataplane_resource_conflict") + seen[marker] = other.vpc_id + + def _fabric_peers_for_plan( + self, plan: VpcPlan, fabric_record: Mapping[str, Any], + ) -> list[dict[str, Any]]: + """Build per-peer overlay plus tenant /32 AllowedIPs. + + WireGuard has one AllowedIPs list per peer. Every VPC sharing a + Fabric therefore contributes only its exact member /32s to the peer + on the member's host. Duplicate addresses are rejected across VPCs + before a host command is rendered. + """ + from .vpc_dataplane import _key + + plans: list[VpcPlan] = [plan] + for key, raw in self.store.list("vpc_desired").items(): + if key == plan.vpc_id: + continue + try: + candidate = _plan_from_record(json.loads(raw)) + except (TypeError, ValueError, VpcError) as exc: + raise VpcError("VPC 资源目录损坏", 500, + "vpc_record_corrupt") from exc + if (candidate.fabric_id == plan.fabric_id + and candidate.region == plan.region): + plans.append(candidate) + address_owner: dict[str, str] = {} + tenant_by_host: dict[str, set[str]] = {} + for candidate in plans: + for member in candidate.members: + cidr = f"{member.private_ip}/32" + owner = address_owner.get(cidr) + if owner is not None and owner != candidate.vpc_id: + raise VpcError("VPC 私网地址跨 VPC 重复", 409, + "vpc_private_ip_conflict") + address_owner[cidr] = candidate.vpc_id + tenant_by_host.setdefault(member.host_id, set()).add(cidr) + # A custom service route is cryptokey-routed to the host that + # owns its next hop. It must be part of that peer's exact + # AllowedIPs set just like a VM /32; otherwise WireGuard sends it + # to no peer and the Fabric quarantine drops it. + members_by_id = {item.member_id: item for item in candidate.members} + for route in candidate.routes: + target = (members_by_id.get(route.next_hop_member_id) + if route.next_hop_member_id is not None else None) + target_host = target.host_id if target is not None else route.next_hop_host_id + if target_host is None: + raise VpcError("VPC route next hop 缺失", 409, + "vpc_route_next_hop_missing") + cidr = route.destination_cidr + owner = address_owner.get(cidr) + if owner is not None and owner != candidate.vpc_id: + raise VpcError("VPC 路由地址跨 VPC 重复", 409, + "vpc_route_address_conflict") + address_owner[cidr] = candidate.vpc_id + tenant_by_host.setdefault(target_host, set()).add(cidr) + + raw_nodes = fabric_record.get("nodes") + raw_keys = fabric_record.get("public_keys") + if not isinstance(raw_nodes, list) or not isinstance(raw_keys, Mapping): + raise VpcError("Fabric peer 记录不完整", 500, + "vpc_fabric_record_corrupt") + peers: list[dict[str, Any]] = [] + wanted_hosts = set(plan.host_ids) + for raw in raw_nodes: + if not isinstance(raw, Mapping): + continue + host_id = raw.get("host_id") + if not isinstance(host_id, str) or host_id not in wanted_hosts: + continue + # The caller supplies the local host separately when parsing each + # host plan; keep every other participating host in this list. + public_key = raw_keys.get(host_id) + overlay_ip = raw.get("overlay_ip") + if not isinstance(public_key, str) or not isinstance(overlay_ip, str): + raise VpcError("Fabric peer 记录无效", 500, + "vpc_fabric_record_corrupt") + _key(public_key) + peers.append({ + "host_id": host_id, + "public_key": public_key, + "overlay_ip": overlay_ip, + "tenant_allowed_ips": sorted(tenant_by_host.get(host_id, set())), + }) + return peers + + @staticmethod + def _private_routes(plan: VpcPlan, member: VpcMember) -> list[str]: + destinations = { + f"{other.private_ip}/32" for other in plan.members + if other.private_ip != member.private_ip + } + destinations.update(route.destination_cidr for route in plan.routes) + destinations.discard(f"{member.private_ip}/32") + return sorted(destinations) + + @staticmethod + def _observation_error(exc: Exception) -> str: + code = getattr(exc, "error_code", None) + if isinstance(code, str) and re.fullmatch(r"[a-z0-9_]{1,64}", code): + return code + return "vpc_private_dataplane_apply_failed" + + def _run_host_dataplane( + self, plan: VpcPlan, host_id: str, component: Any, + profile: Mapping[str, Any], fabric_peers: list[dict[str, Any]], + previous_plan: VpcPlan | None, + retiring_members: Sequence[Mapping[str, Any]] | None = None, + fabric_public_keys: Mapping[str, str] | None = None, + ) -> dict[str, Any]: + """Apply and read back one host synchronously behind the VPC lock.""" + from .libvirt_service import VMService + from .vpc_dataplane import ( + VpcDataplanePlan, VpcPrivateHostAdapter, + parse_vpc_dataplane_plan, resource_names, + ) + + if host_id in plan.host_ids: + payload = plan.canonical() + payload["fabric_peers"] = [ + peer for peer in fabric_peers + if peer.get("host_id") != host_id + ] + trusted_peer_tenant_ips = { + str(peer["host_id"]): tuple(peer.get("tenant_allowed_ips", ())) + for peer in payload["fabric_peers"] + if isinstance(peer, Mapping) and isinstance(peer.get("host_id"), str) + } + authoritative_peer_keys = None + if fabric_public_keys is not None: + authoritative_peer_keys = [ + key for peer_host, key in fabric_public_keys.items() + if peer_host != host_id + ] + dataplane = parse_vpc_dataplane_plan( + payload, host_id, + trusted_tenant_allowed_ips=trusted_peer_tenant_ips, + fabric_peer_keys=authoritative_peer_keys) + else: + # A retiring host is intentionally absent from the new desired + # plan. Construct a typed empty-local plan directly so the + # removal transaction can validate the deterministic VPC + # resources without reintroducing the old host into Fabric. + dataplane = VpcDataplanePlan( + plan.vpc, host_id, tuple(plan.members), tuple(), + resource_names(plan.vpc_id)) + adapter = VpcPrivateHostAdapter(component.manager, profile) + service = VMService( + profile["libvirt_uri"], profile["storage_pool"], + profile["iso_pool"], profile["default_network"], + rescue_iso_pool=profile.get("rescue_iso_pool", ""), + ) + old_members: list[VpcMember] = [] + if previous_plan is not None: + old_members.extend( + member for member in previous_plan.members + if member.host_id == host_id) + if retiring_members is not None: + for raw in retiring_members: + if not isinstance(raw, Mapping): + continue + try: + private_ip = str(raw.get("private_ip_cidr", "")).removesuffix("/32") + old_members.append(VpcMember( + str(raw["member_id"]), str(raw["instance_uuid"]), + str(raw.get("host_id", host_id)), private_ip, + str(raw.get("subnet_id", "retiring")), + str(raw.get("private_mac", "")))) + except (KeyError, TypeError, ValueError): + raise VpcError("VPC 宿主机清理成员证据无效", 500, + "vpc_retiring_member_invalid") + current_ids = {member.member_id for member in plan.members} + cleanup_plan = previous_plan or plan + seen_old: set[str] = set() + for old_member in old_members: + if old_member.member_id in seen_old: + continue + seen_old.add(old_member.member_id) + if old_member.host_id != host_id: + continue + if old_member.member_id in current_ids: + continue + service.remove_private_interface( + old_member.instance_uuid, + vpc_id=cleanup_plan.vpc_id, + resources=resource_names(cleanup_plan.vpc_id), + desired_revision=cleanup_plan.desired_revision, + desired_digest=cleanup_plan.desired_digest, + ) + # A host with no local members is a removal target. Run the + # manager-aware teardown and require its positive absence marker; + # returning a normal empty observation would leave stale bridge, + # route, nft, and peer state behind. + if not dataplane.local_members: + removed = adapter.remove(dataplane) + removed.update({ + "vpc_id": plan.vpc_id, + "host_id": host_id, + "desired_revision": plan.desired_revision, + "desired_digest": plan.desired_digest, + "transport_verified": True, + "private_dataplane_verified": True, + "rollback": removed.get("rollback", "none"), + }) + return removed + adapter.apply(dataplane) + for member in dataplane.local_members: + service.ensure_private_interface( + member.instance_uuid, member=member, + resources=dataplane.resources, vpc_id=plan.vpc_id, + desired_revision=plan.desired_revision, + desired_digest=plan.desired_digest, + private_routes=self._private_routes(plan, member), + ) + xml_by_instance: dict[str, Mapping[str, str | None]] = {} + for member in dataplane.local_members: + pair = service.read_private_domain_pair(member.instance_uuid) + inactive = pair.get("inactive") + if not isinstance(inactive, str): + raise VpcError("私网网卡持久配置回读缺失", 502, + "vpc_private_xml_readback_missing") + live = pair.get("live") + if live is not None and not isinstance(live, str): + raise VpcError("私网网卡实时配置回读无效", 502, + "vpc_private_live_readback_missing") + xml_by_instance[member.instance_uuid] = { + "inactive": inactive, "live": live, + } + observed = adapter.observe(dataplane, xml_by_instance=xml_by_instance) + observed.update({ + "vpc_id": plan.vpc_id, + "host_id": host_id, + "desired_revision": plan.desired_revision, + "desired_digest": plan.desired_digest, + "transport_verified": True, + "private_dataplane_verified": observed.get("state") == "active", + "rollback": observed.get("rollback", "none"), + }) + return observed + + async def _reconcile_dataplane( + self, plan: VpcPlan, record: dict[str, Any], gate: Mapping[str, Any], + previous_plan: VpcPlan | None = None, + ) -> None: + """Apply/read back every participating host; stay closed on failure.""" + retiring_ids = { + item.get("host_id") for item in record.get("hosts", []) + if isinstance(item, Mapping) + and item.get("retiring") is True + and isinstance(item.get("host_id"), str) + } + # A Fabric gate is required for normal applies. Retiring hosts still + # need one final SSH pass even when the new VPC has no members and the + # Fabric coordinator has already marked the tenant gate inactive. + if self.registry is None or ( + gate.get("active") is not True and not retiring_ids): + self._finish(record, gate) + return + try: + self._validate_dataplane_resources(plan) + fabric_record = self._fabric_record(plan) + full_fabric_plan = self.fabric._plan_from_record(fabric_record) + raw_fabric_keys = fabric_record.get("public_keys") + if not isinstance(raw_fabric_keys, Mapping): + raise VpcError("Fabric 公钥记录不完整", 500, + "vpc_fabric_record_corrupt") + fabric_public_keys = { + node.host_id: raw_fabric_keys.get(node.host_id) + for node in full_fabric_plan.nodes + } + if any(not isinstance(key, str) for key in fabric_public_keys.values()): + raise VpcError("Fabric 公钥记录不完整", 500, + "vpc_fabric_record_corrupt") + fabric_plan = full_fabric_plan + wanted = set(plan.host_ids) | retiring_ids + fabric_plan = replace( + fabric_plan, + nodes=tuple(node for node in fabric_plan.nodes + if node.host_id in wanted), + ) + components = await self.fabric._components(fabric_plan) + all_peers = self._fabric_peers_for_plan(plan, fabric_record) + except Exception as exc: + code = self._observation_error(exc) + for host in record.get("hosts", []): + if isinstance(host, dict): + host.update({"state": "uncertain", + "transport_verified": False, + "private_dataplane_verified": False, + "last_error_code": code}) + self._finish(record, gate) + return + + for host in record.get("hosts", []): + if not isinstance(host, dict): + continue + host_id = host.get("host_id") + if not isinstance(host_id, str) or host_id not in components: + host.update({"state": "uncertain", + "transport_verified": False, + "private_dataplane_verified": False, + "last_error_code": "vpc_host_unavailable"}) + continue + component, profile = components[host_id] + try: + observed = await asyncio.to_thread( + self._run_host_dataplane, plan, host_id, component, + profile, all_peers, previous_plan, + host.get("retiring_members", []), fabric_public_keys) + host.update(observed) + host["observed_revision"] = ( + plan.desired_revision + if observed.get("state") == "active" else 0) + host["observed_digest"] = ( + plan.desired_digest + if observed.get("state") == "active" else None) + host["state"] = observed.get("state", "degraded") + host["last_error_code"] = observed.get("reason_code") + if host.get("retiring") is True: + host["removed"] = observed.get("removed") is True + except Exception as exc: + host.update({"state": "uncertain", + "transport_verified": False, + "private_dataplane_verified": False, + "observed_revision": 0, + "observed_digest": None, + "last_error_code": self._observation_error(exc)}) + self._finish(record, gate) + @staticmethod def _desired_record(plan: VpcPlan, gate: Mapping[str, Any], *, state: str, observed_revision: int = 0, observed_digest: str | None = None, previous_hosts: Mapping[str, Mapping[str, Any]] | None = None, + previous_plan: VpcPlan | None = None, updated_at: int | None = None) -> dict[str, Any]: now = int(time.time()) if updated_at is None else updated_at previous_hosts = previous_hosts or {} @@ -837,16 +1234,21 @@ class VpcCoordinator: old_digest = _digest(old_digest, "observed_digest") except VpcError: old_digest = None - if not isinstance(old_readback, Mapping): - old_readback = {} - safe_readback = { - str(key): value for key, value in old_readback.items() - if isinstance(key, str) and len(key) <= 64 - and _safe_scalar(value) - } + if isinstance(old_readback, str) and len(old_readback) <= 128: + safe_readback: Any = old_readback + elif isinstance(old_readback, Mapping): + safe_readback = { + str(key): value for key, value in old_readback.items() + if isinstance(key, str) and len(key) <= 64 + and _safe_scalar(value) + } + else: + safe_readback = {} host_records.append({ "host_id": host.host_id, "member_ids": list(host.member_ids), "desired_revision": plan.desired_revision, + "vpc_id": plan.vpc_id, + "desired_digest": plan.desired_digest, "observed_revision": old_revision, "observed_digest": old_digest, "state": "applying" if gate.get("active") else "uncertain", @@ -855,8 +1257,61 @@ class VpcCoordinator: # tenant VPC. Only the future host adapter may set this # after private0/route/nft/member readback. "private_dataplane_verified": False, + "removed": bool(old.get("removed", False)) if isinstance(old, Mapping) else False, + "bridge": old.get("bridge") if isinstance(old, Mapping) else None, + "bridge_owner": old.get("bridge_owner") if isinstance(old, Mapping) else None, + "nft_table": old.get("nft_table") if isinstance(old, Mapping) else None, + "anti_spoof": bool(old.get("anti_spoof")) if isinstance(old, Mapping) else False, + "rp_filter": old.get("rp_filter") if isinstance(old, Mapping) else None, + "proxy_arp": old.get("proxy_arp") if isinstance(old, Mapping) else None, + "proxy_arp_pvlan": old.get("proxy_arp_pvlan") if isinstance(old, Mapping) else None, + "proxy_ips": old.get("proxy_ips", []) if isinstance(old, Mapping) else [], + "acl_revision": old.get("acl_revision") if isinstance(old, Mapping) else None, + "rollback": old.get("rollback", "none") if isinstance(old, Mapping) else "none", + "member_nics": old.get("member_nics", []) if isinstance(old, Mapping) else [], + "routes": old.get("routes", []) if isinstance(old, Mapping) else [], + "wg_allowed_ips": old.get("wg_allowed_ips", []) if isinstance(old, Mapping) else [], "readback": safe_readback, }) + # Keep host tombstones in the durable engine record until the host-side + # removal script returns its typed absence proof. They are excluded + # from the new VPC plan by _plan_from_record(retiring=true), but retain + # the old instance identity so a restart can still remove private0. + current_host_ids = {host.host_id for host in plan.hosts} + if previous_plan is not None: + for old_host in previous_plan.hosts: + if old_host.host_id in current_host_ids: + continue + old_members = [ + {"member_id": member.member_id, + "instance_uuid": member.instance_uuid, + "host_id": member.host_id, + "private_ip_cidr": f"{member.private_ip}/32", + "subnet_id": member.subnet_id, + "private_mac": member.private_mac} + for member in previous_plan.members + if member.host_id == old_host.host_id + ] + host_records.append({ + "host_id": old_host.host_id, + "member_ids": [item["member_id"] for item in old_members], + "vpc_id": plan.vpc_id, + "desired_revision": plan.desired_revision, + "desired_digest": plan.desired_digest, + "observed_revision": 0, + "observed_digest": None, + "state": "deleting", + "transport_verified": bool(gate.get("active")), + "private_dataplane_verified": False, + "retiring": True, + "retiring_members": old_members, + "bridge": None, "bridge_owner": None, "nft_table": None, + "anti_spoof": False, "rp_filter": None, + "proxy_arp": None, "proxy_arp_pvlan": None, + "proxy_ips": [], "acl_revision": None, + "rollback": "none", "member_nics": [], "routes": [], + "wg_allowed_ips": [], "readback": {}, + }) return { "schema_version": VPC_SCHEMA_VERSION, "vpc_id": plan.vpc_id, "region": plan.region, @@ -930,10 +1385,12 @@ class VpcCoordinator: if not isinstance(raw, Mapping): continue item = {key: raw[key] for key in ( - "host_id", "member_ids", "desired_revision", + "host_id", "member_ids", "vpc_id", "desired_revision", + "desired_digest", "bridge", "bridge_owner", "nft_table", "observed_revision", "observed_digest", "state", "transport_verified", "private_dataplane_verified", - "last_error_code") if key in raw} + "last_error_code", "removed", "retiring", "anti_spoof", "rp_filter", "acl_revision", "rollback", + "proxy_arp", "proxy_arp_pvlan", "proxy_ips", "member_nics", "routes", "wg_allowed_ips") if key in raw} readback = raw.get("readback") if isinstance(readback, Mapping): item["readback"] = { @@ -941,6 +1398,8 @@ class VpcCoordinator: if isinstance(key, str) and len(key) <= 64 and _safe_scalar(val) } + elif isinstance(readback, str) and len(readback) <= 128: + item["readback"] = readback result["hosts"].append(item) # PHP's typed VPC service consumes an explicit observed projection and # keys host evidence by stable host ID. Keep this projection bounded @@ -955,9 +1414,29 @@ class VpcCoordinator: item: dict[str, Any] = {} for key in ("state", "observed_revision", "observed_digest", "transport_verified", "private_dataplane_verified", - "last_error_code"): + "last_error_code", "vpc_id", "host_id", + "desired_revision", "desired_digest", "bridge", + "bridge_owner", "nft_table", "anti_spoof", + "rp_filter", "proxy_arp", "proxy_arp_pvlan", "proxy_ips", "acl_revision", "rollback", "removed", "retiring", "member_nics", + "routes", "wg_allowed_ips", "readback"): if key in raw: - item[key] = raw[key] + value_item = raw[key] + if key in {"member_nics", "routes", "wg_allowed_ips", "proxy_ips"}: + if isinstance(value_item, (list, tuple)): + if key == "proxy_ips": + item[key] = [str(ip)[:64] for ip in value_item[:4096] + if isinstance(ip, str)] + else: + item[key] = [dict(row) for row in value_item[:4096] + if isinstance(row, Mapping)] + elif key == "readback": + if isinstance(value_item, str) and len(value_item) <= 128: + item[key] = value_item + elif isinstance(value_item, Mapping): + item[key] = {str(k): v for k, v in value_item.items() + if isinstance(k, str) and _safe_scalar(v)} + elif _safe_scalar(value_item): + item[key] = value_item item["next_stage_allowed"] = ( raw.get("state") == "active" and raw.get("transport_verified") is True @@ -1107,8 +1586,33 @@ class VpcCoordinator: and item.get("transport_verified") is True and item.get("private_dataplane_verified") is True for item in hosts) + retiring_hosts = [ + item for item in hosts if isinstance(item, Mapping) + and item.get("retiring") is True + ] if isinstance(hosts, list) else [] + live_hosts = [ + item for item in hosts if not (isinstance(item, Mapping) + and item.get("retiring") is True) + ] if isinstance(hosts, list) else [] + all_removed = bool(retiring_hosts) and all( + item.get("state") == "active" + and item.get("removed") is True + and item.get("observed_revision") == desired_revision + and item.get("observed_digest") == desired_digest + and item.get("transport_verified") is True + and item.get("private_dataplane_verified") is True + for item in retiring_hosts) fabric_active = gate.get("active") is True - if fabric_active and all_observed: + if all_removed and not live_hosts: + # A VPC with no remaining members is a terminal removal proof; + # the Fabric gate may correctly be inactive because there is no + # tenant transport left to activate. + record["state"] = "active" + record["next_stage_allowed"] = True + record["private_dataplane_verified"] = True + record["observed_revision"] = desired_revision + record["observed_digest"] = desired_digest + elif fabric_active and all_observed: record["state"] = "active" record["next_stage_allowed"] = True record["private_dataplane_verified"] = True @@ -1136,6 +1640,7 @@ class VpcCoordinator: plan = parse_vpc_plan(value) async with self._lock(plan.vpc_id): previous = self._load("vpc_desired", plan.vpc_id) + previous_plan: VpcPlan | None = None old_revision = plan.desired_revision if previous is not None: # Validate the durable prior target before accepting a newer @@ -1162,6 +1667,8 @@ class VpcCoordinator: gate = self._fabric_gate(plan) record = dict(previous) self._finish(record, gate) + await self._reconcile_dataplane( + plan, record, gate, previous_plan) self._save("vpc_desired", plan.vpc_id, record) self._save_children(record) return self._public(record) @@ -1209,8 +1716,11 @@ class VpcCoordinator: observed_revision=previous_observed_revision, observed_digest=previous_observed_digest, previous_hosts=previous_hosts, + previous_plan=previous_plan, ) self._finish(record, gate) + await self._reconcile_dataplane( + plan, record, gate, previous_plan) self._save("vpc_desired", plan.vpc_id, record) self._save_children(record) return self._public(record) @@ -1283,13 +1793,39 @@ class VpcCoordinator: state = "applying" observation_error = "vpc_private_dataplane_unverified" readback = raw.get("readback", {}) - if not isinstance(readback, Mapping) or len(readback) > 64: + if isinstance(readback, str) and len(readback) <= 128: + safe_readback: Any = readback + elif isinstance(readback, Mapping) and len(readback) <= 64: + safe_readback = { + str(key): value for key, value in readback.items() + if isinstance(key, str) and len(key) <= 64 + and _safe_scalar(value) + } + else: raise VpcError("VPC readback 无效") - safe_readback = { - str(key): value for key, value in readback.items() - if isinstance(key, str) and len(key) <= 64 - and _safe_scalar(value) - } + typed_fields = ( + "vpc_id", "host_id", "desired_revision", "desired_digest", + "bridge", "bridge_owner", "nft_table", "anti_spoof", + "rp_filter", "proxy_arp", "proxy_arp_pvlan", "proxy_ips", "acl_revision", "rollback", "removed", "member_nics", "routes", + "wg_allowed_ips", + ) + typed = {} + for field in typed_fields: + if field not in raw: + continue + item_value = raw[field] + if field in {"member_nics", "routes", "wg_allowed_ips", "proxy_ips"}: + if isinstance(item_value, (list, tuple)) and len(item_value) <= VPC_MAX_READBACK: + if field == "proxy_ips": + typed[field] = [str(ip)[:64] for ip in item_value + if isinstance(ip, str)] + else: + typed[field] = [dict(row) for row in item_value + if isinstance(row, Mapping)] + elif field == "readback": + continue + elif _safe_scalar(item_value): + typed[field] = item_value host.update({"state": state, "observed_revision": observed_revision, "observed_digest": observed_digest, @@ -1299,8 +1835,9 @@ class VpcCoordinator: "last_error_code": observation_error if isinstance(observation_error, str) and len(observation_error) <= 64 else None}) + host.update(typed) gate = self._fabric_gate(plan) - self._finish(record, gate) + await self._reconcile_dataplane(plan, record, gate, plan) self._save("vpc_desired", vpc_id, record) self._save_children(record) return self._public(record) @@ -1316,7 +1853,10 @@ class VpcCoordinator: raise VpcError("VPC 计划摘要与持久化记录不一致", 500, "vpc_record_corrupt") gate = self._fabric_gate(plan) - self._finish(record, gate) + # Reconcile is the durable retry path after a host response was + # lost or the engine restarted. Refreshing only the Fabric gate + # would leave private0/routes/nft in an unknown state forever. + await self._reconcile_dataplane(plan, record, gate, plan) self._save("vpc_desired", vpc_id, record) self._save_children(record) return self._public(record) diff --git a/engine/virsh_panel/vpc_dataplane.py b/engine/virsh_panel/vpc_dataplane.py new file mode 100644 index 00000000..880ba7b9 --- /dev/null +++ b/engine/virsh_panel/vpc_dataplane.py @@ -0,0 +1,2955 @@ +"""Panel-owned VPC private L3 data-plane primitives. + +This module is deliberately independent from :mod:`virsh_panel.fabric`. +Fabric owns the host overlay (``wg-fabric0``); this boundary owns only a +VPC's bridge, policy route table, tenant AllowedIPs and nftables table. The +pure builders are usable in unit tests and the host adapter runs one fixed +shell transaction through a pinned remote manager. +""" +from __future__ import annotations + +import base64 +import hashlib +import ipaddress +import re +import shlex +import xml.etree.ElementTree as ET +from dataclasses import dataclass +from typing import Any, Mapping, Sequence + +from .network_roles import ( + PRIVATE_INTERFACE_ALIAS, + PUBLIC_INTERFACE_ALIAS, + select_private_interface, + select_public_interface, +) +from .vpc import VpcError, VpcMember, VpcPlan, parse_vpc_plan + +DATAPLANE_SCHEMA_VERSION = 1 +DATAPLANE_OWNER_MARKER = "virt-cloud-vpc-dataplane-v1" +FABRIC_OWNER_MARKER = "virt-cloud-wg-fabric-v1" +FABRIC_INTERFACE = "wg-fabric0" +FABRIC_LOCK = "/run/virt-cloud/wg-fabric0.lock" +PRIVATE_INTERFACE = PRIVATE_INTERFACE_ALIAS +PANEL_NS = "urn:virsh-panel:1" +BRIDGE_PREFIX = "vcv-" +NFT_PREFIX = "virt_cloud_vpc_" +ROUTE_TABLE_MIN, ROUTE_TABLE_MAX = 10000, 19999 +RULE_PRIORITY_MIN, RULE_PRIORITY_MAX = 20000, 29999 +MAX_OUTPUT = 262144 +_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}\Z") +_HOST = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}\Z") +_MAC = re.compile(r"[0-9a-fA-F]{2}(?::[0-9a-fA-F]{2}){5}\Z") +_KEY = re.compile(r"[A-Za-z0-9+/]{42}==\Z|[A-Za-z0-9+/]{43}=\Z") +_DIGEST = re.compile(r"[0-9a-f]{64}\Z") + + +class VpcDataplaneError(Exception): + """Safe, typed error at the VPC host boundary.""" + + def __init__(self, message: str, status: int = 400, + error_code: str = "vpc_dataplane_invalid") -> None: + super().__init__(message) + self.status = status + self.error_code = error_code + + +@dataclass(frozen=True) +class VpcFabricPeer: + host_id: str + public_key: str + overlay_ip: str + # Tenant /32s from every panel VPC sharing this Fabric peer. WireGuard + # has one AllowedIPs list per peer, so a VPC must merge this typed set + # instead of replacing another active VPC's entries. + tenant_allowed_ips: tuple[str, ...] = () + + @property + def overlay_cidr(self) -> str: + return f"{self.overlay_ip}/32" + + +@dataclass(frozen=True) +class VpcDataplaneResources: + token: str + bridge: str + nft_table: str + route_table: int + rule_priority: int + owner_file: str + state_file: str + lock_file: str + transaction_dir: str + + +@dataclass(frozen=True) +class VpcDataplanePlan: + vpc: VpcPlan + host_id: str + members: tuple[VpcMember, ...] + peers: tuple[VpcFabricPeer, ...] + resources: VpcDataplaneResources + # The authenticated full Fabric peer set, excluding this host. It is + # separate from ``peers`` because one VPC can use only a subset of the + # peers present on a shared Fabric. + fabric_peer_keys: frozenset[str] | None = None + + @property + def desired_revision(self) -> int: + return self.vpc.desired_revision + + @property + def desired_digest(self) -> str: + return self.vpc.desired_digest + + @property + def local_members(self) -> tuple[VpcMember, ...]: + return tuple(m for m in self.members if m.host_id == self.host_id) + + @property + def remote_members(self) -> tuple[VpcMember, ...]: + return tuple(m for m in self.members if m.host_id != self.host_id) + + +@dataclass(frozen=True) +class VpcDataplaneObservation: + vpc_id: str + host_id: str + desired_revision: int + observed_revision: int + desired_digest: str + observed_digest: str | None + state: str + bridge: str + bridge_owner: str | None + member_nics: tuple[dict[str, Any], ...] + routes: tuple[dict[str, Any], ...] + wg_allowed_ips: tuple[dict[str, Any], ...] + nft_table: str | None + acl_revision: int | None + anti_spoof: bool + rp_filter: int | None + proxy_arp: int | None + proxy_arp_pvlan: int | None + proxy_ips: tuple[str, ...] + readback: str + rollback: str + reason_code: str | None = None + removed: bool = False + + def as_dict(self) -> dict[str, Any]: + return { + "vpc_id": self.vpc_id, "host_id": self.host_id, + "desired_revision": self.desired_revision, + "observed_revision": self.observed_revision, + "desired_digest": self.desired_digest, + "observed_digest": self.observed_digest, + "state": self.state, "bridge": self.bridge, + "bridge_owner": self.bridge_owner, + "member_nics": [dict(x) for x in self.member_nics], + "routes": [dict(x) for x in self.routes], + "wg_allowed_ips": [dict(x) for x in self.wg_allowed_ips], + "nft_table": self.nft_table, "acl_revision": self.acl_revision, + "anti_spoof": self.anti_spoof, "rp_filter": self.rp_filter, + "proxy_arp": self.proxy_arp, + "proxy_arp_pvlan": self.proxy_arp_pvlan, + "proxy_ips": list(self.proxy_ips), + "readback": self.readback, + "rollback": self.rollback, "reason_code": self.reason_code, + "removed": self.removed, + } + + +def _id(value: Any, label: str = "标识") -> str: + if not isinstance(value, str) or _ID.fullmatch(value) is None: + raise VpcDataplaneError(f"{label}无效") + return value + + +def _host(value: Any) -> str: + if not isinstance(value, str) or _HOST.fullmatch(value) is None: + raise VpcDataplaneError("宿主机标识无效") + return value + + +def _key(value: Any) -> str: + if not isinstance(value, str) or _KEY.fullmatch(value) is None: + raise VpcDataplaneError("WireGuard 公钥无效") + try: + raw = base64.b64decode(value, validate=True) + except Exception as exc: + raise VpcDataplaneError("WireGuard 公钥无效") from exc + if len(raw) != 32 or not any(raw): + raise VpcDataplaneError("WireGuard 公钥无效") + return value + + +def _mac(value: Any, label: str = "私网 MAC") -> str: + if not isinstance(value, str) or _MAC.fullmatch(value) is None: + raise VpcDataplaneError(f"{label}无效") + octets = [int(x, 16) for x in value.split(":")] + if octets[0] & 1 or not any(octets): + raise VpcDataplaneError(f"{label}无效") + return value.lower() + + +def derive_private_mac(vpc_id: str, member_id: str) -> str: + """Stable locally-administered unicast MAC for legacy plans without MAC.""" + digest = hashlib.sha256(f"virt-cloud:vpc-private0:{vpc_id}:{member_id}".encode()).digest() + first = (digest[0] & 0xfc) | 0x02 + return ":".join(f"{x:02x}" for x in bytes([first]) + digest[1:6]) + + +def resource_names(vpc_id: str) -> VpcDataplaneResources: + vpc_id = _id(vpc_id, "VPC") + digest = hashlib.sha256(vpc_id.encode()).hexdigest() + token = digest[:11] + span = ROUTE_TABLE_MAX - ROUTE_TABLE_MIN + 1 + # Each VPC owns two policy rules (private bridge and Fabric ingress). + # Allocate an aligned pair so ``base + 1`` can never be another VPC's + # base slot. The coordinator still checks collisions across records and + # the host transaction rejects a foreign rule already occupying either + # slot, but a single-slot hash would make those checks order-dependent. + rule_span = (RULE_PRIORITY_MAX - RULE_PRIORITY_MIN + 1) // 2 + rule_base = RULE_PRIORITY_MIN + 2 * (int(digest[20:28], 16) % rule_span) + return VpcDataplaneResources( + token=token, bridge=BRIDGE_PREFIX + token, + nft_table=NFT_PREFIX + digest[:12], + route_table=ROUTE_TABLE_MIN + int(digest[12:20], 16) % span, + rule_priority=rule_base, + owner_file=f"/etc/virt-cloud/vpc-dataplane/{token}.owner", + state_file=f"/etc/virt-cloud/vpc-dataplane/{token}.state", + lock_file=f"/run/virt-cloud/vpc-{token}.lock", + transaction_dir=f"/etc/virt-cloud/.vpc-dataplane-{token}.txn", + ) + + +def _expected_peer_tenant_ips(vpc: VpcPlan) -> dict[str, frozenset[str]]: + """Return the exact /32 set a peer may route for this VPC. + + The WireGuard peer list is a cryptokey-routing boundary. RFC1918 alone + is not an ownership check: an otherwise valid private /32 from another + VPC would create a cross-tenant route. The coordinator may pass a + trusted aggregate for a Fabric shared by several VPCs; the default here + covers a standalone plan and keeps direct parser callers fail-closed. + """ + members = {item.member_id: item for item in vpc.members} + allowed: dict[str, set[str]] = {host: set() for host in vpc.host_ids} + for item in vpc.members: + allowed.setdefault(item.host_id, set()).add(f"{item.private_ip}/32") + for route in vpc.routes: + target = (members.get(route.next_hop_member_id) + if route.next_hop_member_id is not None else None) + target_host = target.host_id if target is not None else route.next_hop_host_id + if target_host is not None: + allowed.setdefault(target_host, set()).add(route.destination_cidr) + return {host: frozenset(values) for host, values in allowed.items()} + + +def _parse_peers( + raw: Any, + host_ids: frozenset[str], + local: str, + expected_tenant_ips: Mapping[str, frozenset[str]] | None = None, +) -> tuple[VpcFabricPeer, ...]: + if raw is None: + raw = [] + if not isinstance(raw, (list, tuple)) or len(raw) > 64: + raise VpcDataplaneError("Fabric peer 列表无效") + peers: list[VpcFabricPeer] = [] + seen_hosts: set[str] = set() + seen_keys: set[str] = set() + seen_ips: set[str] = set() + seen_tenant_ips: set[str] = set() + for item in raw: + if not isinstance(item, Mapping) or set(item) - {"host_id", "public_key", "overlay_ip", "overlay_ip_cidr", "tenant_allowed_ips"}: + raise VpcDataplaneError("Fabric peer 字段无效") + host_id = _host(item.get("host_id")) + if host_id == local or host_id not in host_ids or host_id in seen_hosts: + raise VpcDataplaneError("Fabric peer 宿主机无效或重复") + public_key = _key(item.get("public_key")) + if public_key in seen_keys: + raise VpcDataplaneError("Fabric peer 公钥重复") + raw_ip = item.get("overlay_ip", item.get("overlay_ip_cidr")) + try: + interface = ipaddress.ip_interface(raw_ip) + except (ValueError, TypeError) as exc: + raise VpcDataplaneError("Fabric peer overlay 地址无效") from exc + fabric_overlay = ipaddress.IPv4Network("100.64.0.0/10") + if (not isinstance(interface, ipaddress.IPv4Interface) + or interface.network.prefixlen != 32 + or interface.ip not in fabric_overlay + or interface.ip.is_loopback + or interface.ip.is_link_local): + raise VpcDataplaneError("Fabric peer overlay 地址无效") + overlay_ip = str(interface.ip) + if overlay_ip in seen_ips: + raise VpcDataplaneError("Fabric peer overlay 地址重复") + raw_tenant = item.get("tenant_allowed_ips", ()) + if not isinstance(raw_tenant, (list, tuple)) or len(raw_tenant) > 4096: + raise VpcDataplaneError("Fabric peer tenant AllowedIPs 无效") + tenant: set[str] = set() + for raw_ip in raw_tenant: + if not isinstance(raw_ip, str) or not raw_ip.endswith("/32"): + raise VpcDataplaneError("Fabric peer tenant AllowedIPs 必须是 /32") + try: + network = ipaddress.ip_network(raw_ip, strict=True) + except ValueError as exc: + raise VpcDataplaneError("Fabric peer tenant AllowedIPs 无效") from exc + if network.prefixlen != 32: + raise VpcDataplaneError("Fabric peer tenant AllowedIPs 必须是 /32") + # Tenant routes are panel-private RFC1918 /32s. In particular, + # never accept a public prefix or a Fabric overlay address from + # an otherwise authenticated payload: that would turn a peer's + # cryptokey routing table into a host-wide egress route. + private_ranges = ( + ipaddress.IPv4Network("10.0.0.0/8"), + ipaddress.IPv4Network("172.16.0.0/12"), + ipaddress.IPv4Network("192.168.0.0/16"), + ) + if not any(network.subnet_of(item) for item in private_ranges): + raise VpcDataplaneError("Fabric peer tenant AllowedIPs 必须位于 RFC1918 私网") + tenant_ip = str(network) + if tenant_ip in seen_tenant_ips: + raise VpcDataplaneError("Fabric peer tenant AllowedIPs 重复", 409, + "vpc_tenant_allowed_ip_conflict") + seen_tenant_ips.add(tenant_ip) + tenant.add(tenant_ip) + if expected_tenant_ips is not None: + expected = set(expected_tenant_ips.get(host_id, frozenset())) + if tenant != expected: + raise VpcDataplaneError( + "Fabric peer tenant AllowedIPs 超出 VPC 所有权闭集", 409, + "vpc_tenant_allowed_ip_unowned") + seen_hosts.add(host_id); seen_keys.add(public_key); seen_ips.add(overlay_ip) + peers.append(VpcFabricPeer(host_id, public_key, overlay_ip, + tuple(sorted(tenant)))) + return tuple(sorted(peers, key=lambda p: p.host_id)) + + +def parse_vpc_dataplane_plan( + value: Mapping[str, Any], host_id: str, *, + fabric_peers: Sequence[Mapping[str, Any]] | None = None, + trusted_tenant_allowed_ips: Mapping[str, Sequence[str]] | None = None, + fabric_peer_keys: Sequence[str] | None = None, +) -> VpcDataplanePlan: + """Parse existing VPC DTO plus an optional engine-only Fabric snapshot.""" + if not isinstance(value, Mapping): + raise VpcDataplaneError("VPC 数据面计划必须是对象") + host_id = _host(host_id) + payload = dict(value) + embedded = payload.pop("fabric_peers", None) + if embedded is None: + embedded = payload.pop("peers", None) + else: + payload.pop("peers", None) + try: + vpc = parse_vpc_plan(payload) + except VpcError as exc: + raise VpcDataplaneError(str(exc), exc.status, exc.error_code) from exc + if host_id not in vpc.host_ids: + raise VpcDataplaneError("VPC 宿主机不在参与列表中", 409, "vpc_host_not_member") + members: list[VpcMember] = [] + seen_macs: set[str] = set() + for member in vpc.members: + private_mac = _mac(member.private_mac) if member.private_mac else derive_private_mac(vpc.vpc_id, member.member_id) + if private_mac in seen_macs: + raise VpcDataplaneError("VPC 成员私网 MAC 重复", 409, "vpc_private_mac_conflict") + seen_macs.add(private_mac) + members.append(VpcMember(member.member_id, member.instance_uuid, + member.host_id, member.private_ip, + member.subnet_id, private_mac)) + if trusted_tenant_allowed_ips is None: + expected_tenant_ips = _expected_peer_tenant_ips(vpc) + else: + if not isinstance(trusted_tenant_allowed_ips, Mapping): + raise VpcDataplaneError("Fabric peer tenant 所有权闭集无效") + expected_tenant_ips = {} + remote_hosts = vpc.host_ids - {host_id} + if set(trusted_tenant_allowed_ips) - remote_hosts: + raise VpcDataplaneError("Fabric peer tenant 所有权宿主机无效") + for peer_host, values in trusted_tenant_allowed_ips.items(): + if not isinstance(peer_host, str) or peer_host not in remote_hosts: + raise VpcDataplaneError("Fabric peer tenant 所有权宿主机无效") + if not isinstance(values, (list, tuple, set, frozenset)): + raise VpcDataplaneError("Fabric peer tenant 所有权闭集无效") + canonical: set[str] = set() + for value in values: + if not isinstance(value, str): + raise VpcDataplaneError("Fabric peer tenant 所有权闭集无效") + try: + network = ipaddress.ip_network(value, strict=True) + except ValueError as exc: + raise VpcDataplaneError("Fabric peer tenant 所有权闭集无效") from exc + if (not isinstance(network, ipaddress.IPv4Network) + or network.prefixlen != 32 + or not any(network.subnet_of(block) for block in ( + ipaddress.IPv4Network("10.0.0.0/8"), + ipaddress.IPv4Network("172.16.0.0/12"), + ipaddress.IPv4Network("192.168.0.0/16")))): + raise VpcDataplaneError("Fabric peer tenant 所有权闭集无效") + canonical.add(str(network)) + expected_tenant_ips[peer_host] = frozenset(canonical) + peers = _parse_peers( + embedded if fabric_peers is None else fabric_peers, + vpc.host_ids, host_id, expected_tenant_ips) + remote_hosts = {m.host_id for m in members if m.host_id != host_id} + if peers and remote_hosts - {p.host_id for p in peers}: + raise VpcDataplaneError("跨宿主机成员缺少 Fabric peer", 409, "vpc_fabric_peer_missing") + authoritative_keys: frozenset[str] | None = None + if fabric_peer_keys is not None: + if not isinstance(fabric_peer_keys, (list, tuple, set, frozenset)): + raise VpcDataplaneError("Fabric peer 公钥闭集无效", 409, + "vpc_fabric_peer_set_invalid") + if len(fabric_peer_keys) > 64: + raise VpcDataplaneError("Fabric peer 公钥闭集过大", 409, + "vpc_fabric_peer_set_invalid") + canonical_keys: set[str] = set() + for raw_key in fabric_peer_keys: + key = _key(raw_key) + if key in canonical_keys: + raise VpcDataplaneError("Fabric peer 公钥重复", 409, + "vpc_fabric_peer_set_invalid") + canonical_keys.add(key) + if not {peer.public_key for peer in peers}.issubset(canonical_keys): + raise VpcDataplaneError("VPC peer 不属于 Fabric 公钥闭集", 409, + "vpc_fabric_peer_set_invalid") + authoritative_keys = frozenset(canonical_keys) + return VpcDataplanePlan( + vpc, host_id, tuple(members), peers, resource_names(vpc.vpc_id), + authoritative_keys) + + +def _routes(plan: VpcDataplanePlan) -> tuple[dict[str, Any], ...]: + members = {m.member_id: m for m in plan.members} + result: list[dict[str, Any]] = [] + seen: set[str] = set() + for member in plan.members: + destination = f"{member.private_ip}/32" + seen.add(destination) + result.append({"destination_cidr": destination, + "device": plan.resources.bridge if member.host_id == plan.host_id else FABRIC_INTERFACE, + "table": plan.resources.route_table, + "owner": DATAPLANE_OWNER_MARKER, + "metric": 100, + "via": None, + "member_id": member.member_id}) + for route in plan.vpc.routes: + destination = route.destination_cidr + network = ipaddress.ip_network(destination) + if network.prefixlen != 32: + raise VpcDataplaneError( + "VPC 数据面只支持成员精确 /32 路由", 409, + "vpc_route_not_exact") + if any(ipaddress.IPv4Address(m.private_ip) in network + and destination != f"{m.private_ip}/32" for m in plan.members): + raise VpcDataplaneError("VPC route 不能覆盖成员精确 /32", 409, "vpc_route_member_overlap") + if destination in seen: + raise VpcDataplaneError("VPC route 与成员地址重复", 409, "vpc_route_conflict") + next_host = route.next_hop_host_id + if route.next_hop_member_id is not None: + target = members.get(route.next_hop_member_id) + if target is None: + raise VpcDataplaneError("VPC route next hop member 不存在", 409) + next_host = target.host_id + if next_host is None: + raise VpcDataplaneError("VPC route next hop 缺失") + target_members = [item for item in plan.members + if item.host_id == next_host] + if not target_members: + raise VpcDataplaneError("VPC route next hop 宿主机没有成员", 409, + "vpc_route_next_hop_missing") + # A host-only next hop is ambiguous when several VMs share that host. + # Require an explicit member in that case; using a bare bridge route + # would ARP for the service address and could leak traffic to an + # unrelated guest. + if route.next_hop_member_id is None and len(target_members) != 1: + raise VpcDataplaneError("VPC route 宿主机 next hop 不明确", 409, + "vpc_route_next_hop_ambiguous") + target = (members.get(route.next_hop_member_id) + if route.next_hop_member_id is not None else target_members[0]) + if target is None: + raise VpcDataplaneError("VPC route next hop member 不存在", 409, + "vpc_route_next_hop_missing") + is_local = next_host == plan.host_id + if not is_local and next_host not in {peer.host_id for peer in plan.peers}: + raise VpcDataplaneError("VPC route next hop 缺少 Fabric peer", 409, + "vpc_fabric_peer_missing") + seen.add(destination) + result.append({"destination_cidr": destination, + "device": plan.resources.bridge if is_local else FABRIC_INTERFACE, + "table": plan.resources.route_table, + "owner": DATAPLANE_OWNER_MARKER, + # A local host must forward the service /32 through + # the selected VM. Across the overlay the destination + # itself is a WireGuard AllowedIP, so no `via` is used. + "via": target.private_ip if is_local else None, + "metric": route.metric, + "route_id": route.route_id}) + return tuple(result) + + +def _q(value: Any) -> str: + return shlex.quote(str(value)) + + +def _nft_proto(acl: Any) -> str: + if acl.protocol == "any": + return "" + if acl.protocol == "icmp": + return " ip protocol icmp" + suffix = f" ip protocol {acl.protocol}" + if acl.port_from is not None: + ports = str(acl.port_from) if acl.port_from == acl.port_to else f"{acl.port_from}-{acl.port_to}" + suffix += f" {acl.protocol} dport {ports}" + return suffix + + +def _nft_marker(plan: VpcDataplanePlan) -> str: + """Return a bounded ownership marker safe for nft comment userdata. + + libnftnl limits rule comments to 128 bytes. VPC/host identifiers are + intentionally allowed to be long, so embedding them and the full digest + in every rule would make otherwise valid plans fail at ``nft -c``. The + state file keeps the full identifiers; comments only need a collision + resistant, deterministic token for ownership/readback. + """ + seed = (f"{plan.vpc.vpc_id}:{plan.host_id}:{plan.desired_revision}:" + f"{plan.desired_digest}").encode() + token = hashlib.sha256(seed).hexdigest()[:16] + return f"{DATAPLANE_OWNER_MARKER}:{plan.resources.token}:{token}" + + +def render_vpc_nft_rules(plan: VpcDataplanePlan) -> str: + """Render scoped VPC ACL/anti-spoof rules for routed and L2 paths. + + The base chains use ``policy accept`` deliberately. A VPC table must not + become a host-wide firewall that drops public bridges or unrelated Fabric + traffic; only packets carrying this VPC's member addresses are subject to + its default deny. A separate bridge-family table covers same-host VM to + VM forwarding and ARP, which do not reliably traverse an inet forward + hook. + """ + r = plan.resources + marker = _nft_marker(plan) + dataplane_routes = _routes(plan) + member_cidrs = {f"{m.private_ip}/32" for m in plan.members} + local_member_cidrs = {f"{m.private_ip}/32" for m in plan.local_members} + # Custom VPC routes are exact /32s too. Keep source sets restricted to + # actual member addresses, while destination sets include routed service + # addresses; otherwise the isolation rules would silently drop a valid + # route before the ACL/default-deny decision. + destination_cidrs = member_cidrs | { + str(item["destination_cidr"]) for item in dataplane_routes + } + # A packet entering a local tap may be routed either to another local + # tap or out through wg-fabric0 to a remote member/service /32. The + # bridge-family unknown-destination guard therefore needs the complete + # VPC destination set; restricting it to local routes would drop every + # same-VPC cross-host flow before the inet routing policy can run. + local_destination_cidrs = set(destination_cidrs) + # Use explicit proxy-neighbour entries for the guest's routed /32 model. + # The generic kernel proxy responder stays disabled, so a nftables reload + # or a short ordering window cannot make the host answer for arbitrary + # addresses. proxy_arp_pvlan is enabled only for the same-bridge + # next-hop case and is still bounded by the exact neighbour set and ARP + # family output chain below. + proxy_ips = sorted( + str(ipaddress.ip_network(item["destination_cidr"], strict=True).network_address) + for item in dataplane_routes) + members = ", ".join(sorted(member_cidrs)) + local_members = ", ".join(sorted(local_member_cidrs)) + destinations = ", ".join(sorted(destination_cidrs)) + local_destinations = ", ".join(sorted(local_destination_cidrs)) + proxy_destinations = ", ".join(proxy_ips) + local_sources = ", ".join( + f"{m.private_mac} . {m.private_ip}" for m in plan.local_members) + + def nft_set(name: str, type_name: str, elements: str, *, interval: bool = False) -> str: + flags = " flags interval;" if interval else "" + body = f" set {name} {{ type {type_name};{flags}" + if elements: + body += f" elements = {{ {elements} }};" + return body + " }" + + lines = [ + f"# {DATAPLANE_OWNER_MARKER}", f"# vpc-token={r.token}", + f"# vpc={plan.vpc.vpc_id} revision={plan.desired_revision} digest={plan.desired_digest}", + f"table inet {r.nft_table} {{", + nft_set("member_ips", "ipv4_addr", members, interval=True), + nft_set("local_member_ips", "ipv4_addr", local_members, interval=True), + nft_set("vpc_dest_ips", "ipv4_addr", destinations, interval=True), + nft_set("local_member_sources", "ether_addr . ipv4_addr", local_sources), + " chain forward { type filter hook forward priority -190; policy accept;", + f' iifname "{r.bridge}" ip saddr != @local_member_ips drop comment "{marker}:anti-spoof-local-ip"', + f' iifname "{r.bridge}" ip6 saddr ::/0 drop comment "{marker}:ipv6-drop-bridge"', + # A source address is not an ingress identity. A packet arriving on + # the public/management side must never be able to spoof a member /32 + # and use the VPC policy route to reach a private destination. Close + # both egress legs by interface before the source-address checks. + # The whole VPC CIDR is guarded, including currently unallocated + # addresses. A missing /32 route must therefore fail closed instead + # of falling through to the host's public/default route. + f' oifname "{r.bridge}" ip daddr {plan.vpc.cidr} iifname != "{r.bridge}" iifname != "{FABRIC_INTERFACE}" drop comment "{marker}:anti-spoof-public-to-vpc-bridge"', + f' oifname "{FABRIC_INTERFACE}" ip daddr {plan.vpc.cidr} iifname != "{r.bridge}" iifname != "{FABRIC_INTERFACE}" drop comment "{marker}:anti-spoof-public-to-vpc-fabric"', + f' iifname "{r.bridge}" ip daddr {plan.vpc.cidr} oifname != "{r.bridge}" oifname != "{FABRIC_INTERFACE}" drop comment "{marker}:anti-spoof-bridge-vpc-to-foreign"', + f' iifname "{FABRIC_INTERFACE}" ip daddr {plan.vpc.cidr} oifname != "{r.bridge}" oifname != "{FABRIC_INTERFACE}" drop comment "{marker}:anti-spoof-fabric-vpc-to-foreign"', + f' oifname "{r.bridge}" ip daddr @vpc_dest_ips iifname != "{r.bridge}" iifname != "{FABRIC_INTERFACE}" drop comment "{marker}:anti-spoof-public-to-bridge"', + f' oifname "{FABRIC_INTERFACE}" ip daddr @vpc_dest_ips iifname != "{r.bridge}" iifname != "{FABRIC_INTERFACE}" drop comment "{marker}:anti-spoof-public-to-fabric"', + # A VPC destination must also leave through one of the two owned legs. + # If a policy route disappears or a foreign/default route wins, the + # packet must be dropped rather than sent to a public or management + # interface. This is deliberately independent of source-IP checks. + f' iifname "{r.bridge}" ip daddr @vpc_dest_ips oifname != "{r.bridge}" oifname != "{FABRIC_INTERFACE}" drop comment "{marker}:anti-spoof-bridge-to-foreign"', + f' iifname "{FABRIC_INTERFACE}" ip daddr @vpc_dest_ips oifname != "{r.bridge}" oifname != "{FABRIC_INTERFACE}" drop comment "{marker}:anti-spoof-fabric-to-foreign"', + f' oifname "{r.bridge}" ip daddr @vpc_dest_ips ip saddr != @member_ips drop comment "{marker}:anti-spoof-egress"', + f' iifname "{FABRIC_INTERFACE}" ip daddr @vpc_dest_ips ip saddr != @member_ips drop comment "{marker}:anti-spoof-wg-ingress"', + f' oifname "{FABRIC_INTERFACE}" ip saddr @member_ips ip daddr != @vpc_dest_ips drop comment "{marker}:anti-spoof-wg-egress"', + f' iifname "{FABRIC_INTERFACE}" ip daddr @vpc_dest_ips ip saddr != @member_ips drop comment "{marker}:anti-spoof-wg-source"', + f' iifname "{r.bridge}" ip saddr @local_member_ips ip daddr != @vpc_dest_ips drop comment "{marker}:member-egress-isolation"', + f' iifname "{FABRIC_INTERFACE}" ip saddr @member_ips ip daddr != @vpc_dest_ips drop comment "{marker}:member-fabric-isolation"', + ] + # ACL priority is first-match order. Direction is relative to the VPC + # boundary: ingress is wg -> private bridge; egress is bridge -> wg. + # Same-host members have no wg leg, so their source/destination tuple is + # enforced on the bridge path as well. + for acl in plan.vpc.acls: + action = "accept" if acl.action == "allow" else "drop" + clause = (f" ip saddr {acl.source_cidr} ip daddr {acl.destination_cidr}" + f"{_nft_proto(acl)} {action} comment \"{marker}:acl:{acl.acl_id}\"") + if acl.direction == "ingress": + lines.append(f' iifname "{FABRIC_INTERFACE}" oifname "{r.bridge}"{clause}') + else: + lines.append(f' iifname "{r.bridge}" oifname "{FABRIC_INTERFACE}"{clause}') + lines.append(f' iifname "{r.bridge}" oifname "{r.bridge}"{clause}') + # Scope default-deny to member-to-member VPC traffic. The following + # interface-wide accepts preserve unrelated host/public forwarding. + lines += [ + f' iifname "{FABRIC_INTERFACE}" oifname "{r.bridge}" ip saddr @member_ips ip daddr @vpc_dest_ips counter drop comment "{marker}:default-deny"', + f' iifname "{r.bridge}" oifname "{FABRIC_INTERFACE}" ip saddr @member_ips ip daddr @vpc_dest_ips counter drop comment "{marker}:default-deny"', + f' iifname "{r.bridge}" oifname "{r.bridge}" ip saddr @member_ips ip daddr @vpc_dest_ips counter drop comment "{marker}:default-deny"', + f' iifname "{FABRIC_INTERFACE}" oifname "{FABRIC_INTERFACE}" ip saddr @member_ips ip daddr @vpc_dest_ips counter drop comment "{marker}:wg-transit-deny"', + f' iifname "{FABRIC_INTERFACE}" oifname "{r.bridge}" ip6 saddr ::/0 drop comment "{marker}:ipv6-drop-fabric"', + f' iifname "{r.bridge}" accept comment "{marker}:scope-bridge-in"', + f' oifname "{r.bridge}" accept comment "{marker}:scope-bridge-out"', + f' iifname "{FABRIC_INTERFACE}" accept comment "{marker}:scope-fabric-in"', + f' oifname "{FABRIC_INTERFACE}" accept comment "{marker}:scope-fabric-out"', + " }", + " chain input { type filter hook input priority -190; policy accept;", + f' iifname "{r.bridge}" ip saddr @member_ips drop comment "{marker}:host-isolation"', + f' iifname "{FABRIC_INTERFACE}" ip daddr @vpc_dest_ips drop comment "{marker}:host-isolation-wg"', + f' iifname "{FABRIC_INTERFACE}" ip saddr @member_ips ip daddr != @vpc_dest_ips drop comment "{marker}:host-isolation-wg-source"', + f' iifname "{r.bridge}" ip6 saddr ::/0 drop comment "{marker}:ipv6-input-drop-bridge"', + f' iifname "{FABRIC_INTERFACE}" ip6 saddr ::/0 drop comment "{marker}:ipv6-input-drop-fabric"', + " }", + " chain output { type filter hook output priority -190; policy accept;", + f' oifname "{r.bridge}" ip daddr @vpc_dest_ips drop comment "{marker}:host-isolation-out"', + # Host-originated packets must not be able to bind a tenant /32 and + # bypass the private egress boundary. Keep this leg unconditional; + # the source address is not an ingress identity. + f' oifname "{FABRIC_INTERFACE}" ip daddr @vpc_dest_ips drop comment "{marker}:host-isolation-out-wg"', + f' oifname "{r.bridge}" ip daddr {plan.vpc.cidr} drop comment "{marker}:host-isolation-vpc-out"', + f' oifname "{FABRIC_INTERFACE}" ip daddr {plan.vpc.cidr} drop comment "{marker}:host-isolation-vpc-out-wg"', + f' oifname "{r.bridge}" ip6 daddr ::/0 drop comment "{marker}:ipv6-output-drop-bridge"', + " }", "}", "", + ] + + # Bridge-family rules are emitted only when this host has a local VM. An + # empty VPC still gets the routed table above, while no empty nft set is + # needed for the L2/ARP path. + if plan.local_members: + lines += [ + f"table bridge {r.nft_table} {{", + nft_set("local_member_ips", "ipv4_addr", local_members, interval=True), + nft_set("local_dest_ips", "ipv4_addr", local_destinations, interval=True), + nft_set("local_member_sources", "ether_addr . ipv4_addr", local_sources), + " chain forward { type filter hook forward priority -190; policy accept;", + f' meta ibrname "{r.bridge}" ether type ip ether saddr . ip saddr != @local_member_sources drop comment "{marker}:bridge-anti-spoof-ingress"', + f' meta ibrname "{r.bridge}" ether type arp ether saddr != arp saddr ether drop comment "{marker}:bridge-anti-spoof-arp-mac"', + f' meta ibrname "{r.bridge}" ether type arp arp saddr ether . arp saddr ip != @local_member_sources drop comment "{marker}:bridge-anti-spoof-arp"', + f' meta ibrname "{r.bridge}" ether type ip ip saddr != @local_member_ips drop comment "{marker}:bridge-anti-spoof-ip"', + f' meta ibrname "{r.bridge}" ether type arp arp saddr ip != @local_member_ips drop comment "{marker}:bridge-anti-spoof-arp-ip"', + # This is an L3 /32 fabric. Do not let broadcast or multicast + # discovery turn the private bridge back into a shared L2 LAN. + f' meta ibrname "{r.bridge}" ip daddr 224.0.0.0/4 drop comment "{marker}:bridge-multicast-drop"', + f' meta ibrname "{r.bridge}" ip daddr 255.255.255.255 drop comment "{marker}:bridge-limited-broadcast-drop"', + f' meta ibrname "{r.bridge}" ip daddr {ipaddress.ip_network(plan.vpc.cidr).broadcast_address} drop comment "{marker}:bridge-vpc-broadcast-drop"', + f' meta ibrname "{r.bridge}" ip saddr @local_member_ips ip daddr != @local_dest_ips drop comment "{marker}:bridge-unknown-destination-drop"', + ] + for acl in plan.vpc.acls: + action = "accept" if acl.action == "allow" else "drop" + clause = (f" ip saddr {acl.source_cidr} ip daddr {acl.destination_cidr}" + f"{_nft_proto(acl)} {action} comment \"{marker}:acl:{acl.acl_id}\"") + lines.append(f' meta ibrname "{r.bridge}" meta obrname "{r.bridge}"{clause}') + lines += [ + f' meta ibrname "{r.bridge}" meta obrname "{r.bridge}" ip saddr @local_member_ips ip daddr @local_dest_ips counter drop comment "{marker}:bridge-default-deny"', + f' meta ibrname "{r.bridge}" ether type arp accept comment "{marker}:bridge-arp-accept"', + f' meta ibrname "{r.bridge}" ether type ip accept comment "{marker}:bridge-scope-accept"', + f' meta ibrname "{r.bridge}" counter drop comment "{marker}:bridge-non-ip-drop"', + " }", + " chain input { type filter hook input priority -190; policy accept;", + f' meta ibrname "{r.bridge}" ether type arp ether saddr != arp saddr ether drop comment "{marker}:bridge-anti-spoof-arp-input-mac"', + f' meta ibrname "{r.bridge}" ether type ip ether saddr . ip saddr != @local_member_sources drop comment "{marker}:bridge-anti-spoof-input-ip"', + f' meta ibrname "{r.bridge}" ether type arp arp saddr ether . arp saddr ip != @local_member_sources drop comment "{marker}:bridge-anti-spoof-input"', + f' meta ibrname "{r.bridge}" ether type ip6 drop comment "{marker}:bridge-ipv6-input-drop"', + f' meta ibrname "{r.bridge}" ether type arp accept comment "{marker}:bridge-arp-input-accept"', + # Proxy ARP makes remote /32 packets arrive at the bridge MAC and + # then enter the host routing path. Source/MAC checks above have + # already authenticated the guest, so IPv4 must be accepted here + # for the inet forward hook to route it to wg-fabric0. + f' meta ibrname "{r.bridge}" ether type ip accept comment "{marker}:bridge-ip-input-accept"', + f' meta ibrname "{r.bridge}" counter drop comment "{marker}:bridge-input-non-ip-drop"', + " }", + "}", "", + ] + lines += [ + f"table arp {r.nft_table} {{", + nft_set("proxy_ips", "ipv4_addr", proxy_destinations, interval=True), + " chain output { type filter hook output priority -190; policy accept;", + f' oifname "{r.bridge}" arp operation reply arp saddr ip != @proxy_ips drop comment "{marker}:arp-proxy-output"', + " }", + "}", "", + ] + return "\n".join(lines) + + +def _here(path: str, content: str) -> str: + marker = "__VC_VPC_" + hashlib.sha256(content.encode()).hexdigest()[:16] + return f"cat > {_q(path)} <<'{marker}'\n{content}{'' if content.endswith(chr(10)) else chr(10)}{marker}\n" + + +def _state(plan: VpcDataplanePlan, routes: Sequence[Mapping[str, Any]]) -> str: + r = plan.resources + lines = [f"owner|{DATAPLANE_OWNER_MARKER}", f"vpc|{plan.vpc.vpc_id}", + f"cidr|{plan.vpc.cidr}", f"fabric|{plan.vpc.fabric_id}", + f"host|{plan.host_id}", f"revision|{plan.desired_revision}", + f"digest|{plan.desired_digest}", f"bridge|{r.bridge}", + f"table|{r.route_table}", f"priority|{r.rule_priority}"] + for route in routes: + lines.append("route|{destination}|{device}|{table}|{via}|{metric}".format( + destination=route["destination_cidr"], device=route["device"], + table=route["table"], via=route.get("via") or "-", + metric=route.get("metric", 100))) + for peer in plan.peers: + ips = sorted(set( + [m.private_ip + "/32" for m in plan.remote_members + if m.host_id == peer.host_id] + + list(peer.tenant_allowed_ips))) + if ips: + lines.append(f"peer|{peer.host_id}|{peer.public_key}|{','.join(ips)}") + return "\n".join(lines) + "\n" + + +def _allowed(plan: VpcDataplanePlan, peer: VpcFabricPeer) -> str: + members = {m.member_id: m for m in plan.members} + ips = {m.private_ip + "/32" for m in plan.remote_members + if m.host_id == peer.host_id} + for route in plan.vpc.routes: + target = (members.get(route.next_hop_member_id) + if route.next_hop_member_id is not None else None) + target_host = target.host_id if target is not None else route.next_hop_host_id + if target_host == peer.host_id: + ips.add(route.destination_cidr) + return ",".join([peer.overlay_cidr] + sorted(ips | set(peer.tenant_allowed_ips))) + + +def render_apply_script(plan: VpcDataplanePlan) -> str: + """Generate a shell transaction with panel ownership and rollback markers.""" + routes = _routes(plan) + if plan.remote_members and not plan.peers: + raise VpcDataplaneError("跨宿主机 VPC 缺少 Fabric peer", 409, "vpc_fabric_peer_missing") + r = plan.resources + nft = render_vpc_nft_rules(plan) + state = _state(plan, routes) + route_specs = "\\n".join( + f"{x['destination_cidr']}|{x['device']}|{x['table']}" for x in routes) + peer_specs = "\\n".join( + f"{p.host_id}|{p.public_key}|{_allowed(plan,p)}" for p in plan.peers) + route_checks = "\\n".join( + f'''actual=$("$IP" -o -4 route show table {_q(x["table"])} {_q(x["destination_cidr"])} 2>/dev/null || true) +if printf '%s\\n' "$actual" | grep -Fq "dev {_q(x["device"])}" && printf '%s\\n' "$actual" | grep -Eq 'proto 186([[:space:]]|$)'; then + printf '%s\\n' "__VC_VPC_ROUTE__={x["destination_cidr"]}|{x["device"]}|{x["table"]}|owned" +else + printf '%s\\n' "__VC_VPC_ROUTE__={x["destination_cidr"]}|{x["device"]}|{x["table"]}|missing" +fi''' + for x in routes) + peer_checks = "\\n".join( + f'''actual=$("$WG" show "$WG_IFACE" allowed-ips 2>/dev/null | awk -v wanted={_q(p.public_key)} '$1==wanted {{print $2; exit}}' || true) +tenant={_q(','.join(_allowed(plan, p).split(',')[1:]))} +case ",$actual," in *",$tenant,"*) printf '%s\\n' "__VC_VPC_WG_ALLOWED__={p.host_id}|{p.public_key}|$tenant";; *) printf '%s\\n' "__VC_VPC_WG_ALLOWED__={p.host_id}|{p.public_key}|missing";; esac''' + for p in plan.peers) + script = f'''#!/bin/sh +set -eu +umask 077 +PATH=/usr/sbin:/usr/bin:/sbin:/bin +export PATH +IP=/usr/sbin/ip; [ -x "$IP" ] || IP=/usr/bin/ip +WG=/usr/bin/wg; [ -x "$WG" ] || WG=/usr/sbin/wg +NFT=/usr/sbin/nft; [ -x "$NFT" ] || NFT=/usr/bin/nft +FLOCK=/usr/bin/flock; [ -x "$FLOCK" ] || FLOCK=/usr/bin/flock +BASE=/etc/virt-cloud/vpc-dataplane +BRIDGE={_q(r.bridge)}; TABLE={_q(r.nft_table)}; ROUTE_TABLE={r.route_table}; RULE_PRIORITY={r.rule_priority} +WG_IFACE={_q(FABRIC_INTERFACE)}; OWNER={_q(r.owner_file)}; STATE={_q(r.state_file)}; LOCK={_q(r.lock_file)}; TXN={_q(r.transaction_dir)} +COMMITTED=no; BRIDGE_CREATED=no; NFT_BEFORE=no; WG_BEFORE=no; ROLLBACK_FAILED=no +mkdir -p /run/virt-cloud "$BASE" +[ ! -L /run/virt-cloud ] && [ ! -L "$BASE" ] || exit 71 +: >> "$LOCK"; chmod 600 "$LOCK"; exec 9>>"$LOCK"; "$FLOCK" -x 9 +rollback() {{ + status=$?; [ "$COMMITTED" = yes ] && return "$status"; trap - EXIT HUP INT TERM + oldIFS=$IFS; IFS=' ' + for spec in { _q(route_specs) }; do destination=${{spec%%|*}}; device=${{spec#*|}}; "$IP" route del "$destination" table "$ROUTE_TABLE" dev "$device" >/dev/null 2>&1 || true; done + IFS=$oldIFS + "$IP" rule del pref "$RULE_PRIORITY" iif "$BRIDGE" to {_q(plan.vpc.cidr)} lookup "$ROUTE_TABLE" >/dev/null 2>&1 || true + if [ "$WG_BEFORE" = yes ] && [ -f "$TXN/wg.conf" ]; then "$WG" setconf "$WG_IFACE" "$TXN/wg.conf" >/dev/null 2>&1 || ROLLBACK_FAILED=yes; fi + if [ "$NFT_BEFORE" = yes ] && [ -f "$TXN/nft.before" ]; then "$NFT" delete table inet "$TABLE" >/dev/null 2>&1 || true; "$NFT" -f "$TXN/nft.before" >/dev/null 2>&1 || ROLLBACK_FAILED=yes; else "$NFT" delete table inet "$TABLE" >/dev/null 2>&1 || true; fi + if [ "$BRIDGE_CREATED" = yes ]; then "$IP" link del dev "$BRIDGE" >/dev/null 2>&1 || ROLLBACK_FAILED=yes; fi + [ "$ROLLBACK_FAILED" = yes ] && printf '%s\\n' '__VC_VPC_ROLLBACK__=failed' >&2 || printf '%s\\n' '__VC_VPC_ROLLBACK__=ok' >&2 + exit "$status" +}} +trap rollback EXIT HUP INT TERM +[ -x "$IP" ] && [ -x "$WG" ] && [ -x "$NFT" ] && [ -x "$FLOCK" ] || exit 70 +[ -f /etc/virt-cloud/wg-fabric0.owner ] && grep -Fqx { _q(FABRIC_OWNER_MARKER) } /etc/virt-cloud/wg-fabric0.owner || exit 71 +"$IP" link show dev "$WG_IFACE" >/dev/null 2>&1 && "$WG" show "$WG_IFACE" >/dev/null 2>&1 || exit 72 +[ ! -e "$TXN" ] && [ ! -L "$TXN" ] || exit 79 +mkdir -p "$TXN"; printf '%s\\n' '{DATAPLANE_OWNER_MARKER}:{plan.vpc.vpc_id}:{plan.host_id}:{plan.desired_revision}:{plan.desired_digest}' > "$TXN/inflight" +if [ -f "$STATE" ]; then cp -p "$STATE" "$TXN/state.before"; grep -Fqx 'owner|{DATAPLANE_OWNER_MARKER}' "$STATE" || exit 71; fi +if [ -f "$OWNER" ]; then grep -Fqx { _q(DATAPLANE_OWNER_MARKER) } "$OWNER" || exit 71; else printf '%s\\n' { _q(DATAPLANE_OWNER_MARKER) } > "$OWNER"; chmod 600 "$OWNER"; fi +if "$IP" link show dev "$BRIDGE" >/dev/null 2>&1; then + "$IP" -d link show dev "$BRIDGE" | grep -Eq '(^|[[:space:]])bridge[[:space:]]+(forward_delay|stp_state|hello_time|ageing_time)([[:space:]]|$)' || exit 71 +else + "$IP" link add name "$BRIDGE" type bridge; BRIDGE_CREATED=yes +fi +"$IP" link set dev "$BRIDGE" up +if "$WG" showconf "$WG_IFACE" > "$TXN/wg.conf" 2>/dev/null; then WG_BEFORE=yes; fi +if "$NFT" list table inet "$TABLE" > "$TXN/nft.before" 2>/dev/null; then NFT_BEFORE=yes; grep -Fq { _q(DATAPLANE_OWNER_MARKER) } "$TXN/nft.before" || exit 71; fi +'''+_here('$TXN/rules.nft', nft)+f'''"$NFT" delete table inet "$TABLE" >/dev/null 2>&1 || true +"$NFT" -f "$TXN/rules.nft" +oldIFS=$IFS; IFS=' ' +for spec in { _q(route_specs) }; do destination=${{spec%%|*}}; device=${{spec#*|}}; "$IP" route replace "$destination" table "$ROUTE_TABLE" dev "$device" metric 100; done +IFS=$oldIFS +"$IP" rule replace pref "$RULE_PRIORITY" iif "$BRIDGE" to {_q(plan.vpc.cidr)} lookup "$ROUTE_TABLE" +oldIFS=$IFS; IFS=' ' +for spec in { _q(peer_specs) }; do rest=${{spec#*|}}; key=${{rest%%|*}}; allowed=${{rest#*|}}; "$WG" show "$WG_IFACE" peers | grep -Fqx "$key" || exit 74; "$WG" set "$WG_IFACE" peer "$key" allowed-ips "$allowed"; done +IFS=$oldIFS +'''+_here('$STATE', state)+f'''chmod 600 "$STATE" +printf '%s\\n' '__VC_VPC_APPLIED__=yes' +printf '%s\\n' '__VC_VPC_OWNER__={DATAPLANE_OWNER_MARKER}' +printf '%s\\n' '__VC_VPC_REVISION__={plan.desired_revision}' +printf '%s\\n' '__VC_VPC_DIGEST__={plan.desired_digest}' +COMMITTED=yes; trap - EXIT HUP INT TERM; rm -rf "$TXN"; exit 0 +''' + if len(script) > MAX_OUTPUT: + raise VpcDataplaneError("VPC 数据面脚本过大", 413, "vpc_script_too_large") + return script + + +def _render_apply_script_v2( + plan: VpcDataplanePlan, + *, + deployment_mode: str = "networkmanager_nmcli", + ifup_path: str = "/usr/sbin/ifup", + ifdown_path: str = "/usr/sbin/ifdown", + ifquery_path: str = "/usr/sbin/ifquery", +) -> str: + """Generate the production transaction used by the host adapter. + + The original control-plane module predates distribution-specific bridge + persistence. Keep its public builder for compatibility, but route real + applies through this stricter builder: every list is newline-delimited, + every path is fixed/quoted, and rollback only removes exact resources + tagged with the panel route protocol or ownership marker. + """ + if deployment_mode not in {"networkmanager_nmcli", "ifupdown"}: + raise VpcDataplaneError("宿主机网络管理模式不支持", 409, + "vpc_dataplane_network_manager_conflict") + allowed_ifup = {"/usr/sbin/ifup", "/usr/bin/ifup", "/sbin/ifup", "/bin/ifup"} + allowed_ifdown = {"/usr/sbin/ifdown", "/usr/bin/ifdown", "/sbin/ifdown", "/bin/ifdown"} + allowed_ifquery = {"/usr/sbin/ifquery", "/usr/bin/ifquery", "/sbin/ifquery", "/bin/ifquery"} + if ifup_path not in allowed_ifup or ifdown_path not in allowed_ifdown or ifquery_path not in allowed_ifquery: + raise VpcDataplaneError("ifupdown 工具路径不受支持", 409, + "vpc_dataplane_network_manager_conflict") + from .fabric import _VPC_STATE_LOADER + + routes = _routes(plan) + if plan.remote_members and not plan.peers: + raise VpcDataplaneError("跨宿主机 VPC 缺少 Fabric peer", 409, + "vpc_fabric_peer_missing") + r = plan.resources + nft = render_vpc_nft_rules(plan) + include = f"/etc/nftables.d/virt-cloud-vpc-{r.token}.nft" + include_line = f'include "{include}"' + fragment = f"/etc/network/interfaces.d/virt-cloud-vpc-{r.token}" + sysctl_file = f"/etc/sysctl.d/99-virt-cloud-vpc-{r.token}.conf" + state_dir = f"/etc/virt-cloud/vpc-dataplane" + proxy_file = f"{state_dir}/{r.token}.proxy" + route_lines = "\n".join( + f"{item['destination_cidr']}|{item['device']}|{item['table']}|" + f"{item.get('via') or '-'}|{item.get('metric', 100)}" + for item in routes) + bridge_route_lines = "\n".join( + f"{item['destination_cidr']}|{item['device']}|{item['table']}|" + f"{item.get('via') or '-'}|{item.get('metric', 100)}|186" + for item in routes if item["device"] == r.bridge) + proxy_lines = "\n".join( + str(ipaddress.ip_network(item["destination_cidr"], strict=True).network_address) + for item in routes) + peer_lines = "\n".join( + f"{peer.host_id}|{peer.public_key}|{_allowed(plan, peer)}" + for peer in plan.peers) + state = _state(plan, routes) + # Local service /32s use a guest address as the next hop on an otherwise + # unnumbered private bridge. Linux therefore needs the explicit `onlink` + # assertion; without it iproute2 rejects the route as an invalid gateway. + # Use a quoted heredoc for data, while keeping the destination as a shell + # variable expanded by the surrounding script. This avoids the literal + # ``$TXN`` path bug in the former builder. + nft_marker = "__VC_VPC_NFT_" + hashlib.sha256(nft.encode()).hexdigest()[:12] + state_marker = "__VC_VPC_STATE_" + hashlib.sha256(state.encode()).hexdigest()[:12] + frag_marker = "__VC_VPC_IFUP_" + r.token + route_marker = "__VC_VPC_ROUTES_" + r.token + proxy_marker = "__VC_VPC_PROXY_" + r.token + peer_marker = "__VC_VPC_PEERS_" + r.token + state_loader = _VPC_STATE_LOADER.replace( + "__VC_FABRIC_HOST_ID__", plan.host_id).replace( + "__VC_FABRIC_ID__", plan.vpc.fabric_id).replace( + "__VC_FABRIC_NETWORK__", "100.64.0.0/10").replace( + "__VC_VPC_STATE_OBSERVE__", "no") + script = f'''#!/bin/sh +set -eu +umask 077 +PATH=/usr/sbin:/usr/bin:/sbin:/bin +export PATH +IP=$(for p in /usr/sbin/ip /usr/bin/ip /sbin/ip /bin/ip; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +WG=$(for p in /usr/bin/wg /usr/sbin/wg /bin/wg /sbin/wg; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +NFT=$(for p in /usr/sbin/nft /usr/bin/nft /sbin/nft /bin/nft; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +FLOCK=$(for p in /usr/bin/flock /usr/sbin/flock /bin/flock /sbin/flock; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +STAT=$(for p in /usr/bin/stat /bin/stat /usr/sbin/stat /sbin/stat; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +CMP=$(for p in /usr/bin/cmp /bin/cmp /usr/sbin/cmp /sbin/cmp; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +SYSCTL=$(for p in /usr/sbin/sysctl /usr/bin/sysctl /sbin/sysctl /bin/sysctl; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +BRIDGE_CMD=$(for p in /usr/sbin/bridge /usr/bin/bridge /sbin/bridge /bin/bridge; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +BRIDGE={_q(r.bridge)}; TABLE={_q(r.nft_table)}; ROUTE_TABLE={r.route_table}; RULE_PRIORITY={r.rule_priority}; WG_RULE_PRIORITY=$((RULE_PRIORITY + 1)) +WG_IFACE={_q(FABRIC_INTERFACE)}; OWNER_MARKER={_q(DATAPLANE_OWNER_MARKER)}; FABRIC_OWNER={_q(FABRIC_OWNER_MARKER)} +OWNER_FILE={_q(r.owner_file)}; STATE_FILE={_q(r.state_file)}; LOCK={_q(r.lock_file)}; TXN={_q(r.transaction_dir)}; PROXY_FILE={_q(proxy_file)} +NFT_FILE={_q(include)}; NFT_INCLUDE={_q(include_line)}; IF_FRAGMENT={_q(fragment)}; SYSCTL_FILE={_q(sysctl_file)}; MODE={_q(deployment_mode)}; NFT_MAIN= +IFUP={_q(ifup_path)}; IFDOWN={_q(ifdown_path)}; IFQUERY={_q(ifquery_path)}; NMCLI= +NM_PROFILE_MARKER={_q(DATAPLANE_OWNER_MARKER + " vpc=" + plan.vpc.vpc_id)} +COMMITTED=no; BRIDGE_CREATED=no; BRIDGE_WAS_UP=no; NM_CREATED=no; NM_WAS_ACTIVE=no; NM_ACTIVATION_ATTEMPTED=no; IF_CREATED=no; IF_ACTIVATION_ATTEMPTED=no; IF_FRAGMENT_CHANGED=no; SYSCTL_CHANGED=no; RP_FILTER_CHANGED=no; PROXY_ARP_CHANGED=no; PROXY_ARP_PVLAN_CHANGED=no; NFT_FILE_CHANGED=no; NFT_MAIN_CHANGED=no; NFT_FILE_BEFORE=no; NFT_MAIN_BEFORE=no; BRIDGE_NFT_BEFORE=no; ARP_NFT_BEFORE=no; FABRIC_NFT_BEFORE=no; PROXY_ENTRIES_CHANGED=no; PROXY_FILE_CHANGED=no; ROLLBACK_FAILED=no +[ -n "$IP" ] && [ -n "$WG" ] && [ -n "$NFT" ] && [ -n "$FLOCK" ] && [ -n "$STAT" ] && [ -n "$CMP" ] && [ -n "$SYSCTL" ] && [ -n "$BRIDGE_CMD" ] || exit 70 +if [ "$MODE" = networkmanager_nmcli ]; then + NMCLI=$(for p in /usr/bin/nmcli /usr/sbin/nmcli /bin/nmcli /sbin/nmcli; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) + [ -n "$NMCLI" ] || exit 70 +fi +if [ -L /run/virt-cloud ] || {{ [ -e /run/virt-cloud ] && [ ! -d /run/virt-cloud ]; }}; then exit 71; fi +if [ -L /etc/virt-cloud ] || {{ [ -e /etc/virt-cloud ] && [ ! -d /etc/virt-cloud ]; }}; then exit 71; fi +if [ -L {state_dir} ] || {{ [ -e {state_dir} ] && [ ! -d {state_dir} ]; }}; then exit 71; fi +mkdir -p /run/virt-cloud {state_dir} +chmod 700 /run/virt-cloud {state_dir} +[ ! -L {state_dir} ] && [ "$($STAT -c '%u:%a' {state_dir} 2>/dev/null)" = 0:700 ] || exit 71 +[ ! -L "$LOCK" ] && {{ [ ! -e "$LOCK" ] || [ -f "$LOCK" ]; }} || exit 71 +: >> "$LOCK"; chmod 600 "$LOCK" +exec 8>>{_q(FABRIC_LOCK)}; "$FLOCK" -x 8 +exec 9>>"$LOCK"; "$FLOCK" -x 9 +[ -f /etc/virt-cloud/wg-fabric0.owner ] && [ "$(cat /etc/virt-cloud/wg-fabric0.owner)" = "$FABRIC_OWNER" ] || exit 71 +"$WG" show "$WG_IFACE" >/dev/null 2>&1 || exit 71 +NFT_MAIN_COUNT=0 +for nft_candidate in /etc/nftables.conf /etc/sysconfig/nftables.conf; do + if [ -f "$nft_candidate" ] && [ ! -L "$nft_candidate" ] && [ "$("$STAT" -c '%u' "$nft_candidate" 2>/dev/null)" = 0 ]; then + case "$("$STAT" -c '%a' "$nft_candidate" 2>/dev/null)" in + [0-7][0145][0145]) : ;; + *) continue ;; + esac + NFT_MAIN="$nft_candidate"; NFT_MAIN_COUNT=$((NFT_MAIN_COUNT + 1)) + fi +done +[ "$NFT_MAIN_COUNT" -eq 1 ] || exit 71 +if [ -L /etc/nftables.d ] || {{ [ -e /etc/nftables.d ] && [ ! -d /etc/nftables.d ]; }}; then exit 71; fi +if [ -e /etc/nftables.d ]; then + [ "$("$STAT" -c '%u:%a' /etc/nftables.d 2>/dev/null)" = 0:755 ] || exit 71 +else + mkdir /etc/nftables.d; chmod 755 /etc/nftables.d +fi +if [ -L /etc/sysctl.d ] || {{ [ -e /etc/sysctl.d ] && [ ! -d /etc/sysctl.d ]; }}; then exit 71; fi +if [ -e /etc/sysctl.d ]; then + [ "$("$STAT" -c '%u:%a' /etc/sysctl.d 2>/dev/null)" = 0:755 ] || exit 71 +else + mkdir /etc/sysctl.d; chmod 755 /etc/sysctl.d +fi +if [ -e "$SYSCTL_FILE" ] || [ -L "$SYSCTL_FILE" ]; then + [ -f "$SYSCTL_FILE" ] && [ ! -L "$SYSCTL_FILE" ] || exit 71 + [ "$("$STAT" -c '%u' "$SYSCTL_FILE" 2>/dev/null)" = 0 ] || exit 71 + grep -Fqx '# virt-cloud-vpc-dataplane-v1' "$SYSCTL_FILE" || exit 71 +fi +if [ -e "$PROXY_FILE" ] || [ -L "$PROXY_FILE" ]; then + [ -f "$PROXY_FILE" ] && [ ! -L "$PROXY_FILE" ] || exit 71 + [ "$($STAT -c '%u:%a' "$PROXY_FILE" 2>/dev/null)" = 0:600 ] || exit 71 + sed -n '1p' "$PROXY_FILE" | grep -Fqx '# virt-cloud-vpc-proxy-v1' || exit 71 + awk 'NR > 1 && $0 !~ /^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$/ {{ exit 1 }}' "$PROXY_FILE" || exit 71 +fi +if [ -e "$NFT_FILE" ] || [ -L "$NFT_FILE" ]; then + [ -f "$NFT_FILE" ] && [ ! -L "$NFT_FILE" ] || exit 71 + [ "$("$STAT" -c '%u' "$NFT_FILE" 2>/dev/null)" = 0 ] || exit 71 + grep -Fqx '# virt-cloud-vpc-dataplane-v1' "$NFT_FILE" || exit 71 +fi +if [ -L "$OWNER_FILE" ] || {{ [ -e "$OWNER_FILE" ] && [ ! -f "$OWNER_FILE" ]; }}; then exit 71; fi +if [ -L "$STATE_FILE" ] || {{ [ -e "$STATE_FILE" ] && [ ! -f "$STATE_FILE" ]; }}; then exit 71; fi +if [ -f "$STATE_FILE" ]; then + [ "$($STAT -c '%u:%a' "$STATE_FILE" 2>/dev/null)" = 0:600 ] || exit 71 + grep -Fqx 'owner|{DATAPLANE_OWNER_MARKER}' "$STATE_FILE" || exit 71 + grep -Fqx 'vpc|{plan.vpc.vpc_id}' "$STATE_FILE" || exit 71 + grep -Fqx 'fabric|{plan.vpc.fabric_id}' "$STATE_FILE" || exit 71 + grep -Fqx 'host|{plan.host_id}' "$STATE_FILE" || exit 71 + grep -Fqx 'bridge|{r.bridge}' "$STATE_FILE" || exit 71 + grep -Fqx 'table|{r.route_table}' "$STATE_FILE" || exit 71 + state_revision=$(awk -F'|' '$1=="revision" {{print $2; exit}}' "$STATE_FILE") + state_digest=$(awk -F'|' '$1=="digest" {{print $2; exit}}' "$STATE_FILE") + case "$state_revision" in ''|*[!0-9]*) exit 79;; esac + printf '%s\n' "$state_digest" | grep -Eq '^[0-9a-f]{{64}}$' || exit 79 + [ "$state_revision" -le {plan.desired_revision} ] || exit 79 + if [ "$state_revision" = {plan.desired_revision} ] && [ "$state_digest" != { _q(plan.desired_digest) } ]; then exit 79; fi +fi +if [ -e "$TXN" ] || [ -L "$TXN" ]; then + # A process can die after writing the committed marker but before removing + # its transaction directory. That state is safe to reap after validating + # ownership; preparing/ready/rollback_failed states remain blocked so a + # later reconcile cannot guess whether runtime resources were partially + # applied. + [ -d "$TXN" ] && [ ! -L "$TXN" ] || exit 79 + [ "$("$STAT" -c '%u:%a' "$TXN" 2>/dev/null)" = 0:700 ] || exit 79 + [ -f "$TXN/inflight" ] && [ ! -L "$TXN/inflight" ] || exit 79 + grep -Fqx '{DATAPLANE_OWNER_MARKER}:{plan.vpc.vpc_id}:{plan.host_id}:{plan.desired_revision}:{plan.desired_digest}' "$TXN/inflight" || exit 79 + [ -f "$TXN/state" ] && [ "$(cat "$TXN/state" 2>/dev/null)" = committed ] || exit 79 + rm -rf "$TXN" || exit 79 +fi +mkdir -m 700 "$TXN" +printf '%s\\n' preparing > "$TXN/state"; chmod 600 "$TXN/state" +rollback() {{ + status=$?; [ "$COMMITTED" = yes ] && exit "$status"; trap - EXIT HUP INT TERM + set +e + while IFS='|' read -r destination device table via metric; do + [ -n "$destination" ] || continue + actual=$("$IP" -o -4 route show table "$table" "$destination" 2>/dev/null || true) + [ -n "$actual" ] || continue + actual_count=$(printf '%s\n' "$actual" | awk 'NF {{count++}} END {{print count + 0}}') + actual_device=$(printf '%s\n' "$actual" | awk '{{for (i=1;i<=NF;i++) if ($i=="dev" && i/dev/null || ROLLBACK_FAILED=yes + else + "$IP" route del "$destination" table "$table" via "$via" dev "$device" proto 186 metric "$metric" 2>/dev/null || ROLLBACK_FAILED=yes + fi + done <<'{route_marker}' +{route_lines} +{route_marker} + if [ "$ROLLBACK_FAILED" = no ] && [ -f "$TXN/routes.before" ]; then + while IFS='|' read -r old_destination old_device old_table old_via old_metric; do + [ -n "$old_destination" ] || continue + if [ "$old_via" = - ]; then + "$IP" route replace "$old_destination" table "$old_table" dev "$old_device" proto 186 metric "$old_metric" 2>/dev/null || ROLLBACK_FAILED=yes + else + "$IP" route replace "$old_destination" table "$old_table" via "$old_via" dev "$old_device" proto 186 metric "$old_metric" 2>/dev/null || ROLLBACK_FAILED=yes + fi + done < "$TXN/routes.before" + fi + if [ "$ROLLBACK_FAILED" = no ]; then + for rule_spec in "$RULE_PRIORITY|$ROUTE_TABLE|-" "$WG_RULE_PRIORITY|$ROUTE_TABLE|$WG_IFACE"; do + rule_pref=${{rule_spec%%|*}}; rule_rest=${{rule_spec#*|}}; rule_table=${{rule_rest%%|*}}; rule_iif=${{rule_rest#*|}} + actual_rule=$("$IP" -o rule show pref "$rule_pref" 2>/dev/null || true) + [ -n "$actual_rule" ] || continue + actual_rule_count=$(printf '%s\n' "$actual_rule" | awk 'NF {{count++}} END {{print count + 0}}') + if [ "$actual_rule_count" != 1 ] || ! printf '%s\n' "$actual_rule" | grep -Fq "to {_q(plan.vpc.cidr)} lookup $rule_table"; then + ROLLBACK_FAILED=yes + continue + fi + if [ "$rule_iif" = - ]; then + if printf '%s\n' "$actual_rule" | grep -Eq '(^|[[:space:]])iif[[:space:]]'; then + ROLLBACK_FAILED=yes + continue + fi + elif ! printf '%s\n' "$actual_rule" | grep -Fq "iif $rule_iif"; then + ROLLBACK_FAILED=yes + continue + fi + "$IP" rule del pref "$rule_pref" 2>/dev/null || ROLLBACK_FAILED=yes + remaining_rule=$("$IP" -o rule show pref "$rule_pref" 2>/dev/null || true) + [ -z "$remaining_rule" ] || ROLLBACK_FAILED=yes + done + fi + if [ "$ROLLBACK_FAILED" = no ] && [ -f "$TXN/rules.before" ]; then + while IFS='|' read -r old_pref old_iif old_to old_lookup; do + [ -n "$old_pref" ] || continue + if [ "$old_iif" = - ]; then + "$IP" rule add pref "$old_pref" to "$old_to" lookup "$old_lookup" 2>/dev/null || ROLLBACK_FAILED=yes + else + "$IP" rule add pref "$old_pref" iif "$old_iif" to "$old_to" lookup "$old_lookup" 2>/dev/null || ROLLBACK_FAILED=yes + fi + done < "$TXN/rules.before" + fi + if [ -f "$TXN/wg.conf" ]; then "$WG" setconf "$WG_IFACE" "$TXN/wg.conf" >/dev/null 2>&1 || ROLLBACK_FAILED=yes; fi + if [ "$PROXY_ENTRIES_CHANGED" = yes ]; then + "$IP" neigh show proxy dev "$BRIDGE" 2>/dev/null | awk '$1 ~ /^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$/ {{print $1}}' | LC_ALL=C sort -u > "$TXN/proxy.rollback.current" + cat <<'{proxy_marker}' | LC_ALL=C sort -u > "$TXN/proxy.rollback.desired" +{proxy_lines} +{proxy_marker} + if "$CMP" -s "$TXN/proxy.rollback.current" "$TXN/proxy.rollback.desired"; then + while IFS= read -r rollback_proxy; do + [ -n "$rollback_proxy" ] || continue + "$IP" neigh del proxy "$rollback_proxy" dev "$BRIDGE" >/dev/null 2>&1 || ROLLBACK_FAILED=yes + done < "$TXN/proxy.rollback.desired" + while IFS= read -r rollback_proxy; do + [ -n "$rollback_proxy" ] || continue + "$IP" neigh replace proxy "$rollback_proxy" dev "$BRIDGE" >/dev/null 2>&1 || ROLLBACK_FAILED=yes + done < "$TXN/proxy.before" + else + # Do not delete an entry added concurrently by an operator or another + # controller. Leave the transaction recoverable and report rollback + # failure rather than risking an unrelated ARP outage. + ROLLBACK_FAILED=yes + fi + fi + if [ "$PROXY_FILE_CHANGED" = yes ]; then + if [ -f "$TXN/proxy_file.before" ]; then + cp -p "$TXN/proxy_file.before" "$PROXY_FILE" || ROLLBACK_FAILED=yes + else + rm -f "$PROXY_FILE" || ROLLBACK_FAILED=yes + fi + fi + # Restore runtime sysctls while the new ARP guard is still installed; this + # avoids a rollback window in which proxy_arp is enabled without its exact + # output filter. + if [ "$PROXY_ARP_CHANGED" = yes ] && [ -e "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp" ]; then + if [ -f "$TXN/proxy_arp.before" ]; then + cat "$TXN/proxy_arp.before" > "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp" || ROLLBACK_FAILED=yes + else + printf '%s\\n' 0 > "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp" || ROLLBACK_FAILED=yes + fi + fi + if [ "$PROXY_ARP_PVLAN_CHANGED" = yes ] && [ -e "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp_pvlan" ]; then + if [ -f "$TXN/proxy_arp_pvlan.before" ]; then + cat "$TXN/proxy_arp_pvlan.before" > "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp_pvlan" || ROLLBACK_FAILED=yes + else + printf '%s\n' 0 > "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp_pvlan" || ROLLBACK_FAILED=yes + fi + fi + if [ "$RP_FILTER_CHANGED" = yes ] && [ -e "/proc/sys/net/ipv4/conf/$BRIDGE/rp_filter" ]; then + if [ -f "$TXN/rp_filter.before" ]; then + cat "$TXN/rp_filter.before" > "/proc/sys/net/ipv4/conf/$BRIDGE/rp_filter" || ROLLBACK_FAILED=yes + fi + fi + NFT_ROLLBACK="$TXN/rollback.nft" + : > "$NFT_ROLLBACK" + if "$NFT" list table inet "$TABLE" >/dev/null 2>&1; then printf 'delete table inet %s\\n' "$TABLE" >> "$NFT_ROLLBACK"; fi + if "$NFT" list table bridge "$TABLE" >/dev/null 2>&1; then printf 'delete table bridge %s\\n' "$TABLE" >> "$NFT_ROLLBACK"; fi + if "$NFT" list table arp "$TABLE" >/dev/null 2>&1; then printf 'delete table arp %s\\n' "$TABLE" >> "$NFT_ROLLBACK"; fi + if [ -f "$TXN/nft.before" ]; then cat "$TXN/nft.before" >> "$NFT_ROLLBACK"; fi + if [ -f "$TXN/nft.bridge.before" ]; then cat "$TXN/nft.bridge.before" >> "$NFT_ROLLBACK"; fi + if [ -f "$TXN/nft.arp.before" ]; then cat "$TXN/nft.arp.before" >> "$NFT_ROLLBACK"; fi + if [ -s "$NFT_ROLLBACK" ]; then + "$NFT" -c -f "$NFT_ROLLBACK" >/dev/null 2>&1 || ROLLBACK_FAILED=yes + "$NFT" -f "$NFT_ROLLBACK" >/dev/null 2>&1 || ROLLBACK_FAILED=yes + fi + if [ -f "$TXN/fabric.nft.before" ]; then + "$NFT" delete table inet virt_cloud_wg_fabric >/dev/null 2>&1 || true + "$NFT" -f "$TXN/fabric.nft.before" >/dev/null 2>&1 || ROLLBACK_FAILED=yes + fi + if [ "$NFT_FILE_CHANGED" = yes ]; then + if [ -f "$TXN/nft_file.before" ]; then cp -p "$TXN/nft_file.before" "$NFT_FILE" || ROLLBACK_FAILED=yes; else rm -f "$NFT_FILE" || ROLLBACK_FAILED=yes; fi + fi + if [ "$NFT_MAIN_CHANGED" = yes ] && [ -f "$TXN/nft_main.before" ]; then + cp -p "$TXN/nft_main.before" "$NFT_MAIN" || ROLLBACK_FAILED=yes + fi + if [ "$MODE" = networkmanager_nmcli ] && [ -n "$NMCLI" ]; then + if [ "$NM_ACTIVATION_ATTEMPTED" = yes ] && [ "$NM_WAS_ACTIVE" = no ]; then + "$NMCLI" connection down "$BRIDGE" >/dev/null 2>&1 || ROLLBACK_FAILED=yes + if "$NMCLI" -t --escape no -f NAME connection show --active 2>/dev/null | grep -Fqx "$BRIDGE"; then ROLLBACK_FAILED=yes; fi + fi + [ "$NM_CREATED" = yes ] && "$NMCLI" connection delete "$BRIDGE" >/dev/null 2>&1 || true + elif [ "$MODE" = ifupdown ]; then + if [ "$IF_ACTIVATION_ATTEMPTED" = yes ] && [ "$BRIDGE_WAS_UP" = no ]; then + "$IFDOWN" --force "$BRIDGE" >/dev/null 2>&1 || ROLLBACK_FAILED=yes + fi + [ "$IF_CREATED" = yes ] && "$IFDOWN" --force "$BRIDGE" >/dev/null 2>&1 || true + fi + if [ "$IF_FRAGMENT_CHANGED" = yes ]; then + if [ -f "$TXN/if_fragment.before" ]; then cp -p "$TXN/if_fragment.before" "$IF_FRAGMENT" || ROLLBACK_FAILED=yes; else rm -f "$IF_FRAGMENT" || ROLLBACK_FAILED=yes; fi + fi + if [ "$SYSCTL_CHANGED" = yes ]; then + if [ -f "$TXN/sysctl.before" ]; then + cp -p "$TXN/sysctl.before" "$SYSCTL_FILE" || ROLLBACK_FAILED=yes + else + rm -f "$SYSCTL_FILE" || ROLLBACK_FAILED=yes + fi + fi + if [ "$BRIDGE_CREATED" = yes ]; then + # Never delete a bridge that acquired a libvirt tap or an operator port. + ports=$($BRIDGE_CMD link show master "$BRIDGE" 2>/dev/null) + if [ "$?" -ne 0 ]; then + # An inability to inspect ports is a rollback failure. Treating an + # empty error result as "no ports" could delete a bridge still carrying + # a libvirt tap and strand the host network. + ROLLBACK_FAILED=yes + elif [ -z "$ports" ]; then + "$IP" link del dev "$BRIDGE" type bridge 2>/dev/null || ROLLBACK_FAILED=yes + fi + elif [ "$BRIDGE_WAS_UP" = no ] && "$IP" link show dev "$BRIDGE" >/dev/null 2>&1; then + # Applying a revision may have activated an existing panel bridge through + # NetworkManager/ifupdown. Restore its prior DOWN state only when no tap + # or operator port appeared while the transaction was running. + ports=$($BRIDGE_CMD link show master "$BRIDGE" 2>/dev/null) + if [ "$?" -ne 0 ] || [ -n "$ports" ]; then + ROLLBACK_FAILED=yes + else + "$IP" link set dev "$BRIDGE" down 2>/dev/null || ROLLBACK_FAILED=yes + "$IP" link show dev "$BRIDGE" 2>/dev/null | grep -q 'state UP' && ROLLBACK_FAILED=yes + fi + fi + if [ -f "$TXN/owner.before" ]; then cp -p "$TXN/owner.before" "$OWNER_FILE" || ROLLBACK_FAILED=yes; else rm -f "$OWNER_FILE"; fi + if [ -f "$TXN/state.before" ]; then cp -p "$TXN/state.before" "$STATE_FILE" || ROLLBACK_FAILED=yes; else rm -f "$STATE_FILE"; fi + if [ "$ROLLBACK_FAILED" = yes ]; then printf '%s\\n' rollback_failed > "$TXN/state"; chmod 600 "$TXN/state"; exit 79; fi + rm -rf "$TXN"; exit "$status" +}} +trap rollback EXIT HUP INT TERM +if [ -f "$OWNER_FILE" ]; then + [ ! -L "$OWNER_FILE" ] && grep -Fqx "$OWNER_MARKER" "$OWNER_FILE" || exit 71 + cp -p "$OWNER_FILE" "$TXN/owner.before" +fi +if [ -f "$STATE_FILE" ]; then + [ ! -L "$STATE_FILE" ] || exit 71 + grep -Fqx 'owner|{DATAPLANE_OWNER_MARKER}' "$STATE_FILE" || exit 71 + cp -p "$STATE_FILE" "$TXN/state.before" +fi +"$WG" showconf "$WG_IFACE" > "$TXN/wg.conf"; chmod 600 "$TXN/wg.conf" +if "$NFT" list table inet virt_cloud_wg_fabric > "$TXN/fabric.nft.before" 2>/dev/null; then + grep -Fq 'virt-cloud-wg-fabric-v1' "$TXN/fabric.nft.before" || exit 71 +else + exit 71 +fi +if "$NFT" list table inet "$TABLE" > "$TXN/nft.before" 2>/dev/null; then + grep -Fq '{DATAPLANE_OWNER_MARKER}' "$TXN/nft.before" || exit 71 +else + rm -f "$TXN/nft.before" +fi +if "$NFT" list table bridge "$TABLE" > "$TXN/nft.bridge.before" 2>/dev/null; then + grep -Fq '{DATAPLANE_OWNER_MARKER}' "$TXN/nft.bridge.before" || exit 71 +else + rm -f "$TXN/nft.bridge.before" +fi +if "$NFT" list table arp "$TABLE" > "$TXN/nft.arp.before" 2>/dev/null; then + grep -Fq '{DATAPLANE_OWNER_MARKER}' "$TXN/nft.arp.before" || exit 71 +else + rm -f "$TXN/nft.arp.before" +fi +cp -p "$NFT_MAIN" "$TXN/nft_main.before"; NFT_MAIN_BEFORE=yes +if [ -f "$NFT_FILE" ]; then cp -p "$NFT_FILE" "$TXN/nft_file.before"; NFT_FILE_BEFORE=yes; fi +if [ -f "$SYSCTL_FILE" ]; then cp -p "$SYSCTL_FILE" "$TXN/sysctl.before"; fi +if [ -f "$PROXY_FILE" ]; then cp -p "$PROXY_FILE" "$TXN/proxy_file.before"; fi +if "$IP" link show dev "$BRIDGE" >/dev/null 2>&1; then + "$IP" -d link show dev "$BRIDGE" | grep -Eq '(^|[[:space:]])bridge[[:space:]]+(forward_delay|stp_state|hello_time|ageing_time)([[:space:]]|$)' || exit 71 + [ -f "$OWNER_FILE" ] || exit 71 +else + "$IP" link add name "$BRIDGE" type bridge + BRIDGE_CREATED=yes + printf '%s\\n' "$OWNER_MARKER" > "$OWNER_FILE"; chmod 600 "$OWNER_FILE" +fi +if "$IP" link show dev "$BRIDGE" 2>/dev/null | grep -q 'state UP'; then BRIDGE_WAS_UP=yes; fi +"$IP" link set dev "$BRIDGE" up +# A private bridge is an unnumbered, panel-owned L3 boundary. Reject an +# address, a default/connected route, or a physical/foreign bridge port before +# installing any policy. Libvirt tap names are the only accepted members; +# attaching br0, an underlay NIC, or an operator bridge would make VPC traffic +# escape into the public network. +bridge_addrs=$($IP -o addr show dev "$BRIDGE" 2>/dev/null || true) +printf '%s\\n' "$bridge_addrs" | grep -Eq '[[:space:]]inet6?[[:space:]]' && exit 71 || true +bridge_ports=$($BRIDGE_CMD link show master "$BRIDGE" 2>/dev/null) || exit 71 +while IFS= read -r bridge_port_line; do + [ -n "$bridge_port_line" ] || continue + bridge_port=$(printf '%s\\n' "$bridge_port_line" | sed -n 's/^[0-9][0-9]*: \\([^:[:space:]]*\\).*/\\1/p') + [ -n "$bridge_port" ] || exit 71 + case "$bridge_port" in + vnet[0-9]*|tap[0-9A-Za-z_.-]*|macvtap[0-9]*|fwpr[0-9A-Za-z_.-]*|fwln[0-9A-Za-z_.-]*) : ;; + *) exit 71 ;; + esac +done <<__VC_VPC_BRIDGE_PORTS__ +$bridge_ports +__VC_VPC_BRIDGE_PORTS__ +cat > "$TXN/bridge.routes.allowed" <<'{route_marker}.bridge' +{bridge_route_lines} +{route_marker}.bridge +if [ -f "$TXN/state.before" ]; then + awk -F'|' '$1 == "route" && $3 == "{r.bridge}" {{print $2 "|" $3 "|" $4 "|" $5 "|" $6 "|186"}}' "$TXN/state.before" >> "$TXN/bridge.routes.allowed" +fi +sort -u "$TXN/bridge.routes.allowed" -o "$TXN/bridge.routes.allowed" +bridge_routes=$($IP -o -4 route show table all dev "$BRIDGE" 2>/dev/null) || exit 71 +while IFS='|' read -r destination device table via metric proto; do + [ -n "$destination" ] || continue + printf '%s\\n' "$destination|$device|$table|$via|$metric|$proto" | grep -Fqx -f "$TXN/bridge.routes.allowed" || exit 71 +done </dev/null) || exit 71 +[ -z "$bridge_routes6" ] || exit 71 +: > "$TXN/proxy.before" +"$IP" neigh show proxy dev "$BRIDGE" 2>/dev/null | awk '$1 ~ /^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$/ {{print $1}}' | LC_ALL=C sort -u > "$TXN/proxy.before" +if [ -f "$PROXY_FILE" ]; then + sed '1d' "$PROXY_FILE" | LC_ALL=C sort -u > "$TXN/proxy.file.before" +else + : > "$TXN/proxy.file.before" +fi +"$CMP" -s "$TXN/proxy.before" "$TXN/proxy.file.before" || exit 71 +if [ -r "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp" ]; then + cat "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp" > "$TXN/proxy_arp.before" +else + exit 72 +fi +if [ -r "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp_pvlan" ]; then + cat "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp_pvlan" > "$TXN/proxy_arp_pvlan.before" +else + exit 72 +fi +if [ -r "/proc/sys/net/ipv4/conf/$BRIDGE/rp_filter" ]; then + cat "/proc/sys/net/ipv4/conf/$BRIDGE/rp_filter" > "$TXN/rp_filter.before" +else + exit 72 +fi +SYSCTL_TMP=$(mktemp "/etc/sysctl.d/.virt-cloud-vpc-{r.token}.XXXXXX") || exit 72 +cat > "$SYSCTL_TMP" <<'__VC_VPC_SYSCTL_{r.token}' +# virt-cloud-vpc-dataplane-v1 +# vpc={plan.vpc.vpc_id} revision={plan.desired_revision} digest={plan.desired_digest} +net.ipv4.conf.{r.bridge}.rp_filter = 2 +net.ipv4.conf.{r.bridge}.proxy_arp = 0 +net.ipv4.conf.{r.bridge}.proxy_arp_pvlan = 1 +__VC_VPC_SYSCTL_{r.token} +chmod 600 "$SYSCTL_TMP" +mv -f "$SYSCTL_TMP" "$SYSCTL_FILE"; SYSCTL_CHANGED=yes +if [ "$MODE" = networkmanager_nmcli ]; then + [ -n "$NMCLI" ] || exit 70 + nm_field() {{ "$NMCLI" -t --escape no -g "$1" connection show "$BRIDGE" 2>/dev/null | sed -n '1p'; }} + nm_empty() {{ value=$(nm_field "$1"); [ -z "$value" ] || [ "$value" = "--" ]; }} + NM_PROFILE_COUNT=$("$NMCLI" -t --escape no -f NAME connection show 2>/dev/null | awk -v wanted="$BRIDGE" '$0 == wanted {{ count++ }} END {{ print count + 0 }}') + if [ "$NM_PROFILE_COUNT" = 0 ]; then + "$NMCLI" connection add type bridge ifname "$BRIDGE" con-name "$BRIDGE" \ + ipv4.method disabled ipv6.method disabled bridge.stp no \ + connection.autoconnect yes connection.stable-id "$NM_PROFILE_MARKER" >/dev/null + NM_CREATED=yes + elif [ "$NM_PROFILE_COUNT" = 1 ]; then + # A deterministic profile name is not ownership by itself. Reusing an + # operator profile with an address, route, controller, or non-bridge type + # could leak VPC traffic into the public network. Require the exact + # panel marker (stored in NetworkManager's supported stable-id property) + # and validate every field that can add L3 reachability before activating + # an existing profile. + [ "$(nm_field connection.type)" = bridge ] || exit 71 + [ "$(nm_field connection.interface-name)" = "$BRIDGE" ] || exit 71 + [ "$(nm_field ipv4.method)" = disabled ] || exit 71 + [ "$(nm_field ipv6.method)" = disabled ] || exit 71 + nm_empty ipv4.addresses || exit 71 + nm_empty ipv4.routes || exit 71 + nm_empty ipv4.routing-rules || exit 71 + nm_empty ipv4.gateway || exit 71 + nm_empty ipv4.dns || exit 71 + nm_empty ipv4.dns-search || exit 71 + nm_empty ipv6.addresses || exit 71 + nm_empty ipv6.routes || exit 71 + nm_empty ipv6.routing-rules || exit 71 + nm_empty ipv6.gateway || exit 71 + nm_empty ipv6.dns || exit 71 + nm_empty ipv6.dns-search || exit 71 + nm_empty connection.master || exit 71 + nm_empty connection.controller || exit 71 + nm_empty connection.slave-type || exit 71 + nm_empty connection.port-type || exit 71 + nm_empty connection.secondaries || exit 71 + nm_empty connection.zone || exit 71 + case "$(nm_field bridge.stp)" in no|false|off|0|--) : ;; *) exit 71 ;; esac + NM_PROFILE_STABLE_ID=$(nm_field connection.stable-id) + [ "$NM_PROFILE_STABLE_ID" = "$NM_PROFILE_MARKER" ] || exit 71 + else + # More than one same-name profile makes `connection up ` ambiguous; + # fail closed instead of possibly activating a public profile. + exit 71 + fi + if "$NMCLI" -t --escape no -f NAME connection show --active 2>/dev/null | grep -Fqx "$BRIDGE"; then NM_WAS_ACTIVE=yes; fi + NM_ACTIVATION_ATTEMPTED=yes + "$NMCLI" connection up "$BRIDGE" >/dev/null +else + [ -x "$IFUP" ] && [ -x "$IFQUERY" ] && [ -x "$IFDOWN" ] || exit 70 + [ ! -L /etc/network ] && [ ! -L /etc/network/interfaces.d ] || exit 71 + # A stanza in the administrator-owned main file wins over an + # interfaces.d fragment on some ifupdown versions. Refuse that ambiguous + # ownership instead of letting a same-name bridge inherit ports, addresses, + # routes, or hooks from /etc/network/interfaces. + if [ -f /etc/network/interfaces ] && + grep -Eq '^[[:space:]]*(auto|allow-[^[:space:]]+|iface)[[:space:]]+'"$BRIDGE"'([[:space:]]|$)' /etc/network/interfaces; then + exit 71 + fi + mkdir -p /etc/network/interfaces.d + if [ -e "$IF_FRAGMENT" ] || [ -L "$IF_FRAGMENT" ]; then + [ -f "$IF_FRAGMENT" ] && [ ! -L "$IF_FRAGMENT" ] || exit 71 + grep -Fq '# {DATAPLANE_OWNER_MARKER} vpc=' "$IF_FRAGMENT" || exit 71 + cp -p "$IF_FRAGMENT" "$TXN/if_fragment.before" + fi + IF_TMP=$(mktemp "/etc/network/interfaces.d/.virt-cloud-vpc-{r.token}.XXXXXX") || exit 72 + cat > "$IF_TMP" <<'{frag_marker}' +# {DATAPLANE_OWNER_MARKER} vpc={plan.vpc.vpc_id} revision={plan.desired_revision} digest={plan.desired_digest} +auto {r.bridge} +iface {r.bridge} inet manual + bridge_ports none + bridge-stp off +{frag_marker} + chmod 600 "$IF_TMP" + mv -f "$IF_TMP" "$IF_FRAGMENT"; IF_FRAGMENT_CHANGED=yes + # Classic Debian ifquery accepts the interface as its positional operand; + # `--list ` is an ifquery2/listing form and fails on ifupdown. + "$IFQUERY" "$BRIDGE" >/dev/null 2>&1 || exit 72 + # An existing bridge is shared with libvirt; never ifdown it during + # rollback. A newly created bridge is the only interface this transaction + # may tear down. + [ "$BRIDGE_CREATED" = yes ] && IF_CREATED=yes + IF_ACTIVATION_ATTEMPTED=yes + VC_FABRIC_APPLYING=1 "$IFUP" --force "$BRIDGE" >/dev/null 2>&1 || exit 72 +fi +cat > "$TXN/rules.nft" <<'{nft_marker}' +{nft.rstrip()} +{nft_marker} +chmod 600 "$TXN/rules.nft" +"$NFT" -c -f "$TXN/rules.nft" >/dev/null || exit 72 +NFT_TMP=$(mktemp "/etc/nftables.d/.virt-cloud-vpc-{r.token}.XXXXXX") || exit 72 +cp -p "$TXN/rules.nft" "$NFT_TMP" || exit 72 +chmod 600 "$NFT_TMP" +mv -f "$NFT_TMP" "$NFT_FILE"; NFT_FILE_CHANGED=yes +if ! grep -Fqx "$NFT_INCLUDE" "$NFT_MAIN" && + ! grep -Fqx 'include "/etc/nftables.d/*.nft"' "$NFT_MAIN" && + ! grep -Fqx 'include "/etc/nftables.d/*"' "$NFT_MAIN"; then + NFT_MAIN_TMP=$(mktemp "$NFT_MAIN.virt-cloud-vpc.XXXXXX") || exit 72 + cat "$NFT_MAIN" > "$NFT_MAIN_TMP" + printf '%s\\n' "$NFT_INCLUDE" >> "$NFT_MAIN_TMP" + "$NFT" -c -f "$NFT_MAIN_TMP" >/dev/null || exit 72 + chmod "$($STAT -c '%a' "$NFT_MAIN")" "$NFT_MAIN_TMP" + mv -f "$NFT_MAIN_TMP" "$NFT_MAIN"; NFT_MAIN_CHANGED=yes +fi +"$NFT" -c -f "$NFT_MAIN" >/dev/null || exit 72 +NFT_BATCH="$TXN/apply.nft" +: > "$NFT_BATCH" +if [ -f "$TXN/nft.before" ]; then printf 'delete table inet %s\\n' "$TABLE" >> "$NFT_BATCH"; fi +if [ -f "$TXN/nft.bridge.before" ]; then printf 'delete table bridge %s\\n' "$TABLE" >> "$NFT_BATCH"; fi +if [ -f "$TXN/nft.arp.before" ]; then printf 'delete table arp %s\\n' "$TABLE" >> "$NFT_BATCH"; fi +cat "$TXN/rules.nft" >> "$NFT_BATCH" +chmod 600 "$NFT_BATCH" +"$NFT" -c -f "$NFT_BATCH" >/dev/null || exit 72 +# A single nft batch is atomic in the kernel: the old owned tables remain in +# place if any delete or new-table rule fails validation/application. +"$NFT" -f "$NFT_BATCH" >/dev/null || exit 72 +RP_FILTER_CHANGED=yes +printf '%s\\n' 2 > "/proc/sys/net/ipv4/conf/$BRIDGE/rp_filter" || exit 72 +[ "$(cat "/proc/sys/net/ipv4/conf/$BRIDGE/rp_filter" 2>/dev/null)" = 2 ] || exit 72 +PROXY_ARP_CHANGED=yes +printf '%s\\n' 0 > "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp" || exit 72 +[ "$(cat "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp" 2>/dev/null)" = 0 ] || exit 72 +PROXY_ARP_PVLAN_CHANGED=yes +printf '%s\\n' 1 > "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp_pvlan" || exit 72 +[ "$(cat "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp_pvlan" 2>/dev/null)" = 1 ] || exit 72 +PROXY_ENTRIES_CHANGED=yes +while IFS= read -r old_proxy; do + [ -n "$old_proxy" ] || continue + "$IP" neigh del proxy "$old_proxy" dev "$BRIDGE" >/dev/null 2>&1 || exit 72 +done < "$TXN/proxy.before" +while IFS= read -r proxy_ip; do + [ -n "$proxy_ip" ] || continue + "$IP" neigh replace proxy "$proxy_ip" dev "$BRIDGE" >/dev/null 2>&1 || exit 72 +done <<'{proxy_marker}' +{proxy_lines} +{proxy_marker} +PROXY_TMP=$(mktemp "$PROXY_FILE.XXXXXX") || exit 72 +{{ + printf '%s\\n' '# virt-cloud-vpc-proxy-v1' + cat <<'{proxy_marker}' +{proxy_lines} +{proxy_marker} +}} > "$PROXY_TMP" +chmod 600 "$PROXY_TMP" +mv -f "$PROXY_TMP" "$PROXY_FILE"; PROXY_FILE_CHANGED=yes +"$IP" neigh show proxy dev "$BRIDGE" 2>/dev/null | awk '$1 ~ /^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$/ {{print $1}}' | LC_ALL=C sort -u > "$TXN/proxy.after" +cat <<'{proxy_marker}' | LC_ALL=C sort -u > "$TXN/proxy.desired" +{proxy_lines} +{proxy_marker} +"$CMP" -s "$TXN/proxy.after" "$TXN/proxy.desired" || exit 72 +: > "$TXN/routes.before" +cat > "$TXN/routes.desired" <<'{route_marker}' +{route_lines} +{route_marker} +if [ -f "$STATE_FILE" ]; then + while IFS='|' read -r old_kind old_destination old_device old_table old_via old_metric; do + [ "$old_kind" = route ] || continue + printf '%s\\n' "$old_destination|$old_device|$ROUTE_TABLE|${{old_via:--}}|${{old_metric:-100}}" | grep -Fqx -f "$TXN/routes.desired" && continue + old_existing=$("$IP" -o route show table "$ROUTE_TABLE" "$old_destination" 2>/dev/null || true) + [ -n "$old_existing" ] || continue + printf '%s\\n' "$old_existing" | grep -Eq 'proto 186([[:space:]]|$)' || exit 73 + old_metric_actual=$(printf '%s\\n' "$old_existing" | awk '{{for (i=1; i<=NF; i++) if ($i == "metric" && i < NF) {{print $(i+1); exit}}}}') + [ -n "$old_metric_actual" ] || old_metric_actual=100 + old_actual_device=$(printf '%s\\n' "$old_existing" | awk '{{for (i=1; i<=NF; i++) if ($i == "dev" && i < NF) {{print $(i+1); exit}}}}') + [ "$old_actual_device" = "$old_device" ] || exit 73 + old_via_actual=$(printf '%s\\n' "$old_existing" | awk '{{for (i=1; i<=NF; i++) if ($i == "via" && i < NF) {{print $(i+1); exit}}}}') + [ "${{old_via_actual:--}}" = "${{old_via:--}}" ] || exit 73 + printf '%s|%s|%s|%s|%s\\n' "$old_destination" "$old_device" "$ROUTE_TABLE" "${{old_via:--}}" "$old_metric_actual" >> "$TXN/routes.before" + if [ "${{old_via:--}}" = - ]; then + "$IP" route del "$old_destination" table "$ROUTE_TABLE" dev "$old_device" proto 186 || exit 73 + else + "$IP" route del "$old_destination" table "$ROUTE_TABLE" via "$old_via" dev "$old_device" proto 186 || exit 73 + fi + done < "$STATE_FILE" +fi +while IFS='|' read -r destination device table via metric; do + [ -n "$destination" ] || continue + existing=$("$IP" -o route show table "$table" "$destination" 2>/dev/null || true) + [ -z "$existing" ] || printf '%s\\n' "$existing" | grep -Eq 'proto 186([[:space:]]|$)' || exit 73 + if [ -n "$existing" ]; then + old_device=$(printf '%s\\n' "$existing" | awk '{{for (i=1; i<=NF; i++) if ($i == "dev" && i < NF) {{print $(i+1); exit}}}}') + old_metric=$(printf '%s\\n' "$existing" | awk '{{for (i=1; i<=NF; i++) if ($i == "metric" && i < NF) {{print $(i+1); exit}}}}') + [ -n "$old_device" ] || exit 73 + [ "$old_device" = "$device" ] || exit 73 + old_via=$(printf '%s\\n' "$existing" | awk '{{for (i=1; i<=NF; i++) if ($i == "via" && i < NF) {{print $(i+1); exit}}}}') + [ "${{old_via:--}}" = "$via" ] || exit 73 + [ -n "$old_metric" ] || old_metric=100 + printf '%s|%s|%s|%s|%s\\n' "$destination" "$old_device" "$table" "${{old_via:--}}" "$old_metric" >> "$TXN/routes.before" + fi + [ -n "$metric" ] || metric=100 + if [ "$via" = - ]; then + "$IP" route replace "$destination" table "$table" dev "$device" proto 186 metric "$metric" || exit 73 + else + "$IP" route replace "$destination" table "$table" via "$via" dev "$device" onlink proto 186 metric "$metric" || exit 73 + fi +done <<'{route_marker}' +{route_lines} +{route_marker} +: > "$TXN/rules.before" +for pref in "$RULE_PRIORITY" "$WG_RULE_PRIORITY"; do + existing=$("$IP" -o rule show pref "$pref" 2>/dev/null || true) + if [ -n "$existing" ]; then + printf '%s\\n' "$existing" | grep -Fq "lookup $ROUTE_TABLE" || exit 73 + old_iif=$(printf '%s\\n' "$existing" | awk '{{for (i=1; i<=NF; i++) if ($i == "iif" && i < NF) {{print $(i+1); exit}}}}') + old_to=$(printf '%s\\n' "$existing" | awk '{{for (i=1; i<=NF; i++) if ($i == "to" && i < NF) {{print $(i+1); exit}}}}') + old_lookup=$(printf '%s\\n' "$existing" | awk '{{for (i=1; i<=NF; i++) if ($i == "lookup" && i < NF) {{print $(i+1); exit}}}}') + [ -n "$old_to" ] && [ -n "$old_lookup" ] || exit 73 + if [ "$pref" = "$RULE_PRIORITY" ]; then + [ -z "$old_iif" ] && [ "$old_to" = {_q(plan.vpc.cidr)} ] || exit 73 + else + [ "$old_iif" = "$WG_IFACE" ] && [ "$old_to" = {_q(plan.vpc.cidr)} ] || exit 73 + fi + printf '%s|%s|%s|%s\\n' "$pref" "${{old_iif:--}}" "$old_to" "$old_lookup" >> "$TXN/rules.before" + fi +done +"$IP" rule replace pref "$RULE_PRIORITY" to {_q(plan.vpc.cidr)} lookup "$ROUTE_TABLE" +"$IP" rule replace pref "$WG_RULE_PRIORITY" iif "$WG_IFACE" to {_q(plan.vpc.cidr)} lookup "$ROUTE_TABLE" +cat > "$STATE_FILE" <<'{state_marker}' +{state.rstrip()} +{state_marker} +chmod 600 "$STATE_FILE" +{state_loader} +vpc_state_load || exit 74 +vpc_state_refresh_nft || exit 74 +while IFS='|' read -r peer_host key allowed; do + [ -n "$peer_host" ] || continue + "$WG" show "$WG_IFACE" peers | grep -Fqx "$key" || exit 74 + case ",$allowed," in *',0.0.0.0/0,'*|*',0.0.0.0/1,'*|*',128.0.0.0/1,'* ) exit 74 ;; esac + # Fabric has one AllowedIPs list per public key. Merge the complete, + # validated tenant set from every panel-owned VPC state file while keeping + # the peer's single overlay /32. Never replace the list with this VPC's + # partial view: doing so would black-hole another concurrently active VPC. + merge_actual=$("$WG" show "$WG_IFACE" allowed-ips 2>/dev/null | awk -v wanted="$key" '$1 == wanted {{print $2; exit}}' || true) + merge_overlay=$(printf '%s\\n' "$merge_actual" | tr ',' '\\n' | awk '/^100\\.64\\.[0-9]+\\.[0-9]+\\/32$/ {{print; count++}} END {{exit count == 1 ? 0 : 1}}') || exit 74 + merge_extra=$(vpc_state_allowed_for_peer "$key") || exit 74 + merge_allowed="$merge_overlay" + [ -z "$merge_extra" ] || merge_allowed="$merge_allowed,$merge_extra" + "$WG" set "$WG_IFACE" peer "$key" allowed-ips "$merge_allowed" || exit 74 +done <<'{peer_marker}' +{peer_lines} +{peer_marker} +rm -f "$VPC_PEER_FILE" "$VPC_ROUTE_FILE" "$VPC_TENANT_FILE" "$VPC_TENANT_FILE.nft" +printf '%s\\n' ready > "$TXN/state"; chmod 600 "$TXN/state" +printf '%s\\n' '__VC_VPC_APPLIED__=yes' +printf '%s\\n' '__VC_VPC_OWNER__={DATAPLANE_OWNER_MARKER}' +printf '%s\\n' '__VC_VPC_REVISION__={plan.desired_revision}' +printf '%s\\n' '__VC_VPC_DIGEST__={plan.desired_digest}' +COMMITTED=yes +printf '%s\\n' committed > "$TXN/state"; chmod 600 "$TXN/state" +rm -rf "$TXN" +trap - EXIT HUP INT TERM +exit 0 +''' + if len(script) > MAX_OUTPUT: + raise VpcDataplaneError("VPC 数据面脚本过大", 413, "vpc_script_too_large") + return script + + +def render_remove_script( + plan: VpcDataplanePlan, + *, + deployment_mode: str = "networkmanager_nmcli", + ifup_path: str = "/usr/sbin/ifup", + ifdown_path: str = "/usr/sbin/ifdown", + ifquery_path: str = "/usr/sbin/ifquery", +) -> str: + """Render a fail-closed removal transaction for an empty host.""" + if plan.local_members: + raise VpcDataplaneError( + "仍有本机私网成员,不能执行宿主机 VPC 销毁", + 409, "vpc_remove_has_local_members") + if deployment_mode not in {"networkmanager_nmcli", "ifupdown"}: + raise VpcDataplaneError("宿主机网络管理模式不支持", 409, + "vpc_dataplane_network_manager_conflict") + allowed_ifup = {"/usr/sbin/ifup", "/usr/bin/ifup", "/sbin/ifup", "/bin/ifup"} + allowed_ifdown = {"/usr/sbin/ifdown", "/usr/bin/ifdown", "/sbin/ifdown", "/bin/ifdown"} + allowed_ifquery = {"/usr/sbin/ifquery", "/usr/bin/ifquery", "/sbin/ifquery", "/bin/ifquery"} + if (ifup_path not in allowed_ifup or ifdown_path not in allowed_ifdown + or ifquery_path not in allowed_ifquery): + raise VpcDataplaneError("ifupdown 工具路径不受支持", 409, + "vpc_dataplane_network_manager_conflict") + from .fabric import _VPC_STATE_LOADER + + r = plan.resources + include = f"/etc/nftables.d/virt-cloud-vpc-{r.token}.nft" + fragment = f"/etc/network/interfaces.d/virt-cloud-vpc-{r.token}" + sysctl_file = f"/etc/sysctl.d/99-virt-cloud-vpc-{r.token}.conf" + proxy_file = f"/etc/virt-cloud/vpc-dataplane/{r.token}.proxy" + state_loader = _VPC_STATE_LOADER.replace( + "__VC_FABRIC_HOST_ID__", plan.host_id).replace( + "__VC_FABRIC_ID__", plan.vpc.fabric_id).replace( + "__VC_FABRIC_NETWORK__", "100.64.0.0/10").replace( + "__VC_VPC_STATE_OBSERVE__", "no") + nm_profile_marker = DATAPLANE_OWNER_MARKER + " vpc=" + plan.vpc.vpc_id + ifup_marker = f"# {DATAPLANE_OWNER_MARKER} vpc={plan.vpc.vpc_id}" + inflight_marker = (f"{DATAPLANE_OWNER_MARKER}:{plan.vpc.vpc_id}:" + f"{plan.host_id}:{plan.desired_revision}:{plan.desired_digest}") + script = f'''#!/bin/sh +set -eu +umask 077 +PATH=/usr/sbin:/usr/bin:/sbin:/bin +export PATH +IP=$(for p in /usr/sbin/ip /usr/bin/ip /sbin/ip /bin/ip; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +WG=$(for p in /usr/bin/wg /usr/sbin/wg /bin/wg /sbin/wg; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +NFT=$(for p in /usr/sbin/nft /usr/bin/nft /sbin/nft /bin/nft; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +FLOCK=$(for p in /usr/bin/flock /usr/sbin/flock /bin/flock /sbin/flock; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +STAT=$(for p in /usr/bin/stat /bin/stat /usr/sbin/stat /sbin/stat; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +MKTEMP=$(for p in /usr/bin/mktemp /bin/mktemp /usr/sbin/mktemp /sbin/mktemp; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +BRIDGE_CMD=$(for p in /usr/sbin/bridge /usr/bin/bridge /sbin/bridge /bin/bridge; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +BRIDGE={_q(r.bridge)}; TABLE={_q(r.nft_table)}; ROUTE_TABLE={r.route_table}; WG_IFACE={_q(FABRIC_INTERFACE)} +OWNER_FILE={_q(r.owner_file)}; STATE_FILE={_q(r.state_file)}; LOCK={_q(r.lock_file)}; TXN={_q(r.transaction_dir)} +NFT_FILE={_q(include)}; IF_FRAGMENT={_q(fragment)}; SYSCTL_FILE={_q(sysctl_file)}; PROXY_FILE={_q(proxy_file)}; STATE_DIR=/etc/virt-cloud/vpc-dataplane +MODE={_q(deployment_mode)}; IFUP={_q(ifup_path)}; IFDOWN={_q(ifdown_path)}; IFQUERY={_q(ifquery_path)}; NMCLI=; NFT_MAIN=; NFT_INCLUDE={_q(f'include "{include}"')} +[ -n "$IP" ] && [ -n "$WG" ] && [ -n "$NFT" ] && [ -n "$FLOCK" ] && [ -n "$STAT" ] && [ -n "$MKTEMP" ] && [ -n "$BRIDGE_CMD" ] || exit 70 +if [ "$MODE" = networkmanager_nmcli ]; then + NMCLI=$(for p in /usr/bin/nmcli /usr/sbin/nmcli /bin/nmcli /sbin/nmcli; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) + [ -n "$NMCLI" ] || exit 70 +fi +[ ! -L /run/virt-cloud ] && [ ! -L /etc/virt-cloud ] || exit 71 +mkdir -p /run/virt-cloud; chmod 700 /run/virt-cloud +if [ -e "$STATE_DIR" ] || [ -L "$STATE_DIR" ]; then + [ -d "$STATE_DIR" ] && [ ! -L "$STATE_DIR" ] || exit 71 + [ "$($STAT -c '%u:%a' "$STATE_DIR" 2>/dev/null)" = 0:700 ] || exit 71 +fi +if [ -e /etc/nftables.d ] || [ -L /etc/nftables.d ]; then + [ -d /etc/nftables.d ] && [ ! -L /etc/nftables.d ] || exit 71 + [ "$($STAT -c '%u:%a' /etc/nftables.d 2>/dev/null)" = 0:755 ] || exit 71 +fi +if [ -e /etc/sysctl.d ] || [ -L /etc/sysctl.d ]; then + [ -d /etc/sysctl.d ] && [ ! -L /etc/sysctl.d ] || exit 71 + [ "$($STAT -c '%u:%a' /etc/sysctl.d 2>/dev/null)" = 0:755 ] || exit 71 +fi +[ ! -L "$LOCK" ] && {{ [ ! -e "$LOCK" ] || [ -f "$LOCK" ]; }} || exit 71 +: >> "$LOCK"; chmod 600 "$LOCK"; exec 9>>"$LOCK"; "$FLOCK" -x 9 +exec 8>>{_q(FABRIC_LOCK)}; "$FLOCK" -x 8 +[ -f /etc/virt-cloud/wg-fabric0.owner ] && grep -Fqx 'virt-cloud-wg-fabric-v1' /etc/virt-cloud/wg-fabric0.owner || exit 71 +"$WG" show "$WG_IFACE" >/dev/null 2>&1 || exit 71 +BRIDGE_PRESENT=no +if "$IP" link show dev "$BRIDGE" >/dev/null 2>&1; then BRIDGE_PRESENT=yes; fi +PHASE=preparing; RESUME=no +if [ -e "$TXN" ]; then + [ -d "$TXN" ] && [ ! -L "$TXN" ] || exit 79 + [ "$($STAT -c '%u:%a' "$TXN" 2>/dev/null)" = 0:700 ] || exit 79 + [ -f "$TXN/inflight" ] && [ ! -L "$TXN/inflight" ] || exit 79 + [ "$($STAT -c '%u:%a' "$TXN/inflight" 2>/dev/null)" = 0:600 ] || exit 79 + grep -Fqx '{inflight_marker}' "$TXN/inflight" || exit 79 + [ -f "$TXN/state" ] && [ ! -L "$TXN/state" ] || exit 79 + [ "$($STAT -c '%u:%a' "$TXN/state" 2>/dev/null)" = 0:600 ] || exit 79 + PHASE=$(cat "$TXN/state" 2>/dev/null) || exit 79 + case "$PHASE" in + preparing|routes_removed|manager_removed|bridge_removed|nft_removed|files_removed|wg_merged|committed) : ;; + *) exit 79 ;; + esac + RESUME=yes + for snapshot in "$TXN/state.before" "$TXN/routes.before" "$TXN/rules.before" "$TXN/proxy.before"; do + [ -e "$snapshot" ] || continue + [ -f "$snapshot" ] && [ ! -L "$snapshot" ] || exit 79 + [ "$($STAT -c '%u:%a' "$snapshot" 2>/dev/null)" = 0:600 ] || exit 79 + done +fi +set_phase() {{ + phase_tmp="$TXN/.state.$$" + printf '%s\\n' "$1" > "$phase_tmp" + chmod 600 "$phase_tmp" + mv -f "$phase_tmp" "$TXN/state" + PHASE="$1" +}} +verify_routes_removed() {{ + verify_routes=$($IP -o -4 route show table "$ROUTE_TABLE" 2>/dev/null || true) + [ -z "$verify_routes" ] || return 1 + verify_rule=$($IP -o rule show pref "{r.rule_priority}" 2>/dev/null || true) + [ -z "$verify_rule" ] || return 1 + verify_rule=$($IP -o rule show pref "$(( {r.rule_priority} + 1 ))" 2>/dev/null || true) + [ -z "$verify_rule" ] || return 1 + if $IP link show dev "$BRIDGE" >/dev/null 2>&1; then + verify_proxy=$($IP neigh show proxy dev "$BRIDGE" 2>/dev/null | awk '$1 ~ /^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$/') || return 1 + [ -z "$verify_proxy" ] || return 1 + fi + return 0 +}} +case "$PHASE" in + preparing|routes_removed|manager_removed|bridge_removed|nft_removed) PRE_FILES=yes ;; + files_removed|wg_merged|committed) PRE_FILES=no ;; + *) exit 79 ;; +esac +if [ "$PRE_FILES" = yes ]; then +if [ -f "$OWNER_FILE" ]; then + [ ! -L "$OWNER_FILE" ] || exit 71 + [ "$($STAT -c '%u:%a' "$OWNER_FILE" 2>/dev/null)" = 0:600 ] || exit 71 + grep -Fqx 'virt-cloud-vpc-dataplane-v1' "$OWNER_FILE" || exit 71 +elif [ -e "$STATE_FILE" ] || [ "$BRIDGE_PRESENT" = yes ] || [ -e "$NFT_FILE" ] || + [ -e "$SYSCTL_FILE" ] || [ -e "$PROXY_FILE" ] || [ -e "$IF_FRAGMENT" ]; then + # A deterministic bridge/file name is not ownership. Refuse to remove + # anything when the panel's owner marker disappeared or was replaced. + exit 71 +fi +if [ -f "$STATE_FILE" ]; then + [ ! -L "$STATE_FILE" ] || exit 71 + [ "$($STAT -c '%u:%a' "$STATE_FILE" 2>/dev/null)" = 0:600 ] || exit 71 + grep -Fqx 'owner|{DATAPLANE_OWNER_MARKER}' "$STATE_FILE" || exit 71 + grep -Fqx 'vpc|{plan.vpc.vpc_id}' "$STATE_FILE" || exit 71 + grep -Fqx 'cidr|{plan.vpc.cidr}' "$STATE_FILE" || exit 71 + grep -Fqx 'fabric|{plan.vpc.fabric_id}' "$STATE_FILE" || exit 71 + grep -Fqx 'host|{plan.host_id}' "$STATE_FILE" || exit 71 + grep -Fqx 'bridge|{r.bridge}' "$STATE_FILE" || exit 71 + grep -Fqx 'table|{r.route_table}' "$STATE_FILE" || exit 71 + state_revision=$(awk -F'|' '$1=="revision" {{print $2; exit}}' "$STATE_FILE") + state_digest=$(awk -F'|' '$1=="digest" {{print $2; exit}}' "$STATE_FILE") + case "$state_revision" in ''|*[!0-9]*) exit 79;; esac + printf '%s\n' "$state_digest" | grep -Eq '^[0-9a-f]{{64}}$' || exit 79 + [ "$state_revision" -le {plan.desired_revision} ] || exit 79 + if [ "$state_revision" = {plan.desired_revision} ] && [ "$state_digest" != { _q(plan.desired_digest) } ]; then exit 79; fi +elif [ -f "$OWNER_FILE" ] && [ "$BRIDGE_PRESENT" = yes ]; then + # A live panel bridge without its state cannot be reconciled safely. + exit 71 +else + # Without the state file there is no safe owner proof for deterministic + # policy routes/rules. Refuse to claim a clean removal while any of those + # resources remain; an operator can restore the state and retry. + orphan_routes=$("$IP" -o -4 route show table "$ROUTE_TABLE" 2>/dev/null || true) + [ -z "$orphan_routes" ] || exit 71 + orphan_rule=$("$IP" -o rule show pref "{r.rule_priority}" 2>/dev/null || true) + [ -z "$orphan_rule" ] || exit 71 + orphan_rule=$("$IP" -o rule show pref "$(( {r.rule_priority} + 1 ))" 2>/dev/null || true) + [ -z "$orphan_rule" ] || exit 71 +fi +for artifact in "$NFT_FILE" "$SYSCTL_FILE" "$PROXY_FILE" "$IF_FRAGMENT"; do + [ -e "$artifact" ] || continue + [ -f "$artifact" ] && [ ! -L "$artifact" ] || exit 71 +done +if [ -f "$NFT_FILE" ]; then + [ "$($STAT -c '%u:%a' "$NFT_FILE" 2>/dev/null)" = 0:600 ] || exit 71 + grep -Fqx '# virt-cloud-vpc-dataplane-v1' "$NFT_FILE" || exit 71 +fi +if [ -f "$SYSCTL_FILE" ]; then + [ "$($STAT -c '%u:%a' "$SYSCTL_FILE" 2>/dev/null)" = 0:600 ] || exit 71 + sed -n '1p' "$SYSCTL_FILE" | grep -Fqx '# virt-cloud-vpc-dataplane-v1' || exit 71 +fi +if [ -f "$PROXY_FILE" ]; then + [ "$($STAT -c '%u:%a' "$PROXY_FILE" 2>/dev/null)" = 0:600 ] || exit 71 + sed -n '1p' "$PROXY_FILE" | grep -Fqx '# virt-cloud-vpc-proxy-v1' || exit 71 + awk 'NR > 1 && $0 !~ /^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$/ {{ exit 1 }}' "$PROXY_FILE" || exit 71 +fi +if [ -f "$IF_FRAGMENT" ]; then + [ "$($STAT -c '%u:%a' "$IF_FRAGMENT" 2>/dev/null)" = 0:600 ] || exit 71 + sed -n '1p' "$IF_FRAGMENT" | grep -Fqx '{ifup_marker}' || exit 71 + grep -Fqx 'auto {r.bridge}' "$IF_FRAGMENT" || exit 71 + grep -Fqx 'iface {r.bridge} inet manual' "$IF_FRAGMENT" || exit 71 + if grep -Eq '^[[:space:]]*bridge_ports([[:space:]]|$)' "$IF_FRAGMENT"; then + grep -Eq '^[[:space:]]*bridge_ports[[:space:]]+none[[:space:]]*$' "$IF_FRAGMENT" || exit 71 + fi + grep -Eq '^[[:space:]]*(address|gateway|up|down|pre-up|post-up|pre-down|post-down)([[:space:]]|$)' "$IF_FRAGMENT" && exit 71 || true +fi +else + for artifact in "$NFT_FILE" "$SYSCTL_FILE" "$PROXY_FILE" "$IF_FRAGMENT" "$OWNER_FILE" "$STATE_FILE"; do + [ ! -e "$artifact" ] && [ ! -L "$artifact" ] || exit 79 + done +fi +if [ "$MODE" = networkmanager_nmcli ]; then + if [ "$PHASE" = preparing ] || [ "$PHASE" = routes_removed ]; then + nm_field() {{ "$NMCLI" -t --escape no -g "$1" connection show "$BRIDGE" 2>/dev/null | sed -n '1p'; }} + nm_empty() {{ value=$(nm_field "$1"); [ -z "$value" ] || [ "$value" = "--" ]; }} + NM_PROFILE_COUNT=$("$NMCLI" -t --escape no -f NAME connection show 2>/dev/null | awk -v wanted="$BRIDGE" '$0 == wanted {{ count++ }} END {{ print count + 0 }}') + case "$NM_PROFILE_COUNT" in ''|*[!0-9]*) exit 71;; esac + if [ "$NM_PROFILE_COUNT" = 1 ]; then + # The deterministic profile name is not sufficient ownership evidence. + # Match the apply-side contract before taking a profile down or deleting + # it, so a public/operator bridge can never be removed by this cleanup. + [ "$(nm_field connection.type)" = bridge ] || exit 71 + [ "$(nm_field connection.interface-name)" = "$BRIDGE" ] || exit 71 + [ "$(nm_field connection.stable-id)" = "{nm_profile_marker}" ] || exit 71 + [ "$(nm_field ipv4.method)" = disabled ] || exit 71 + [ "$(nm_field ipv6.method)" = disabled ] || exit 71 + nm_empty ipv4.addresses || exit 71 + nm_empty ipv4.routes || exit 71 + nm_empty ipv4.routing-rules || exit 71 + nm_empty ipv4.gateway || exit 71 + nm_empty ipv4.dns || exit 71 + nm_empty ipv4.dns-search || exit 71 + nm_empty ipv6.addresses || exit 71 + nm_empty ipv6.routes || exit 71 + nm_empty ipv6.routing-rules || exit 71 + nm_empty ipv6.gateway || exit 71 + nm_empty ipv6.dns || exit 71 + nm_empty ipv6.dns-search || exit 71 + nm_empty connection.master || exit 71 + nm_empty connection.controller || exit 71 + nm_empty connection.slave-type || exit 71 + nm_empty connection.port-type || exit 71 + nm_empty connection.secondaries || exit 71 + nm_empty connection.zone || exit 71 + case "$(nm_field bridge.stp)" in no|false|off|0|--) : ;; *) exit 71 ;; esac + elif [ "$NM_PROFILE_COUNT" -gt 1 ]; then + exit 71 + elif [ "$BRIDGE_PRESENT" = yes ]; then + # An unmanaged live bridge is foreign/ambiguous; do not delete it. + exit 71 + fi + else + if "$NMCLI" connection show "$BRIDGE" >/dev/null 2>&1; then exit 79; fi + fi +else + if [ "$PHASE" = preparing ] || [ "$PHASE" = routes_removed ]; then + if [ "$BRIDGE_PRESENT" = yes ] || [ -e "$IF_FRAGMENT" ]; then + [ -f "$IF_FRAGMENT" ] || exit 71 + [ ! -L /etc/network ] && [ ! -L /etc/network/interfaces ] && [ ! -L /etc/network/interfaces.d ] || exit 71 + if [ -f /etc/network/interfaces ] && + grep -Eq '^[[:space:]]*(auto|allow-[^[:space:]]+|iface)[[:space:]]+'"$BRIDGE"'([[:space:]]|$)' /etc/network/interfaces; then + exit 71 + fi + "$IFQUERY" "$BRIDGE" >/dev/null 2>&1 || exit 71 + fi + fi +fi +if [ "$PHASE" = preparing ] || [ "$PHASE" = routes_removed ] || [ "$PHASE" = manager_removed ]; then + if "$IP" link show dev "$BRIDGE" >/dev/null 2>&1; then + [ -f "$OWNER_FILE" ] || exit 71 + bridge_info=$("$IP" -d link show dev "$BRIDGE" 2>/dev/null) || exit 71 + printf '%s\\n' "$bridge_info" | grep -Eq '(^|[[:space:]])bridge[[:space:]]+(forward_delay|stp_state|hello_time|ageing_time)([[:space:]]|$)' || exit 71 + bridge_ports=$("$BRIDGE_CMD" link show master "$BRIDGE" 2>/dev/null) || exit 71 + [ -z "$bridge_ports" ] || exit 79 + bridge_addrs=$("$IP" -o addr show dev "$BRIDGE" 2>/dev/null) || exit 71 + [ -z "$bridge_addrs" ] || exit 79 + fi +else + if "$IP" link show dev "$BRIDGE" >/dev/null 2>&1; then exit 79; fi +fi +NFT_MAIN_COUNT=0 +for nft_candidate in /etc/nftables.conf /etc/sysconfig/nftables.conf; do + if [ -f "$nft_candidate" ] && [ ! -L "$nft_candidate" ] && [ "$($STAT -c '%u' "$nft_candidate" 2>/dev/null)" = 0 ]; then + case "$($STAT -c '%a' "$nft_candidate" 2>/dev/null)" in + [0-7][0145][0145]) : ;; + *) continue ;; + esac + NFT_MAIN="$nft_candidate"; NFT_MAIN_COUNT=$((NFT_MAIN_COUNT + 1)) + fi +done +[ "$NFT_MAIN_COUNT" -eq 1 ] || exit 71 +if [ "$PHASE" = preparing ] || [ "$PHASE" = routes_removed ] || [ "$PHASE" = manager_removed ] || [ "$PHASE" = bridge_removed ]; then +if [ -f "$NFT_FILE" ]; then + nft_tables=$(awk '$1=="table" {{print $2 "|" $3}}' "$NFT_FILE") + nft_table_count=0 + while IFS='|' read -r family name; do + [ -n "$family" ] || continue + case "$family:$name" in inet:*|bridge:*|arp:*) : ;; *) exit 71 ;; esac + [ "$name" = "$TABLE" ] || exit 71 + table_dump=$("$NFT" list table "$family" "$name" 2>/dev/null) || exit 71 + printf '%s\\n' "$table_dump" | grep -Fq 'virt-cloud-vpc-dataplane-v1' || exit 71 + nft_table_count=$((nft_table_count + 1)) + done </dev/null 2>&1; then exit 79; fi + done < "$TXN/inflight"; chmod 600 "$TXN/inflight" + set_phase preparing + if [ -f "$STATE_FILE" ]; then cp -p "$STATE_FILE" "$TXN/state.before"; fi + : > "$TXN/routes.before"; : > "$TXN/rules.before"; : > "$TXN/proxy.before" + chmod 600 "$TXN/routes.before" "$TXN/rules.before" "$TXN/proxy.before" +else + # A resumed transaction must use the original snapshots. Creating an empty + # snapshot after a partial failure would turn an unknown host state into an + # apparently clean state and could make the next destructive step unsafe. + for snapshot in "$TXN/routes.before" "$TXN/rules.before" "$TXN/proxy.before"; do + [ -f "$snapshot" ] && [ ! -L "$snapshot" ] || exit 79 + [ "$($STAT -c '%u:%a' "$snapshot" 2>/dev/null)" = 0:600 ] || exit 79 + done +fi +if [ -f "$TXN/state.before" ]; then + while IFS='|' read -r kind destination device table via metric; do + [ "$kind" = route ] || continue + [ "$table" = "$ROUTE_TABLE" ] || exit 71 + [ "$device" = "$BRIDGE" ] || [ "$device" = "$WG_IFACE" ] || exit 71 + printf '%s\\n' "$destination" | grep -Eq '^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+/32$' || exit 71 + case "$via" in + -|'') : ;; + *) printf '%s\\n' "$via" | grep -Eq '^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$' || exit 71 ;; + esac + case "$metric" in ''|*[!0-9]*) exit 71;; esac + existing=$("$IP" -o -4 route show table "$table" "$destination" 2>/dev/null || true) + [ -n "$existing" ] || continue + existing_count=$(printf '%s\\n' "$existing" | awk 'NF {{ count++ }} END {{ print count + 0 }}') + [ "$existing_count" = 1 ] || exit 71 + actual_device=$(printf '%s\\n' "$existing" | awk '{{for (i=1;i<=NF;i++) if ($i=="dev" && i> "$TXN/routes.before" + if [ "${{old_via:--}}" != - ]; then + "$IP" route del "$destination" table "$table" via "$old_via" dev "$device" proto 186 metric "$old_metric" || exit 72 + else + "$IP" route del "$destination" table "$table" dev "$device" proto 186 metric "$old_metric" || exit 72 + fi + done < "$TXN/state.before" + old_priority=$(awk -F'|' '$1=="priority" {{print $2; exit}}' "$TXN/state.before") + old_cidr=$(awk -F'|' '$1=="cidr" {{print $2; exit}}' "$TXN/state.before") + [ -n "$old_priority" ] && [ -n "$old_cidr" ] || exit 71 + case "$old_priority" in ''|*[!0-9]*) exit 71;; esac + [ "$old_priority" = "{r.rule_priority}" ] || exit 71 + for pref in "$old_priority" "$((old_priority + 1))"; do + existing=$("$IP" -o rule show pref "$pref" 2>/dev/null || true) + [ -n "$existing" ] || continue + existing_count=$(printf '%s\\n' "$existing" | awk 'NF {{ count++ }} END {{ print count + 0 }}') + [ "$existing_count" = 1 ] || exit 71 + printf '%s\\n' "$existing" | grep -Fq "to $old_cidr lookup $ROUTE_TABLE" || exit 71 + old_iif=$(printf '%s\\n' "$existing" | awk '{{for (i=1;i<=NF;i++) if ($i=="iif" && i> "$TXN/rules.before" + "$IP" rule del pref "$pref" || exit 72 + done +fi +if [ -f "$PROXY_FILE" ]; then + while IFS= read -r proxy_ip; do + [ -n "$proxy_ip" ] || continue + if "$IP" neigh show proxy dev "$BRIDGE" 2>/dev/null | grep -Fqx "$proxy_ip"; then + printf '%s\\n' "$proxy_ip" >> "$TXN/proxy.before" + "$IP" neigh del proxy "$proxy_ip" dev "$BRIDGE" || exit 72 + fi + done </dev/null 2>&1; then + "$NMCLI" connection down "$BRIDGE" >/dev/null 2>&1 || true + "$NMCLI" connection delete "$BRIDGE" >/dev/null 2>&1 || exit 72 + if "$NMCLI" connection show "$BRIDGE" >/dev/null 2>&1; then exit 72; fi + fi +else + if [ -f "$IF_FRAGMENT" ]; then + "$IFQUERY" "$BRIDGE" >/dev/null 2>&1 || exit 71 + "$IFDOWN" --force "$BRIDGE" >/dev/null 2>&1 || exit 72 + fi +fi +set_phase manager_removed +if "$IP" link show dev "$BRIDGE" >/dev/null 2>&1; then + bridge_info=$("$IP" -d link show dev "$BRIDGE" 2>/dev/null) || exit 71 + printf '%s\\n' "$bridge_info" | grep -Eq '(^|[[:space:]])bridge[[:space:]]+(forward_delay|stp_state|hello_time|ageing_time)([[:space:]]|$)' || exit 71 + ports=$("$BRIDGE_CMD" link show master "$BRIDGE" 2>/dev/null) || exit 71 + [ -z "$ports" ] || exit 79 + bridge_addrs=$("$IP" -o addr show dev "$BRIDGE" 2>/dev/null) || exit 71 + [ -z "$bridge_addrs" ] || exit 79 + bridge_routes=$("$IP" -o -4 route show table all dev "$BRIDGE" 2>/dev/null) || exit 71 + [ -z "$bridge_routes" ] || exit 79 + bridge_routes6=$("$IP" -o -6 route show table all dev "$BRIDGE" 2>/dev/null) || exit 71 + [ -z "$bridge_routes6" ] || exit 79 + proxy_left=$("$IP" neigh show proxy dev "$BRIDGE" 2>/dev/null | awk '$1 ~ /^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$/') || exit 71 + [ -z "$proxy_left" ] || exit 79 + "$IP" link del dev "$BRIDGE" type bridge || exit 72 +fi +if "$IP" link show dev "$BRIDGE" >/dev/null 2>&1; then exit 72; fi +set_phase bridge_removed +if [ -f "$NFT_FILE" ]; then + nft_tables=$(awk '$1=="table" {{print $2 "|" $3}}' "$NFT_FILE") + nft_table_count=0 + while IFS='|' read -r family name; do + [ -n "$family" ] || continue + case "$family:$name" in inet:*|bridge:*|arp:*) : ;; *) exit 71 ;; esac + [ "$name" = "$TABLE" ] || exit 71 + table_dump=$("$NFT" list table "$family" "$name" 2>/dev/null) || exit 71 + printf '%s\\n' "$table_dump" | grep -Fq 'virt-cloud-vpc-dataplane-v1' || exit 71 + "$NFT" delete table "$family" "$name" || exit 72 + if "$NFT" list table "$family" "$name" >/dev/null 2>&1; then exit 72; fi + nft_table_count=$((nft_table_count + 1)) + done < "$NFT_MAIN_TMP" || {{ rm -f "$NFT_MAIN_TMP"; exit 72; }} + "$NFT" -c -f "$NFT_MAIN_TMP" >/dev/null || {{ rm -f "$NFT_MAIN_TMP"; exit 72; }} + chmod "$($STAT -c '%a' "$NFT_MAIN")" "$NFT_MAIN_TMP" || {{ rm -f "$NFT_MAIN_TMP"; exit 72; }} + mv -f "$NFT_MAIN_TMP" "$NFT_MAIN" || exit 72 + grep -Fqx "$NFT_INCLUDE" "$NFT_MAIN" && exit 72 || true +fi +set_phase nft_removed +if [ -e "$NFT_FILE" ] || [ -L "$NFT_FILE" ]; then + [ -f "$NFT_FILE" ] && [ ! -L "$NFT_FILE" ] || exit 71 + grep -Fqx '# virt-cloud-vpc-dataplane-v1' "$NFT_FILE" || exit 71 + grep -Fqx '# vpc={plan.vpc.vpc_id} revision={plan.desired_revision} digest={plan.desired_digest}' "$NFT_FILE" || exit 71 +fi +if [ -e "$SYSCTL_FILE" ] || [ -L "$SYSCTL_FILE" ]; then + [ -f "$SYSCTL_FILE" ] && [ ! -L "$SYSCTL_FILE" ] || exit 71 + sed -n '1p' "$SYSCTL_FILE" | grep -Fqx '# virt-cloud-vpc-dataplane-v1' || exit 71 +fi +if [ -e "$PROXY_FILE" ] || [ -L "$PROXY_FILE" ]; then + [ -f "$PROXY_FILE" ] && [ ! -L "$PROXY_FILE" ] || exit 71 + sed -n '1p' "$PROXY_FILE" | grep -Fqx '# virt-cloud-vpc-proxy-v1' || exit 71 +fi +if [ -e "$IF_FRAGMENT" ] || [ -L "$IF_FRAGMENT" ]; then + [ -f "$IF_FRAGMENT" ] && [ ! -L "$IF_FRAGMENT" ] || exit 71 + sed -n '1p' "$IF_FRAGMENT" | grep -Fqx '{ifup_marker}' || exit 71 +fi +if [ -f "$STATE_FILE" ]; then + [ ! -L "$STATE_FILE" ] || exit 71 + grep -Fqx 'owner|{DATAPLANE_OWNER_MARKER}' "$STATE_FILE" || exit 71 + grep -Fqx 'vpc|{plan.vpc.vpc_id}' "$STATE_FILE" || exit 71 + grep -Fqx 'fabric|{plan.vpc.fabric_id}' "$STATE_FILE" || exit 71 + grep -Fqx 'host|{plan.host_id}' "$STATE_FILE" || exit 71 + grep -Fqx 'bridge|{r.bridge}' "$STATE_FILE" || exit 71 + grep -Fqx 'table|{r.route_table}' "$STATE_FILE" || exit 71 + state_revision=$(awk -F'|' '$1=="revision" {{print $2; exit}}' "$STATE_FILE") + state_digest=$(awk -F'|' '$1=="digest" {{print $2; exit}}' "$STATE_FILE") + case "$state_revision" in ''|*[!0-9]*) exit 79;; esac + [ "$state_revision" -le {plan.desired_revision} ] || exit 79 + if [ "$state_revision" = {plan.desired_revision} ] && [ "$state_digest" != { _q(plan.desired_digest) } ]; then exit 79; fi +fi +rm -f "$NFT_FILE" "$SYSCTL_FILE" "$PROXY_FILE" "$IF_FRAGMENT" "$OWNER_FILE" "$STATE_FILE" +[ ! -e "$NFT_FILE" ] && [ ! -e "$SYSCTL_FILE" ] && [ ! -e "$PROXY_FILE" ] && + [ ! -e "$IF_FRAGMENT" ] && [ ! -e "$OWNER_FILE" ] && [ ! -e "$STATE_FILE" ] || exit 72 +set_phase files_removed +{state_loader} +vpc_state_load || exit 74 +vpc_state_refresh_nft || exit 74 +for key in $("$WG" show "$WG_IFACE" peers 2>/dev/null); do + actual=$("$WG" show "$WG_IFACE" allowed-ips 2>/dev/null | awk -v wanted="$key" '$1==wanted {{print $2; exit}}' || true) + overlay=$(printf '%s\\n' "$actual" | tr ',' '\\n' | awk '/^100\\.64\\.[0-9]+\\.[0-9]+\\/32$/ {{print; count++}} END {{exit count == 1 ? 0 : 1}}') || exit 74 + extra=$(vpc_state_allowed_for_peer "$key") || exit 74 + merged="$overlay"; [ -z "$extra" ] || merged="$merged,$extra" + "$WG" set "$WG_IFACE" peer "$key" allowed-ips "$merged" || exit 74 +done +set_phase wg_merged +verify_routes_removed || exit 79 +for family in inet bridge arp; do + "$NFT" list table "$family" "$TABLE" >/dev/null 2>&1 && exit 79 || true +done +grep -Fqx "$NFT_INCLUDE" "$NFT_MAIN" && exit 79 || true +if [ "$MODE" = networkmanager_nmcli ] && [ -n "$NMCLI" ]; then + "$NMCLI" connection show "$BRIDGE" >/dev/null 2>&1 && exit 79 || true +fi +[ ! -e "$STATE_FILE" ] && [ ! -e "$OWNER_FILE" ] || exit 79 +if "$IP" link show dev "$BRIDGE" >/dev/null 2>&1; then exit 79; fi +printf '%s\\n' '__VC_VPC_REMOVED__=yes' +printf '%s\\n' '__VC_VPC_OWNER__={DATAPLANE_OWNER_MARKER}' +printf '%s\\n' '__VC_VPC_REVISION__={plan.desired_revision}' +printf '%s\\n' '__VC_VPC_DIGEST__={plan.desired_digest}' +set_phase committed +rm -rf "$TXN" +printf '%s\\n' '__VC_VPC_ROLLBACK__=none' +exit 0 +''' + if len(script) > MAX_OUTPUT: + raise VpcDataplaneError("VPC 销毁脚本过大", 413, "vpc_script_too_large") + return script + + +# Real host calls use the strict, manager-aware builder. The old positional +# function remains above for compatibility with callers that only render a +# fixture. +render_apply_script = _render_apply_script_v2 + + +def render_observe_script(plan: VpcDataplanePlan) -> str: + routes = _routes(plan) + r = plan.resources + proxy_file = f"/etc/virt-cloud/vpc-dataplane/{r.token}.proxy" + nft_file = f"/etc/nftables.d/virt-cloud-vpc-{r.token}.nft" + nft_include = f'include "{nft_file}"' + sysctl_file = f"/etc/sysctl.d/99-virt-cloud-vpc-{r.token}.conf" + ifup_fragment = f"/etc/network/interfaces.d/virt-cloud-vpc-{r.token}" + nm_profile_marker = DATAPLANE_OWNER_MARKER + " vpc=" + plan.vpc.vpc_id + route_lines = "\n".join( + f"{x['destination_cidr']}|{x['device']}|{x.get('via') or '-'}|{x.get('metric', 100)}" + for x in routes) + peer_lines = "\n".join( + f"{p.host_id}|{p.public_key}|{_allowed(plan, p)}" + for p in plan.peers) + fabric_peer_key_words = " ".join(sorted(plan.fabric_peer_keys or ())) + fabric_peer_key_arg = _q(fabric_peer_key_words) + fabric_peer_keys_provided = "yes" if plan.fabric_peer_keys is not None else "no" + route_marker = "__VC_VPC_OBS_ROUTES_" + hashlib.sha256( + route_lines.encode()).hexdigest()[:12] + peer_marker = "__VC_VPC_OBS_PEERS_" + hashlib.sha256( + peer_lines.encode()).hexdigest()[:12] + nft_marker = _nft_marker(plan) + # These comments are emitted by render_vpc_nft_rules. Requiring the full + # owned shape prevents a stale or foreign table being reported as active + # merely because the deterministic table name exists. + nft_suffixes = ( + "anti-spoof-local-ip", "anti-spoof-egress", + "anti-spoof-public-to-bridge", "anti-spoof-public-to-fabric", + "anti-spoof-bridge-to-foreign", "anti-spoof-fabric-to-foreign", + "anti-spoof-public-to-vpc-bridge", "anti-spoof-public-to-vpc-fabric", + "anti-spoof-bridge-vpc-to-foreign", "anti-spoof-fabric-vpc-to-foreign", + "anti-spoof-wg-ingress", "anti-spoof-wg-egress", + "anti-spoof-wg-source", "member-egress-isolation", + "member-fabric-isolation", + "default-deny", + "wg-transit-deny", + "ipv6-drop-bridge", "ipv6-drop-fabric", + "ipv6-input-drop-bridge", "ipv6-input-drop-fabric", + "ipv6-output-drop-bridge", + "host-isolation", "host-isolation-wg", "host-isolation-out", + "host-isolation-wg-source", "host-isolation-out-wg", + "host-isolation-vpc-out", "host-isolation-vpc-out-wg", + "scope-bridge-in", "scope-bridge-out", "scope-fabric-in", + "scope-fabric-out", + *(f"acl:{acl.acl_id}" for acl in plan.vpc.acls), + ) + nft_checks = "\n".join( + f''' printf '%s\\n' "$nft_text" | grep -Fq "comment \\\"$NFT_MARKER:{suffix}\\\"" || nft_verified=no''' + for suffix in nft_suffixes) + bridge_suffixes = ( + "bridge-anti-spoof-ingress", "bridge-anti-spoof-arp", + "bridge-anti-spoof-arp-mac", "bridge-anti-spoof-ip", + "bridge-anti-spoof-arp-ip", + "bridge-multicast-drop", "bridge-limited-broadcast-drop", + "bridge-vpc-broadcast-drop", + "bridge-unknown-destination-drop", + "bridge-default-deny", "bridge-scope-accept", + "bridge-arp-accept", "bridge-non-ip-drop", + "bridge-anti-spoof-arp-input-mac", "bridge-anti-spoof-input", + "bridge-anti-spoof-input-ip", "bridge-ipv6-input-drop", + "bridge-arp-input-accept", "bridge-ip-input-accept", + "bridge-input-non-ip-drop", + *(f"acl:{acl.acl_id}" for acl in plan.vpc.acls), + ) + bridge_checks = "\n".join( + f''' printf '%s\\n' "$bridge_text" | grep -Fq "comment \\\"$NFT_MARKER:{suffix}\\\"" || bridge_verified=no''' + for suffix in bridge_suffixes) + if plan.local_members: + bridge_observe = f'''bridge_text=$($NFT list table bridge "$TABLE" 2>/dev/null || true) +bridge_verified=yes +printf '%s\\n' "$bridge_text" | grep -Fq "table bridge $TABLE" || bridge_verified=no +printf '%s\\n' "$bridge_text" | grep -Fq "chain forward" || bridge_verified=no +printf '%s\\n' "$bridge_text" | grep -Fq "hook forward priority -190" || bridge_verified=no +printf '%s\\n' "$bridge_text" | grep -Fq "policy accept" || bridge_verified=no +printf '%s\\n' "$bridge_text" | grep -Fq "set local_member_ips" || bridge_verified=no +printf '%s\\n' "$bridge_text" | grep -Fq "set local_dest_ips" || bridge_verified=no +{bridge_checks} +if [ "$bridge_verified" = yes ]; then printf '%s\\n' '__VC_VPC_BRIDGE_NFT__=yes'; else printf '%s\\n' '__VC_VPC_BRIDGE_NFT__=no'; fi''' + else: + # An empty VPC must not silently retain a stale bridge-family table + # from a previous revision or host membership. + bridge_observe = ''' +if $NFT list table bridge "$TABLE" >/dev/null 2>&1; then + printf '%s\\n' '__VC_VPC_BRIDGE_NFT__=no' +else + printf '%s\\n' '__VC_VPC_BRIDGE_NFT__=none' +fi'''.strip() + if plan.local_members: + arp_observe = f'''arp_text=$($NFT list table arp "$TABLE" 2>/dev/null || true) +arp_verified=yes +printf '%s\\n' "$arp_text" | grep -Fq "table arp $TABLE" || arp_verified=no +printf '%s\\n' "$arp_text" | grep -Fq "set proxy_ips" || arp_verified=no +printf '%s\\n' "$arp_text" | grep -Fq "chain output" || arp_verified=no +printf '%s\\n' "$arp_text" | grep -Fq "hook output priority -190" || arp_verified=no +printf '%s\\n' "$arp_text" | grep -Fq "policy accept" || arp_verified=no +printf '%s\\n' "$arp_text" | grep -Fq "comment \\\"$NFT_MARKER:arp-proxy-output\\\"" || arp_verified=no +if [ "$arp_verified" = yes ]; then printf '%s\\n' '__VC_VPC_ARP_NFT__=yes'; else printf '%s\\n' '__VC_VPC_ARP_NFT__=no'; fi''' + else: + arp_observe = ''' +if $NFT list table arp "$TABLE" >/dev/null 2>&1; then + printf '%s\\n' '__VC_VPC_ARP_NFT__=no' +else + printf '%s\\n' '__VC_VPC_ARP_NFT__=none' +fi'''.strip() + route_extra_awk = "\n".join( + f' $0 == "{x["destination_cidr"]}|{x["device"]}|{x.get("via") or "-"}|{x.get("metric", 100)}|186" {{ next }}' + for x in routes) + route_checks = "\n".join( + f'''state=missing +if printf '%s\\n' "$route_records" | awk -F'|' -v wanted={_q(x['destination_cidr'])} -v expected_device={_q(x['device'])} -v expected_via={_q(x.get('via') or '-')} -v expected_metric={_q(str(x.get('metric', 100)))} '$1 == wanted && $2 == expected_device && $3 == expected_via && $4 == expected_metric && $5 == "186" {{found=1}} END {{exit found ? 0 : 1}}'; then + state=owned +fi +printf '%s\\n' '__VC_VPC_ROUTE__={x['destination_cidr']}|{x['device']}|'"$ROUTE_TABLE"'|{x.get('via') or '-'}|{x.get('metric', 100)}|'"$state" +'''.rstrip() + for x in routes) + if not route_checks: + route_checks = ": # no expected VPC routes" + rule_specs = ( + (str(r.rule_priority), "-", plan.vpc.cidr, str(r.route_table)), + (str(r.rule_priority + 1), FABRIC_INTERFACE, plan.vpc.cidr, + str(r.route_table)), + ) + rule_checks = "\n".join( + f'''rule_state=missing +if printf '%s\\n' "$rule_records" | awk -F'|' -v pref={_q(pref)} -v expected_iif={_q(iif)} -v expected_to={_q(destination)} -v expected_table={_q(table)} '$1 == pref && $2 == expected_iif && $3 == expected_to && $4 == expected_table {{found=1}} END {{exit found ? 0 : 1}}'; then + rule_state=owned +fi +printf '%s\\n' '__VC_VPC_RULE__={pref}|{iif}|{destination}|{table}|'"$rule_state" +'''.rstrip() + for pref, iif, destination, table in rule_specs) + return f'''#!/bin/sh +set -eu +PATH=/usr/sbin:/usr/bin:/sbin:/bin +IP=/usr/sbin/ip; [ -x "$IP" ] || IP=/usr/bin/ip +WG=/usr/bin/wg; [ -x "$WG" ] || WG=/usr/sbin/wg +NFT=/usr/sbin/nft; [ -x "$NFT" ] || NFT=/usr/bin/nft +FLOCK=/usr/bin/flock; [ -x "$FLOCK" ] || FLOCK=/usr/sbin/flock +LOCK=/run/virt-cloud/wg-fabric0.lock +if [ -L /run/virt-cloud ] || {{ [ -e /run/virt-cloud ] && [ ! -d /run/virt-cloud ]; }}; then exit 71; fi +mkdir -p /run/virt-cloud; chmod 700 /run/virt-cloud +[ ! -L "$LOCK" ] && {{ [ ! -e "$LOCK" ] || [ -f "$LOCK" ]; }} || exit 71 +: >> "$LOCK"; chmod 600 "$LOCK"; exec 8>>"$LOCK"; "$FLOCK" -s 8 +BRIDGE_CMD= +for p in /usr/sbin/bridge /usr/bin/bridge /sbin/bridge /bin/bridge; do + if [ -x "$p" ]; then BRIDGE_CMD=$p; break; fi +done +BRIDGE={_q(r.bridge)}; TABLE={_q(r.nft_table)}; ROUTE_TABLE={r.route_table}; WG_IFACE={_q(FABRIC_INTERFACE)}; OWNER={_q(r.owner_file)}; STATE={_q(r.state_file)}; PROXY_FILE={_q(proxy_file)} +NFT_FILE={_q(nft_file)}; NFT_INCLUDE={_q(nft_include)}; SYSCTL_FILE={_q(sysctl_file)}; IF_FRAGMENT={_q(ifup_fragment)}; NM_PROFILE_MARKER={_q(nm_profile_marker)}; NFT_MAIN=; NFT_MAIN_COUNT=0 +NFT_MARKER={_q(nft_marker)} +owner=missing; [ -f "$OWNER" ] && owner=$(cat "$OWNER" 2>/dev/null || printf missing) +printf '%s\\n' "__VC_VPC_BRIDGE_OWNER__=$owner" +for nft_candidate in /etc/nftables.conf /etc/sysconfig/nftables.conf; do + if [ -f "$nft_candidate" ] && [ ! -L "$nft_candidate" ] && [ "$(stat -c '%u' "$nft_candidate" 2>/dev/null)" = 0 ]; then + case "$(stat -c '%a' "$nft_candidate" 2>/dev/null)" in + [0-7][0145][0145]) NFT_MAIN="$nft_candidate"; NFT_MAIN_COUNT=$((NFT_MAIN_COUNT + 1)) ;; + *) : ;; + esac + fi +done +persistence=no +nft_file_ok=no +if [ -f "$NFT_FILE" ] && [ ! -L "$NFT_FILE" ] && [ "$(stat -c '%u:%a' "$NFT_FILE" 2>/dev/null)" = 0:600 ] && + grep -Fqx '# virt-cloud-vpc-dataplane-v1' "$NFT_FILE" && + grep -Fqx '# vpc={plan.vpc.vpc_id} revision={plan.desired_revision} digest={plan.desired_digest}' "$NFT_FILE"; then + nft_file_ok=yes +fi +sysctl_file_ok=no +if [ -f "$SYSCTL_FILE" ] && [ ! -L "$SYSCTL_FILE" ] && [ "$(stat -c '%u:%a' "$SYSCTL_FILE" 2>/dev/null)" = 0:600 ] && + grep -Fqx '# virt-cloud-vpc-dataplane-v1' "$SYSCTL_FILE" && + grep -Fqx 'net.ipv4.conf.{r.bridge}.rp_filter = 2' "$SYSCTL_FILE" && + grep -Fqx 'net.ipv4.conf.{r.bridge}.proxy_arp = 0' "$SYSCTL_FILE" && + grep -Fqx 'net.ipv4.conf.{r.bridge}.proxy_arp_pvlan = 1' "$SYSCTL_FILE"; then + sysctl_file_ok=yes +fi +nm_owned=no +NMCLI=$(for p in /usr/bin/nmcli /usr/sbin/nmcli /bin/nmcli /sbin/nmcli; do [ -x "$p" ] && {{ printf '%s' "$p"; break; }}; done) +if [ -n "$NMCLI" ] && [ "$($NMCLI -t --escape no -f NAME connection show 2>/dev/null | awk -v wanted="$BRIDGE" '$0 == wanted {{count++}} END {{print count + 0}}')" = 1 ]; then + nm_stable=$($NMCLI -t --escape no -g connection.stable-id connection show "$BRIDGE" 2>/dev/null | sed -n '1p') + nm_type=$($NMCLI -t --escape no -g connection.type connection show "$BRIDGE" 2>/dev/null | sed -n '1p') + nm_iface=$($NMCLI -t --escape no -g connection.interface-name connection show "$BRIDGE" 2>/dev/null | sed -n '1p') + nm_method=$($NMCLI -t --escape no -g ipv4.method connection show "$BRIDGE" 2>/dev/null | sed -n '1p') + nm6_method=$($NMCLI -t --escape no -g ipv6.method connection show "$BRIDGE" 2>/dev/null | sed -n '1p') + if [ "$nm_stable" = "$NM_PROFILE_MARKER" ] && [ "$nm_type" = bridge ] && [ "$nm_iface" = "$BRIDGE" ] && [ "$nm_method" = disabled ] && [ "$nm6_method" = disabled ]; then nm_owned=yes; fi +fi +ifup_owned=no +if [ -f "$IF_FRAGMENT" ] && [ ! -L "$IF_FRAGMENT" ] && [ "$(stat -c '%u:%a' "$IF_FRAGMENT" 2>/dev/null)" = 0:600 ] && + grep -Fqx '# {DATAPLANE_OWNER_MARKER} vpc={plan.vpc.vpc_id} revision={plan.desired_revision} digest={plan.desired_digest}' "$IF_FRAGMENT" && + grep -Fqx 'auto {r.bridge}' "$IF_FRAGMENT" && grep -Fqx 'iface {r.bridge} inet manual' "$IF_FRAGMENT"; then + ifup_owned=yes +fi +if [ "$NFT_MAIN_COUNT" = 1 ] && [ "$nft_file_ok" = yes ] && [ "$sysctl_file_ok" = yes ] && + grep -Fqx "$NFT_INCLUDE" "$NFT_MAIN" && "$NFT" -c -f "$NFT_MAIN" >/dev/null 2>&1 && + ( [ "$nm_owned" = yes ] && [ "$ifup_owned" = no ] || + [ "$nm_owned" = no ] && [ "$ifup_owned" = yes ] ); then + persistence=yes +fi +printf '%s\\n' "__VC_VPC_PERSISTENCE__=$persistence" +if "$IP" -d link show dev "$BRIDGE" >/dev/null 2>&1; then printf '%s\\n' '__VC_VPC_BRIDGE__='"$BRIDGE"; else printf '%s\\n' '__VC_VPC_BRIDGE__=missing'; fi +bridge_boundary=no +bridge_shape=no; bridge_addr_ok=no; bridge_ports_ok=no; bridge_routes_ok=no; bridge_routes6_ok=no +if [ -n "$BRIDGE_CMD" ]; then + if bridge_shape_text=$("$IP" -d link show dev "$BRIDGE" 2>/dev/null) && + printf '%s\n' "$bridge_shape_text" | grep -Eq '(^|[[:space:]])bridge[[:space:]]+(forward_delay|stp_state|hello_time|ageing_time)([[:space:]]|$)'; then + bridge_shape=yes + fi + if bridge_addr4=$("$IP" -o -4 addr show dev "$BRIDGE" 2>/dev/null) && + bridge_addr6=$("$IP" -o -6 addr show dev "$BRIDGE" 2>/dev/null) && + [ -z "$bridge_addr4$bridge_addr6" ]; then + bridge_addr_ok=yes + fi + if bridge_ports=$("$BRIDGE_CMD" link show master "$BRIDGE" 2>/dev/null); then + bridge_ports_ok=yes + fi + if bridge_routes=$("$IP" -o -4 route show table all dev "$BRIDGE" 2>/dev/null) && + printf '%s\n' "$bridge_routes" | awk -v wanted_table="$ROUTE_TABLE" ' + NF {{table="main"; proto=""; prefix=$1 + for (i=1;i<=NF;i++) {{if ($i=="table") table=$(i+1); if ($i=="proto") proto=$(i+1)}} + if (table=="254") table="main" + if (prefix=="default" || table!=wanted_table || proto!="186") bad=1}} + END {{exit bad ? 1 : 0}}'; then + bridge_routes_ok=yes + fi + if bridge_routes6=$($IP -o -6 route show table all dev "$BRIDGE" 2>/dev/null) && [ -z "$bridge_routes6" ]; then + bridge_routes6_ok=yes + fi +fi +if [ "$bridge_shape" = yes ] && [ "$bridge_addr_ok" = yes ] && + [ "$bridge_ports_ok" = yes ] && [ "$bridge_routes_ok" = yes ] && + [ "$bridge_routes6_ok" = yes ]; then + bridge_bad=no + while IFS= read -r bridge_port_line; do + [ -n "$bridge_port_line" ] || continue + bridge_port=$(printf '%s\\n' "$bridge_port_line" | sed -n 's/^[0-9][0-9]*: \\([^:[:space:]]*\\).*/\\1/p') + case "$bridge_port" in + vnet[0-9]*|tap[0-9A-Za-z_.-]*|macvtap[0-9]*|fwpr[0-9A-Za-z_.-]*|fwln[0-9A-Za-z_.-]*) : ;; + *) bridge_bad=yes ;; + esac + done <<__VC_VPC_OBS_PORTS__ +$bridge_ports +__VC_VPC_OBS_PORTS__ + if [ "$bridge_bad" = no ]; then + bridge_boundary=yes + fi +fi +printf '%s\\n' "__VC_VPC_BRIDGE_BOUNDARY__=$bridge_boundary" +if [ -r "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp" ]; then printf '%s\\n' '__VC_VPC_PROXY_ARP__='"$(cat "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp")"; else printf '%s\\n' '__VC_VPC_PROXY_ARP__=missing'; fi +if [ -r "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp_pvlan" ]; then printf '%s\\n' '__VC_VPC_PROXY_ARP_PVLAN__='"$(cat "/proc/sys/net/ipv4/conf/$BRIDGE/proxy_arp_pvlan")"; else printf '%s\\n' '__VC_VPC_PROXY_ARP_PVLAN__=missing'; fi +if [ -r "/proc/sys/net/ipv4/conf/$BRIDGE/rp_filter" ]; then printf '%s\\n' '__VC_VPC_RP_FILTER__='"$(cat "/proc/sys/net/ipv4/conf/$BRIDGE/rp_filter")"; else printf '%s\\n' '__VC_VPC_RP_FILTER__=missing'; fi +proxy_records=$($IP neigh show proxy dev "$BRIDGE" 2>/dev/null | awk '$1 ~ /^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$/ {{print $1}}' | LC_ALL=C sort -u || true) +printf '%s\\n' "$proxy_records" | while IFS= read -r proxy_ip; do + [ -n "$proxy_ip" ] && printf '%s\\n' "__VC_VPC_PROXY_IP__=$proxy_ip" +done +proxy_state=missing +if [ -f "$PROXY_FILE" ] && sed -n '1p' "$PROXY_FILE" | grep -Fqx '# virt-cloud-vpc-proxy-v1'; then + expected_proxy=$(sed '1d' "$PROXY_FILE" | LC_ALL=C sort -u) + if [ "$proxy_records" = "$expected_proxy" ]; then proxy_state=owned; fi +fi +printf '%s\\n' '__VC_VPC_PROXY_STATE__='"$proxy_state" +if "$NFT" list table inet "$TABLE" >/dev/null 2>&1; then printf '%s\\n' '__VC_VPC_NFT_TABLE__='"$TABLE"; else printf '%s\\n' '__VC_VPC_NFT_TABLE__=missing'; fi +if [ -f "$STATE" ] && grep -Fqx 'owner|{DATAPLANE_OWNER_MARKER}' "$STATE"; then + printf '%s\\n' '__VC_VPC_STATE_OWNER__=owned' + printf '%s\\n' "__VC_VPC_STATE_REVISION__=$(awk -F'|' '$1==\"revision\"{{print $2; exit}}' \"$STATE\")" + printf '%s\\n' "__VC_VPC_STATE_DIGEST__=$(awk -F'|' '$1==\"digest\"{{print $2; exit}}' \"$STATE\")" +else + printf '%s\\n' '__VC_VPC_STATE_OWNER__=missing' +fi +nft_text=$($NFT list table inet "$TABLE" 2>/dev/null || true) +nft_verified=yes +printf '%s\\n' "$nft_text" | grep -Fq "table inet $TABLE" || nft_verified=no +printf '%s\\n' "$nft_text" | grep -Fq "chain forward" || nft_verified=no +printf '%s\\n' "$nft_text" | grep -Fq "hook forward priority -190" || nft_verified=no +printf '%s\\n' "$nft_text" | grep -Fq "chain input" || nft_verified=no +printf '%s\\n' "$nft_text" | grep -Fq "chain output" || nft_verified=no +printf '%s\\n' "$nft_text" | grep -Fq "set member_ips" || nft_verified=no +printf '%s\\n' "$nft_text" | grep -Fq "set vpc_dest_ips" || nft_verified=no +{nft_checks} +if [ "$nft_verified" = yes ]; then + printf '%s\\n' '__VC_VPC_ACL_REVISION__={plan.desired_revision}' + printf '%s\\n' '__VC_VPC_ACL_DIGEST__={plan.desired_digest}' + printf '%s\\n' '__VC_VPC_ANTI_SPOOF__=yes' +else + printf '%s\\n' '__VC_VPC_ACL_REVISION__=missing' + printf '%s\\n' '__VC_VPC_ACL_DIGEST__=missing' + printf '%s\\n' '__VC_VPC_ANTI_SPOOF__=no' +fi +{bridge_observe} +{arp_observe} +route_records=$($IP -o -4 route show table "$ROUTE_TABLE" 2>/dev/null | awk '{{ + destination=$1; device=""; via="-"; metric="100"; proto="" + for (i=1; i<=NF; i++) {{ + if ($i == "dev" && i < NF) device=$(i+1) + if ($i == "via" && i < NF) via=$(i+1) + if ($i == "metric" && i < NF) metric=$(i+1) + if ($i == "proto" && i < NF) proto=$(i+1) + }} + if (destination != "") printf "%s|%s|%s|%s|%s\\n", destination, device, via, metric, proto +}}' || true) +rule_records=$($IP -o rule show 2>/dev/null | awk '{{ + pref=$1; sub(/:$/, "", pref); iif="-"; destination=""; table="" + for (i=1;i<=NF;i++) {{ + if ($i == "iif" && i < NF) iif=$(i+1) + if ($i == "to" && i < NF) destination=$(i+1) + if ($i == "lookup" && i < NF) table=$(i+1) + }} + if (pref != "" && iif != "" && destination != "" && table != "") printf "%s|%s|%s|%s\\n", pref, iif, destination, table +}}' || true) +{rule_checks} +route_extra=$(printf '%s\\n' "$route_records" | awk '{{ + if (length($0) == 0) next + count++ +{route_extra_awk} + extra=1 +}} END {{ if (count != {len(routes)}) extra=1; print extra ? "yes" : "no" }}') +printf '%s\\n' "__VC_VPC_ROUTE_EXTRA__=$route_extra" +{route_checks} +while IFS='|' read -r peer_host key expected_allowed; do + [ -n "$peer_host" ] || continue + actual=$(printf '%s\\n' "$($WG show "$WG_IFACE" allowed-ips 2>/dev/null || true)" | awk -v wanted="$key" '$1 == wanted {{print $2; exit}}') + # ``wg show`` does not promise AllowedIPs order. Canonicalize both + # comma-separated lists before comparing, and retain the complete set in + # the marker. The Python adapter projects this to this VPC's tenant /32s + # after proving that no extra or missing entry exists. + expected_set=$(printf '%s\\n' "$expected_allowed" | tr ',' '\\n' | awk 'NF' | LC_ALL=C sort -u) + actual_set=$(printf '%s\\n' "$actual" | tr ',' '\\n' | awk 'NF' | LC_ALL=C sort -u) + allowed=$(printf '%s\\n' "$actual_set" | awk 'BEGIN {{ ORS=""; sep="" }} NF {{ printf "%s%s", sep, $0; sep="," }}') + state=missing + if [ -n "$actual_set" ] && [ "$actual_set" = "$expected_set" ]; then + state=owned + else + allowed=missing + fi + printf '%s\\n' "__VC_VPC_WG_ALLOWED__=$peer_host|$key|$allowed" + printf '%s\\n' "__VC_VPC_WG_STATE__=$peer_host|$state" +done <<'{peer_marker}' +{peer_lines} +{peer_marker} +expected_fabric_peer_keys={fabric_peer_key_arg} +wg_peer_set=unverified +if [ "{fabric_peer_keys_provided}" = yes ]; then + live_fabric_peer_keys=$("$WG" show "$WG_IFACE" peers 2>/dev/null || true) + wg_peer_set=exact + for live_peer_key in $live_fabric_peer_keys; do + case " $expected_fabric_peer_keys " in + *" $live_peer_key "*) : ;; + *) wg_peer_set=extra ;; + esac + done + for expected_peer_key in $expected_fabric_peer_keys; do + printf '%s\n' "$live_fabric_peer_keys" | grep -Fqx "$expected_peer_key" || wg_peer_set=missing + done +fi +printf '%s\n' "__VC_VPC_WG_PEER_SET__=$wg_peer_set" +exit 0 +''' + + +def _markers(output: str) -> dict[str, Any]: + if not isinstance(output, str) or len(output) > MAX_OUTPUT: + raise VpcDataplaneError("VPC 回读输出过大", 502, "vpc_readback_invalid") + result: dict[str, Any] = {"routes": [], "wg_allowed_ips": [], + "wg_states": {}, "rules": [], "proxy_ips": []} + for line in output.splitlines(): + if not line.startswith("__VC_VPC_") or "=" not in line: + continue + key, value = line.split("=", 1) + # A peer can legitimately carry many exact /32s from multiple VPCs; + # keep a bounded upper limit without truncating the authenticated set. + if len(value) > 65536: + raise VpcDataplaneError("VPC 回读字段过长", 502, "vpc_readback_invalid") + if key == "__VC_VPC_ROUTE__": + p = value.split("|") + if len(p) == 6: + result["routes"].append({ + "destination_cidr": p[0], "device": p[1], "table": p[2], + "via": None if p[3] == "-" else p[3], + "metric": p[4], "owner": DATAPLANE_OWNER_MARKER, + "state": p[5], + }) + elif key == "__VC_VPC_PROXY_IP__": + if re.fullmatch(r"[0-9]{1,3}(?:\.[0-9]{1,3}){3}", value): + try: + address = ipaddress.IPv4Address(value) + except ipaddress.AddressValueError: + continue + result["proxy_ips"].append(str(address)) + elif key == "__VC_VPC_RULE__": + p = value.split("|") + if len(p) == 5: + result["rules"].append({"priority": p[0], "iif": p[1], + "destination_cidr": p[2], + "table": p[3], "state": p[4]}) + elif key == "__VC_VPC_WG_ALLOWED__": + p = value.split("|") + if len(p) == 3: + result["wg_allowed_ips"].append({"peer_host_id": p[0], "public_key": p[1], "tenant_allowed_ips": [] if p[2] == "missing" else [x for x in p[2].split(",") if x]}) + elif key == "__VC_VPC_WG_STATE__": + p = value.split("|") + if len(p) == 2 and p[1] in {"owned", "missing"}: + result["wg_states"][p[0]] = p[1] + else: + result[key.removeprefix("__VC_VPC_").removesuffix("__").lower()] = value + return result + + +def patch_private_interface_xml(xml: str | bytes, *, member: VpcMember, + resources: VpcDataplaneResources, + link_state: str = "up", + vpc_id: str | None = None, + desired_revision: int | None = None, + desired_digest: str | None = None) -> str: + """Add/validate a private0 NIC on an explicit panel-owned bridge.""" + if link_state not in {"up", "down"}: + raise VpcDataplaneError("私网网卡 link 状态无效") + private_mac = _mac(member.private_mac) + try: + root = ET.fromstring(xml) + except ET.ParseError as exc: + raise VpcDataplaneError("虚拟机 XML 无效", 409, "vpc_private_xml_invalid") from exc + devices = root.find("./devices") + if devices is None: + raise VpcDataplaneError("虚拟机 XML 缺少 devices", 409, "vpc_private_xml_invalid") + interfaces = list(devices.findall("interface")) + try: + public = select_public_interface(interfaces, allow_legacy_single=True) + # Legacy domains may have a single public NIC without an alias. Give + # it the stable role name before adding private0 so the next + # reconciliation does not mistake the public NIC for an unknown role. + alias = public.find("alias") + if alias is None: + alias = ET.SubElement(public, "alias") + alias.set("name", PUBLIC_INTERFACE_ALIAS) + private = select_private_interface(interfaces) + except ValueError as exc: + raise VpcDataplaneError(str(exc), 409, "vpc_private_xml_role_invalid") from exc + if private is None: + private = ET.SubElement(devices, "interface", {"type": "bridge"}) + else: + if private.get("type") != "bridge": + raise VpcDataplaneError("private0 必须使用 bridge", 409, "vpc_private_xml_source_invalid") + existing_filters = private.findall("filterref") + if existing_filters and any( + item.get("filter") != "clean-traffic" + for item in existing_filters): + raise VpcDataplaneError("private0 nwfilter 不受面板管理", 409, + "vpc_private_xml_filter_invalid") + source = private.find("source") + if source is None or source.get("network") is not None or source.get("bridge") != resources.bridge: + raise VpcDataplaneError("private0 bridge 不匹配", 409, "vpc_private_xml_source_mismatch") + source = private.find("source") + if source is None: + source = ET.Element("source") + private.insert(0, source) + source.attrib.clear(); source.set("bridge", resources.bridge) + mac = private.find("mac") + if mac is None: + mac = ET.Element("mac"); private.insert(0, mac) + mac.set("address", private_mac) + alias = private.find("alias") + if alias is None: + alias = ET.SubElement(private, "alias") + alias.set("name", PRIVATE_INTERFACE) + model = private.find("model") + if model is None: + model = ET.SubElement(private, "model") + model.set("type", "virtio") + link = private.find("link") + if link is None: + link = ET.SubElement(private, "link") + link.set("state", link_state) + for item in list(private.findall("filterref")): + private.remove(item) + # The private L3 data plane owns anti-spoofing and ACL enforcement in its + # dedicated bridge/inet/arp nft tables. Do not attach the public + # libvirt ``clean-traffic`` nwfilter to private0; the role observer + # deliberately treats any private filter as an unsafe mixed policy. + metadata = root.find("metadata") + if metadata is None: + metadata = ET.Element("metadata"); root.insert(0, metadata) + managed = metadata.find(f"{{{PANEL_NS}}}managed") + if managed is None: + managed = ET.SubElement(metadata, f"{{{PANEL_NS}}}managed") + managed.set("private-member-id", member.member_id) + managed.set("private-ip-cidr", f"{member.private_ip}/32") + managed.set("private-network-bridge", resources.bridge) + managed.set("private-network-verified", "true") + managed.set("private-dataplane-owner", DATAPLANE_OWNER_MARKER) + if vpc_id is not None: + managed.set("private-vpc-id", vpc_id) + if desired_revision is not None: + managed.set("private-network-revision", str(desired_revision)) + if desired_digest is not None: + managed.set("private-network-digest", desired_digest) + ET.register_namespace("panel", PANEL_NS) + return ET.tostring(root, encoding="unicode") + + +def _member_nics( + plan: VpcDataplanePlan, + xml_by_instance: Mapping[str, Any] | None, +) -> tuple[dict[str, Any], ...]: + def verified_xml(xml: str, member: VpcMember, *, metadata: bool) -> bool: + try: + root = ET.fromstring(xml) + private = select_private_interface( + list(root.findall("./devices/interface"))) + source = private.find("source") if private is not None else None + mac = private.find("mac") if private is not None else None + ok = bool( + private and private.get("type") == "bridge" + and source is not None + and source.get("bridge") == plan.resources.bridge + and mac is not None + and mac.get("address", "").lower() == member.private_mac + # VPC isolation is provided by the dedicated bridge/inet/arp + # nft context. The public libvirt nwfilter is intentionally + # absent from private0. + and not private.findall("filterref") + ) + if not metadata: + return ok + managed = root.find(f"./metadata/{{{PANEL_NS}}}managed") + return bool( + ok and managed is not None + and managed.get("private-vpc-id") == plan.vpc.vpc_id + and managed.get("private-member-id") == member.member_id + and managed.get("private-ip-cidr") == f"{member.private_ip}/32" + and managed.get("private-network-revision") + == str(plan.desired_revision) + and managed.get("private-network-digest") + == plan.desired_digest + ) + except (ET.ParseError, ValueError): + return False + + result = [] + for member in plan.local_members: + verified = False + if xml_by_instance and member.instance_uuid in xml_by_instance: + value = xml_by_instance[member.instance_uuid] + if isinstance(value, Mapping): + inactive = value.get("inactive") + live = value.get("live") + verified = ( + isinstance(inactive, str) + and verified_xml(inactive, member, metadata=True) + and (live is None + or (isinstance(live, str) + and verified_xml(live, member, metadata=False))) + ) + elif isinstance(value, str): + verified = verified_xml(value, member, metadata=True) + result.append({"member_id": member.member_id, "instance_uuid": member.instance_uuid, + "interface": PRIVATE_INTERFACE, "private_ip_cidr": f"{member.private_ip}/32", + "private_mac": member.private_mac, "xml_verified": verified}) + return tuple(result) + + +class VpcPrivateHostAdapter: + """Execute generated scripts through a pinned remote host manager.""" + + def __init__(self, manager: Any, profile: Mapping[str, Any] | None = None): + self.manager = manager + self.profile = dict(profile) if isinstance(profile, Mapping) else None + + def _run(self, script: str) -> str: + current = self.profile if self.profile is not None else self.manager.current() + if not isinstance(current, Mapping) or not current: + raise VpcDataplaneError("宿主机尚未配置", 409, "vpc_host_not_configured") + if current.get("key_locked"): + raise VpcDataplaneError("宿主机 SSH 私钥仍锁定", 409, "vpc_host_key_locked") + argv = [getattr(self.manager, "ssh_binary", "ssh"), "-F", current["ssh_config_file"], "-T", "-o", "ConnectTimeout=10", current["ssh_target"], "/bin/sh -s"] + try: + result = self.manager._exec(argv, timeout=35, input_text=script) + except Exception as exc: + raise VpcDataplaneError("宿主机 VPC SSH 请求失败", 502, "vpc_host_connection_failed") from exc + if result.returncode != 0: + raise VpcDataplaneError("宿主机 VPC 命令失败", 502, "vpc_remote_command_failed") + return result.stdout + + def _deployment_contract(self) -> tuple[str, str, str, str]: + """Validate the same immutable host capability gate as Fabric.""" + from .fabric import ( + FabricError, _profile_ifdown_path, _profile_ifquery_path, + _profile_ifup_path, _profile_network_mode, + ) + + current = self.profile if self.profile is not None else self.manager.current() + try: + mode = _profile_network_mode(current) + except FabricError as exc: + raise VpcDataplaneError( + "宿主机网络管理器与 VPC 部署模式不匹配", 409, + "vpc_dataplane_network_manager_conflict") from exc + capabilities = current.get("capabilities") if isinstance(current, Mapping) else None + network = capabilities.get("network") if isinstance(capabilities, Mapping) else None + wireguard = capabilities.get("wireguard") if isinstance(capabilities, Mapping) else None + nftables = capabilities.get("nftables") if isinstance(capabilities, Mapping) else None + if (not isinstance(network, Mapping) + or not isinstance(wireguard, Mapping) + or not isinstance(nftables, Mapping) + or capabilities.get("vpc_ready") is not True + or network.get("firewall_manager") != "nftables" + or network.get("ip_forward") != 1 + or nftables.get("ready") is not True + or wireguard.get("interface") != FABRIC_INTERFACE + or wireguard.get("interface_present") is not True + or wireguard.get("interface_is_wireguard") is not True + or wireguard.get("owned_by_panel") is not True): + raise VpcDataplaneError( + "宿主机 VPC 网络或防火墙能力未通过探测", 409, + "vpc_host_capability_missing") + return ( + mode, + _profile_ifup_path(current), + _profile_ifdown_path(current), + _profile_ifquery_path(current), + ) + + def apply(self, plan: VpcDataplanePlan) -> dict[str, Any]: + mode, ifup_path, ifdown_path, ifquery_path = self._deployment_contract() + script = render_apply_script( + plan, deployment_mode=mode, + ifup_path=ifup_path, ifdown_path=ifdown_path, + ifquery_path=ifquery_path, + ) + markers = _markers(self._run(script)) + if markers.get("applied") != "yes": + raise VpcDataplaneError("宿主机未确认 VPC 应用", 502, "vpc_apply_unconfirmed") + return {"state": "applying", "readback": "pending", "rollback": "none", "owner": DATAPLANE_OWNER_MARKER} + + def remove(self, plan: VpcDataplanePlan) -> dict[str, Any]: + """Remove a panel-owned empty-host VPC and prove the absence. + + The removal script is deliberately separate from ``apply``: it may + only run when the parsed plan has no local members and it validates + every persisted artifact/bridge owner before deleting anything. + A positive marker is required before the caller can advance a host + tombstone. + """ + mode, ifup_path, ifdown_path, ifquery_path = self._deployment_contract() + markers = _markers(self._run(render_remove_script( + plan, deployment_mode=mode, ifup_path=ifup_path, + ifdown_path=ifdown_path, ifquery_path=ifquery_path))) + if markers.get("removed") != "yes": + raise VpcDataplaneError( + "宿主机未确认 VPC 清理", 502, "vpc_remove_unconfirmed") + return { + "vpc_id": plan.vpc.vpc_id, + "host_id": plan.host_id, + "desired_revision": plan.desired_revision, + "observed_revision": plan.desired_revision, + "desired_digest": plan.desired_digest, + "observed_digest": plan.desired_digest, + "state": "active", + "removed": True, + "bridge": None, + "bridge_owner": None, + "member_nics": [], + "routes": [], + "wg_allowed_ips": [], + "nft_table": None, + "acl_revision": plan.desired_revision, + "anti_spoof": False, + "rp_filter": None, + "proxy_arp": None, + "proxy_arp_pvlan": None, + "proxy_ips": [], + "readback": "confirmed", + "rollback": markers.get("rollback", "none"), + "reason_code": None, + } + + def observe( + self, plan: VpcDataplanePlan, *, + xml_by_instance: Mapping[str, Any] | None = None, + ) -> dict[str, Any]: + self._deployment_contract() + parsed = _markers(self._run(render_observe_script(plan))) + expected_routes = { + (x["destination_cidr"], x["device"], str(x["table"]), + x.get("via"), str(x.get("metric", 100))) + for x in _routes(plan) + } + expected_proxy_ips = { + str(ipaddress.ip_network(x["destination_cidr"], strict=True).network_address) + for x in _routes(plan) + } + actual_proxy_ips = set(parsed.get("proxy_ips", [])) + actual_routes = { + (x.get("destination_cidr"), x.get("device"), str(x.get("table")), + x.get("via"), str(x.get("metric", 100))) + for x in parsed.get("routes", []) + } + expected_wg_full = { + # The live `wg show` value includes the peer's overlay /32 as the + # first AllowedIP. Compare the complete cryptokey-routing set; + # project tenant entries only after that exact check. + p.host_id: (p.public_key, set(_allowed(plan, p).split(","))) + for p in plan.peers + } + actual_wg_full = { + x.get("peer_host_id"): (x.get("public_key"), + set(x.get("tenant_allowed_ips", []))) + for x in parsed.get("wg_allowed_ips", []) + } + # The live peer may carry /32s belonging to other VPCs sharing this + # Fabric. Verify the complete aggregate here, then expose only this + # VPC's tenant set to the PHP contract. + expected_tenant: dict[str, set[str]] = { + p.host_id: {m.private_ip + "/32" for m in plan.remote_members + if m.host_id == p.host_id} + for p in plan.peers + } + members_by_id = {m.member_id: m for m in plan.members} + for route in plan.vpc.routes: + target = (members_by_id.get(route.next_hop_member_id) + if route.next_hop_member_id is not None else None) + target_host = target.host_id if target is not None else route.next_hop_host_id + if target_host in expected_tenant: + expected_tenant[target_host].add(route.destination_cidr) + expected_wg = { + p.host_id: (p.public_key, expected_tenant.get(p.host_id, set())) + for p in plan.peers + } + actual_wg = { + host: (key, ips & expected_wg.get(host, (None, set()))[1]) + for host, (key, ips) in actual_wg_full.items() + } + members = _member_nics(plan, xml_by_instance) + actual_route_state = { + (x.get("destination_cidr"), x.get("device"), str(x.get("table")), + x.get("via"), str(x.get("metric", 100))) + for x in parsed.get("routes", []) if x.get("state") == "owned" + } + expected_rules = { + (str(plan.resources.rule_priority), "-", + plan.vpc.cidr, str(plan.resources.route_table)), + (str(plan.resources.rule_priority + 1), FABRIC_INTERFACE, + plan.vpc.cidr, str(plan.resources.route_table)), + } + actual_rules = { + (str(x.get("priority")), x.get("iif"), + x.get("destination_cidr"), str(x.get("table"))) + for x in parsed.get("rules", []) if x.get("state") == "owned" + } + expected_peer_states = {p.host_id: "owned" for p in plan.peers} + expected_bridge_nft = "yes" if plan.local_members else "none" + active = (parsed.get("bridge") == plan.resources.bridge + and parsed.get("bridge_owner") == DATAPLANE_OWNER_MARKER + and parsed.get("persistence") == "yes" + and parsed.get("bridge_boundary") == "yes" + and parsed.get("proxy_arp") == "0" + and parsed.get("proxy_arp_pvlan") == "1" + and parsed.get("proxy_state") == "owned" + and actual_proxy_ips == expected_proxy_ips + and parsed.get("rp_filter") == "2" + and parsed.get("nft_table") == plan.resources.nft_table + and parsed.get("state_owner") == "owned" + and str(parsed.get("state_revision")) == str(plan.desired_revision) + and parsed.get("state_digest") == plan.desired_digest + and str(parsed.get("acl_revision")) == str(plan.desired_revision) + and parsed.get("acl_digest") == plan.desired_digest + and parsed.get("anti_spoof") == "yes" + and parsed.get("bridge_nft") == expected_bridge_nft + and parsed.get("route_extra") == "no" + and expected_routes == actual_routes + and actual_routes == actual_route_state + and expected_rules == actual_rules + and expected_wg_full == actual_wg_full + and (plan.fabric_peer_keys is None + or parsed.get("wg_peer_set") == "exact") + and expected_peer_states == parsed.get("wg_states", {}) + and parsed.get("arp_nft") == ("yes" if plan.local_members else "none") + and all(x["xml_verified"] for x in members)) + projected_wg = tuple( + dict(item, tenant_allowed_ips=sorted( + expected_wg[item.get("peer_host_id")][1] + & set(item.get("tenant_allowed_ips", [])))) + for item in parsed.get("wg_allowed_ips", []) + if item.get("peer_host_id") in expected_wg + and expected_wg[item.get("peer_host_id")][1] + ) + rp_filter = int(parsed["rp_filter"]) if str(parsed.get("rp_filter", "")).isdigit() else None + proxy_arp = int(parsed["proxy_arp"]) if str(parsed.get("proxy_arp", "")).isdigit() else None + proxy_arp_pvlan = (int(parsed["proxy_arp_pvlan"]) + if str(parsed.get("proxy_arp_pvlan", "")).isdigit() + else None) + return VpcDataplaneObservation( + plan.vpc.vpc_id, plan.host_id, plan.desired_revision, + plan.desired_revision if active else 0, plan.desired_digest, + plan.desired_digest if active else None, + "active" if active else "degraded", plan.resources.bridge, + parsed.get("bridge_owner"), members, tuple(parsed.get("routes", [])), + projected_wg, parsed.get("nft_table"), + plan.desired_revision if active else None, + parsed.get("anti_spoof") == "yes", rp_filter, proxy_arp, + proxy_arp_pvlan, + tuple(sorted(actual_proxy_ips)), "confirmed" if active else "mismatch", + "none", None if active else "vpc_private_dataplane_readback_mismatch", + ).as_dict() + + +__all__ = ["DATAPLANE_OWNER_MARKER", "FABRIC_INTERFACE", "PRIVATE_INTERFACE", "VpcDataplaneError", "VpcFabricPeer", "VpcDataplaneResources", "VpcDataplanePlan", "VpcDataplaneObservation", "derive_private_mac", "resource_names", "parse_vpc_dataplane_plan", "render_vpc_nft_rules", "render_apply_script", "render_remove_script", "render_observe_script", "patch_private_interface_xml", "VpcPrivateHostAdapter"] diff --git a/web/app/Services/Cloud/CloudEngineClient.php b/web/app/Services/Cloud/CloudEngineClient.php index ffd56f53..5e131e0f 100644 --- a/web/app/Services/Cloud/CloudEngineClient.php +++ b/web/app/Services/Cloud/CloudEngineClient.php @@ -238,6 +238,14 @@ final class CloudEngineClient 'vpc_record_corrupt' => 'VPC 控制面记录损坏,请联系管理员', 'vpc_observation_incomplete' => 'VPC 宿主机回读未完成,正在核对', 'vpc_data_plane_deferred' => 'VPC 私网数据面尚未启用', + 'vpc_private_dataplane_unverified' => 'VPC 私网数据面回读未通过,正在核对', + 'vpc_private_readback_missing' => 'VPC 私网宿主机回读缺失,正在核对', + 'vpc_private_readback_mismatch' => 'VPC 私网宿主机回读不一致,正在核对', + 'vpc_private_nic_readback_mismatch' => 'VPC 私网网卡回读不一致,正在核对', + 'vpc_private_route_readback_mismatch' => 'VPC 私网路由回读不一致,正在核对', + 'vpc_private_wireguard_readback_missing' => 'VPC WireGuard 私网回读缺失,正在核对', + 'vpc_private_wireguard_readback_mismatch' => 'VPC WireGuard 私网路由回读不一致,正在核对', + 'vpc_private_dataplane_readback_mismatch' => 'VPC 私网数据面回读不一致,正在核对', 'vpc_operation_mismatch' => 'VPC 引擎结果身份不一致,正在核对', ][$value] ?? null; } diff --git a/web/app/Services/Cloud/CloudVpcService.php b/web/app/Services/Cloud/CloudVpcService.php index eae56b2a..c9b681b1 100644 --- a/web/app/Services/Cloud/CloudVpcService.php +++ b/web/app/Services/Cloud/CloudVpcService.php @@ -23,8 +23,9 @@ use App\Models\User; * the public network mutation lane. It stores only typed tenant intent, * serialises each VPC with its own row lock, and advances observed state only after the engine * reports an exact desired revision/digest for every participating host. - * Tenant NICs, routes and nftables are data-plane work owned by the engine's - * later VPC phase; a VPC remains unusable while that phase is pending. + * Tenant NICs, routes and nftables are applied by the engine's independent + * VPC dataplane lane; a VPC remains unusable until typed host readback proves + * the requested revision on every participating host. */ final class CloudVpcService { @@ -41,6 +42,10 @@ final class CloudVpcService private const DIRECTIONS = ['ingress', 'egress']; private const ACTIONS = ['allow', 'deny']; private const PROTOCOLS = ['all', 'tcp', 'udp', 'icmp']; + /** Stable private NIC/dataplane contract shared with the engine. */ + private const PRIVATE_INTERFACE = 'private0'; + private const FABRIC_INTERFACE = 'wg-fabric0'; + private const PRIVATE_DATAPLANE_OWNER = 'virt-cloud-vpc-dataplane-v1'; /** Return VPCs visible to an actor without contacting a host. */ public static function listing(array $actor): array @@ -750,8 +755,9 @@ final class CloudVpcService /** * Send the latest desired document to the private engine VPC lane. The - * engine rejects it unless the referenced Fabric is active on every host. - * No general VM-job or public-network mutation row is created here. + * engine rejects it unless the referenced Fabric is active on every host, + * then applies/readbacks the private dataplane. No general VM-job or + * public-network mutation row is created here. */ public static function reconcile(string $vpcKey, array $actor, bool $allowDeferredRetry = false): array { @@ -839,6 +845,25 @@ final class CloudVpcService throw new CloudError('引擎 VPC 结果与操作编号不一致,正在核对', 502); } $observed = is_array($result['observed'] ?? null) ? $result['observed'] : $result; + // Some engine versions expose a compact `observed` projection and + // the full typed host readback beside it. Merge the latter into + // the bounded projection before validating; never discard + // member_nics/routes/WireGuard evidence merely because the + // transport envelope used a compact view. + if (is_array($result['hosts'] ?? null)) { + if (!is_array($observed['hosts'] ?? null)) { + $observed['hosts'] = []; + } + foreach ($result['hosts'] as $hostKey => $hostItem) { + if (!is_array($hostItem)) { + continue; + } + $hostKey = (string) ($hostItem['host_id'] ?? $hostKey); + $compact = is_array($observed['hosts'][$hostKey] ?? null) + ? $observed['hosts'][$hostKey] : []; + $observed['hosts'][$hostKey] = array_replace($compact, $hostItem); + } + } if (isset($observed['operation_id']) && (string) $observed['operation_id'] !== (string) $operation->operation_id) { throw new CloudError('引擎 VPC 观测与操作编号不一致,正在核对', 502); @@ -941,6 +966,86 @@ final class CloudVpcService $hostKey = (string) ($item['host_id'] ?? $key); $hosts[$hostKey] = $item; } + // Validate typed tenant dataplane evidence before evaluating the + // all-host gate. Fabric transport alone can only leave this + // independent VPC lane waiting/uncertain. + $expectedMembersByHost = []; + $allExpectedMembers = []; + $expectedDestinations = []; + $desiredRoutes = []; + $desiredContractValid = true; + try { + $desired = self::desiredDocument($vpc); + // The host adapter installs only member /32 routes and the + // explicitly configured VPC routes. The VPC/subnet CIDRs + // themselves are control-plane address ranges, not an + // allowance for a broad host route in the data plane. + foreach (is_array($desired['routes'] ?? null) ? $desired['routes'] : [] as $route) { + if (is_array($route) && isset($route['destination_cidr'])) { + $desiredRoutes[] = $route; + $expectedDestinations[] = (string) $route['destination_cidr']; + } + } + foreach (is_array($desired['members'] ?? null) ? $desired['members'] : [] as $member) { + if (!is_array($member) || !isset($member['member_id'])) { + continue; + } + $memberId = (string) $member['member_id']; + $memberHost = (string) ($member['host_id'] ?? ''); + $member['private_mac'] = strtolower((string) ($member['private_mac'] ?? '')); + $expectedMembersByHost[$memberHost][$memberId] = $member; + $allExpectedMembers[$memberId] = $member; + if (isset($member['private_ip_cidr'])) { + $expectedDestinations[] = (string) $member['private_ip_cidr']; + } + } + } catch (\Throwable) { + // A malformed desired ledger is itself a closed gate. + $desiredContractValid = false; + $expectedMembersByHost = []; + $allExpectedMembers = []; + $expectedDestinations = []; + $desiredRoutes = []; + } + $expectedDestinations = array_values(array_unique(array_filter( + $expectedDestinations, + static fn ($value): bool => is_string($value) && $value !== '' + ))); + foreach ($hosts as $hostKey => $item) { + if (($item['private_dataplane_verified'] ?? false) !== true) { + continue; + } + $errorCode = $desiredContractValid + ? self::validateHostDataplaneEvidence( + $item, + (string) $hostKey, + $expectedMembersByHost[(string) $hostKey] ?? [], + array_values($allExpectedMembers), + $expectedDestinations, + $desiredRoutes, + $vpcKey, + $revision, + $digest + ) + : 'vpc_private_readback_mismatch'; + if ($errorCode !== null) { + $item['private_dataplane_verified'] = false; + $item['last_error_code'] = $errorCode; + $hosts[$hostKey] = $item; + $observedHosts = is_array($observed['hosts'] ?? null) + ? $observed['hosts'] : []; + $observedHosts[$hostKey] = $item; + $observed['hosts'] = $observedHosts; + $observed['private_dataplane_verified'] = false; + } elseif (($item['removed'] ?? false) === true) { + $item['removal_verified'] = true; + $hosts[$hostKey] = $item; + $observedHosts = is_array($observed['hosts'] ?? null) + ? $observed['hosts'] : []; + $observedHosts[$hostKey] = $item; + $observed['hosts'] = $observedHosts; + } + } $required = CloudVpcHostDeployment::where('vpc_id', $vpc->id) ->whereNotIn('state', ['deleted']) ->lockForUpdate()->get()->keyBy(static fn ($row): int => (int) $row->host_id); @@ -992,10 +1097,10 @@ final class CloudVpcService } $liveRequired = $required->filter(static fn ($row): bool => (string) $row->state !== 'deleting'); - // This phase has no private-NIC/route/nft readback. A Fabric or - // host control-plane digest therefore cannot prove that a + // A Fabric or host control-plane digest cannot prove that a // deleting child/host is gone from the data plane. Keep every - // tombstone closed until that later evidence is introduced. + // tombstone closed until the typed private-NIC/route/nft evidence + // is introduced by the engine. $pendingChildTombstone = false; foreach ([ CloudVpcSubnet::class, @@ -1014,6 +1119,8 @@ final class CloudVpcService (string) $row->state === 'deleting'); $allActive = $globalActive && $liveRequired->count() > 0 && !$pendingChildTombstone && !$pendingHostTombstone; + $allRemovalProof = true; + $hasRemovalTarget = false; foreach ($hosts as $hostKey => $_item) { if (!$required->has((int) $hostKey)) { $allActive = false; @@ -1044,17 +1151,36 @@ final class CloudVpcService && $itemRevision <= $revision && $itemRevision === $revision && hash_equals($digest, $itemDigest); $deleting = (string) $deployment->state === 'deleting'; + $removalActive = $deleting + && ($item['removed'] ?? false) === true + && ($item['removal_verified'] ?? false) === true + && ($item['state'] ?? null) === 'active' + && ($item['transport_verified'] ?? false) === true + && ($item['private_dataplane_verified'] ?? false) === true + && $itemRevision === $revision + && hash_equals($digest, $itemDigest); + if ($deleting) { + $hasRemovalTarget = true; + if (!$removalActive) { + $allRemovalProof = false; + } + } $deployment->observed_revision = $itemRevision; $deployment->observed_digest = $itemDigest !== '' ? $itemDigest : null; // An empty-host target is only a desired control-plane // document. Without a data-plane removal readback, preserve // the deleting state even when the Fabric digest is exact. - if (!$deleting) { + if ($removalActive) { + $deployment->state = 'deleted'; + $deployment->last_error_code = null; + } elseif (!$deleting) { $deployment->state = $active ? 'active' : 'degraded'; + $deployment->last_error_code = $active ? null : 'vpc_host_observation_mismatch'; + } else { + $deployment->last_error_code = 'vpc_host_removal_unverified'; } - $deployment->last_error_code = $active ? null : 'vpc_host_observation_mismatch'; $deployment->updated_at = time(); - if ($active) { + if ($active || $removalActive) { $deployment->last_success_at = time(); } else { $deployment->last_failure_at = time(); @@ -1062,12 +1188,36 @@ final class CloudVpcService } $deployment->save(); } + $removalOnlyComplete = $hasRemovalTarget && $allRemovalProof + && $liveRequired->count() === 0 && !$pendingChildTombstone; + if ($hasRemovalTarget && $allRemovalProof && $liveRequired->count() === 0) { + $observedAt = time(); + foreach ([ + CloudVpcSubnet::class, + CloudVpcPrivateIp::class, + CloudVpcMember::class, + CloudVpcRoute::class, + CloudVpcAclRule::class, + ] as $childModel) { + $childModel::where('vpc_id', $vpc->id) + ->where('state', 'deleting') + ->update([ + 'observed_revision' => $revision, + 'observed_digest' => $digest, + 'state' => 'deleted', + 'last_error_code' => null, + 'updated_at' => $observedAt, + ]); + } + $removalOnlyComplete = true; + } + $operationSucceeded = $allActive || $removalOnlyComplete; // The engine's current observed contract is host-scoped: an // active exact digest means the complete typed document for this // revision was accepted by every participating host. Mirror that // gate onto live child rows. Deletion tombstones intentionally - // remain untouched until the later data-plane readback phase. + // remain untouched until a typed removal readback proves absence. if ($allActive) { $observedAt = time(); // Persist a proof marker on each member only after the full @@ -1101,27 +1251,27 @@ final class CloudVpcService } $operation->observed_json = json_encode(self::boundedObserved($observed), JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES); - $operation->status = $allActive ? 'succeeded' + $operation->status = $operationSucceeded ? 'succeeded' : ($dataPlaneDeferred ? 'waiting_observed' : ($terminalGate ? 'failed' : 'uncertain')); - $operation->error_code = $allActive ? null + $operation->error_code = $operationSucceeded ? null : ($dataPlaneDeferred ? 'vpc_data_plane_deferred' : ($terminalGate ? $gateError : 'vpc_observation_incomplete')); $operation->updated_at = time(); - $operation->finished_at = ($allActive || $dataPlaneDeferred || $terminalGate) + $operation->finished_at = ($operationSucceeded || $dataPlaneDeferred || $terminalGate) ? time() : null; $operation->lease_until = 0; $operation->save(); - $vpc->observed_revision = $allActive ? $revision : (int) $vpc->observed_revision; - $vpc->observed_digest = $allActive ? $digest : $vpc->observed_digest; - $vpc->state = $allActive ? 'active' : 'degraded'; - $vpc->sync_state = $allActive ? 'applied' + $vpc->observed_revision = $operationSucceeded ? $revision : (int) $vpc->observed_revision; + $vpc->observed_digest = $operationSucceeded ? $digest : $vpc->observed_digest; + $vpc->state = $operationSucceeded ? 'active' : 'degraded'; + $vpc->sync_state = $operationSucceeded ? 'applied' : ($dataPlaneDeferred ? 'waiting' : ($terminalGate ? 'failed' : 'uncertain')); - $vpc->last_error_code = $allActive ? null + $vpc->last_error_code = $operationSucceeded ? null : ($dataPlaneDeferred ? 'vpc_data_plane_deferred' : ($terminalGate ? $gateError : 'vpc_observation_incomplete')); - $vpc->last_success_at = $allActive ? time() : (int) $vpc->last_success_at; - $vpc->last_failure_at = $allActive ? (int) $vpc->last_failure_at : time(); + $vpc->last_success_at = $operationSucceeded ? time() : (int) $vpc->last_success_at; + $vpc->last_failure_at = $operationSucceeded ? (int) $vpc->last_failure_at : time(); $vpc->updated_at = time(); $vpc->save(); }, 3); @@ -1156,6 +1306,7 @@ final class CloudVpcService ->whereIn('member_id', $members->pluck('id')->map(static fn ($id): int => (int) $id)->all()) ->get()->keyBy('member_id'); $memberKeys = []; + $privateMacs = []; $memberRows = []; foreach ($members as $row) { $instance = $instances[(int) $row->instance_id] ?? null; @@ -1174,12 +1325,22 @@ final class CloudVpcService } $memberKey = (string) $row->member_key; $memberKeys[(int) $row->id] = $memberKey; + // The MAC is derived from the immutable VPC/member identities so + // retries, host migration and engine restarts keep the same NIC + // identity. It is locally administered and unicast; no schema + // column is needed and the value remains part of the signed DTO. + $privateMac = self::privateMacForMember((string) $vpc->vpc_key, $memberKey); + if ($privateMac === null || isset($privateMacs[$privateMac])) { + throw new CloudError('VPC 成员私网 MAC 无效,无法生成引擎目标', 409); + } + $privateMacs[$privateMac] = $memberKey; $memberRows[] = [ 'member_id' => $memberKey, 'instance_uuid' => strtolower((string) $instance->uuid), 'host_id' => (string) $row->host_id, 'private_ip_cidr' => (string) $privateIp->private_ip . '/32', 'subnet_id' => $subnetKey, + 'private_mac' => $privateMac, ]; } $hostMembers = []; @@ -1399,13 +1560,28 @@ final class CloudVpcService 'reason_code' => 'vpc_private_expectation_invalid', ]; } + $privateMac = self::privateMacForMember( + (string) $vpc->vpc_key, (string) $member->member_key + ); + if ($privateMac === null) { + return [ + 'required' => true, 'state' => 'uncertain', + 'desired_state' => $desiredState, + 'vpc_id' => (string) $vpc->vpc_key, + 'member_id' => (string) $member->member_key, + 'private_ip_cidr' => $validIp ? $member->private_ip . '/32' : null, + 'private_mac' => null, 'desired_revision' => max(0, $revision), + 'desired_digest' => $validDigest ? $digest : null, + 'reason_code' => 'vpc_private_expectation_invalid', + ]; + } return [ 'required' => true, 'state' => $state, 'desired_state' => $desiredState, 'vpc_id' => (string) $vpc->vpc_key, 'member_id' => (string) $member->member_key, 'private_ip_cidr' => $member->private_ip . '/32', - 'private_mac' => null, + 'private_mac' => $privateMac, 'desired_revision' => $revision, 'desired_digest' => $digest, 'reason_code' => null, @@ -1436,7 +1612,7 @@ final class CloudVpcService // target is bound by desired_state, identity, IP, revision and digest; // removal remains strict because it changes desired_state to removed. foreach (['required', 'desired_state', 'vpc_id', 'member_id', - 'private_ip_cidr', 'desired_revision', 'desired_digest'] as $key) { + 'private_ip_cidr', 'private_mac', 'desired_revision', 'desired_digest'] as $key) { if ((string) ($captured[$key] ?? null) !== (string) ($current[$key] ?? null)) { return false; } @@ -1461,7 +1637,7 @@ final class CloudVpcService 'observed_digest' => null, 'readback' => $expectation['required'] ? 'missing' : 'confirmed', 'link_state' => $expectation['required'] ? 'absent' : 'absent', 'private_ip_cidr' => $expectation['private_ip_cidr'] ?? null, - 'private_mac' => null, + 'private_mac' => $expectation['private_mac'] ?? null, 'reason_code' => $expectation['reason_code'] ?? ($expectation['required'] ? 'vpc_private_observation_missing' : null), 'observed_at' => 0, @@ -1580,6 +1756,10 @@ final class CloudVpcService && $memberExact && $privateExact; $base['observed_revision'] = $observedRevision; $base['observed_digest'] = $observedDigest; + // Keep the stable desired identity in the projection even before + // a host readback is confirmed. The observation validator below + // still requires the engine to echo the exact same MAC. + $base['private_mac'] = $expectation['private_mac'] ?? null; $base['state'] = $confirmed ? 'active' : ((string) $member->state === 'degraded' || (string) $privateIp->state === 'degraded' @@ -1627,9 +1807,8 @@ final class CloudVpcService * Validate one engine private_state at a mutation commit boundary. * * The engine's XML observation is necessary but not sufficient for an - * attached VPC: the member identity, desired revision and digest must - * also be echoed by a future data-plane reconciler. Until then this - * method intentionally returns an uncertain gate for VPC members. + * attached VPC: the member identity, stable MAC, desired revision and + * digest must be echoed by the VPC data-plane readback. */ public static function validatePrivateObservation( array $expectation, ?array $observation, string $kind @@ -1645,7 +1824,7 @@ final class CloudVpcService 'desired_digest' => $expectation['desired_digest'] ?? null, 'observed_digest' => null, 'readback' => 'missing', 'link_state' => 'absent', 'private_ip_cidr' => null, - 'private_mac' => null, + 'private_mac' => $expectation['private_mac'] ?? null, 'reason_code' => 'vpc_private_observation_missing', 'observed_at' => time(), ]; @@ -1745,11 +1924,17 @@ final class CloudVpcService $ip = $expectedState === 'removed' || (is_string($expectation['private_ip_cidr']) && hash_equals((string) $expectation['private_ip_cidr'], (string) $state['private_ip_cidr'])); + $mac = $expectedState === 'removed' + || (is_string($expectation['private_mac'] ?? null) + && is_string($observation['private_mac'] ?? null) + && is_string($state['private_mac'] ?? null) + && hash_equals(strtolower((string) $expectation['private_mac']), + strtolower((string) $state['private_mac']))); $desired = $expectedState === 'removed' ? in_array($state['state'], ['disabled', 'removed'], true) : in_array($state['state'], ['active', 'suspended'], true); $link = $linkExpected === null || $state['link_state'] === $linkExpected; - $ok = $shape && $identity && $revision && $digest && $ip && $desired && $link + $ok = $shape && $identity && $revision && $digest && $ip && $mac && $desired && $link && $state['readback'] === 'confirmed'; if (!$ok) { $state['state'] = $state['state'] === 'degraded' ? 'degraded' : 'uncertain'; @@ -2450,7 +2635,12 @@ final class CloudVpcService } CloudInput::only($item, ['route_key', 'destination_cidr', 'next_hop_ip', 'metric']); $key = self::assertKey($item['route_key'] ?? null, '路由'); - $destination = self::cidr($item['destination_cidr'] ?? null, 8, 32, '路由目标'); + // The host data plane is intentionally routed as exact /32s. + // Accepting a wider prefix here would let a tenant's route + // replace the per-member cryptokey and nft boundary, even though + // the engine later rejects it. Reject it at the PHP boundary so + // the API and engine cannot disagree about a usable target. + $destination = self::cidr($item['destination_cidr'] ?? null, 32, 32, '路由目标'); $next = self::ipv4($item['next_hop_ip'] ?? null, '路由下一跳'); $metric = self::positiveInt($item['metric'] ?? 100, 1, 65535, '路由 metric 无效'); $result[] = ['route_key' => $key, 'destination' => $destination, @@ -2519,6 +2709,401 @@ final class CloudVpcService && hash_equals($left, $right); } + /** + * Derive the stable locally-administered MAC used by one VPC member. + * + * Member keys are scoped to a VPC, so binding both identities prevents a + * key reused in another tenant from receiving the same NIC identity. The + * first octet is forced to unicast/local-administered (02/06/0a/0e + * families) and the remaining bytes are cryptographic hash material. + */ + private static function privateMacForMember(string $vpcKey, string $memberKey): ?string + { + if (preg_match(self::KEY_PATTERN, $vpcKey) !== 1 + || preg_match(self::KEY_PATTERN, $memberKey) !== 1) { + return null; + } + $digest = hash('sha256', 'virt-cloud:vpc-private0:' . $vpcKey . ':' . $memberKey); + $octets = []; + for ($index = 0; $index < 6; $index++) { + $octets[] = hexdec(substr($digest, $index * 2, 2)); + } + $octets[0] = ($octets[0] & 0xfc) | 0x02; + return implode(':', array_map( + static fn (int $octet): string => sprintf('%02x', $octet), $octets + )); + } + + private static function privateBridgeForVpc(string $vpcKey): ?string + { + return preg_match(self::KEY_PATTERN, $vpcKey) === 1 + ? 'vcv-' . substr(hash('sha256', $vpcKey), 0, 11) : null; + } + + private static function privateNftTableForVpc(string $vpcKey): ?string + { + return preg_match(self::KEY_PATTERN, $vpcKey) === 1 + ? 'virt_cloud_vpc_' . substr(hash('sha256', $vpcKey), 0, 12) : null; + } + + private static function privateRouteTableForVpc(string $vpcKey): ?int + { + if (preg_match(self::KEY_PATTERN, $vpcKey) !== 1) { + return null; + } + $digest = hash('sha256', $vpcKey); + return 10000 + (hexdec(substr($digest, 12, 8)) % 10000); + } + + /** + * Validate typed host-side private dataplane evidence. Raw command output + * is deliberately ignored: only bounded identity, route, ACL and XML + * readback fields can open the PHP VPC gate. + * + * A null return means the evidence is exact; otherwise the returned code + * is safe to persist as a diagnostic and keeps the host degraded. + */ + private static function validateHostDataplaneEvidence( + array $item, + string $hostId, + array $expectedMembers, + array $allMembers, + array $expectedDestinations, + array $desiredRoutes, + string $vpcKey, + int $revision, + string $digest + ): ?string { + // These fields are identity evidence, not optional status hints. A + // compact/legacy host projection must therefore stay closed until a + // full typed readback is supplied by the engine. + if (!array_key_exists('vpc_id', $item) + || !array_key_exists('host_id', $item) + || !array_key_exists('desired_revision', $item) + || !array_key_exists('desired_digest', $item) + || !array_key_exists('observed_revision', $item) + || !array_key_exists('observed_digest', $item) + || (string) $item['vpc_id'] !== $vpcKey + || !self::digestMatches($digest, (string) $item['desired_digest']) + || (string) $item['host_id'] !== $hostId + || (string) ($item['state'] ?? '') !== 'active' + || (int) $item['desired_revision'] !== $revision + || (int) $item['observed_revision'] !== $revision + || !self::digestMatches($digest, (string) $item['observed_digest'])) { + return 'vpc_private_readback_mismatch'; + } + // A host removal is a distinct typed proof. It must not be treated + // as an empty successful apply: all panel-owned resources and + // tenant-facing evidence must be absent before a deleting deployment + // can be finalized. + if (($item['removed'] ?? false) === true) { + $readback = $item['readback'] ?? null; + $readbackState = is_string($readback) ? strtolower($readback) + : (is_array($readback) + ? strtolower((string) ($readback['state'] ?? $readback['status'] ?? '')) + : ''); + foreach (['member_nics', 'routes', 'wg_allowed_ips', 'proxy_ips'] as $field) { + if (!is_array($item[$field] ?? null) || $item[$field] !== []) { + return 'vpc_private_removal_readback_mismatch'; + } + } + if ($expectedMembers !== [] + || $readbackState !== 'confirmed' + || ($item['bridge'] ?? null) !== null + || ($item['bridge_owner'] ?? null) !== null + || ($item['nft_table'] ?? null) !== null + || !in_array((string) ($item['rollback'] ?? ''), ['none', 'ok'], true)) { + return 'vpc_private_removal_readback_mismatch'; + } + return null; + } + $bridge = self::privateBridgeForVpc($vpcKey); + $nftTable = self::privateNftTableForVpc($vpcKey); + $routeTable = self::privateRouteTableForVpc($vpcKey); + if ($bridge === null || $nftTable === null + || $routeTable === null + || (string) ($item['bridge'] ?? '') !== $bridge + || (string) ($item['bridge_owner'] ?? '') !== self::PRIVATE_DATAPLANE_OWNER + || (string) ($item['nft_table'] ?? '') !== $nftTable + || ($item['anti_spoof'] ?? false) !== true + || (int) ($item['rp_filter'] ?? -1) !== 2 + || (int) ($item['proxy_arp'] ?? -1) !== 0 + || (int) ($item['proxy_arp_pvlan'] ?? -1) !== 1 + || (int) ($item['acl_revision'] ?? 0) !== $revision + || !array_key_exists('rollback', $item) + || !in_array((string) $item['rollback'], ['none', 'ok'], true)) { + return 'vpc_private_dataplane_unverified'; + } + $readback = $item['readback'] ?? null; + $readbackState = is_string($readback) ? strtolower($readback) + : (is_array($readback) + ? strtolower((string) ($readback['state'] ?? $readback['status'] ?? '')) + : ''); + if ($readbackState !== 'confirmed') { + return 'vpc_private_readback_missing'; + } + + // The bridge uses routed guest /32s. Generic proxy ARP stays off; + // only exact panel-owned proxy-neighbour entries (with pvlan enabled + // for same-bridge next hops) may answer. A missing or broadened + // proxy set keeps the host degraded. + $proxyIps = $item['proxy_ips'] ?? null; + if (!is_array($proxyIps)) { + return 'vpc_private_proxy_arp_readback_missing'; + } + $expectedProxyIps = []; + foreach ($expectedDestinations as $destination) { + if (!is_string($destination) + || !preg_match('/^([0-9]{1,3}(?:\.[0-9]{1,3}){3})\/32$/D', $destination, $match) + || filter_var($match[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) { + return 'vpc_private_proxy_arp_readback_mismatch'; + } + $expectedProxyIps[] = $match[1]; + } + $expectedProxyIps = array_values(array_unique($expectedProxyIps)); + sort($expectedProxyIps, SORT_STRING); + $observedProxyIps = []; + foreach ($proxyIps as $proxyIp) { + if (!is_string($proxyIp) + || filter_var($proxyIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) { + return 'vpc_private_proxy_arp_readback_mismatch'; + } + $observedProxyIps[] = $proxyIp; + } + $observedProxyIps = array_values(array_unique($observedProxyIps)); + sort($observedProxyIps, SORT_STRING); + if ($observedProxyIps !== $expectedProxyIps) { + return 'vpc_private_proxy_arp_readback_mismatch'; + } + + $nics = $item['member_nics'] ?? null; + if (!is_array($nics) || count($nics) !== count($expectedMembers)) { + return 'vpc_private_nic_readback_mismatch'; + } + $seen = []; + foreach ($nics as $nic) { + if (!is_array($nic)) { + return 'vpc_private_nic_readback_mismatch'; + } + $memberId = (string) ($nic['member_id'] ?? ''); + if ($memberId === '' || isset($seen[$memberId]) + || !isset($expectedMembers[$memberId])) { + return 'vpc_private_nic_readback_mismatch'; + } + $expected = $expectedMembers[$memberId]; + $observedMac = strtolower((string) ($nic['private_mac'] ?? '')); + if ((string) ($nic['interface'] ?? '') !== self::PRIVATE_INTERFACE + || strtolower((string) ($nic['instance_uuid'] ?? '')) + !== strtolower((string) $expected['instance_uuid']) + || (string) ($nic['private_ip_cidr'] ?? '') + !== (string) $expected['private_ip_cidr'] + || $observedMac !== strtolower((string) $expected['private_mac']) + || ($nic['xml_verified'] ?? false) !== true) { + return 'vpc_private_nic_readback_mismatch'; + } + $seen[$memberId] = true; + } + if (count($seen) !== count($expectedMembers)) { + return 'vpc_private_nic_readback_mismatch'; + } + + // Routes are checked against the exact host-specific next hop and + // metric. A dataplane readback must never install a default or + // otherwise broad route owned by a different subsystem. + $routes = $item['routes'] ?? null; + if (!is_array($routes)) { + return 'vpc_private_route_readback_missing'; + } + $memberById = []; + foreach ($allMembers as $member) { + if (is_array($member) && isset($member['member_id'])) { + $memberById[(string) $member['member_id']] = $member; + } + } + $expectedRouteRows = []; + foreach ($allMembers as $member) { + if (!is_array($member) || !isset($member['private_ip_cidr'])) { + continue; + } + $expectedRouteRows[] = [ + 'destination_cidr' => (string) $member['private_ip_cidr'], + 'device' => (string) (($member['host_id'] ?? '') === $hostId + ? $bridge : self::FABRIC_INTERFACE), + 'via' => null, + 'metric' => 100, + ]; + } + foreach ($desiredRoutes as $desiredRoute) { + if (!is_array($desiredRoute) + || !isset($desiredRoute['destination_cidr'])) { + return 'vpc_private_route_readback_mismatch'; + } + $nextMemberId = isset($desiredRoute['next_hop_member_id']) + ? (string) $desiredRoute['next_hop_member_id'] : ''; + $nextMember = $nextMemberId !== '' + ? ($memberById[$nextMemberId] ?? null) : null; + $nextHost = is_array($nextMember) + ? (string) ($nextMember['host_id'] ?? '') + : (string) ($desiredRoute['next_hop_host_id'] ?? ''); + if ($nextHost === '') { + return 'vpc_private_route_readback_mismatch'; + } + $expectedRouteRows[] = [ + 'destination_cidr' => (string) $desiredRoute['destination_cidr'], + 'device' => $nextHost === $hostId ? $bridge : self::FABRIC_INTERFACE, + 'via' => $nextHost === $hostId && is_array($nextMember) + ? (string) preg_replace( + '/\/32$/D', '', + (string) ($nextMember['private_ip'] + ?? $nextMember['private_ip_cidr'] ?? '') + ) + : null, + 'metric' => (int) ($desiredRoute['metric'] ?? 100), + ]; + } + $expectedRouteMap = []; + foreach ($expectedRouteRows as $expectedRoute) { + $via = (string) ($expectedRoute['via'] ?? ''); + $key = $expectedRoute['destination_cidr'] . '|' + . $expectedRoute['device'] . '|' . $via . '|' + . (string) $expectedRoute['metric']; + if (isset($expectedRouteMap[$key])) { + return 'vpc_private_route_readback_mismatch'; + } + $expectedRouteMap[$key] = true; + } + $seenRoutes = []; + foreach ($routes as $route) { + if (!is_array($route) + || !is_string($route['destination_cidr'] ?? null) + || !isset($route['device']) + || !is_string($route['device']) + || $route['device'] === '' + || !array_key_exists('table', $route) + || !in_array($route['device'], [$bridge, self::FABRIC_INTERFACE], true) + || (string) ($route['owner'] ?? '') !== self::PRIVATE_DATAPLANE_OWNER) { + return 'vpc_private_route_readback_mismatch'; + } + $destination = (string) $route['destination_cidr']; + if (in_array($destination, ['0.0.0.0/0', '::/0'], true) + || !in_array($destination, $expectedDestinations, true)) { + return 'vpc_private_route_readback_mismatch'; + } + $via = $route['via'] ?? null; + if ($via !== null && !is_string($via)) { + return 'vpc_private_route_readback_mismatch'; + } + $metric = $route['metric'] ?? null; + if ((is_string($metric) && !ctype_digit($metric)) + || (!is_int($metric) && !is_string($metric))) { + return 'vpc_private_route_readback_mismatch'; + } + $metric = (int) $metric; + $key = $destination . '|' . (string) $route['device'] . '|' + . (string) ($via ?? '') . '|' . (string) $metric; + if (isset($seenRoutes[$key])) { + return 'vpc_private_route_readback_mismatch'; + } + if (!isset($expectedRouteMap[$key])) { + return 'vpc_private_route_readback_mismatch'; + } + $seenRoutes[$key] = true; + if ((!is_int($route['table']) + && !(is_string($route['table']) && is_numeric($route['table']))) + || (int) $route['table'] !== $routeTable) { + return 'vpc_private_route_readback_mismatch'; + } + } + $expectedRouteSet = array_keys($expectedRouteMap); + $observedRouteSet = array_keys($seenRoutes); + sort($expectedRouteSet, SORT_STRING); + sort($observedRouteSet, SORT_STRING); + if ($observedRouteSet !== $expectedRouteSet) { + return 'vpc_private_route_readback_mismatch'; + } + + // The engine reports tenant AllowedIPs separately from Fabric overlay + // addresses. Require an exact remote-member /32 set, preventing a + // broad prefix from crossing a host or VPC boundary. + $expectedPeers = []; + foreach ($allMembers as $member) { + if ((string) ($member['host_id'] ?? '') === $hostId) { + continue; + } + $peerHost = (string) ($member['host_id'] ?? ''); + $expectedPeers[$peerHost][] = (string) $member['private_ip_cidr']; + } + foreach ($desiredRoutes as $route) { + if (!is_array($route)) { + return 'vpc_private_wireguard_readback_mismatch'; + } + $target = null; + if (isset($route['next_hop_member_id'])) { + $target = $memberById[(string) $route['next_hop_member_id']] ?? null; + } + $peerHost = is_array($target) + ? (string) ($target['host_id'] ?? '') + : (string) ($route['next_hop_host_id'] ?? ''); + if ($peerHost !== '' && $peerHost !== $hostId + && isset($route['destination_cidr'])) { + $expectedPeers[$peerHost][] = (string) $route['destination_cidr']; + } + } + foreach ($expectedPeers as &$ips) { + $ips = array_values(array_unique($ips)); + sort($ips, SORT_STRING); + } + unset($ips); + $wg = $item['wg_allowed_ips'] ?? null; + if (!is_array($wg)) { + return 'vpc_private_wireguard_readback_missing'; + } + $seenPeers = []; + foreach ($wg as $peer) { + if (!is_array($peer)) { + return 'vpc_private_wireguard_readback_mismatch'; + } + $peerHost = (string) ($peer['peer_host_id'] ?? ''); + $tenantIps = $peer['tenant_allowed_ips'] ?? $peer['allowed_ips'] ?? null; + $publicKey = $peer['public_key'] ?? null; + if ($peerHost === '' || isset($seenPeers[$peerHost]) + || !array_key_exists($peerHost, $expectedPeers) + || !is_array($tenantIps) + || !is_string($publicKey) + || preg_match('/^[A-Za-z0-9+\/]{42}[A-Za-z0-9+\/]==$|^[A-Za-z0-9+\/]{43}=$/D', + $publicKey) !== 1) { + return 'vpc_private_wireguard_readback_mismatch'; + } + $decodedKey = base64_decode($publicKey, true); + if ($decodedKey === false || strlen($decodedKey) !== 32 + || trim($decodedKey, "\0") === '') { + return 'vpc_private_wireguard_readback_mismatch'; + } + $normalizedIps = []; + foreach ($tenantIps as $ip) { + if (!is_string($ip)) { + return 'vpc_private_wireguard_readback_mismatch'; + } + $normalizedIps[] = $ip; + } + $normalizedIps = array_values(array_unique($normalizedIps)); + sort($normalizedIps, SORT_STRING); + foreach ($normalizedIps as $ip) { + if (!preg_match('/^[0-9.]+\/32$/D', $ip)) { + return 'vpc_private_wireguard_readback_mismatch'; + } + } + if ($normalizedIps !== $expectedPeers[$peerHost]) { + return 'vpc_private_wireguard_readback_mismatch'; + } + $seenPeers[$peerHost] = true; + } + if (count($seenPeers) !== count($expectedPeers)) { + return 'vpc_private_wireguard_readback_mismatch'; + } + return null; + } + private static function boundedObserved(array $value): array { $hosts = []; @@ -2526,7 +3111,14 @@ final class CloudVpcService if (!is_array($host) || count($hosts) >= 256) { continue; } - $hosts[(string) $key] = [ + $bounded = [ + 'host_id' => is_string($host['host_id'] ?? null) + ? substr($host['host_id'], 0, 64) : (string) $key, + 'vpc_id' => is_string($host['vpc_id'] ?? null) + ? substr($host['vpc_id'], 0, 64) : null, + 'desired_revision' => max(0, (int) ($host['desired_revision'] ?? 0)), + 'desired_digest' => is_string($host['desired_digest'] ?? null) + ? substr($host['desired_digest'], 0, 64) : null, 'state' => is_string($host['state'] ?? null) ? substr($host['state'], 0, 16) : 'unknown', 'observed_revision' => max(0, (int) ($host['observed_revision'] ?? $host['revision'] ?? 0)), 'observed_digest' => is_string($host['observed_digest'] ?? $host['digest'] ?? null) @@ -2535,8 +3127,102 @@ final class CloudVpcService 'private_dataplane_verified' => ( ($host['private_dataplane_verified'] ?? false) === true ), + 'removed' => ($host['removed'] ?? false) === true, + 'retiring' => ($host['retiring'] ?? false) === true, 'next_stage_allowed' => ($host['next_stage_allowed'] ?? false) === true, ]; + if (is_string($host['last_error_code'] ?? null)) { + $bounded['last_error_code'] = substr($host['last_error_code'], 0, 64); + } + foreach (['bridge', 'bridge_owner', 'nft_table', 'readback', 'rollback'] as $field) { + if (is_string($host[$field] ?? null)) { + $bounded[$field] = substr($host[$field], 0, 128); + } + } + if (isset($host['anti_spoof'])) { + $bounded['anti_spoof'] = $host['anti_spoof'] === true; + } + if (isset($host['acl_revision'])) { + $bounded['acl_revision'] = max(0, (int) $host['acl_revision']); + } + if (isset($host['rp_filter'])) { + $bounded['rp_filter'] = max(0, (int) $host['rp_filter']); + } + if (isset($host['proxy_arp'])) { + $bounded['proxy_arp'] = max(0, (int) $host['proxy_arp']); + } + if (isset($host['proxy_arp_pvlan'])) { + $bounded['proxy_arp_pvlan'] = max(0, (int) $host['proxy_arp_pvlan']); + } + if (is_array($host['proxy_ips'] ?? null)) { + $bounded['proxy_ips'] = array_values(array_slice(array_map( + static fn ($ip): string => substr((string) $ip, 0, 64), + $host['proxy_ips'] + ), 0, 4096)); + } + if (is_array($host['member_nics'] ?? null)) { + $bounded['member_nics'] = []; + foreach (array_slice($host['member_nics'], 0, 4096) as $nic) { + if (!is_array($nic)) { + continue; + } + $bounded['member_nics'][] = [ + 'member_id' => is_string($nic['member_id'] ?? null) + ? substr($nic['member_id'], 0, 64) : null, + 'instance_uuid' => is_string($nic['instance_uuid'] ?? null) + ? substr($nic['instance_uuid'], 0, 64) : null, + 'interface' => is_string($nic['interface'] ?? null) + ? substr($nic['interface'], 0, 32) : null, + 'private_ip_cidr' => is_string($nic['private_ip_cidr'] ?? null) + ? substr($nic['private_ip_cidr'], 0, 64) : null, + 'private_mac' => is_string($nic['private_mac'] ?? null) + ? substr(strtolower($nic['private_mac']), 0, 32) : null, + 'xml_verified' => ($nic['xml_verified'] ?? false) === true, + ]; + } + } + if (is_array($host['routes'] ?? null)) { + $bounded['routes'] = []; + foreach (array_slice($host['routes'], 0, 256) as $route) { + if (!is_array($route)) { + continue; + } + $bounded['routes'][] = [ + 'destination_cidr' => is_string($route['destination_cidr'] ?? null) + ? substr($route['destination_cidr'], 0, 64) : null, + 'device' => is_string($route['device'] ?? null) + ? substr($route['device'], 0, 64) : null, + 'table' => is_scalar($route['table'] ?? null) + ? substr((string) $route['table'], 0, 32) : null, + 'owner' => is_string($route['owner'] ?? null) + ? substr($route['owner'], 0, 64) : null, + 'via' => is_string($route['via'] ?? null) + ? substr($route['via'], 0, 64) : null, + 'metric' => is_scalar($route['metric'] ?? null) + ? substr((string) $route['metric'], 0, 16) : null, + ]; + } + } + if (is_array($host['wg_allowed_ips'] ?? null)) { + $bounded['wg_allowed_ips'] = []; + foreach (array_slice($host['wg_allowed_ips'], 0, 256) as $peer) { + if (!is_array($peer)) { + continue; + } + $ips = $peer['tenant_allowed_ips'] ?? $peer['allowed_ips'] ?? []; + $bounded['wg_allowed_ips'][] = [ + 'peer_host_id' => is_string($peer['peer_host_id'] ?? null) + ? substr($peer['peer_host_id'], 0, 64) : null, + 'public_key' => is_string($peer['public_key'] ?? null) + ? substr($peer['public_key'], 0, 64) : null, + 'tenant_allowed_ips' => is_array($ips) + ? array_values(array_slice(array_map( + static fn ($ip): string => substr((string) $ip, 0, 64), $ips + ), 0, 4096)) : [], + ]; + } + } + $hosts[(string) $key] = $bounded; } return ['hosts' => $hosts]; } diff --git a/web/app/Services/Cloud/CloudVpcWorkerService.php b/web/app/Services/Cloud/CloudVpcWorkerService.php index 025e7a29..27a28cd5 100644 --- a/web/app/Services/Cloud/CloudVpcWorkerService.php +++ b/web/app/Services/Cloud/CloudVpcWorkerService.php @@ -19,17 +19,22 @@ final class CloudVpcWorkerService $candidate = (new CloudVpcOperation())->getConnection()->transaction( static function (): ?array { $now = time(); + $allowDeferredRetry = false; $operation = CloudVpcOperation::where(function ($query) use ($now): void { $query->where(function ($queued) use ($now): void { $queued->where('status', 'queued') ->where('updated_at', '<=', $now - 2); })->orWhere(function ($uncertain) use ($now): void { - // Transport ambiguity is retryable. A deliberate - // waiting_observed result is excluded: phase 3 - // has no private-NIC/readback lane, so only the - // explicit reconcile API may resume it later. + // Transport ambiguity is retryable. $uncertain->where('status', 'uncertain') ->where('updated_at', '<=', $now - 30); + })->orWhere(function ($waiting) use ($now): void { + // The Fabric gate may complete before the host + // private0/route/nft readback. Retry this same + // VPC operation on its own lane after a quiet + // period; it never enters network_change. + $waiting->where('status', 'waiting_observed') + ->where('updated_at', '<=', $now - 30); })->orWhere(function ($running) use ($now): void { $running->where('status', 'running') ->where('lease_until', '<=', $now); @@ -39,6 +44,7 @@ final class CloudVpcWorkerService if ($operation === null) { return null; } + $allowDeferredRetry = (string) $operation->status === 'waiting_observed'; $vpc = CloudVpc::where('id', (int) $operation->vpc_id)->first(); if ($vpc === null) { $operation->status = 'failed'; @@ -48,24 +54,24 @@ final class CloudVpcWorkerService $operation->save(); return null; } - return [(string) $vpc->vpc_key, (int) $operation->user_id]; + return [(string) $vpc->vpc_key, (int) $operation->user_id, + $allowDeferredRetry]; }, 3 ); if ($candidate === null) { return false; } - [$vpcKey, $userId] = $candidate; + [$vpcKey, $userId, $allowDeferredRetry] = $candidate; $actor = [ 'user_id' => $userId, 'is_admin' => false, 'is_super_admin' => false, 'can_manage' => true, 'session_id' => '', ]; try { - CloudVpcService::reconcile($vpcKey, $actor); + CloudVpcService::reconcile($vpcKey, $actor, $allowDeferredRetry); } catch (CloudError) { // The service records failed/uncertain status under the operation - // lease. waiting_observed is intentionally not selected again; - // no destructive replay is performed by this worker. + // lease. No public network job is replayed by this worker. } return true; } diff --git a/web/app/Services/Cloud/CloudWorkerService.php b/web/app/Services/Cloud/CloudWorkerService.php index 6b7c1684..7f0a7ac5 100644 --- a/web/app/Services/Cloud/CloudWorkerService.php +++ b/web/app/Services/Cloud/CloudWorkerService.php @@ -1147,7 +1147,7 @@ final class CloudWorkerService // immutable target. Removal is represented by desired_state and // therefore remains strict. foreach (['required', 'desired_state', 'vpc_id', 'member_id', - 'private_ip_cidr', 'desired_revision', 'desired_digest'] as $key) { + 'private_ip_cidr', 'private_mac', 'desired_revision', 'desired_digest'] as $key) { $left = $capturedExpectation[$key] ?? null; $right = $currentExpectation[$key] ?? null; if ((string) $left !== (string) $right) { diff --git a/web/tests/CloudVpcControlPlaneContractTest.php b/web/tests/CloudVpcControlPlaneContractTest.php index 23fdd424..40e1d32e 100644 --- a/web/tests/CloudVpcControlPlaneContractTest.php +++ b/web/tests/CloudVpcControlPlaneContractTest.php @@ -24,6 +24,7 @@ $accountDeletion = $read('app/Services/UserDataDeletionService.php'); $jobService = $read('app/Services/Cloud/CloudJobService.php'); $orderService = $read('app/Services/Cloud/CloudOrderService.php'); $workerService = $read('app/Services/Cloud/CloudWorkerService.php'); +$vpcWorkerService = $read('app/Services/Cloud/CloudVpcWorkerService.php'); foreach ([ 'cloud_region_fabrics', @@ -105,9 +106,27 @@ $assert(str_contains($service, '$orphanLease') $assert(str_contains($service, '当前 VPC 控制面不支持子网网关') && str_contains($service, "'private_ip_cidr'") && str_contains($service, "'next_hop_member_id'") + && str_contains($service, "self::cidr(\$item['destination_cidr'] ?? null, 32, 32, '路由目标')") && str_contains($service, 'VPC 私网地址账本与成员不一致') && str_contains($service, 'firstFreeIp($subnet, $privateIps)'), 'VPC service lost no-gateway, /32 member or typed route boundaries.'); +$assert(str_contains($service, 'privateMacForMember') + && str_contains($service, "'private_mac' => \$privateMac") + && str_contains($service, 'validateHostDataplaneEvidence') + && str_contains($service, 'member_nics') + && str_contains($service, 'wg_allowed_ips') + && str_contains($service, 'privateRouteTableForVpc') + && str_contains($service, 'expectedRouteSet') + && str_contains($service, 'desiredContractValid') + && str_contains($service, "array_key_exists('observed_digest', \$item)") + && str_contains($service, "base64_decode(\$publicKey, true)") + && str_contains($service, 'FABRIC_INTERFACE') + && str_contains($service, 'PRIVATE_DATAPLANE_OWNER'), + 'VPC desired DTO or host dataplane readback contract lost stable NIC identity/ACL gates.'); +$assert(str_contains($vpcWorkerService, "'waiting_observed'") + && str_contains($vpcWorkerService, 'allowDeferredRetry') + && str_contains($vpcWorkerService, 'CloudVpcService::reconcile($vpcKey, $actor, $allowDeferredRetry)'), + 'VPC worker must retry waiting_observed through its independent apply lane.'); $assert(str_contains($routes, "'/vpcs'") && str_contains($routes, "'/vpcs/{vpc_key:[0-9a-f]{32}}/reconcile'") @@ -136,5 +155,8 @@ $assert(str_contains($workerService, '$hasPrivateState') && $privateReadback !== false && $legacyPrivateGate < $privateReadback, 'Legacy public-only jobs without private_state must remain compatible while structured observations stay gated.'); +$assert(str_contains($workerService, "'private_mac', 'desired_revision'") + && str_contains($service, "'private_mac', 'desired_revision'"), + 'Private MAC must remain part of the immutable lifecycle/VPC target tuple.'); echo "VPC control-plane schema, API, typed DTO and independent operation contracts passed.\n";