From 9f0d16600de483ec3eefe02864c8fcab91358a4e Mon Sep 17 00:00:00 2001 From: admin Date: Tue, 6 Oct 2026 00:49:15 +0800 Subject: [PATCH] feat: add per-instance platform test policies --- engine/tests/test_app.py | 23 +- engine/tests/test_libvirt_service.py | 476 +++++++++++++- engine/virsh_panel/app.py | 115 +++- engine/virsh_panel/internal.py | 37 +- engine/virsh_panel/libvirt_service.py | 406 +++++++++++- engine/virsh_panel/platform_network_policy.py | 194 ++++++ .../Controllers/Admin/CloudPageController.php | 19 + .../CloudAdminPlatformPolicyController.php | 66 ++ web/app/Middleware/CloudApi.php | 1 + .../Models/CloudPlatformTestPolicyRule.php | 20 + .../Models/CloudPlatformTestPolicyState.php | 16 + web/app/Services/Cloud/CloudOrderService.php | 13 + .../Services/Cloud/CloudPlacementService.php | 9 + .../Cloud/CloudPlatformTestNetworkPolicy.php | 602 ++++++++++++++++++ web/config/routes_cloud.php | 8 + web/public/cloud/admin-platform-policy.js | 238 +++++++ .../admin/cloud/platform_default_policy.tpl | 36 +- web/resources/views/venix/layout_assets.tpl | 2 +- web/sql/cloud.sql | 30 + .../AdminPlatformDefaultNetworkPolicyTest.php | 105 ++- web/tests/CloudFinancialWorkflowTest.php | 65 +- web/tests/CloudFirewallUiContractTest.php | 2 +- .../CloudPlatformTestNetworkPolicyTest.php | 211 ++++++ 23 files changed, 2646 insertions(+), 48 deletions(-) create mode 100644 web/app/Controllers/CloudAdminPlatformPolicyController.php create mode 100644 web/app/Models/CloudPlatformTestPolicyRule.php create mode 100644 web/app/Models/CloudPlatformTestPolicyState.php create mode 100644 web/app/Services/Cloud/CloudPlatformTestNetworkPolicy.php create mode 100644 web/public/cloud/admin-platform-policy.js create mode 100644 web/tests/CloudPlatformTestNetworkPolicyTest.php diff --git a/engine/tests/test_app.py b/engine/tests/test_app.py index d54229da..983b4833 100644 --- a/engine/tests/test_app.py +++ b/engine/tests/test_app.py @@ -40,6 +40,9 @@ from virsh_panel.libvirt_service import ( # noqa: E402 ) from virsh_panel.metrics import host_scope, query_interval_seconds # noqa: E402 from virsh_panel.panel_state import PanelState # noqa: E402 +from virsh_panel.platform_network_policy import ( # noqa: E402 + default_platform_policy_snapshot, +) from virsh_panel.remote_host import RemoteHostError, validate_public_pool # noqa: E402 @@ -120,6 +123,7 @@ class FakeVMService: self.firewall_enabled = False self.firewall_rules: list[dict] = [] self.firewall_filter_digest: str | None = None + self.platform_policy_snapshot = default_platform_policy_snapshot() self.firewall_apply_error: VMError | None = None self.firewall_cleanup_error: VMError | None = None self.vm = { @@ -236,6 +240,10 @@ class FakeVMService: def create_cloud_vm(self, spec, template_volume_name): self.calls.append(("create_cloud_vm", spec, template_volume_name)) + self.platform_policy_snapshot = spec.get( + "platform_network_policy_snapshot", + default_platform_policy_snapshot(), + ) if self.vm.get("os_source") == "cloud_template": self.other_vms.append(self.vm.copy()) self.vm = { @@ -417,13 +425,19 @@ class FakeVMService: def get_firewall_policy(self, vm_id): self.calls.append(("get_firewall_policy", vm_id)) + policy_evidence = { + "platform_policy_snapshot": self.platform_policy_snapshot, + "platform_policy_digest": self.platform_policy_snapshot["digest"], + } if self.firewall_filter_digest is None: return { + **policy_evidence, "enabled": False, "filter_mode": "baseline", "filter_digest": None, "sync_state": "active", "matches": True, "coherent": True, } return { + **policy_evidence, "enabled": self.firewall_enabled, "filter_mode": "managed", "filter_digest": self.firewall_filter_digest, "sync_state": "active", "matches": True, "coherent": True, @@ -438,11 +452,15 @@ class FakeVMService: self.firewall_enabled = enabled self.firewall_rules = normalized self.firewall_filter_digest = build_firewall_filter_xml( - vm_id, enabled, normalized)[3] + vm_id, enabled, normalized, + platform_policy_snapshot=self.platform_policy_snapshot, + )[3] return { "enabled": enabled, "rules": normalized, "policy_digest": digest, "filter_digest": self.firewall_filter_digest, + "platform_policy_snapshot": self.platform_policy_snapshot, + "platform_policy_digest": self.platform_policy_snapshot["digest"], "sync_state": "active", "matches": True, "coherent": True, } @@ -459,6 +477,7 @@ class FakeVMService: expected_filter = build_firewall_filter_xml( vm_id, enabled, normalized, compiler_version=compiler_version, + platform_policy_snapshot=self.platform_policy_snapshot, )[3] matches = ( self.firewall_filter_digest == expected_filter @@ -469,6 +488,8 @@ class FakeVMService: "enabled": self.firewall_enabled, "filter_mode": "managed" if self.firewall_filter_digest else "baseline", "filter_digest": self.firewall_filter_digest, + "platform_policy_snapshot": self.platform_policy_snapshot, + "platform_policy_digest": self.platform_policy_snapshot["digest"], "sync_state": "active", "matches": matches, "coherent": True, "policy_digest": digest, "expected_filter_digest": expected_filter, diff --git a/engine/tests/test_libvirt_service.py b/engine/tests/test_libvirt_service.py index 26761227..ed46fdd4 100644 --- a/engine/tests/test_libvirt_service.py +++ b/engine/tests/test_libvirt_service.py @@ -4,6 +4,7 @@ from __future__ import annotations import hashlib import importlib.util +import json import pathlib import sys import tempfile @@ -949,6 +950,209 @@ class VMServiceTests(unittest.TestCase): self.assertFalse(any( rule.get("action") == "drop" for rule in legacy_v2.findall("rule"))) + def platform_snapshot(self, *dynamic_rules, revision=1): + baseline = self.service_module.default_platform_policy_snapshot() + document = { + "schema_version": baseline["schema_version"], + "base_policy_version": baseline["base_policy_version"], + "catalog_revision": revision, + "rules": [*baseline["rules"], *dynamic_rules], + } + encoded = json.dumps( + document, ensure_ascii=False, separators=(",", ":"), + ).encode("utf-8") + return self.service_module.normalize_platform_policy_snapshot({ + **document, + "digest": hashlib.sha256(encoded).hexdigest(), + }) + + def platform_policy_stripping_define(self, *, persistent=False): + """Return a defineXML double that removes the platform metadata.""" + original_define = FakeConnection.defineXML + stripped = {"done": False} + namespace = self.service_module.PANEL_NS + + def define(connection, xml): + root = ET.fromstring(xml) + managed = root.find( + f"./metadata/{{{namespace}}}managed") + node = (managed.find(f"{{{namespace}}}platform-policy") + if managed is not None else None) + if node is not None and (persistent or not stripped["done"]): + managed.remove(node) + stripped["done"] = True + xml = ET.tostring(root, encoding="unicode") + return original_define(connection, xml) + + return define + + @staticmethod + def test_platform_rule( + rule_id="test-11111111111111111111111111111111", + *, protocols=None, directions=None, port_from=8080, port_to=8080, + ): + return { + "id": rule_id, + "label": "Temporary web test", + "category": "test", + "protocols": protocols or ["tcp"], + "port_from": port_from, + "port_to": port_to, + "directions": directions or ["ingress"], + "reason": "Verify future-instance policy snapshots.", + } + + def test_platform_test_drop_precedes_conflicting_tenant_allow(self): + vm_id = "00000000-0000-4000-8000-000000000001" + snapshot = self.platform_snapshot(self.test_platform_rule()) + tenant_rule = [{ + "protocol": "tcp", "source_cidr": "0.0.0.0/0", + "port_from": 8080, "port_to": 8080, + "description": "Tenant tries to allow the test-blocked port", + }] + + xml = self.service_module.build_firewall_filter_xml( + vm_id, True, tenant_rule, + platform_policy_snapshot=snapshot, + )[0] + root = ET.fromstring(xml) + platform_drop = next( + rule for rule in root.findall("rule") + if rule.get("action") == "drop" + and (rule.find("tcp") is not None) + and rule.find("tcp").get("dstportstart") == "8080" + ) + tenant_allow = next( + rule for rule in root.findall("rule") + if rule.get("action") == "accept" + and (rule.find("tcp") is not None) + and rule.find("tcp").get("dstportstart") == "8080" + ) + self.assertEqual(platform_drop.get("direction"), "in") + self.assertLess( + int(platform_drop.get("priority")), + int(tenant_allow.get("priority")), + ) + + def test_platform_snapshot_digest_matches_php_for_line_terminators(self): + rule = self.test_platform_rule() + rule["label"] = "Line\u2028separator" + rule["reason"] = "Paragraph\u2029separator" + snapshot = self.platform_snapshot(rule, revision=7) + + self.assertEqual( + snapshot["digest"], + "ffb4b8b3e09189d55180b280cde172e1dbbd83ef0965d27e2f8210cc6b20bb2f", + ) + + def test_new_vm_seals_test_snapshot_and_firewall_reuses_it(self): + service = self.cloud_service() + snapshot = self.platform_snapshot(self.test_platform_rule()) + created = self.create_cloud_vm(service, self.cloud_spec( + platform_network_policy_snapshot=snapshot, + )) + domain = self.backend.domains[0] + + for root in (domain.inactive_root, domain.live_root): + node = root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed/" + f"{{{self.service_module.PANEL_NS}}}platform-policy" + ) + self.assertIsNotNone(node) + self.assertEqual(node.get("digest"), snapshot["digest"]) + self.assertEqual(json.loads(node.text), snapshot) + + tenant_rule = [{ + "protocol": "tcp", "source_cidr": "0.0.0.0/0", + "port_from": 8080, "port_to": 8080, + "description": "Conflicting tenant allow", + }] + applied = service.apply_firewall_policy( + created["uuid"], enabled=True, rules=tenant_rule) + self.assertEqual(applied["platform_policy_digest"], snapshot["digest"]) + evidence = service.reconcile_firewall_policy( + created["uuid"], enabled=True, rules=tenant_rule) + self.assertTrue(evidence["matches"]) + self.assertEqual( + evidence["platform_policy_snapshot"], snapshot, + ) + + def test_new_vm_rejects_stripped_platform_snapshot_metadata(self): + service = self.cloud_service() + snapshots = [ + self.service_module.default_platform_policy_snapshot(), + self.platform_snapshot(self.test_platform_rule()), + ] + original_define = FakeConnection.defineXML + + for snapshot in snapshots: + stripped = {"done": False} + + def strip_policy_once(connection, xml): + root = ET.fromstring(xml) + if not stripped["done"]: + managed = root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed") + node = managed.find( + f"{{{self.service_module.PANEL_NS}}}platform-policy") + managed.remove(node) + stripped["done"] = True + xml = ET.tostring(root, encoding="unicode") + return original_define(connection, xml) + + with self.subTest(catalog_revision=snapshot["catalog_revision"]), \ + patch.object(FakeConnection, "defineXML", strip_policy_once), \ + self.assertRaises(self.service_module.VMError) as raised: + self.create_cloud_vm(service, self.cloud_spec( + platform_network_policy_snapshot=snapshot, + )) + + self.assertEqual(raised.exception.status, 502) + self.assertEqual( + raised.exception.error_code, "firewall_result_uncertain") + self.assertFalse(self.backend.domains) + self.assertEqual( + set(self.backend.pools["images"].volumes), {TEMPLATE_NAME}) + self.assertEqual(set(self.backend.nwfilters), {"clean-traffic"}) + self.assertEqual(self.backend.domain_starts, 0) + + def test_firewall_rejects_inactive_live_policy_presence_drift(self): + service = self.cloud_service() + created = self.create_cloud_vm(service, self.cloud_spec()) + domain = self.backend.domains[0] + managed = domain.live_root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed") + node = managed.find( + f"{{{self.service_module.PANEL_NS}}}platform-policy") + managed.remove(node) + + with self.assertRaises(self.service_module.VMError) as raised: + service.get_firewall_policy(created["uuid"]) + + self.assertEqual(raised.exception.status, 409) + self.assertEqual( + raised.exception.error_code, "firewall_drift_detected") + + def test_corrupt_platform_snapshot_metadata_fails_closed(self): + service = self.cloud_service() + snapshot = self.platform_snapshot(self.test_platform_rule()) + created = self.create_cloud_vm(service, self.cloud_spec( + platform_network_policy_snapshot=snapshot, + )) + domain = self.backend.domains[0] + node = domain.inactive_root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed/" + f"{{{self.service_module.PANEL_NS}}}platform-policy" + ) + node.set("digest", "0" * 64) + + with self.assertRaises(self.service_module.VMError) as raised: + service.get_firewall_policy(created["uuid"]) + + self.assertEqual(raised.exception.status, 409) + self.assertEqual( + raised.exception.error_code, "firewall_drift_detected") + def test_new_cloud_vm_first_boot_uses_verified_platform_wrapper(self): service = self.cloud_service() created = self.create_cloud_vm(service, self.cloud_spec()) @@ -1271,7 +1475,9 @@ class VMServiceTests(unittest.TestCase): def test_cloud_network_change_preserves_firewall_and_outbound_allow(self): service = self.cloud_service() - spec = self.cloud_spec() + platform_snapshot = self.platform_snapshot(self.test_platform_rule()) + spec = self.cloud_spec( + platform_network_policy_snapshot=platform_snapshot) created = self.create_cloud_vm(service, spec) domain = self.backend.domains[0] rules = [{ @@ -1337,6 +1543,13 @@ class VMServiceTests(unittest.TestCase): filterref.find("parameter").attrib, {"name": "IP", "value": "8.8.8.19"}, ) + policy_node = root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed/" + f"{{{self.service_module.PANEL_NS}}}platform-policy" + ) + self.assertEqual( + policy_node.get("digest"), platform_snapshot["digest"]) + self.assertEqual(json.loads(policy_node.text), platform_snapshot) self.assertEqual( self.backend.nwfilters[filter_name].XMLDesc(0), filter_xml_before) self.assertEqual( @@ -1350,6 +1563,107 @@ class VMServiceTests(unittest.TestCase): created["uuid"], enabled=True, rules=rules) self.assertTrue(evidence["matches"]) + def test_cloud_network_change_rolls_back_if_policy_metadata_is_stripped(self): + service = self.cloud_service() + platform_snapshot = self.platform_snapshot(self.test_platform_rule()) + created = self.create_cloud_vm(service, self.cloud_spec( + platform_network_policy_snapshot=platform_snapshot, + )) + domain = self.backend.domains[0] + managed = domain.inactive_root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed") + seed_name = managed.get("seed-volume") + original_seed = bytes( + self.backend.pools["images"].volumes[seed_name].contents) + mac = domain.inactive_root.find( + "./devices/interface/mac").get("address") + network = { + "source_public_pool_key": "a" * 32, + "public_pool_key": "a" * 32, + "public_ip_cidr": "8.8.8.19/24", + "gateway": "8.8.8.1", + "dns_servers": ["1.1.1.1", "8.8.8.8"], + } + original_define = FakeConnection.defineXML + stripped = {"done": False} + + def strip_policy_once(connection, xml): + root = ET.fromstring(xml) + if not stripped["done"]: + updated_managed = root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed") + node = updated_managed.find( + f"{{{self.service_module.PANEL_NS}}}platform-policy") + updated_managed.remove(node) + stripped["done"] = True + xml = ET.tostring(root, encoding="unicode") + return original_define(connection, xml) + + with patch.object(self.service_module, "read_seed_network", return_value={ + "public_ip_cidr": "8.8.8.18/24", "gateway": "8.8.8.1", + "dns_servers": ["1.1.1.1", "8.8.8.8"], "mac": mac, + }), patch.object( + self.service_module, "replace_seed_network", + return_value=b"NEW-SEED", + ), patch.object(FakeConnection, "defineXML", strip_policy_once), \ + self.assertRaises(self.service_module.VMError) as raised: + service.change_cloud_vm_network( + created["uuid"], network, confirm_restart=True) + + self.assertEqual(raised.exception.status, 502) + self.assertEqual( + raised.exception.error_code, "firewall_result_uncertain") + restored = domain.inactive_root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed") + self.assertEqual(restored.get("public-ip-cidr"), "8.8.8.18/24") + policy_node = restored.find( + f"{{{self.service_module.PANEL_NS}}}platform-policy") + self.assertEqual(policy_node.get("digest"), platform_snapshot["digest"]) + self.assertEqual(json.loads(policy_node.text), platform_snapshot) + self.assertEqual( + bytes(self.backend.pools["images"].volumes[seed_name].contents), + original_seed, + ) + + def test_cloud_network_change_reports_incomplete_persistent_policy_strip(self): + service = self.cloud_service() + platform_snapshot = self.platform_snapshot(self.test_platform_rule()) + created = self.create_cloud_vm(service, self.cloud_spec( + platform_network_policy_snapshot=platform_snapshot, + )) + domain = self.backend.domains[0] + mac = domain.inactive_root.find( + "./devices/interface/mac").get("address") + network = { + "source_public_pool_key": "a" * 32, + "public_pool_key": "a" * 32, + "public_ip_cidr": "8.8.8.19/24", + "gateway": "8.8.8.1", + "dns_servers": ["1.1.1.1", "8.8.8.8"], + } + + with patch.object(self.service_module, "read_seed_network", return_value={ + "public_ip_cidr": "8.8.8.18/24", "gateway": "8.8.8.1", + "dns_servers": ["1.1.1.1", "8.8.8.8"], "mac": mac, + }), patch.object( + self.service_module, "replace_seed_network", + return_value=b"NEW-SEED", + ), patch.object( + FakeConnection, "defineXML", + self.platform_policy_stripping_define(persistent=True), + ), self.assertRaises(self.service_module.VMError) as raised: + service.change_cloud_vm_network( + created["uuid"], network, confirm_restart=True) + + self.assertEqual(raised.exception.status, 502) + self.assertIn("自动回滚不完整", str(raised.exception)) + self.assertFalse(domain.isActive()) + managed = domain.inactive_root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed") + self.assertEqual(managed.get("public-ip-cidr"), "8.8.8.18/24") + self.assertIsNone(managed.find( + f"{{{self.service_module.PANEL_NS}}}platform-policy")) + def test_cloud_network_change_rejects_unconfirmed_restart_without_touching_vm(self): service = self.cloud_service() created = self.create_cloud_vm(service, self.cloud_spec()) @@ -1402,6 +1716,52 @@ class VMServiceTests(unittest.TestCase): b"NEW-SETTINGS-SEED", ) + def test_cloud_settings_rolls_back_if_platform_metadata_is_stripped(self): + service = self.cloud_service() + platform_snapshot = self.platform_snapshot(self.test_platform_rule()) + spec = self.cloud_spec( + platform_network_policy_snapshot=platform_snapshot) + created = self.create_cloud_vm(service, spec) + domain = self.backend.domains[0] + managed = domain.inactive_root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed") + seed_name = managed.get("seed-volume") + original_hostname = managed.get("guest-hostname") + original_seed = bytes( + self.backend.pools["images"].volumes[seed_name].contents) + + with patch.object(self.service_module, "replace_seed_settings", + return_value=b"NEW-SETTINGS-SEED"), \ + patch.object(self.service_module, "read_seed_network", return_value={ + "public_ip_cidr": spec["public_ip_cidr"], + "gateway": spec["gateway"], + "dns_servers": spec["dns_servers"], + "mac": domain.inactive_root.find( + "./devices/interface/mac").get("address"), + }), patch.object( + FakeConnection, "defineXML", + self.platform_policy_stripping_define(), + ), self.assertRaises(self.service_module.VMError) as raised: + service.change_cloud_vm_settings( + created["uuid"], hostname="node.example", + confirm_restart=True, + ) + + self.assertEqual(raised.exception.status, 502) + self.assertEqual( + raised.exception.error_code, "firewall_result_uncertain") + self.assertTrue(domain.isActive()) + restored = domain.inactive_root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed") + self.assertEqual(restored.get("guest-hostname"), original_hostname) + policy_node = restored.find( + f"{{{self.service_module.PANEL_NS}}}platform-policy") + self.assertEqual(json.loads(policy_node.text), platform_snapshot) + self.assertEqual( + bytes(self.backend.pools["images"].volumes[seed_name].contents), + original_seed, + ) + def test_cloud_settings_change_requires_restart_confirmation(self): service = self.cloud_service() created = self.create_cloud_vm(service, self.cloud_spec()) @@ -1896,6 +2256,80 @@ class VMServiceTests(unittest.TestCase): self.assertIn(snapshot["volume_name"], self.backend.pools["images"].volumes) self.assertTrue(domain.isActive()) + def test_live_snapshot_restore_rolls_back_stripped_platform_metadata(self): + service = self.cloud_service() + platform_snapshot = self.platform_snapshot(self.test_platform_rule()) + created = self.create_cloud_vm(service, self.cloud_spec( + platform_network_policy_snapshot=platform_snapshot, + )) + domain = self.backend.domains[0] + managed = domain.inactive_root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed") + old_name = managed.get("disk-volume") + snapshot_key = "4" * 32 + snapshot = service.create_live_snapshot( + created["uuid"], snapshot_key, consistency="crash") + operation_id = "restore-policy-strip-once" + replacement_name = self.service_module.snapshot_restore_volume_name( + created["uuid"], operation_id) + + with patch.object( + FakeConnection, "defineXML", + self.platform_policy_stripping_define()), \ + self.assertRaises(self.service_module.VMError) as raised: + service.restore_live_snapshot( + created["uuid"], snapshot_key, snapshot["volume_name"], + operation_id, + ) + + self.assertEqual(raised.exception.status, 502) + self.assertEqual( + raised.exception.error_code, "firewall_result_uncertain") + self.assertTrue(domain.isActive()) + restored = domain.inactive_root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed") + self.assertEqual(restored.get("disk-volume"), old_name) + policy_node = restored.find( + f"{{{self.service_module.PANEL_NS}}}platform-policy") + self.assertEqual(json.loads(policy_node.text), platform_snapshot) + self.assertIn(old_name, self.backend.pools["images"].volumes) + self.assertNotIn(replacement_name, self.backend.pools["images"].volumes) + + def test_live_snapshot_restore_retains_disks_if_rollback_strips_policy(self): + service = self.cloud_service() + platform_snapshot = self.platform_snapshot(self.test_platform_rule()) + created = self.create_cloud_vm(service, self.cloud_spec( + platform_network_policy_snapshot=platform_snapshot, + )) + domain = self.backend.domains[0] + old_name = domain.inactive_root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed" + ).get("disk-volume") + snapshot_key = "5" * 32 + snapshot = service.create_live_snapshot( + created["uuid"], snapshot_key, consistency="crash") + operation_id = "restore-policy-strip-persistent" + replacement_name = self.service_module.snapshot_restore_volume_name( + created["uuid"], operation_id) + + with patch.object( + FakeConnection, "defineXML", + self.platform_policy_stripping_define(persistent=True)), \ + self.assertRaises( + self.service_module.VMSnapshotUncertainError) as raised: + service.restore_live_snapshot( + created["uuid"], snapshot_key, snapshot["volume_name"], + operation_id, + ) + + self.assertEqual(raised.exception.status, 503) + self.assertIn("自动回退不完整", str(raised.exception)) + self.assertFalse(domain.isActive()) + self.assertIn(old_name, self.backend.pools["images"].volumes) + self.assertIn(replacement_name, self.backend.pools["images"].volumes) + self.assertIn( + snapshot["volume_name"], self.backend.pools["images"].volumes) + def test_live_snapshot_restore_allocation_failure_keeps_original_disk(self): service = self.cloud_service() created = self.create_cloud_vm(service, self.cloud_spec()) @@ -3394,7 +3828,9 @@ class VMServiceTests(unittest.TestCase): def test_reinstall_keeps_original_public_network_and_deletes_old_disk_only_after_start(self): from virsh_panel.cloud_init import read_seed_network - service, created, spec, domain, old_seed_name = self.cloud_vm_with_real_seed() + platform_snapshot = self.platform_snapshot(self.test_platform_rule()) + service, created, spec, domain, old_seed_name = self.cloud_vm_with_real_seed( + platform_network_policy_snapshot=platform_snapshot) pool = self.backend.pools["images"] old_disk = pool.volumes["cloud-vm.qcow2"] original_mac = domain.root.find("./devices/interface/mac").get("address") @@ -3429,6 +3865,12 @@ class VMServiceTests(unittest.TestCase): new_seed_name = root.find( f"./metadata/{{{self.service_module.PANEL_NS}}}managed").get("seed-volume") self.assertNotEqual(new_seed_name, old_seed_name) + policy_node = root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed/" + f"{{{self.service_module.PANEL_NS}}}platform-policy" + ) + self.assertEqual(policy_node.get("digest"), platform_snapshot["digest"]) + self.assertEqual(json.loads(policy_node.text), platform_snapshot) network = read_seed_network(bytes(pool.volumes[new_seed_name].contents)) self.assertEqual(network, { "public_ip_cidr": spec["public_ip_cidr"], @@ -4080,6 +4522,36 @@ class VMServiceTests(unittest.TestCase): self.assertEqual(self.backend.destroyed, []) self.assertTrue(service.delete_rescue_iso(RESCUE_NAME)["deleted"]) + def test_rescue_entry_rolls_back_stripped_platform_metadata(self): + service = self.cloud_service() + platform_snapshot = self.platform_snapshot(self.test_platform_rule()) + created = self.create_cloud_vm(service, self.cloud_spec( + platform_network_policy_snapshot=platform_snapshot, + )) + self.rescue_volume() + domain = self.backend.domains[0] + original_xml = service.prepare_rescue_vm( + created["uuid"], RESCUE_NAME) + shutdowns = self.backend.shutdown_calls + + with patch.object( + FakeConnection, "defineXML", + self.platform_policy_stripping_define()), \ + self.assertRaises(self.service_module.VMError) as raised: + service.enter_rescue_vm( + created["uuid"], RESCUE_NAME, original_xml) + + self.assertEqual(raised.exception.status, 502) + self.assertIn("原虚拟机未受影响", str(raised.exception)) + self.assertEqual(self.backend.shutdown_calls, shutdowns) + self.assertTrue(domain.isActive()) + self.assertFalse(service.get_vm(created["uuid"])["rescue_mode"]) + managed = domain.inactive_root.find( + f"./metadata/{{{self.service_module.PANEL_NS}}}managed") + policy_node = managed.find( + f"{{{self.service_module.PANEL_NS}}}platform-policy") + self.assertEqual(json.loads(policy_node.text), platform_snapshot) + def test_traffic_suspension_survives_rescue_exit_until_network_resume(self): service = self.cloud_service() created = self.create_cloud_vm(service, self.cloud_spec()) diff --git a/engine/virsh_panel/app.py b/engine/virsh_panel/app.py index a4d0810e..ae349933 100644 --- a/engine/virsh_panel/app.py +++ b/engine/virsh_panel/app.py @@ -51,6 +51,9 @@ from .inventory_diagnostics import inventory_result, inventory_stage from .metrics import (MAX_QUERY_POINTS, RETENTION_SECONDS, RANGES, MetricsCollector, host_scope, query_interval_seconds) from .panel_state import PanelState, SetupError +from .platform_network_policy import ( + default_platform_policy_snapshot, normalize_platform_policy_snapshot, +) from .remote_host import ( MAX_PUBLIC_NETWORK_POOLS, PUBLIC_POOL_KEY, @@ -280,6 +283,18 @@ class CreateCloudBody(BaseModel): guest_ssh_public_key: str = Field(default="", max_length=16384) guest_ssh_key_id: int | None = Field(default=None, ge=1) root_password: SecretStr | None = None + platform_network_policy_snapshot: dict[str, Any] = Field( + default_factory=default_platform_policy_snapshot) + + @model_validator(mode="after") + def validate_platform_network_policy(self): + try: + self.platform_network_policy_snapshot = ( + normalize_platform_policy_snapshot( + self.platform_network_policy_snapshot)) + except ValueError as exc: + raise ValueError("平台网络策略快照无效") from exc + return self class ChangeNetworkBody(BaseModel): @@ -1272,7 +1287,8 @@ def create_app( }) except (KeyError, TypeError, ValueError) as exc: raise DatabaseError("虚拟机防火墙记录损坏") from exc - if (not isinstance(record, dict) or record.get("version") != 1 + record_version = record.get("version") if isinstance(record, dict) else None + if (not isinstance(record, dict) or record_version not in {1, 2} or record.get("vm_id") != str(uuid.UUID(vm_id)) or not re.fullmatch(r"[0-9a-f]{64}", record.get("policy_digest", "")) @@ -1286,6 +1302,24 @@ def create_app( or not isinstance(filter_version, int) or filter_version not in SUPPORTED_FIREWALL_FILTER_COMPILER_VERSIONS): raise DatabaseError("虚拟机防火墙记录损坏") + try: + platform_policy = ( + normalize_platform_policy_snapshot( + record["platform_policy_snapshot"]) + if record_version == 2 + else default_platform_policy_snapshot() + ) + except (KeyError, TypeError, ValueError) as exc: + raise DatabaseError("虚拟机防火墙记录损坏") from exc + if (record_version == 2 + and (not isinstance(record.get("platform_policy_digest"), str) + or not hmac.compare_digest( + record["platform_policy_digest"], + platform_policy["digest"], + ))): + raise DatabaseError("虚拟机防火墙记录损坏") + if record_version == 1 and filter_version >= 4: + raise DatabaseError("虚拟机防火墙记录损坏") normalized_policy = policy.model_dump() if not hmac.compare_digest( normalized_policy["policy_digest"], @@ -1299,6 +1333,7 @@ def create_app( normalized_policy["enabled"], normalized_policy["rules"], compiler_version=filter_version, + platform_policy_snapshot=platform_policy, )[3] if not hmac.compare_digest( record["filter_digest"], expected_filter_digest): @@ -1306,7 +1341,10 @@ def create_app( return { **record, **normalized_policy, + "version": record_version, "filter_version": filter_version, + "platform_policy_snapshot": platform_policy, + "platform_policy_digest": platform_policy["digest"], } def save_firewall_record(profile: dict, vm_id: str, record: dict) -> None: @@ -1330,8 +1368,10 @@ def create_app( ) -> bool: """Recognize the exact record-free wrapper installed at VM creation.""" observed_digest = observed.get("filter_digest") + platform_policy = observed.get("platform_policy_snapshot") expected_digest = build_firewall_filter_xml( - vm_id, False, [])[3] + vm_id, False, [], + platform_policy_snapshot=platform_policy)[3] return bool( observed.get("filter_mode") == "managed" and observed.get("sync_state") == "active" @@ -1348,6 +1388,15 @@ def create_app( observed = service.get_firewall_policy(vm_id) observed_filter_digest = observed.get("filter_digest") observed_mode = observed.get("filter_mode") + try: + observed_platform_policy = normalize_platform_policy_snapshot( + observed.get("platform_policy_snapshot") + or default_platform_policy_snapshot()) + except ValueError as exc: + raise VMError( + "虚拟机平台网络策略证据无效", 409, + error_code="firewall_drift_detected", + ) from exc observed_active = ( observed.get("sync_state") == "active" and observed.get("coherent") is True) @@ -1366,6 +1415,14 @@ def create_app( observed_active and observed_mode == "managed" and isinstance(observed_filter_digest, str)) + if not hmac.compare_digest( + record["platform_policy_digest"], + observed_platform_policy["digest"]): + raise VMError( + "虚拟机平台网络策略与引擎记录不一致", + 409, + error_code="firewall_drift_detected", + ) if record["filter_version"] >= FIREWALL_FILTER_COMPILER_VERSION: if (observation_active and hmac.compare_digest( observed_filter_digest, record["filter_digest"])): @@ -1376,7 +1433,8 @@ def create_app( error_code="firewall_drift_detected", ) expected_filter_digest = build_firewall_filter_xml( - vm_id, record["enabled"], record["rules"])[3] + vm_id, record["enabled"], record["rules"], + platform_policy_snapshot=observed_platform_policy)[3] if not observation_active: raise VMError( "防火墙实际状态与已保存版本不一致,请先核查漂移", @@ -1387,8 +1445,11 @@ def create_app( observed_filter_digest, expected_filter_digest): upgraded = { **record, + "version": 2, "filter_version": FIREWALL_FILTER_COMPILER_VERSION, "filter_digest": expected_filter_digest, + "platform_policy_snapshot": observed_platform_policy, + "platform_policy_digest": observed_platform_policy["digest"], "applied_at": int(time.time()), } try: @@ -1411,12 +1472,17 @@ def create_app( vm_id, enabled=record["enabled"], rules=record["rules"]) result_policy_digest = result.get("policy_digest") result_filter_digest = result.get("filter_digest") + result_platform_digest = result.get("platform_policy_digest") if (not isinstance(result_policy_digest, str) or not isinstance(result_filter_digest, str) or not hmac.compare_digest( result_policy_digest, record["policy_digest"]) or not hmac.compare_digest( - result_filter_digest, expected_filter_digest)): + result_filter_digest, expected_filter_digest) + or not isinstance(result_platform_digest, str) + or not hmac.compare_digest( + result_platform_digest, + observed_platform_policy["digest"])): raise VMError( "防火墙编译器升级结果不确定,已停止修改网络", 503, @@ -1424,8 +1490,11 @@ def create_app( ) upgraded = { **record, + "version": 2, "filter_version": FIREWALL_FILTER_COMPILER_VERSION, "filter_digest": expected_filter_digest, + "platform_policy_snapshot": observed_platform_policy, + "platform_policy_digest": observed_platform_policy["digest"], "applied_at": int(time.time()), } try: @@ -3860,6 +3929,8 @@ def create_app( and observed.get("filter_mode") == "managed" and observed.get("sync_state") == "active" and observed.get("filter_digest") == record["filter_digest"] + and observed.get("platform_policy_digest") + == record["platform_policy_digest"] ) return { "enabled": record["enabled"] if applied else observed.get("enabled"), @@ -3894,8 +3965,20 @@ def create_app( requested_rules = requested["rules"] requested_digest = firewall_policy_digest( requested["enabled"], requested_rules) + service = new_service(profile) + observed = service.get_firewall_policy(canonical_id) + try: + platform_policy = normalize_platform_policy_snapshot( + observed.get("platform_policy_snapshot") + or default_platform_policy_snapshot()) + except ValueError as exc: + raise VMError( + "虚拟机平台网络策略证据无效", 409, + error_code="firewall_drift_detected", + ) from exc current_filter_digest = build_firewall_filter_xml( - canonical_id, requested["enabled"], requested_rules)[3] + canonical_id, requested["enabled"], requested_rules, + platform_policy_snapshot=platform_policy)[3] if not hmac.compare_digest( requested["policy_digest"], requested_digest): raise VMError( @@ -3903,15 +3986,21 @@ def create_app( error_code="firewall_rule_invalid", ) previous = load_firewall_record(profile, canonical_id) - service = new_service(profile) if previous is not None: + if not hmac.compare_digest( + previous["platform_policy_digest"], + platform_policy["digest"]): + raise VMError( + "虚拟机平台网络策略与引擎记录不一致", + 409, + error_code="firewall_drift_detected", + ) if requested["revision"] < previous["revision"]: raise VMError("防火墙策略版本已更新,请刷新后重试", 409) if (requested["revision"] == previous["revision"] and requested_digest != previous["policy_digest"]): raise VMError("相同防火墙版本对应了不同规则", 409) if requested["revision"] == previous["revision"]: - observed = service.get_firewall_policy(canonical_id) observed_filter_digest = observed.get("filter_digest") if (observed.get("filter_mode") == "managed" and observed.get("sync_state") == "active" @@ -3926,8 +4015,11 @@ def create_app( )): previous = { **previous, + "version": 2, "filter_version": FIREWALL_FILTER_COMPILER_VERSION, "filter_digest": current_filter_digest, + "platform_policy_snapshot": platform_policy, + "platform_policy_digest": platform_policy["digest"], "applied_at": int(time.time()), } save_firewall_record(profile, canonical_id, previous) @@ -3966,8 +4058,13 @@ def create_app( "防火墙策略摘要校验失败,结果待核对", 503, error_code="firewall_result_uncertain", ) + if result.get("platform_policy_digest") != platform_policy["digest"]: + raise VMError( + "平台网络策略摘要校验失败,结果待核对", 503, + error_code="firewall_result_uncertain", + ) record = { - "version": 1, + "version": 2, "filter_version": FIREWALL_FILTER_COMPILER_VERSION, "vm_id": canonical_id, "enabled": requested["enabled"], @@ -3975,6 +4072,8 @@ def create_app( "rules": result["rules"], "policy_digest": result["policy_digest"], "filter_digest": result["filter_digest"], + "platform_policy_snapshot": platform_policy, + "platform_policy_digest": platform_policy["digest"], "applied_at": int(time.time()), } try: diff --git a/engine/virsh_panel/internal.py b/engine/virsh_panel/internal.py index 1f103355..ff3995b4 100644 --- a/engine/virsh_panel/internal.py +++ b/engine/virsh_panel/internal.py @@ -2392,6 +2392,10 @@ class EngineApplication: build_firewall_filter_xml, firewall_policy_digest, ) + from .platform_network_policy import ( + default_platform_policy_snapshot, + normalize_platform_policy_snapshot, + ) if record["operation_id"] in self.active_operations: return record @@ -2466,19 +2470,38 @@ class EngineApplication: }).model_dump() previous_filter_version = previous.get( "filter_version", 1) + previous_record_version = previous.get("version") + previous_platform_policy = ( + normalize_platform_policy_snapshot( + previous["platform_policy_snapshot"]) + if previous_record_version == 2 + else default_platform_policy_snapshot() + ) previous_filter_digest = build_firewall_filter_xml( record["vm_uuid"], previous_policy["enabled"], previous_policy["rules"], compiler_version=previous_filter_version, + platform_policy_snapshot=previous_platform_policy, )[3] previous_valid = ( - previous.get("version") == 1 + previous_record_version in {1, 2} and previous.get("vm_id") == record["vm_uuid"] and not isinstance(previous_filter_version, bool) and isinstance(previous_filter_version, int) and previous_filter_version in SUPPORTED_FIREWALL_FILTER_COMPILER_VERSIONS + and not ( + previous_record_version == 1 + and previous_filter_version >= 4) + and ( + previous_record_version == 1 + or hmac.compare_digest( + previous.get( + "platform_policy_digest", ""), + previous_platform_policy["digest"], + ) + ) and re.fullmatch( r"[0-9a-f]{64}", previous.get("filter_digest", ""), @@ -2499,6 +2522,8 @@ class EngineApplication: **previous, **previous_policy, "filter_version": previous_filter_version, + "platform_policy_snapshot": previous_platform_policy, + "platform_policy_digest": previous_platform_policy["digest"], } except Exception: previous_valid = False @@ -2513,6 +2538,10 @@ class EngineApplication: or ( previous_valid and isinstance(previous, dict) + and hmac.compare_digest( + previous["platform_policy_digest"], + evidence.get("platform_policy_digest", ""), + ) and previous["filter_version"] <= target_filter_version and ( @@ -2540,13 +2569,17 @@ class EngineApplication: "sync_state": "active", } applied_record = { - "version": 1, + "version": 2, "filter_version": target_filter_version, "vm_id": record["vm_uuid"], **{key: result[key] for key in ( "enabled", "revision", "rules", "policy_digest", "filter_digest", )}, + "platform_policy_snapshot": evidence[ + "platform_policy_snapshot"], + "platform_policy_digest": evidence[ + "platform_policy_digest"], "applied_at": int(time.time()), } await asyncio.to_thread( diff --git a/engine/virsh_panel/libvirt_service.py b/engine/virsh_panel/libvirt_service.py index 046679b7..59e4e61b 100644 --- a/engine/virsh_panel/libvirt_service.py +++ b/engine/virsh_panel/libvirt_service.py @@ -34,7 +34,12 @@ from virsh_panel.cloud_init import ( ) from virsh_panel.metrics import RawVMStats from virsh_panel.inventory_diagnostics import inventory_stage -from virsh_panel.platform_network_policy import PLATFORM_DEFAULT_NETWORK_POLICY +from virsh_panel.platform_network_policy import ( + MAX_PLATFORM_POLICY_SNAPSHOT_BYTES, + PLATFORM_DEFAULT_NETWORK_POLICY, + default_platform_policy_snapshot, + normalize_platform_policy_snapshot, +) from virsh_panel.user_isos import ( MAX_USER_ISO_BYTES, MAX_USER_ISOS, MAX_USER_ISO_TOTAL_BYTES, USER_ISO_ID_RE, USER_ISO_VOLUME_RE, verify_user_iso, @@ -46,8 +51,8 @@ GIB = 1024**3 PANEL_NS = "urn:virsh-panel:1" CLEAN_TRAFFIC_FILTER = "clean-traffic" FIREWALL_FILTER_PREFIX = "vc-fw-" -FIREWALL_FILTER_COMPILER_VERSION = 3 -SUPPORTED_FIREWALL_FILTER_COMPILER_VERSIONS = frozenset({1, 2, 3}) +FIREWALL_FILTER_COMPILER_VERSION = 4 +SUPPORTED_FIREWALL_FILTER_COMPILER_VERSIONS = frozenset({1, 2, 3, 4}) MAX_FIREWALL_RULES = 50 NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,62}\Z") INTERNAL_RESOURCE_PREFIX_LENGTHS = (16, 20, 24, 28, 32) @@ -109,6 +114,142 @@ class VMSnapshotUncertainError(VMError): super().__init__(message, 503, error_code="snapshot_result_uncertain") +def _platform_policy_from_domain_xml( + root: ET.Element, *, require_explicit: bool = False, +) -> dict[str, Any]: + """Read one immutable per-VM snapshot; missing means legacy baseline.""" + managed = root.find(f"./metadata/{{{PANEL_NS}}}managed") + if managed is None: + raise VMError( + "虚拟机缺少面板网络策略元数据", 409, + error_code="firewall_drift_detected", + ) + nodes = managed.findall(f"{{{PANEL_NS}}}platform-policy") + if not nodes: + if require_explicit: + raise VMError( + "虚拟机缺少显式平台网络策略元数据", 409, + error_code="firewall_drift_detected", + ) + return default_platform_policy_snapshot() + if len(nodes) != 1 or set(nodes[0].attrib) != {"version", "digest"}: + raise VMError( + "虚拟机平台网络策略元数据已损坏", 409, + error_code="firewall_drift_detected", + ) + node = nodes[0] + raw = node.text or "" + if (node.get("version") != "1" + or len(raw.encode("utf-8")) > MAX_PLATFORM_POLICY_SNAPSHOT_BYTES): + raise VMError( + "虚拟机平台网络策略元数据已损坏", 409, + error_code="firewall_drift_detected", + ) + try: + decoded = json.loads(raw) + snapshot = normalize_platform_policy_snapshot(decoded) + except (TypeError, ValueError, UnicodeError, json.JSONDecodeError) as exc: + raise VMError( + "虚拟机平台网络策略元数据已损坏", 409, + error_code="firewall_drift_detected", + ) from exc + if not hmac.compare_digest(node.get("digest") or "", snapshot["digest"]): + raise VMError( + "虚拟机平台网络策略摘要已漂移", 409, + error_code="firewall_drift_detected", + ) + return snapshot + + +def _platform_policy_state_from_domain_xml( + root: ET.Element, +) -> tuple[dict[str, Any] | None, bool]: + """Return policy evidence for managed domains; unmanaged domains opt out.""" + managed = root.find(f"./metadata/{{{PANEL_NS}}}managed") + if managed is None: + return None, False + explicit = bool( + managed.findall(f"{{{PANEL_NS}}}platform-policy")) + return ( + _platform_policy_from_domain_xml( + root, require_explicit=explicit), + explicit, + ) + + +def _require_same_platform_policy_state( + root: ET.Element, + expected: dict[str, Any] | None, + *, + require_explicit: bool, + message: str, +) -> None: + """Reject a managed policy change between two already-read definitions.""" + observed, observed_explicit = _platform_policy_state_from_domain_xml(root) + if expected is None: + if observed is None: + return + elif (observed is not None + and observed_explicit == require_explicit + and isinstance(observed.get("digest"), str) + and hmac.compare_digest( + observed["digest"], expected["digest"]) + and observed == expected): + return + raise VMError( + message, 409, + error_code="firewall_drift_detected", + ) + + +def _verify_platform_policy_in_domain( + domain: Any, expected: dict[str, Any], *, require_explicit: bool, +) -> dict[str, Any]: + """Prove a defineXML call retained the intended inactive metadata.""" + try: + root = ET.fromstring( + domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)) + observed = _platform_policy_from_domain_xml( + root, require_explicit=require_explicit) + except Exception as exc: + raise VMError( + "虚拟机平台网络策略写入结果无法确认", 502, + error_code="firewall_result_uncertain", + ) from exc + if (not isinstance(observed.get("digest"), str) + or not hmac.compare_digest( + observed["digest"], expected["digest"]) + or observed != expected): + raise VMError( + "虚拟机平台网络策略写入结果无法确认", 502, + error_code="firewall_result_uncertain", + ) + return observed + + +def _store_platform_policy_in_domain_xml( + managed: ET.Element, snapshot: Any, +) -> dict[str, Any]: + """Persist one canonical snapshot as namespaced, libvirt-retained text.""" + try: + normalized = normalize_platform_policy_snapshot(snapshot) + except ValueError as exc: + raise VMError( + "平台网络策略快照无效", 422, + error_code="firewall_rule_invalid", + ) from exc + for old in managed.findall(f"{{{PANEL_NS}}}platform-policy"): + managed.remove(old) + node = ET.SubElement( + managed, f"{{{PANEL_NS}}}platform-policy", + version="1", digest=normalized["digest"], + ) + node.text = json.dumps( + normalized, ensure_ascii=False, separators=(",", ":"), + ) + return normalized + + def firewall_filter_name(vm_uuid: str) -> str: """Return the stable, host-local nwfilter name for one VM UUID.""" try: @@ -227,6 +368,7 @@ def firewall_policy_digest(enabled: bool, rules: Any) -> str: def build_firewall_filter_xml( vm_uuid: str, enabled: bool, rules: Any, *, compiler_version: int = FIREWALL_FILTER_COMPILER_VERSION, + platform_policy_snapshot: Any = None, ) -> tuple[str, list[dict[str, Any]], str, str]: """Compile a bounded typed policy; callers can never supply raw XML.""" if (isinstance(compiler_version, bool) @@ -248,9 +390,28 @@ def build_firewall_filter_xml( # public interface, so these are public ingress/egress restrictions. priority = 10 direction_names = {"ingress": "in", "egress": "out"} - for platform_rule in PLATFORM_DEFAULT_NETWORK_POLICY.rules: - for direction in platform_rule.directions: - for protocol in platform_rule.protocols: + if compiler_version >= 4: + try: + platform_rules = normalize_platform_policy_snapshot( + platform_policy_snapshot + if platform_policy_snapshot is not None + else default_platform_policy_snapshot() + )["rules"] + except ValueError as exc: + raise VMError( + "平台网络策略快照无效", 422, + error_code="firewall_rule_invalid", + ) from exc + else: + platform_rules = [{ + "protocols": platform_rule.protocols, + "port_from": platform_rule.port_from, + "port_to": platform_rule.port_to, + "directions": platform_rule.directions, + } for platform_rule in PLATFORM_DEFAULT_NETWORK_POLICY.rules] + for platform_rule in platform_rules: + for direction in platform_rule["directions"]: + for protocol in platform_rule["protocols"]: rule = ET.SubElement( root, "rule", action="drop", direction=direction_names[direction], @@ -258,11 +419,16 @@ def build_firewall_filter_xml( ) ET.SubElement( rule, protocol, - dstportstart=str(platform_rule.port_from), - dstportend=str(platform_rule.port_to), + dstportstart=str(platform_rule["port_from"]), + dstportend=str(platform_rule["port_to"]), state="NONE", ) priority += 1 + if priority > 80: + raise VMError( + "平台网络策略超过过滤器优先级预算", 422, + error_code="firewall_rule_invalid", + ) # The product does not provision guest IPv6. Enforce that boundary in # this wrapper as well as in an enabled tenant firewall, otherwise the # IPv4 platform deny list could be bypassed if a bridge later starts @@ -452,7 +618,7 @@ class VMService: interface, public_ip_cidr, CLEAN_TRAFFIC_FILTER) def _ensure_default_firewall_filter( - self, conn: Any, vm_uuid: str, + self, conn: Any, vm_uuid: str, platform_policy_snapshot: Any, ) -> tuple[str, str, bool]: """Define the immutable platform wrapper before a new guest can boot. @@ -461,7 +627,10 @@ class VMService: ours for rollback cleanup. """ expected_xml, _rules, _policy_digest, expected_digest = ( - build_firewall_filter_xml(vm_uuid, False, [])) + build_firewall_filter_xml( + vm_uuid, False, [], + platform_policy_snapshot=platform_policy_snapshot, + )) expected_name = firewall_filter_name(vm_uuid) existing = self._lookup_filter(conn, expected_name) if existing is not None: @@ -2327,6 +2496,9 @@ class VMService: current_xml = self._rescue_vm_preflight(domain) if not self._rescue_xml_matches(current_xml, original_xml): raise VMError("虚拟机配置已变化,请重新提交救援操作", 409) + original_root = ET.fromstring(original_xml) + platform_policy, platform_policy_was_explicit = ( + _platform_policy_state_from_domain_xml(original_root)) pool, volume = self._rescue_volume(conn, rescue_volume_name) original_autostart = bool(domain.autostart()) rescue_xml = self._rescue_xml( @@ -2341,6 +2513,11 @@ class VMService: if rescue_domain is None: raise VMError("宿主机未能保存救援启动配置", 502) switched = True + if platform_policy is not None: + _verify_platform_policy_in_domain( + rescue_domain, platform_policy, + require_explicit=platform_policy_was_explicit, + ) self._restore_rescue_autostart(rescue_domain, original_autostart) staged_xml = rescue_domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) except Exception as exc: @@ -2350,6 +2527,11 @@ class VMService: restored_domain = conn.defineXML(original_xml) if restored_domain is None: raise VMError("宿主机未能恢复原虚拟机配置", 502) + if platform_policy is not None: + _verify_platform_policy_in_domain( + restored_domain, platform_policy, + require_explicit=platform_policy_was_explicit, + ) self._restore_rescue_autostart(restored_domain, original_autostart) except Exception: LOG.exception("Could not restore original VM XML for %s", vm_uuid) @@ -2402,6 +2584,11 @@ class VMService: restored_domain = conn.defineXML(original_xml) if restored_domain is None: raise VMError("宿主机未能恢复原虚拟机配置", 502) + if platform_policy is not None: + _verify_platform_policy_in_domain( + restored_domain, platform_policy, + require_explicit=platform_policy_was_explicit, + ) self._restore_rescue_autostart(restored_domain, original_autostart) restart_domain = restored_domain except Exception: @@ -2521,6 +2708,8 @@ class VMService: if (original_root.findtext("uuid") != vm_uuid or original_root.find(f"./metadata/{{{PANEL_NS}}}rescue") is not None): raise VMError("原虚拟机配置备份与目标虚拟机不匹配", 409) + platform_policy, platform_policy_was_explicit = ( + _platform_policy_state_from_domain_xml(original_root)) target_link_state = "down" if network_suspended else "up" for interface in original_root.findall("./devices/interface"): link = interface.find("link") @@ -2533,6 +2722,11 @@ class VMService: rescue_root = ET.fromstring(rescue_xml) except ET.ParseError as exc: raise VMError("救援虚拟机配置 XML 无效", 502) from exc + _require_same_platform_policy_state( + rescue_root, platform_policy, + require_explicit=platform_policy_was_explicit, + message="救援虚拟机平台网络策略已变化,已停止恢复", + ) marker = rescue_root.find(f"./metadata/{{{PANEL_NS}}}rescue") if (marker is None or marker.get("original-sha256") != self._rescue_original_hash(original_xml) @@ -2562,6 +2756,11 @@ class VMService: if normal_domain is None: raise VMError("宿主机未能恢复原虚拟机配置", 502) switched = True + if platform_policy is not None: + _verify_platform_policy_in_domain( + normal_domain, platform_policy, + require_explicit=platform_policy_was_explicit, + ) self._restore_rescue_autostart(normal_domain, original_autostart) except Exception as exc: if switched: @@ -2569,6 +2768,11 @@ class VMService: rescue_domain = conn.defineXML(rescue_xml) if rescue_domain is None: raise VMError("宿主机未能恢复救援启动配置", 502) + if platform_policy is not None: + _verify_platform_policy_in_domain( + rescue_domain, platform_policy, + require_explicit=platform_policy_was_explicit, + ) self._restore_rescue_autostart( rescue_domain, rescue_autostart) except Exception: @@ -2594,6 +2798,11 @@ class VMService: if normal_domain is None: raise VMError("宿主机未能恢复原虚拟机配置", 502) switched = True + if platform_policy is not None: + _verify_platform_policy_in_domain( + normal_domain, platform_policy, + require_explicit=platform_policy_was_explicit, + ) self._restore_rescue_autostart(normal_domain, original_autostart) normal_domain.create() except Exception as exc: @@ -2612,6 +2821,11 @@ class VMService: restored_domain = conn.defineXML(rescue_xml) if restored_domain is None: raise VMError("宿主机未能恢复救援启动配置", 502) + if platform_policy is not None: + _verify_platform_policy_in_domain( + restored_domain, platform_policy, + require_explicit=platform_policy_was_explicit, + ) self._restore_rescue_autostart(restored_domain, rescue_autostart) restart_domain = restored_domain except Exception: @@ -2687,6 +2901,9 @@ class VMService: managed.set("os-source", "cloud_template") if spec.get("os_name") is not None: managed.set("os-name", spec["os_name"]) + _store_platform_policy_in_domain_xml( + managed, spec.get("platform_network_policy_snapshot") + or default_platform_policy_snapshot()) if self.bridge_name is not None: self._attach_public_filter( interface, public_ip_cidr, firewall_filter_name(vm_uuid)) @@ -2697,6 +2914,18 @@ class VMService: validated = self._validate_common_create(spec) validated["created_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") validated["os_name"] = self._validated_os_name(spec.get("os_name")) + try: + validated["platform_network_policy_snapshot"] = ( + normalize_platform_policy_snapshot( + spec.get("platform_network_policy_snapshot") + if "platform_network_policy_snapshot" in spec + else default_platform_policy_snapshot() + )) + except ValueError as exc: + raise VMError( + "平台网络策略快照无效", 422, + error_code="firewall_rule_invalid", + ) from exc requested_uuid = spec.get("vm_uuid") if requested_uuid is not None: try: @@ -2786,7 +3015,8 @@ class VMService: try: (default_filter_xml, default_filter_digest, created_filter) = self._ensure_default_firewall_filter( - conn, vm_uuid) + conn, vm_uuid, + validated["platform_network_policy_snapshot"]) disk = pool.createXMLFrom(self._volume_xml_bytes( disk_name, template_capacity, "qcow2"), template, 0) if disk is None: @@ -2808,11 +3038,23 @@ class VMService: domain = conn.defineXML(domain_xml) if domain is None: raise VMError("宿主机未能定义云镜像虚拟机", 502) + _verify_platform_policy_in_domain( + domain, validated["platform_network_policy_snapshot"], + require_explicit=True, + ) self._enable_vm_autostart(domain) domain.create() evidence = self._firewall_observation( conn, domain, default_filter_xml) - if not evidence["matches"]: + expected_platform_policy = ( + validated["platform_network_policy_snapshot"]) + if (not evidence["matches"] + or evidence["platform_policy_snapshot"] + != expected_platform_policy + or not hmac.compare_digest( + evidence["platform_policy_digest"], + expected_platform_policy["digest"], + )): raise VMError( "实例已启动但平台默认网络策略校验失败", 502, error_code="firewall_result_uncertain", @@ -2876,6 +3118,15 @@ class VMService: if domain.snapshotNum(0) > 0: raise VMError("虚拟机存在快照,请先处理后再重装", 409) original_root = self._vm_xml(domain) + preflight_root = ET.fromstring( + domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)) + platform_policy, platform_policy_was_explicit = ( + _platform_policy_state_from_domain_xml(preflight_root)) + _require_same_platform_policy_state( + original_root, platform_policy, + require_explicit=platform_policy_was_explicit, + message="虚拟机实时与持久平台网络策略不一致,已停止重装", + ) managed = original_root.find(f"./metadata/{{{PANEL_NS}}}managed") if (managed is None or managed.get("version") != "2" or not managed.get("seed-volume") @@ -2939,6 +3190,11 @@ class VMService: old_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) inactive_root = ET.fromstring(old_xml) inactive_managed = inactive_root.find(f"./metadata/{{{PANEL_NS}}}managed") + _require_same_platform_policy_state( + inactive_root, platform_policy, + require_explicit=platform_policy_was_explicit, + message="关机后虚拟机平台网络策略已变化,重装已停止", + ) inactive_interface = inactive_root.find("./devices/interface") inactive_mac = (inactive_interface.find("mac") if inactive_interface is not None else None) @@ -3018,6 +3274,10 @@ class VMService: if new_domain is None: raise VMError("宿主机未能切换虚拟机定义", 502) switched = True + _verify_platform_policy_in_domain( + new_domain, platform_policy, + require_explicit=platform_policy_was_explicit, + ) new_domain.create() except Exception as exc: if switched: @@ -3046,7 +3306,14 @@ class VMService: restored = True if switched: try: - conn.defineXML(old_xml) + restored_domain = conn.defineXML(old_xml) + if restored_domain is None: + raise VMError("宿主机未能恢复原虚拟机定义", 502) + if platform_policy is not None: + _verify_platform_policy_in_domain( + restored_domain, platform_policy, + require_explicit=platform_policy_was_explicit, + ) except Exception: LOG.exception("Could not restore original definition for %s", vm_id) restored = False @@ -3156,6 +3423,15 @@ class VMService: if domain.snapshotNum(0) > 0: raise VMError("虚拟机存在快照,请先处理后再修改网络", 409) original_root = self._vm_xml(domain) + preflight_root = ET.fromstring( + domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)) + platform_policy, platform_policy_was_explicit = ( + _platform_policy_state_from_domain_xml(preflight_root)) + _require_same_platform_policy_state( + original_root, platform_policy, + require_explicit=platform_policy_was_explicit, + message="虚拟机实时与持久平台网络策略不一致,已停止网络修改", + ) managed = original_root.find(f"./metadata/{{{PANEL_NS}}}managed") if (managed is None or managed.get("version") != "2" or managed.get("os-source") != "cloud_template" @@ -3247,6 +3523,11 @@ class VMService: old_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) inactive_root = ET.fromstring(old_xml) inactive_managed = inactive_root.find(f"./metadata/{{{PANEL_NS}}}managed") + _require_same_platform_policy_state( + inactive_root, platform_policy, + require_explicit=platform_policy_was_explicit, + message="关机后虚拟机平台网络策略已变化,网络修改已停止", + ) inactive_interface = inactive_root.find("./devices/interface") inactive_mac = (inactive_interface.find("mac") if inactive_interface is not None else None) @@ -3290,6 +3571,10 @@ class VMService: if new_domain is None: raise VMError("宿主机未能保存新的虚拟机网络配置", 502) switched = True + _verify_platform_policy_in_domain( + new_domain, platform_policy, + require_explicit=platform_policy_was_explicit, + ) if was_running: phase("starting") try: @@ -3320,6 +3605,11 @@ class VMService: restored_domain = conn.defineXML(old_xml) if restored_domain is None: restored = False + elif platform_policy is not None: + _verify_platform_policy_in_domain( + restored_domain, platform_policy, + require_explicit=platform_policy_was_explicit, + ) except Exception: LOG.exception("Could not restore original VM XML for %s", vm_id) restored = False @@ -3400,6 +3690,15 @@ class VMService: raise VMError("虚拟机存在快照,请先处理后再修改设置", 409) was_running = bool(domain.isActive()) original_root = self._vm_xml(domain) + preflight_root = ET.fromstring( + domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)) + platform_policy, platform_policy_was_explicit = ( + _platform_policy_state_from_domain_xml(preflight_root)) + _require_same_platform_policy_state( + original_root, platform_policy, + require_explicit=platform_policy_was_explicit, + message="虚拟机实时与持久平台网络策略不一致,已停止修改设置", + ) managed = original_root.find(f"./metadata/{{{PANEL_NS}}}managed") if (managed is None or managed.get("version") != "2" or managed.get("os-source") != "cloud_template" @@ -3475,6 +3774,11 @@ class VMService: old_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) inactive_root = ET.fromstring(old_xml) inactive_managed = inactive_root.find(f"./metadata/{{{PANEL_NS}}}managed") + _require_same_platform_policy_state( + inactive_root, platform_policy, + require_explicit=platform_policy_was_explicit, + message="关机后虚拟机平台网络策略已变化,设置修改已停止", + ) if (inactive_managed is None or inactive_managed.get("seed-volume") != old_seed.name() or inactive_managed.get("public-ip-cidr") != managed.get("public-ip-cidr")): @@ -3503,6 +3807,11 @@ class VMService: if new_domain is None: raise VMError("宿主机未能保存新的虚拟机主机名", 502) switched = True + if platform_policy is not None: + _verify_platform_policy_in_domain( + new_domain, platform_policy, + require_explicit=platform_policy_was_explicit, + ) if was_running: phase("starting") start_attempted = True @@ -3549,6 +3858,11 @@ class VMService: restored_domain = conn.defineXML(old_xml) if restored_domain is None: restored = False + elif platform_policy is not None: + _verify_platform_policy_in_domain( + restored_domain, platform_policy, + require_explicit=platform_policy_was_explicit, + ) except Exception: LOG.exception("Could not restore original VM XML for %s", vm_id) restored = False @@ -3941,18 +4255,45 @@ class VMService: expected_name = firewall_filter_name(vm_uuid) inactive = ET.fromstring( domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)) + inactive_managed = inactive.find( + f"./metadata/{{{PANEL_NS}}}managed") + inactive_policy_explicit = bool( + inactive_managed is not None + and inactive_managed.findall(f"{{{PANEL_NS}}}platform-policy") + ) + platform_policy = _platform_policy_from_domain_xml(inactive) _inactive_interface, inactive_ip, inactive_filter = self._firewall_interface( inactive, vm_uuid) live_filter = inactive_filter live_ip = inactive_ip if domain.isActive(): live = ET.fromstring(domain.XMLDesc(0)) + live_managed = live.find(f"./metadata/{{{PANEL_NS}}}managed") + live_policy_explicit = bool( + live_managed is not None + and live_managed.findall(f"{{{PANEL_NS}}}platform-policy") + ) + live_platform_policy = _platform_policy_from_domain_xml(live) + if (inactive_policy_explicit != live_policy_explicit + or not hmac.compare_digest( + platform_policy["digest"], + live_platform_policy["digest"]) + or platform_policy != live_platform_policy): + raise VMError( + "虚拟机实时与持久平台网络策略不一致", 409, + error_code="firewall_drift_detected", + ) _live_interface, live_ip, live_filter = self._firewall_interface( live, vm_uuid) + policy_evidence = { + "platform_policy_snapshot": platform_policy, + "platform_policy_digest": platform_policy["digest"], + } coherent_refs = ( inactive_filter == live_filter and inactive_ip == live_ip) if inactive_filter == CLEAN_TRAFFIC_FILTER: return { + **policy_evidence, "enabled": False, "filter_mode": "baseline", "filter_name": CLEAN_TRAFFIC_FILTER, @@ -3963,6 +4304,7 @@ class VMService: } if inactive_filter != expected_name: return { + **policy_evidence, "enabled": None, "filter_mode": "unknown", "filter_name": inactive_filter, @@ -3974,6 +4316,7 @@ class VMService: filter_object = self._lookup_filter(conn, expected_name) if filter_object is None or not callable(getattr(filter_object, "XMLDesc", None)): return { + **policy_evidence, "enabled": None, "filter_mode": "managed", "filter_name": expected_name, @@ -3996,6 +4339,7 @@ class VMService: matches = (coherent_refs and expected_filter_digest is not None and actual_digest == expected_filter_digest) return { + **policy_evidence, "enabled": enabled, "filter_mode": "managed", "filter_name": expected_name, @@ -4019,11 +4363,15 @@ class VMService: compiler_version: int = FIREWALL_FILTER_COMPILER_VERSION, ) -> dict[str, Any]: """Compare exact host evidence with one target policy; never mutate.""" - (expected_xml, normalized, policy_digest, - expected_filter_digest) = build_firewall_filter_xml( - vm_id, enabled, rules, compiler_version=compiler_version) with self._connect() as conn: domain = self._domain(conn, vm_id) + inactive_root = ET.fromstring( + domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)) + platform_policy = _platform_policy_from_domain_xml(inactive_root) + (expected_xml, normalized, policy_digest, + expected_filter_digest) = build_firewall_filter_xml( + vm_id, enabled, rules, compiler_version=compiler_version, + platform_policy_snapshot=platform_policy) observation = self._firewall_observation( conn, domain, expected_xml) return { @@ -4037,9 +4385,6 @@ class VMService: self, vm_id: str, *, enabled: bool, rules: Any, ) -> dict[str, Any]: """Atomically converge one VM's typed ingress policy where possible.""" - (expected_xml, normalized, policy_digest, - expected_filter_digest) = build_firewall_filter_xml( - vm_id, enabled, rules) expected_name = firewall_filter_name(vm_id) with self._connect() as conn: self._require_clean_traffic_filter(conn) @@ -4053,6 +4398,11 @@ class VMService: error_code="firewall_capability_missing") inactive_root = ET.fromstring( domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)) + platform_policy = _platform_policy_from_domain_xml(inactive_root) + (expected_xml, normalized, policy_digest, + expected_filter_digest) = build_firewall_filter_xml( + vm_id, enabled, rules, + platform_policy_snapshot=platform_policy) inactive_interface, public_ip, old_filter_name = \ self._firewall_interface(inactive_root, domain.UUIDString()) old_inactive_xml = ET.tostring( @@ -5116,6 +5466,9 @@ class VMService: was_running = bool(domain.isActive()) old_xml = domain.XMLDesc( libvirt.VIR_DOMAIN_XML_INACTIVE if domain.isPersistent() else 0) + old_root = ET.fromstring(old_xml) + platform_policy, platform_policy_was_explicit = ( + _platform_policy_state_from_domain_xml(old_root)) old_name = old_disk.name() if expected_old_volume is not None and old_name != expected_old_volume: raise VMSnapshotUncertainError( @@ -5159,6 +5512,11 @@ class VMService: time.sleep(SNAPSHOT_RESTORE_SHUTDOWN_POLL_INTERVAL) inactive_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE) inactive_root = ET.fromstring(inactive_xml) + _require_same_platform_policy_state( + inactive_root, platform_policy, + require_explicit=platform_policy_was_explicit, + message="关机后虚拟机平台网络策略已变化,快照恢复已停止", + ) inactive_managed = inactive_root.find( f"./metadata/{{{PANEL_NS}}}managed") if inactive_managed is None or inactive_managed.get("disk-volume") != old_name: @@ -5209,6 +5567,11 @@ class VMService: else: raise VMSnapshotUncertainError( "恢复系统盘切换结果不确定,已保留新旧磁盘") from exc + if platform_policy is not None: + _verify_platform_policy_in_domain( + new_domain, platform_policy, + require_explicit=platform_policy_was_explicit, + ) warning = None if was_running: if progress is not None: @@ -5279,6 +5642,11 @@ class VMService: if restored_domain is None: restored = False else: + if platform_policy is not None: + _verify_platform_policy_in_domain( + restored_domain, platform_policy, + require_explicit=platform_policy_was_explicit, + ) restored_root = ET.fromstring(restored_domain.XMLDesc( libvirt.VIR_DOMAIN_XML_INACTIVE)) restored_managed = restored_root.find( diff --git a/engine/virsh_panel/platform_network_policy.py b/engine/virsh_panel/platform_network_policy.py index c9202690..284471d7 100644 --- a/engine/virsh_panel/platform_network_policy.py +++ b/engine/virsh_panel/platform_network_policy.py @@ -3,6 +3,8 @@ from __future__ import annotations import json +import hashlib +import hmac import re from dataclasses import dataclass from pathlib import Path @@ -17,6 +19,8 @@ POLICY_MANIFEST_PATH = ( MAX_MANIFEST_BYTES = 65536 MAX_CATALOG_RULES = 100 MAX_PLATFORM_FILTER_RULES = 70 +MAX_PLATFORM_POLICY_SNAPSHOT_BYTES = 32768 +PLATFORM_POLICY_SNAPSHOT_SCHEMA_VERSION = 1 @dataclass(frozen=True) @@ -208,3 +212,193 @@ def load_platform_default_network_policy( PLATFORM_DEFAULT_NETWORK_POLICY = load_platform_default_network_policy() + + +def _rule_document(rule: PlatformNetworkRule | dict[str, Any]) -> dict[str, Any]: + if isinstance(rule, PlatformNetworkRule): + return { + "id": rule.rule_id, + "label": rule.label, + "category": rule.category, + "protocols": list(rule.protocols), + "port_from": rule.port_from, + "port_to": rule.port_to, + "directions": list(rule.directions), + "reason": rule.reason, + } + return { + "id": rule["id"], + "label": rule["label"], + "category": rule["category"], + "protocols": list(rule["protocols"]), + "port_from": rule["port_from"], + "port_to": rule["port_to"], + "directions": list(rule["directions"]), + "reason": rule["reason"], + } + + +def _snapshot_document( + catalog_revision: int, rules: list[dict[str, Any]], +) -> dict[str, Any]: + return { + "schema_version": PLATFORM_POLICY_SNAPSHOT_SCHEMA_VERSION, + "base_policy_version": PLATFORM_DEFAULT_NETWORK_POLICY.policy_version, + "catalog_revision": catalog_revision, + "rules": rules, + } + + +def platform_policy_snapshot_digest(document: dict[str, Any]) -> str: + encoded = json.dumps( + document, ensure_ascii=False, separators=(",", ":"), + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +def default_platform_policy_snapshot() -> dict[str, Any]: + """Return an explicit immutable baseline for legacy/no-test creates.""" + document = _snapshot_document( + 0, [_rule_document(rule) for rule in PLATFORM_DEFAULT_NETWORK_POLICY.rules], + ) + return {**document, "digest": platform_policy_snapshot_digest(document)} + + +def normalize_platform_policy_snapshot(value: Any) -> dict[str, Any]: + """Validate one complete PHP-sealed static+test policy snapshot.""" + expected_keys = { + "schema_version", "base_policy_version", "catalog_revision", + "rules", "digest", + } + if not isinstance(value, dict) or set(value) != expected_keys: + raise ValueError("platform policy snapshot fields are invalid") + revision = value.get("catalog_revision") + digest = value.get("digest") + if (value.get("schema_version") != PLATFORM_POLICY_SNAPSHOT_SCHEMA_VERSION + or value.get("base_policy_version") + != PLATFORM_DEFAULT_NETWORK_POLICY.policy_version + or isinstance(revision, bool) or not isinstance(revision, int) + or not 0 <= revision <= 2**63 - 1 + or not isinstance(digest, str) + or re.fullmatch(r"[0-9a-f]{64}", digest) is None + or not isinstance(value.get("rules"), list)): + raise ValueError("platform policy snapshot is invalid") + + base = [ + _rule_document(rule) for rule in PLATFORM_DEFAULT_NETWORK_POLICY.rules + ] + raw_rules = value["rules"] + if len(raw_rules) < len(base) or raw_rules[:len(base)] != base: + raise ValueError("platform policy baseline does not match this engine") + + expanded: list[tuple[str, int, int, str]] = [ + (protocol, rule.port_from, rule.port_to, direction) + for rule in PLATFORM_DEFAULT_NETWORK_POLICY.rules + for direction in rule.directions + for protocol in rule.protocols + ] + unrestricted = { + (item.protocol, item.port) + for item in PLATFORM_DEFAULT_NETWORK_POLICY.explicitly_unrestricted + } + dynamic: list[dict[str, Any]] = [] + seen_ids: set[str] = set() + rule_keys = { + "id", "label", "category", "protocols", "port_from", "port_to", + "directions", "reason", + } + for index, raw in enumerate(raw_rules[len(base):]): + if (not isinstance(raw, dict) or set(raw) != rule_keys + or raw.get("category") != "test"): + raise ValueError(f"platform test rule {index} is invalid") + rule_id = raw.get("id") + if (not isinstance(rule_id, str) + or re.fullmatch(r"test-[0-9a-f]{32}", rule_id) is None + or rule_id in seen_ids): + raise ValueError(f"platform test rule {index} id is invalid") + seen_ids.add(rule_id) + try: + protocols = _string_tuple( + raw.get("protocols"), {"tcp", "udp"}, + f"platform test rule {index} protocols", + ) + except RuntimeError as exc: + raise ValueError( + f"platform test rule {index} protocols are invalid", + ) from exc + protocols = tuple( + item for item in ("tcp", "udp") if item in protocols + ) + try: + directions = _string_tuple( + raw.get("directions"), {"ingress", "egress"}, + f"platform test rule {index} directions", + ) + except RuntimeError as exc: + raise ValueError( + f"platform test rule {index} directions are invalid", + ) from exc + directions = tuple( + item for item in ("ingress", "egress") if item in directions + ) + port_from = raw.get("port_from") + port_to = raw.get("port_to") + if (isinstance(port_from, bool) or not isinstance(port_from, int) + or isinstance(port_to, bool) or not isinstance(port_to, int) + or not 1 <= port_from <= port_to <= 65535): + raise ValueError(f"platform test rule {index} ports are invalid") + for protocol in protocols: + if any( + blocked_protocol == protocol + and port_from <= blocked_port <= port_to + for blocked_protocol, blocked_port in unrestricted + ): + raise ValueError("explicitly unrestricted port cannot be tested") + for direction in directions: + if any( + old_protocol == protocol and old_direction == direction + and port_from <= old_to and port_to >= old_from + for old_protocol, old_from, old_to, old_direction in expanded + ): + raise ValueError("platform test rules overlap") + expanded.append((protocol, port_from, port_to, direction)) + if len(expanded) > MAX_PLATFORM_FILTER_RULES: + raise ValueError("platform policy exceeds the filter priority budget") + try: + label = _text( + raw.get("label"), f"platform test rule {index} label", + max_bytes=120, + ) + reason = _text( + raw.get("reason"), f"platform test rule {index} reason", + max_bytes=500, + ) + except RuntimeError as exc: + raise ValueError( + f"platform test rule {index} text is invalid", + ) from exc + dynamic.append(_rule_document({ + "id": rule_id, + "label": label, + "category": "test", + "protocols": protocols, + "port_from": port_from, + "port_to": port_to, + "directions": directions, + "reason": reason, + })) + dynamic.sort(key=lambda item: item["id"]) + rules = base + dynamic + if raw_rules != rules: + raise ValueError("platform policy rules are not canonical") + document = _snapshot_document(revision, rules) + expected_digest = platform_policy_snapshot_digest(document) + normalized = {**document, "digest": expected_digest} + encoded = json.dumps( + normalized, ensure_ascii=False, separators=(",", ":"), + ).encode("utf-8") + if len(encoded) > MAX_PLATFORM_POLICY_SNAPSHOT_BYTES: + raise ValueError("platform policy snapshot is too large") + if not hmac.compare_digest(expected_digest, digest): + raise ValueError("platform policy snapshot digest is invalid") + return normalized diff --git a/web/app/Controllers/Admin/CloudPageController.php b/web/app/Controllers/Admin/CloudPageController.php index 43244966..7cfa8f88 100644 --- a/web/app/Controllers/Admin/CloudPageController.php +++ b/web/app/Controllers/Admin/CloudPageController.php @@ -12,6 +12,7 @@ use App\Services\Cloud\CloudCountryCatalog; use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudHostInventoryDiagnostics; use App\Services\Cloud\CloudPlatformDefaultNetworkPolicy; +use App\Services\Cloud\CloudPlatformTestNetworkPolicy; /** Admin pages use local or database-only first paints; JSON APIs repeat authorisation. */ final class CloudPageController extends AdminController @@ -189,7 +190,9 @@ final class CloudPageController extends AdminController } $payload = null; + $testPayload = null; $error = ''; + $testError = ''; $status = 200; try { $payload = CloudPlatformDefaultNetworkPolicy::page(); @@ -199,9 +202,25 @@ final class CloudPageController extends AdminController $error = '平台默认策略暂时无法读取,请检查部署文件。'; $status = 503; } + try { + $testPayload = CloudPlatformTestNetworkPolicy::page(); + } catch (\Throwable $exception) { + error_log('Admin platform test policy failed: ' + . get_class($exception)); + $testError = '手动测试配置暂时无法读取,请确认数据库已升级。'; + $status = 503; + } $smarty = $this->view()->assign([ 'platform_policy' => $payload, 'platform_policy_error' => $error, + 'platform_test_policy' => $testPayload, + 'platform_test_policy_error' => $testError, + 'platform_test_policy_bootstrap_json' => json_encode( + $testPayload, + JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT + | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE + | JSON_THROW_ON_ERROR + ), ]); $response->getBody()->write( $smarty->fetch('admin/cloud/platform_default_policy.tpl') diff --git a/web/app/Controllers/CloudAdminPlatformPolicyController.php b/web/app/Controllers/CloudAdminPlatformPolicyController.php new file mode 100644 index 00000000..69a76e52 --- /dev/null +++ b/web/app/Controllers/CloudAdminPlatformPolicyController.php @@ -0,0 +1,66 @@ +getAttribute('cloud_actor') + ?? CloudAccess::actor(false); + if (!($actor['is_admin'] ?? false)) { + throw new CloudError('需要管理员权限', 403); + } + if ($write) { + CloudAccess::manage($actor); + } + return $actor; + } + + private function json($response, array $payload, int $status = 200) + { + return $response->withJson(['test_policy' => $payload], $status) + ->withHeader('Cache-Control', 'private, no-store'); + } + + public function index($request, $response) + { + $this->actor($request); + return $this->json($response, + CloudPlatformTestNetworkPolicy::page()); + } + + public function create($request, $response) + { + $actor = $this->actor($request, true); + return $this->json($response, + CloudPlatformTestNetworkPolicy::create( + CloudInput::object($request), $actor + ), 201); + } + + public function update($request, $response, $args) + { + $actor = $this->actor($request, true); + return $this->json($response, + CloudPlatformTestNetworkPolicy::update( + (string) ($args['rule_key'] ?? ''), + CloudInput::object($request), $actor + )); + } + + public function delete($request, $response, $args) + { + $actor = $this->actor($request, true); + return $this->json($response, + CloudPlatformTestNetworkPolicy::delete( + (string) ($args['rule_key'] ?? ''), + CloudInput::object($request), $actor + )); + } +} diff --git a/web/app/Middleware/CloudApi.php b/web/app/Middleware/CloudApi.php index 56b30d75..7ad863b4 100644 --- a/web/app/Middleware/CloudApi.php +++ b/web/app/Middleware/CloudApi.php @@ -20,6 +20,7 @@ final class CloudApi || preg_match('#^/api/v1/admin/instances(?:/|$)#D', $path) === 1 || preg_match('#^/api/v1/admin/operations(?:/|$)#D', $path) === 1 || preg_match('#^/api/v1/admin/host-inventory(?:/|$)#D', $path) === 1 + || preg_match('#^/api/v1/admin/platform-test-policy(?:/|$)#D', $path) === 1 || preg_match('#^/api/v1/admin/(?:resources|regions|network-lines|resource-pools|resource-reservations)(?:/|$)#D', $path) === 1 || preg_match('#^/api/v1/admin/hosts/[0-9]+/(?:scheduling|capacity-sync)$#D', $path) === 1 || preg_match('#^/api/v1/ssh-keys(?:/|$)#D', $path) === 1 diff --git a/web/app/Models/CloudPlatformTestPolicyRule.php b/web/app/Models/CloudPlatformTestPolicyRule.php new file mode 100644 index 00000000..5b90f0e1 --- /dev/null +++ b/web/app/Models/CloudPlatformTestPolicyRule.php @@ -0,0 +1,20 @@ + 'int', + 'port_from' => 'int', + 'port_to' => 'int', + 'created_by' => 'int', + 'updated_by' => 'int', + 'deleted_by' => 'int', + 'deleted_at' => 'int', + 'created_at' => 'int', + 'updated_at' => 'int', + ]; +} diff --git a/web/app/Models/CloudPlatformTestPolicyState.php b/web/app/Models/CloudPlatformTestPolicyState.php new file mode 100644 index 00000000..a995b2d8 --- /dev/null +++ b/web/app/Models/CloudPlatformTestPolicyState.php @@ -0,0 +1,16 @@ + 'int', + 'revision' => 'int', + 'updated_by' => 'int', + 'updated_at' => 'int', + ]; +} diff --git a/web/app/Services/Cloud/CloudOrderService.php b/web/app/Services/Cloud/CloudOrderService.php index b0eabefe..e4360e8c 100644 --- a/web/app/Services/Cloud/CloudOrderService.php +++ b/web/app/Services/Cloud/CloudOrderService.php @@ -215,6 +215,19 @@ final class CloudOrderService || !is_array($payload['body'] ?? null)) { throw new CloudError('开通订单的加密请求无效', 409); } + // Freeze the complete effective platform deny policy at the payment + // boundary. An unpaid order therefore receives the current catalog, + // while a queued/retried create can never drift after an administrator + // edits or deletes a test rule. + $platformPolicy = CloudPlatformTestNetworkPolicy::snapshotForProvisioning(); + $payload['body']['platform_network_policy_snapshot'] = $platformPolicy; + $orderSpec = json_decode((string) $order->spec_json, true); + if (!is_array($orderSpec) || array_is_list($orderSpec)) { + throw new CloudError('开通订单的规格快照无效', 409); + } + $orderSpec['platform_network_policy_snapshot'] = $platformPolicy; + $order->spec_json = json_encode($orderSpec, JSON_THROW_ON_ERROR + | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); $offer = CloudOffer::where('id', (int) $order->offer_id) ->lockForUpdate()->first(); $plan = Shop::where('id', (int) $order->plan_id)->lockForUpdate()->first(); diff --git a/web/app/Services/Cloud/CloudPlacementService.php b/web/app/Services/Cloud/CloudPlacementService.php index 2d756201..547badfe 100644 --- a/web/app/Services/Cloud/CloudPlacementService.php +++ b/web/app/Services/Cloud/CloudPlacementService.php @@ -664,6 +664,15 @@ final class CloudPlacementService || (int) ($spec['resource_pool_id'] ?? 0) !== (int) $order->resource_pool_id) { throw new CloudError('订单的销售与资源池快照不一致', 409); } + $specPolicy = CloudPlatformTestNetworkPolicy::assertSnapshot( + $spec['platform_network_policy_snapshot'] ?? null + ); + $payloadPolicy = CloudPlatformTestNetworkPolicy::assertSnapshot( + $body['platform_network_policy_snapshot'] ?? null + ); + if ($specPolicy !== $payloadPolicy) { + throw new CloudError('订单与开通请求的平台网络策略快照不一致', 409); + } return $resources; } diff --git a/web/app/Services/Cloud/CloudPlatformTestNetworkPolicy.php b/web/app/Services/Cloud/CloudPlatformTestNetworkPolicy.php new file mode 100644 index 00000000..eba3620b --- /dev/null +++ b/web/app/Services/Cloud/CloudPlatformTestNetworkPolicy.php @@ -0,0 +1,602 @@ +transaction(function (): array { + $state = self::state(true); + $rows = self::activeQuery('share')->get(); + $dynamic = self::dynamicRulesFromRows($rows); + $rules = []; + foreach ($rows as $row) { + $rules[] = self::displayRow($row); + } + return [ + 'revision' => (int) $state->revision, + 'rules' => $rules, + 'maximum_expanded_rules' => self::MAX_EXPANDED_RULES, + 'base_expanded_rules' => self::baseExpandedCount(), + 'available_expanded_rules' => self::MAX_EXPANDED_RULES + - self::expandedCount($dynamic), + ]; + }, 3); + } + + public static function create(array $input, array $actor): array + { + self::requireManager($actor); + CloudInput::only($input, [ + 'expected_revision', 'service', 'protocol', 'port', 'direction', + 'reason', + ]); + $expected = self::revision($input['expected_revision'] ?? null); + $normalized = self::inputRule($input); + self::connection()->transaction(function () use ( + $actor, $expected, $normalized + ): void { + $state = self::lockedState($expected); + $rows = self::activeQuery('update')->get(); + if ($rows->count() >= self::MAX_TEST_RULES) { + throw new CloudError('手动测试规则数量已达上限', 409); + } + $candidate = self::dynamicRulesFromRows($rows); + $ruleKey = bin2hex(random_bytes(16)); + $candidate[] = self::canonicalDynamicRule($ruleKey, $normalized); + self::validateCombined($candidate); + // Reject an oversized catalog before it can be committed. Without + // this exact serialization check the administrator could save a + // valid-looking directory that makes every later payment fail + // while freezing its provisioning snapshot. + self::snapshot($expected + 1, $candidate); + + $now = time(); + $row = new CloudPlatformTestPolicyRule(); + $row->rule_key = $ruleKey; + self::fillRow($row, $normalized); + $row->created_by = $row->updated_by = (int) $actor['user_id']; + $row->created_at = $row->updated_at = $now; + $row->save(); + self::advance($state, $actor, $now); + }, 3); + return self::page(); + } + + public static function update(string $ruleKey, array $input, + array $actor): array + { + self::requireManager($actor); + self::assertRuleKey($ruleKey); + CloudInput::only($input, [ + 'expected_revision', 'service', 'protocol', 'port', 'direction', + 'reason', + ]); + $expected = self::revision($input['expected_revision'] ?? null); + $normalized = self::inputRule($input); + self::connection()->transaction(function () use ( + $actor, $expected, $normalized, $ruleKey + ): void { + $state = self::lockedState($expected); + $rows = self::activeQuery('update')->get(); + $target = $rows->first(static fn ($row): bool => + hash_equals((string) $row->rule_key, $ruleKey)); + if ($target === null) { + throw new CloudError('手动测试规则不存在', 404); + } + $candidate = []; + foreach ($rows as $row) { + $candidate[] = (string) $row->rule_key === $ruleKey + ? self::canonicalDynamicRule($ruleKey, $normalized) + : self::canonicalDynamicRuleFromRow($row); + } + self::validateCombined($candidate); + self::snapshot($expected + 1, $candidate); + + $now = time(); + self::fillRow($target, $normalized); + $target->updated_by = (int) $actor['user_id']; + $target->updated_at = $now; + $target->save(); + self::advance($state, $actor, $now); + }, 3); + return self::page(); + } + + public static function delete(string $ruleKey, array $input, + array $actor): array + { + self::requireManager($actor); + self::assertRuleKey($ruleKey); + CloudInput::only($input, ['expected_revision']); + $expected = self::revision($input['expected_revision'] ?? null); + self::connection()->transaction(function () use ( + $actor, $expected, $ruleKey + ): void { + $state = self::lockedState($expected); + $row = self::activeQuery('update') + ->where('rule_key', $ruleKey)->first(); + if ($row === null) { + throw new CloudError('手动测试规则不存在', 404); + } + $now = time(); + $row->deleted_by = $row->updated_by = (int) $actor['user_id']; + $row->deleted_at = $row->updated_at = $now; + $row->save(); + self::advance($state, $actor, $now); + }, 3); + return self::page(); + } + + /** Freeze the complete effective policy inside an existing DB transaction. */ + public static function snapshotForProvisioning(): array + { + return self::connection()->transaction(function (): array { + $state = self::state(true); + $dynamic = self::dynamicRulesFromRows( + self::activeQuery('share')->get() + ); + self::validateCombined($dynamic); + return self::snapshot((int) $state->revision, $dynamic); + }, 3); + } + + /** Strictly validate a historical snapshot without consulting live rows. */ + public static function assertSnapshot($value): array + { + if (!is_array($value) || array_is_list($value)) { + throw new CloudError('平台网络策略快照无效', 409); + } + self::assertExactKeys($value, self::SNAPSHOT_KEYS, + '平台网络策略快照'); + $manifest = CloudPlatformDefaultNetworkPolicy::manifest(); + $revision = $value['catalog_revision'] ?? null; + if (($value['schema_version'] ?? null) !== self::SNAPSHOT_SCHEMA_VERSION + || ($value['base_policy_version'] ?? null) + !== $manifest['policy_version'] + || is_bool($revision) || !is_int($revision) || $revision < 0 + || !is_string($value['digest'] ?? null) + || preg_match('/^[a-f0-9]{64}$/D', $value['digest']) !== 1 + || !is_array($value['rules'] ?? null) + || !array_is_list($value['rules'])) { + throw new CloudError('平台网络策略快照无效', 409); + } + + $base = array_map([self::class, 'canonicalRule'], $manifest['rules']); + if (count($value['rules']) < count($base) + || array_slice($value['rules'], 0, count($base)) !== $base) { + throw new CloudError('平台网络策略基础版本不匹配', 409); + } + $dynamic = array_slice($value['rules'], count($base)); + $canonicalDynamic = []; + foreach ($dynamic as $rule) { + if (!is_array($rule) || array_is_list($rule)) { + throw new CloudError('平台网络策略测试规则无效', 409); + } + self::assertExactKeys($rule, self::RULE_KEYS, + '平台网络策略测试规则'); + if (($rule['category'] ?? null) !== 'test' + || !is_string($rule['id'] ?? null) + || preg_match('/^test-[a-f0-9]{32}$/D', $rule['id']) !== 1) { + throw new CloudError('平台网络策略测试规则无效', 409); + } + $canonicalDynamic[] = self::canonicalValidatedRule($rule); + } + usort($canonicalDynamic, static fn (array $left, array $right): int => + strcmp($left['id'], $right['id'])); + if ($dynamic !== $canonicalDynamic) { + throw new CloudError('平台网络策略测试规则顺序无效', 409); + } + self::validateCombined($canonicalDynamic); + $expected = self::snapshot($revision, $canonicalDynamic); + if (!hash_equals($expected['digest'], $value['digest']) + || $expected !== $value) { + throw new CloudError('平台网络策略快照摘要不匹配', 409); + } + return $expected; + } + + private static function snapshot(int $revision, array $dynamic): array + { + $manifest = CloudPlatformDefaultNetworkPolicy::manifest(); + $rules = array_map([self::class, 'canonicalRule'], $manifest['rules']); + foreach ($dynamic as $rule) { + $rules[] = self::canonicalRule($rule); + } + $document = [ + 'schema_version' => self::SNAPSHOT_SCHEMA_VERSION, + 'base_policy_version' => (int) $manifest['policy_version'], + 'catalog_revision' => $revision, + 'rules' => $rules, + ]; + $encoded = json_encode($document, JSON_THROW_ON_ERROR + | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE + | JSON_UNESCAPED_LINE_TERMINATORS); + $snapshot = $document + ['digest' => hash('sha256', $encoded)]; + $snapshotBytes = json_encode($snapshot, JSON_THROW_ON_ERROR + | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE + | JSON_UNESCAPED_LINE_TERMINATORS); + if (strlen($snapshotBytes) > 32768) { + throw new CloudError( + '平台网络策略快照超过 32 KiB,请缩短服务或原因说明', 422 + ); + } + return $snapshot; + } + + private static function validateCombined(array $dynamic): void + { + $manifest = CloudPlatformDefaultNetworkPolicy::manifest(); + $expanded = []; + foreach ($manifest['rules'] as $rule) { + self::addExpanded($expanded, $rule, false); + } + $ids = []; + foreach ($dynamic as $rule) { + $rule = self::canonicalValidatedRule($rule); + if (isset($ids[$rule['id']])) { + throw new CloudError('手动测试规则标识重复', 422); + } + $ids[$rule['id']] = true; + foreach ($rule['protocols'] as $protocol) { + foreach ($manifest['explicitly_unrestricted'] as $entry) { + if ($entry['protocol'] === $protocol + && $entry['port'] >= $rule['port_from'] + && $entry['port'] <= $rule['port_to']) { + throw new CloudError( + '该端口已明确保持不限制,不能加入测试封禁', 422 + ); + } + } + } + self::addExpanded($expanded, $rule, true); + } + if (count($expanded) > self::MAX_EXPANDED_RULES) { + throw new CloudError( + '平台规则展开后超过 70 条,请减少协议或方向组合', 422 + ); + } + } + + private static function addExpanded(array &$expanded, array $rule, + bool $rejectOverlap): void + { + foreach ($rule['protocols'] as $protocol) { + foreach ($rule['directions'] as $direction) { + foreach ($expanded as $existing) { + if ($rejectOverlap + && $existing['protocol'] === $protocol + && $existing['direction'] === $direction + && $rule['port_from'] <= $existing['port_to'] + && $rule['port_to'] >= $existing['port_from']) { + throw new CloudError( + '手动测试规则与现有平台规则重复或重叠', 422 + ); + } + } + $expanded[] = [ + 'protocol' => $protocol, + 'direction' => $direction, + 'port_from' => $rule['port_from'], + 'port_to' => $rule['port_to'], + ]; + } + } + } + + private static function canonicalValidatedRule(array $rule): array + { + $label = self::text($rule['label'] ?? null, 120, '服务'); + $reason = self::text($rule['reason'] ?? null, 500, '原因'); + $protocols = self::enumList($rule['protocols'] ?? null, + ['tcp', 'udp'], '协议'); + $directions = self::enumList($rule['directions'] ?? null, + ['ingress', 'egress'], '方向'); + $from = $rule['port_from'] ?? null; + $to = $rule['port_to'] ?? null; + if (is_bool($from) || !is_int($from) || is_bool($to) || !is_int($to) + || $from < 1 || $to > 65535 || $from > $to) { + throw new CloudError('端口范围无效', 422); + } + return self::canonicalRule([ + 'id' => $rule['id'], + 'label' => $label, + 'category' => 'test', + 'protocols' => $protocols, + 'port_from' => $from, + 'port_to' => $to, + 'directions' => $directions, + 'reason' => $reason, + ]); + } + + private static function inputRule(array $input): array + { + $protocol = $input['protocol'] ?? null; + $direction = $input['direction'] ?? null; + if (!is_string($protocol) + || !in_array($protocol, ['tcp', 'udp', 'tcp_udp'], true)) { + throw new CloudError('协议只能选择 TCP、UDP 或 TCP/UDP', 422); + } + if (!is_string($direction) + || !in_array($direction, ['ingress', 'egress', 'both'], true)) { + throw new CloudError('方向只能选择入站、出站或双向', 422); + } + [$from, $to] = self::port($input['port'] ?? null); + return [ + 'service' => self::text($input['service'] ?? null, 120, '服务'), + 'protocol' => $protocol, + 'port_from' => $from, + 'port_to' => $to, + 'direction' => $direction, + 'reason' => self::text($input['reason'] ?? null, 500, '原因'), + ]; + } + + private static function canonicalDynamicRule(string $ruleKey, + array $rule): array + { + return self::canonicalRule([ + 'id' => 'test-' . $ruleKey, + 'label' => $rule['service'], + 'category' => 'test', + 'protocols' => match ($rule['protocol']) { + 'tcp' => ['tcp'], 'udp' => ['udp'], default => ['tcp', 'udp'], + }, + 'port_from' => $rule['port_from'], + 'port_to' => $rule['port_to'], + 'directions' => match ($rule['direction']) { + 'ingress' => ['ingress'], 'egress' => ['egress'], + default => ['ingress', 'egress'], + }, + 'reason' => $rule['reason'], + ]); + } + + private static function canonicalDynamicRuleFromRow($row): array + { + return self::canonicalDynamicRule((string) $row->rule_key, [ + 'service' => (string) $row->service, + 'protocol' => (string) $row->protocol, + 'port_from' => (int) $row->port_from, + 'port_to' => (int) $row->port_to, + 'direction' => (string) $row->direction, + 'reason' => (string) $row->reason, + ]); + } + + private static function dynamicRulesFromRows($rows): array + { + $rules = []; + foreach ($rows as $row) { + $rules[] = self::canonicalDynamicRuleFromRow($row); + } + usort($rules, static fn (array $left, array $right): int => + strcmp($left['id'], $right['id'])); + return $rules; + } + + private static function canonicalRule(array $rule): array + { + return [ + 'id' => $rule['id'], + 'label' => $rule['label'], + 'category' => $rule['category'], + 'protocols' => array_values($rule['protocols']), + 'port_from' => (int) $rule['port_from'], + 'port_to' => (int) $rule['port_to'], + 'directions' => array_values($rule['directions']), + 'reason' => $rule['reason'], + ]; + } + + private static function displayRow($row): array + { + $port = (int) $row->port_from === (int) $row->port_to + ? (string) $row->port_from + : $row->port_from . '–' . $row->port_to; + return [ + 'id' => (string) $row->rule_key, + 'service' => (string) $row->service, + 'protocol' => (string) $row->protocol, + 'protocol_label' => match ((string) $row->protocol) { + 'tcp' => 'TCP', 'udp' => 'UDP', default => 'TCP/UDP', + }, + 'port' => $port, + 'direction' => (string) $row->direction, + 'direction_label' => match ((string) $row->direction) { + 'ingress' => '仅公网入站', 'egress' => '仅公网出站', + default => '公网入站、出站', + }, + 'reason' => (string) $row->reason, + 'created_at' => (int) $row->created_at, + 'updated_at' => (int) $row->updated_at, + ]; + } + + private static function fillRow($row, array $rule): void + { + $row->service = $rule['service']; + $row->protocol = $rule['protocol']; + $row->port_from = $rule['port_from']; + $row->port_to = $rule['port_to']; + $row->direction = $rule['direction']; + $row->reason = $rule['reason']; + } + + private static function activeQuery(string $lock = '') + { + $query = CloudPlatformTestPolicyRule::whereNull('deleted_at') + ->orderBy('rule_key'); + return match ($lock) { + 'share' => $query->sharedLock(), + 'update' => $query->lockForUpdate(), + default => $query, + }; + } + + private static function state(bool $lock) + { + $query = CloudPlatformTestPolicyState::where('id', self::STATE_ID); + if ($lock) { + $query->sharedLock(); + } + $state = $query->first(); + if ($state === null) { + throw new CloudError('手动测试策略尚未初始化,请先执行 cloudInit', 503); + } + return $state; + } + + private static function lockedState(int $expected) + { + $state = CloudPlatformTestPolicyState::where('id', self::STATE_ID) + ->lockForUpdate()->first(); + if ($state === null) { + throw new CloudError('手动测试策略尚未初始化,请先执行 cloudInit', 503); + } + if ((int) $state->revision !== $expected) { + throw new CloudError('测试策略已被其他管理员更新,请刷新后重试', 409); + } + return $state; + } + + private static function advance($state, array $actor, int $now): void + { + $state->revision = (int) $state->revision + 1; + $state->updated_by = (int) $actor['user_id']; + $state->updated_at = $now; + $state->save(); + } + + private static function requireManager(array $actor): void + { + CloudAccess::manage($actor); + } + + private static function revision($value): int + { + $revision = filter_var($value, FILTER_VALIDATE_INT, + ['options' => ['min_range' => 0, 'max_range' => PHP_INT_MAX]]); + if ($revision === false) { + throw new CloudError('测试策略版本无效', 422); + } + return (int) $revision; + } + + private static function port($value): array + { + if (is_int($value)) { + $value = (string) $value; + } + if (!is_string($value) + || preg_match('/^([0-9]{1,5})(?:-([0-9]{1,5}))?$/D', trim($value), + $matches) !== 1) { + throw new CloudError('端口需为单个端口或起止范围', 422); + } + $from = (int) $matches[1]; + $to = isset($matches[2]) && $matches[2] !== '' + ? (int) $matches[2] : $from; + if ($from < 1 || $to > 65535 || $from > $to) { + throw new CloudError('端口需在 1 至 65535 范围内', 422); + } + return [$from, $to]; + } + + private static function text($value, int $maximum, string $name): string + { + if (!is_string($value)) { + throw new CloudError($name . '不能为空', 422); + } + $value = trim($value); + if ($value === '' || strlen($value) > $maximum + || preg_match('//u', $value) !== 1 + || preg_match('/[\x00-\x1F\x7F]/u', $value) === 1) { + throw new CloudError($name . '格式无效或长度超限', 422); + } + return $value; + } + + private static function enumList($value, array $allowed, + string $name): array + { + if (!is_array($value) || !array_is_list($value) || $value === []) { + throw new CloudError($name . '无效', 422); + } + $seen = []; + foreach ($value as $item) { + if (!is_string($item) || !in_array($item, $allowed, true) + || isset($seen[$item])) { + throw new CloudError($name . '无效', 422); + } + $seen[$item] = true; + } + return array_values(array_filter($allowed, + static fn (string $item): bool => isset($seen[$item]))); + } + + private static function assertRuleKey(string $value): void + { + if (preg_match('/^[a-f0-9]{32}$/D', $value) !== 1) { + throw new CloudError('手动测试规则不存在', 404); + } + } + + private static function assertExactKeys(array $value, array $expected, + string $name): void + { + $actual = array_keys($value); + sort($actual, SORT_STRING); + $wanted = $expected; + sort($wanted, SORT_STRING); + if ($actual !== $wanted) { + throw new CloudError($name . '字段无效', 409); + } + } + + private static function expandedCount(array $dynamic): int + { + $count = self::baseExpandedCount(); + foreach ($dynamic as $rule) { + $count += count($rule['protocols']) * count($rule['directions']); + } + return $count; + } + + private static function baseExpandedCount(): int + { + $count = 0; + foreach (CloudPlatformDefaultNetworkPolicy::manifest()['rules'] as $rule) { + $count += count($rule['protocols']) * count($rule['directions']); + } + return $count; + } + + private static function connection() + { + return (new CloudPlatformTestPolicyState())->getConnection(); + } +} diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php index d1f47bd9..fbb774b4 100644 --- a/web/config/routes_cloud.php +++ b/web/config/routes_cloud.php @@ -91,6 +91,14 @@ $app->group('/api/v1', function () { $this->get('/admin/billing/payments', 'App\Controllers\CloudAdminBillingController:payments'); $this->get('/admin/resources', 'App\Controllers\CloudAdminResourceController:resources'); + $this->get('/admin/platform-test-policy', + 'App\Controllers\CloudAdminPlatformPolicyController:index'); + $this->post('/admin/platform-test-policy/rules', + 'App\Controllers\CloudAdminPlatformPolicyController:create'); + $this->put('/admin/platform-test-policy/rules/{rule_key:[a-f0-9]{32}}', + 'App\Controllers\CloudAdminPlatformPolicyController:update'); + $this->delete('/admin/platform-test-policy/rules/{rule_key:[a-f0-9]{32}}', + 'App\Controllers\CloudAdminPlatformPolicyController:delete'); $this->map(['GET', 'PUT'], '/admin/resources/settings', 'App\Controllers\CloudAdminResourceController:settings'); $this->map(['GET', 'POST'], '/admin/regions', diff --git a/web/public/cloud/admin-platform-policy.js b/web/public/cloud/admin-platform-policy.js new file mode 100644 index 00000000..b128419c --- /dev/null +++ b/web/public/cloud/admin-platform-policy.js @@ -0,0 +1,238 @@ +const root = document.querySelector('[data-platform-test-policy]'); + +if (root) { + const state = { + policy: window.PLATFORM_TEST_POLICY_BOOTSTRAP || { revision: 0, rules: [] }, + canManage: root.dataset.canManage === '1', + busy: false, + frozen: false, + editing: '', + }; + const body = document.getElementById('platform-test-policy-body'); + const form = document.getElementById('platform-test-policy-form'); + const message = document.getElementById('platform-test-policy-message'); + const revision = document.getElementById('platform-test-policy-revision'); + const available = document.getElementById('platform-test-policy-available'); + const fields = { + id: document.getElementById('platform-test-policy-rule-id'), + service: document.getElementById('platform-test-service'), + protocol: document.getElementById('platform-test-protocol'), + port: document.getElementById('platform-test-port'), + direction: document.getElementById('platform-test-direction'), + reason: document.getElementById('platform-test-reason'), + submit: document.getElementById('platform-test-submit'), + cancel: document.getElementById('platform-test-cancel'), + }; + + function showMessage(text, kind = 'danger') { + if (!message) return; + message.textContent = text; + message.className = `alert alert-${kind}`; + } + + function clearMessage() { + if (!message) return; + message.textContent = ''; + message.className = 'alert d-none'; + } + + function setBusy(value) { + state.busy = value; + root.querySelectorAll('button, input, select').forEach((element) => { + element.disabled = Boolean(value || state.frozen); + }); + } + + function cell(row, value, className = '') { + const node = document.createElement('td'); + if (className) node.className = className; + const text = document.createTextNode(String(value ?? '')); + if (className.includes('platform-test-service')) { + const strong = document.createElement('strong'); + strong.appendChild(text); + node.appendChild(strong); + } else if (className.includes('platform-test-port')) { + const code = document.createElement('code'); + code.appendChild(text); + node.appendChild(code); + } else { + node.appendChild(text); + } + row.appendChild(node); + } + + function actionButton(label, action, className) { + const button = document.createElement('button'); + button.type = 'button'; + button.textContent = label; + button.dataset.platformTestAction = action; + button.className = className; + button.disabled = state.busy || state.frozen; + return button; + } + + function render() { + if (!body) return; + body.replaceChildren(); + const rules = Array.isArray(state.policy.rules) ? state.policy.rules : []; + if (rules.length === 0) { + const row = document.createElement('tr'); + row.dataset.platformTestEmpty = ''; + const empty = document.createElement('td'); + empty.colSpan = state.canManage ? 6 : 5; + empty.className = 'text-muted text-center py-4'; + empty.textContent = '当前没有手动测试配置。'; + row.appendChild(empty); + body.appendChild(row); + } else { + rules.forEach((rule) => { + const row = document.createElement('tr'); + row.dataset.ruleId = String(rule.id || ''); + cell(row, rule.service, 'platform-test-service'); + cell(row, rule.protocol_label); + cell(row, rule.port, 'platform-test-port'); + cell(row, rule.direction_label); + cell(row, rule.reason, 'text-muted'); + if (state.canManage) { + const actions = document.createElement('td'); + const group = document.createElement('div'); + group.className = 'd-flex gap-2'; + group.appendChild(actionButton('编辑', 'edit', 'btn btn-sm btn-light')); + group.appendChild(actionButton('删除', 'delete', 'btn btn-sm btn-outline-danger')); + actions.appendChild(group); + row.appendChild(actions); + } + body.appendChild(row); + }); + } + if (revision) revision.textContent = `目录版本 ${Number(state.policy.revision || 0)}`; + if (available) available.textContent = String(state.policy.available_expanded_rules ?? '—'); + setBusy(state.busy); + } + + function resetForm() { + state.editing = ''; + if (!form) return; + form.reset(); + if (fields.id) fields.id.value = ''; + if (fields.submit) fields.submit.textContent = '增加'; + if (fields.cancel) fields.cancel.classList.add('d-none'); + } + + function edit(rule) { + if (!form || !rule || state.busy || state.frozen) return; + state.editing = String(rule.id || ''); + fields.id.value = state.editing; + fields.service.value = String(rule.service || ''); + fields.protocol.value = String(rule.protocol || 'tcp'); + fields.port.value = String(rule.port || '').replace('–', '-'); + fields.direction.value = String(rule.direction || 'ingress'); + fields.reason.value = String(rule.reason || ''); + fields.submit.textContent = '保存'; + fields.cancel.classList.remove('d-none'); + fields.service.focus(); + } + + function requireSecureTransport() { + if (location.protocol === 'https:' + || ['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) return; + throw new Error('请通过 HTTPS 修改平台测试策略。'); + } + + async function api(path, options = {}) { + requireSecureTransport(); + const controller = new AbortController(); + const timer = window.setTimeout(() => controller.abort(), 15000); + try { + const response = await fetch(path, { + method: options.method || 'GET', + credentials: 'same-origin', + cache: 'no-store', + signal: controller.signal, + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'X-CSRF-Token': window.ADMIN_CSRF_TOKEN || '', + }, + body: options.body === undefined ? undefined : JSON.stringify(options.body), + }); + let payload = null; + try { payload = await response.json(); } catch (_error) { /* handled below */ } + if (!response.ok) { + throw new Error(payload?.detail || payload?.error || `请求失败(HTTP ${response.status})`); + } + if (!payload || !payload.test_policy) { + throw new Error('服务返回的数据格式无效,请刷新页面。'); + } + return payload.test_policy; + } finally { + window.clearTimeout(timer); + } + } + + async function mutate(path, method, payload, success) { + if (state.busy || state.frozen) return; + clearMessage(); + setBusy(true); + try { + state.policy = await api(path, { method, body: payload }); + resetForm(); + showMessage(success, 'success'); + render(); + } catch (error) { + if (error?.name === 'AbortError') { + state.frozen = true; + showMessage('请求结果暂时未知。为避免重复修改,本页已停止操作,请刷新后核对目录版本。', 'warning'); + } else { + showMessage(error instanceof Error ? error.message : '操作失败,请重试。'); + } + } finally { + setBusy(false); + } + } + + if (form && state.canManage) { + form.addEventListener('submit', (event) => { + event.preventDefault(); + const id = state.editing; + const payload = { + expected_revision: Number(state.policy.revision || 0), + service: fields.service.value.trim(), + protocol: fields.protocol.value, + port: fields.port.value.trim(), + direction: fields.direction.value, + reason: fields.reason.value.trim(), + }; + mutate( + id ? `/api/v1/admin/platform-test-policy/rules/${encodeURIComponent(id)}` + : '/api/v1/admin/platform-test-policy/rules', + id ? 'PUT' : 'POST', payload, + id ? '测试规则已更新;只影响之后进入开通队列的新实例。' + : '测试规则已增加;只影响之后进入开通队列的新实例。', + ); + }); + fields.cancel?.addEventListener('click', () => { + resetForm(); + clearMessage(); + }); + } + + body?.addEventListener('click', (event) => { + const button = event.target.closest('[data-platform-test-action]'); + const row = button?.closest('[data-rule-id]'); + if (!button || !row || !state.canManage || state.busy || state.frozen) return; + const rule = (state.policy.rules || []).find((item) => String(item.id) === row.dataset.ruleId); + if (!rule) return; + if (button.dataset.platformTestAction === 'edit') { + edit(rule); + return; + } + mutate( + `/api/v1/admin/platform-test-policy/rules/${encodeURIComponent(rule.id)}`, + 'DELETE', { expected_revision: Number(state.policy.revision || 0) }, + '测试规则已从未来配置中删除;已排队和已创建实例保持原策略。', + ); + }); + + render(); +} diff --git a/web/resources/views/venix/admin/cloud/platform_default_policy.tpl b/web/resources/views/venix/admin/cloud/platform_default_policy.tpl index e60182ed..b5a98645 100644 --- a/web/resources/views/venix/admin/cloud/platform_default_policy.tpl +++ b/web/resources/views/venix/admin/cloud/platform_default_policy.tpl @@ -3,7 +3,7 @@ {include file='admin/static_header.tpl'}
-

平台默认策略

查看平台在新建公网云镜像实例上强制执行的 IPv4 端口基线;本页只读。

+

平台默认策略

查看不可变端口基线,并维护仅用于后续新实例的手动测试限制。

{if $platform_policy_error|default:''}{$platform_policy_error|escape}{else}策略版本 v{$platform_policy.policy_version|escape}{/if}
{if $platform_policy_error|default:''} @@ -12,7 +12,7 @@

作用范围

新建公网云镜像实例

规则仅挂载到受管公网网卡;该网卡拒绝 IPv6 以防绕过 IPv4 端口基线,不作用于宿主机管理、未来私网网卡或面板自身流量。

现有实例

不迁移

当前测试环境不会自动修改本策略上线前创建的实例。

-

页面边界

只展示目标策略

不统计宿主机或实例的实时执行状态,也不提供解封或编辑操作。

+

优先级边界

平台拒绝优先

平台与测试拒绝规则先于用户允许规则生效;用户允许同一端口不会绕过平台限制。本页不统计宿主机实时执行状态。

永久限制

平台强制规则,不能由用户自定义防火墙覆盖,也不进入后续例外申请流程。

@@ -33,5 +33,37 @@
{/if} +
+
+

手动测试配置

这里的 deny-only 规则只封存到之后支付并进入开通队列的新公网云镜像实例。编辑或删除不会改变已排队、已创建实例,也不会触发宿主机同步。

+ 目录版本 {if $platform_test_policy}{$platform_test_policy.revision|escape}{else}—{/if} +
+
+ {if $platform_test_policy_error|default:''} + + {else} + {if $admin_can_manage|default:false} +
+ +
+
+
+
+
+
+
+ {/if} +
当前静态基线占用 {$platform_test_policy.base_expanded_rules|escape} 条展开规则,测试目录还可使用 {$platform_test_policy.available_expanded_rules|escape} 条。TCP 587 及与静态基线重复或重叠的规则会被拒绝。
+
+
{if $admin_can_manage|default:false}{/if} + {foreach $platform_test_policy.rules|default:[] as $rule}{if $admin_can_manage|default:false}{/if}{foreachelse}{/foreach} +
只用于后续新实例的手动测试限制
服务协议端口方向原因操作
{$rule.service|escape}{$rule.protocol_label|escape}{$rule.port|escape}{$rule.direction_label|escape}{$rule.reason|escape}
当前没有手动测试配置。
+ {/if} +
+
+{if !$platform_test_policy_error|default:''} + + +{/if} {include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 0099acf4..64708400 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026100504' scope='global'} +{assign var=venix_asset_version value='2026100505' scope='global'} diff --git a/web/sql/cloud.sql b/web/sql/cloud.sql index 06714e9a..4df56fff 100644 --- a/web/sql/cloud.sql +++ b/web/sql/cloud.sql @@ -453,6 +453,36 @@ CREATE TABLE IF NOT EXISTS cloud_instance_firewall_rules ( UNIQUE KEY cloud_instance_firewall_rule_sequence (version_id, sequence), KEY cloud_instance_firewall_rule_version (version_id, id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +-- Administrator-owned deny-only test catalog. The single state row provides +-- optimistic concurrency and a stable revision for provisioning snapshots. +-- Rules are soft-deleted for audit, but deployed instances never read this +-- catalog again: their effective policy is sealed into the create job. +CREATE TABLE IF NOT EXISTS cloud_platform_test_policy_state ( + id TINYINT UNSIGNED NOT NULL PRIMARY KEY, + revision BIGINT UNSIGNED NOT NULL DEFAULT 0, + updated_by BIGINT UNSIGNED DEFAULT NULL, + updated_at BIGINT UNSIGNED NOT NULL DEFAULT 0 +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +INSERT IGNORE INTO cloud_platform_test_policy_state + (id, revision, updated_by, updated_at) VALUES (1, 0, NULL, 0); +CREATE TABLE IF NOT EXISTS cloud_platform_test_policy_rules ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + rule_key CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + service VARCHAR(120) NOT NULL, + protocol VARCHAR(8) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + port_from SMALLINT UNSIGNED NOT NULL, + port_to SMALLINT UNSIGNED NOT NULL, + direction VARCHAR(8) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + reason VARCHAR(500) NOT NULL, + created_by BIGINT UNSIGNED NOT NULL, + updated_by BIGINT UNSIGNED NOT NULL, + deleted_by BIGINT UNSIGNED DEFAULT NULL, + deleted_at BIGINT UNSIGNED DEFAULT NULL, + created_at BIGINT UNSIGNED NOT NULL, + updated_at BIGINT UNSIGNED NOT NULL, + UNIQUE KEY cloud_platform_test_policy_rule_key (rule_key), + KEY cloud_platform_test_policy_active (deleted_at, id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- PHP-owned catalog for same-host local recovery points. Only opaque keys and -- bounded metadata are stored here; engine volume names and host paths never -- cross into the business database or tenant API. diff --git a/web/tests/AdminPlatformDefaultNetworkPolicyTest.php b/web/tests/AdminPlatformDefaultNetworkPolicyTest.php index 0786f37c..f0271a16 100644 --- a/web/tests/AdminPlatformDefaultNetworkPolicyTest.php +++ b/web/tests/AdminPlatformDefaultNetworkPolicyTest.php @@ -117,6 +117,11 @@ $routes = file_get_contents($root . '/config/routes.php'); $apiRoutes = file_get_contents($root . '/config/routes_cloud.php'); $controller = file_get_contents( $root . '/app/Controllers/Admin/CloudPageController.php'); +$apiController = file_get_contents( + $root . '/app/Controllers/CloudAdminPlatformPolicyController.php'); +$middleware = file_get_contents($root . '/app/Middleware/CloudApi.php'); +$browser = file_get_contents($root . '/public/cloud/admin-platform-policy.js'); +$schema = file_get_contents($root . '/sql/cloud.sql'); $header = file_get_contents( $root . '/resources/views/venix/admin/static_header.tpl'); $userSidebar = file_get_contents( @@ -128,14 +133,34 @@ $assert(substr_count($routes, $assert(!str_contains($routes, "post('/platform-default-policy'") && !str_contains($routes, "put('/platform-default-policy'") && !str_contains($routes, "delete('/platform-default-policy'") - && !str_contains($apiRoutes, 'platform-default-policy'), - 'The read-only page gained a write or API route.'); + && str_contains($apiRoutes, "get('/admin/platform-test-policy'") + && str_contains($apiRoutes, "post('/admin/platform-test-policy/rules'") + && str_contains($apiRoutes, "put('/admin/platform-test-policy/rules/{rule_key:[a-f0-9]{32}}'") + && str_contains($apiRoutes, "delete('/admin/platform-test-policy/rules/{rule_key:[a-f0-9]{32}}'"), + 'The immutable page route or separate test-policy CRUD routes changed.'); $assert(str_contains($controller, 'public function platformDefaultPolicy(') && str_contains($controller, 'CloudPlatformDefaultNetworkPolicy::page()') + && str_contains($controller, 'CloudPlatformTestNetworkPolicy::page()') && str_contains($controller, 'CloudAccess::actor(false)') && str_contains($controller, "Cache-Control', 'private, no-store"), 'The page controller lost strict local policy loading or private admin authorization.'); +$assert(str_contains($apiController, 'CloudAccess::manage($actor)') + && str_contains($apiController, 'CloudPlatformTestNetworkPolicy::create(') + && str_contains($apiController, 'CloudPlatformTestNetworkPolicy::update(') + && str_contains($apiController, 'CloudPlatformTestNetworkPolicy::delete(') + && str_contains($middleware, '/api/v1/admin/platform-test-policy') + && !str_contains($apiController, 'CloudEngineClient'), + 'Test-policy writes lost super-admin enforcement or became engine-coupled.'); +$assert(str_contains($schema, + 'CREATE TABLE IF NOT EXISTS cloud_platform_test_policy_state (') + && str_contains($schema, + 'CREATE TABLE IF NOT EXISTS cloud_platform_test_policy_rules (') + && str_contains($schema, 'deleted_at BIGINT UNSIGNED DEFAULT NULL') + && str_contains($browser, 'expected_revision') + && str_contains($browser, "method, body: payload") + && str_contains($browser, '请求结果暂时未知'), + 'The revisioned soft-delete catalog or safe browser mutation contract is missing.'); $assert(str_contains($header, 'href="/admin/platform-default-policy"') && str_contains($header, "\$admin_active|default:'' == 'platform-default-policy'"), @@ -155,9 +180,39 @@ $smarty->assign('cdn', ''); $smarty->assign('user', (object) ['isLogin' => false]); $smarty->assign('admin_can_manage', false); $smarty->assign('admin_csrf_token', 'fixture-not-a-real-token'); -$render = static function (?array $value, string $error = '') use ($smarty): string { +$testPage = [ + 'revision' => 3, + 'maximum_expanded_rules' => 70, + 'base_expanded_rules' => 26, + 'available_expanded_rules' => 43, + 'rules' => [[ + 'id' => str_repeat('a', 32), + 'service' => 'Temporary test', + 'protocol' => 'tcp', + 'protocol_label' => 'TCP', + 'port' => '8080', + 'direction' => 'ingress', + 'direction_label' => '仅公网入站', + 'reason' => 'Only future paid creates receive this snapshot.', + 'created_at' => 1, + 'updated_at' => 2, + ]], +]; +$render = static function (?array $value, string $error = '', + ?array $testValue = null, string $testError = '', + bool $canManage = false) use ($smarty, $testPage): string { + $testValue ??= $testPage; $smarty->assign('platform_policy', $value); $smarty->assign('platform_policy_error', $error); + $smarty->assign('platform_test_policy', $testValue); + $smarty->assign('platform_test_policy_error', $testError); + $smarty->assign('admin_can_manage', $canManage); + $smarty->assign('platform_test_policy_bootstrap_json', json_encode( + $testValue, + JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT + | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE + | JSON_THROW_ON_ERROR + )); return $smarty->fetch('admin/cloud/platform_default_policy.tpl'); }; $html = $render($page); @@ -176,17 +231,30 @@ foreach ($xpath->query('//tbody[@id="platform-policy-permanent-body" or @id="pla $assert(!str_contains($restrictedText, '587') && str_contains($xpath->query('//tbody[@id="platform-policy-unrestricted-body"]')->item(0)->textContent, '587'), 'TCP 587 appeared in the restricted tables or disappeared from metadata.'); -$assert($xpath->query('//main[@data-admin-platform-default-policy]//form - | //main[@data-admin-platform-default-policy]//button - | //main[@data-admin-platform-default-policy]//script')->length === 0, - 'The administrator policy page must remain pure read-only SSR.'); +$assert($xpath->query('//form[@id="platform-test-policy-form"] + | //*[@data-platform-test-edit] + | //*[@data-platform-test-delete]')->length === 0 + && $xpath->query('//tbody[@id="platform-test-policy-body"]/tr')->length === 1 + && $xpath->query('//script[contains(@src, "admin-platform-policy.js")]')->length === 1, + 'A read-only administrator received mutation controls or lost test-policy visibility.'); $assert($xpath->query('//a[@href="/admin/platform-default-policy" and contains(concat(" ", normalize-space(@class), " "), " active ")]')->length === 1, 'The audit navigation does not identify the active policy page.'); $assert(str_contains($dom->textContent, '不迁移') && str_contains($dom->textContent, '拒绝 IPv6 以防绕过 IPv4 端口基线') && str_contains($dom->textContent, '例外申请、审核和解除逻辑尚未实现') - && str_contains($dom->textContent, '不统计宿主机或实例的实时执行状态'), - 'The page overclaims migration, exception handling, or observed enforcement.'); + && str_contains($dom->textContent, '平台拒绝优先') + && str_contains($dom->textContent, '已排队、已创建实例') + && str_contains($dom->textContent, '不统计宿主机实时执行状态'), + 'The page overclaims migration, exceptions, observed enforcement or retroactive edits.'); + +$managerHtml = $render($page, '', $testPage, '', true); +$managerDom = new DOMDocument(); +$managerDom->loadHTML('' . $managerHtml); +$managerXpath = new DOMXPath($managerDom); +$assert($managerXpath->query('//form[@id="platform-test-policy-form"]')->length === 1 + && $managerXpath->query('//*[@data-platform-test-edit]')->length === 1 + && $managerXpath->query('//*[@data-platform-test-delete]')->length === 1, + 'A super administrator cannot create, edit and delete test rules.'); $unsafe = $page; $unsafe['permanent_rules'][0]['label'] = ''; @@ -196,9 +264,26 @@ $xpath = new DOMXPath($dom); $assert($xpath->query('//*[@onerror]')->length === 0 && str_contains($dom->textContent, ''), 'Manifest text was rendered as executable markup.'); +$unsafeTest = $testPage; +$unsafeTest['rules'][0]['service'] = ''; +$unsafeTest['rules'][0]['reason'] = ''; +$unsafeTestHtml = $render($page, '', $unsafeTest, '', true); +$dom->loadHTML('' . $unsafeTestHtml); +$xpath = new DOMXPath($dom); +$assert($xpath->query('//*[@onerror]')->length === 0 + && $xpath->query('//*[@data-platform-test-policy]//img')->length === 0 + && str_contains($dom->textContent, + '') + && str_contains($dom->textContent, ''), + 'Test-policy SSR or JSON bootstrap rendered administrator text as markup.'); $failed = $render(null, '策略清单暂时无法读取,请检查部署文件。'); $assert(str_contains($failed, '策略清单暂时无法读取,请检查部署文件。') && !str_contains($failed, '平台永久限制规则'), 'An unavailable manifest was disguised as an empty successful policy.'); +$testFailed = $render($page, '', null, + '手动测试配置暂时无法读取,请确认数据库已升级。'); +$assert(str_contains($testFailed, '手动测试配置暂时无法读取,请确认数据库已升级。') + && !str_contains($testFailed, 'admin-platform-policy.js'), + 'An unavailable test catalog exposed stale mutation controls.'); -echo "Administrator platform default network policy manifest, validation, route and SSR contracts passed.\n"; +echo "Administrator platform network policy manifest, test catalog, route and SSR contracts passed.\n"; diff --git a/web/tests/CloudFinancialWorkflowTest.php b/web/tests/CloudFinancialWorkflowTest.php index 91915a85..4e532ee3 100644 --- a/web/tests/CloudFinancialWorkflowTest.php +++ b/web/tests/CloudFinancialWorkflowTest.php @@ -50,6 +50,7 @@ namespace { use App\Services\Cloud\CloudInstanceDiscovery; use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudMoney; + use App\Services\Cloud\CloudPlatformTestNetworkPolicy; use App\Services\Cloud\CloudDeploymentPageService; use App\Services\Cloud\CloudTemplateDeletionService; use GuzzleHttp\Client; @@ -79,6 +80,8 @@ namespace { $schema->create('cloud_offers', function (Blueprint $t) { $t->increments('id'); $t->integer('plan_id'); $t->integer('resource_pool_id'); $t->string('code')->unique(); $t->string('name'); $t->string('price'); $t->string('currency')->default('USD'); $t->integer('price_version')->default(1); $t->integer('revision')->default(1); $t->integer('status')->default(1); $t->integer('stock')->default(-1); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['plan_id', 'resource_pool_id']); }); $schema->create('cloud_template_retirements', function (Blueprint $t) { $t->string('template_id')->primary(); $t->string('state')->default('deleting'); $t->integer('template_created_at')->default(0); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_template_catalog_locks', function (Blueprint $t) { $t->integer('id')->primary(); $t->integer('updated_at'); $t->string('lease_token')->nullable(); $t->string('lease_kind')->nullable(); $t->integer('lease_until')->default(0); }); + $schema->create('cloud_platform_test_policy_state', function (Blueprint $t) { $t->integer('id')->primary(); $t->integer('revision')->default(0); $t->integer('updated_by')->nullable(); $t->integer('updated_at')->default(0); }); + $schema->create('cloud_platform_test_policy_rules', function (Blueprint $t) { $t->increments('id'); $t->string('rule_key', 32)->unique(); $t->string('service', 120); $t->string('protocol', 8); $t->integer('port_from'); $t->integer('port_to'); $t->string('direction', 8); $t->string('reason', 500); $t->integer('created_by'); $t->integer('updated_by'); $t->integer('deleted_by')->nullable(); $t->integer('deleted_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_orders', function (Blueprint $t) { $t->increments('id'); foreach (['user_id', 'plan_id', 'offer_id', 'resource_pool_id'] as $v) { $t->integer($v); } $t->integer('host_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->string('currency')->default('USD'); $t->string('status'); $t->text('spec_json'); $t->text('payload_cipher')->nullable(); $t->integer('instance_id')->nullable(); $t->integer('refunded_at')->nullable(); $t->integer('stock_reserved_at')->nullable(); $t->integer('stock_released_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); }); $schema->create('cloud_resource_reservations', function (Blueprint $t) { $t->increments('id'); $t->string('reservation_key')->unique(); $t->string('operation_id')->unique(); foreach (['order_id', 'offer_id', 'resource_pool_id', 'host_id', 'user_id'] as $v) { $t->integer($v); } $t->integer('instance_id')->nullable(); $t->integer('network_attachment_id')->nullable(); $t->integer('public_ip_pool_id')->nullable(); $t->integer('public_ip_id')->nullable(); foreach (['cpu_cores', 'memory_mib', 'disk_gib'] as $v) { $t->integer($v); } $t->string('state'); $t->integer('expires_at')->nullable(); $t->integer('released_at')->nullable(); $t->string('release_reason')->default(''); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); }); $schema->create('cloud_jobs', function (Blueprint $t) { $t->increments('id'); $t->string('operation_id')->unique(); foreach (['order_id', 'instance_id', 'snapshot_id'] as $v) { $t->integer($v)->nullable(); } foreach (['user_id', 'host_id'] as $v) { $t->integer($v); } $t->string('kind'); $t->string('status'); $t->text('payload_cipher'); $t->integer('attempts')->default(0); $t->integer('dispatched_at')->nullable(); $t->string('lease_token')->nullable(); $t->integer('lease_until')->default(0); $t->integer('available_at'); $t->string('error_code')->nullable(); $t->text('result_json')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); }); @@ -89,6 +92,9 @@ namespace { $schema->create('cloud_invoice_payments', function (Blueprint $t) { $t->increments('id'); $t->integer('invoice_id'); $t->integer('user_id'); $t->string('provider'); $t->string('provider_order_no'); $t->string('idempotency_key'); $t->string('amount'); $t->string('status'); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['provider', 'provider_order_no']); $t->unique(['user_id', 'idempotency_key']); }); $schema->create('cloud_mail_outbox', function (Blueprint $t) { $t->increments('id'); $t->integer('invoice_id'); $t->string('kind'); $t->string('status'); $t->integer('attempts'); $t->integer('available_at'); $t->string('lease_token')->nullable(); $t->integer('lease_until'); $t->integer('sent_at')->nullable(); $t->string('last_error'); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['invoice_id', 'kind']); }); $schema->create('cloud_ssh_keys', function (Blueprint $t) { $t->increments('id'); $t->integer('user_id'); $t->string('name'); $t->text('public_key'); $t->string('fingerprint'); $t->integer('created_at'); }); + $capsule->connection('default')->table( + 'cloud_platform_test_policy_state' + )->insert(['id' => 1, 'revision' => 0, 'updated_by' => null, 'updated_at' => 0]); $user = new User(); $user->id = 1; $user->money = '0.00'; $user->enable = 1; $user->is_admin = false; $user->save(); $user->isLogin = true; \App\Services\Auth::$user = $user; $now = time(); @@ -278,6 +284,19 @@ namespace { $changedPlan->memory_mib = 8192; $changedPlan->disk_gib = 80; $changedPlan->save(); + $policyManager = [ + 'user_id' => 99, 'is_admin' => true, + 'is_super_admin' => true, 'can_manage' => true, + ]; + $testCatalog = CloudPlatformTestNetworkPolicy::create([ + 'expected_revision' => 0, + 'service' => 'Provision snapshot test', + 'protocol' => 'tcp', + 'port' => '8080', + 'direction' => 'ingress', + 'reason' => 'Verify queued creates retain deleted catalog rules.', + ], $policyManager); + $testRuleKey = (string) $testCatalog['rules'][0]['id']; $paidOpening = CloudInvoiceService::payBalance( $openingInvoice, $actor, 'provision-balance-test-0001'); $paidOpeningAgain = CloudInvoiceService::payBalance( @@ -285,6 +304,28 @@ namespace { $openingOrder = CloudOrder::find($first->id); $openingReservation = CloudResourceReservation::where('order_id', $first->id)->first(); $openingJob = CloudJob::where('order_id', $first->id)->first(); + $queuedCreate = \App\Services\Cloud\CloudSecrets::decrypt( + (string) $openingJob->payload_cipher + ); + $queuedPolicy = $queuedCreate['body']['platform_network_policy_snapshot'] ?? null; + $orderPolicy = json_decode( + (string) $openingOrder->spec_json, true, + flags: JSON_THROW_ON_ERROR + )['platform_network_policy_snapshot'] ?? null; + CloudPlatformTestNetworkPolicy::delete( + $testRuleKey, ['expected_revision' => 1], $policyManager + ); + $currentPolicy = CloudPlatformTestNetworkPolicy::snapshotForProvisioning(); + $sealedJobAfterDelete = CloudJob::where('order_id', $first->id)->first(); + $sealedCreateAfterDelete = \App\Services\Cloud\CloudSecrets::decrypt( + (string) $sealedJobAfterDelete->payload_cipher + ); + $queuedPolicyAfterDelete = $sealedCreateAfterDelete['body'] + ['platform_network_policy_snapshot'] ?? null; + $orderPolicyAfterDelete = json_decode( + (string) CloudOrder::find($first->id)->spec_json, true, + flags: JSON_THROW_ON_ERROR + )['platform_network_policy_snapshot'] ?? null; $assert((string) $paidOpeningAgain->status === 'paid' && User::find(1)->money === '90.01' && $openingOrder->status === 'queued' @@ -300,8 +341,18 @@ namespace { && (string) $openingJob->operation_id === (string) $openingReservation->operation_id && CloudPublicIp::find($openingReservation->public_ip_id)->state === 'reserved' && CloudJob::where('order_id', $first->id)->count() === 1 + && is_array($queuedPolicy) + && $queuedPolicy === $orderPolicy + && ($queuedPolicy['catalog_revision'] ?? null) === 1 + && ($queuedPolicy['rules'][9]['id'] ?? null) === 'test-' . $testRuleKey + && $queuedPolicyAfterDelete === $queuedPolicy + && $orderPolicyAfterDelete === $queuedPolicy + && ($currentPolicy['catalog_revision'] ?? null) === 2 + && count($currentPolicy['rules']) === 9 + && CloudPlatformTestNetworkPolicy::assertSnapshot($queuedPolicy) + === $queuedPolicy && $openingOrder->payload_cipher === null, - 'Opening invoice payment was not an atomic, exactly-once transition into the provisioning queue.'); + 'Opening payment did not atomically freeze an immutable per-instance platform policy.'); $changedPlan->cpu_cores = 2; $changedPlan->memory_mib = 2048; $changedPlan->disk_gib = 20; @@ -396,6 +447,8 @@ namespace { $assert($posted['vcpu'] === 2 && $posted['bandwidth_mbps'] === 100 && $posted['network'] === 'bridge:br0' && $posted['public_pool_key'] === $sourcePoolKey + && ($posted['platform_network_policy_snapshot'] ?? null) + === $queuedPolicy && $signedActor['can_provision'] === true && $signedActor['can_manage'] === true, 'Plan or provisioning authority lost.'); $assert(!str_contains(CloudJob::first()->result_json, 'must-not-persist'), 'Plain password saved in result.'); $terminalPayload = \App\Services\Cloud\CloudSecrets::decrypt( @@ -1184,12 +1237,20 @@ namespace { 'paytaro', 'PT-PROVISION-0001'); $providerOutcomeAgain = CloudInvoicePaymentService::settleForProvider( 'paytaro', 'PT-PROVISION-0001'); + $providerQueuedCreate = \App\Services\Cloud\CloudSecrets::decrypt( + (string) CloudJob::where('order_id', $providerOrder->id) + ->first()->payload_cipher + ); + $providerPolicy = $providerQueuedCreate['body'] + ['platform_network_policy_snapshot'] ?? null; $assert($providerOutcome === 'paid_invoice' && $providerOutcomeAgain === 'paid_invoice' && CloudMoney::cents((string) User::find(1)->money) === $balanceBeforeProviderCredit && CloudInvoice::find($providerInvoice->id)->status === 'paid' && CloudOrder::find($providerOrder->id)->status === 'queued' - && CloudJob::where('order_id', $providerOrder->id)->count() === 1, + && CloudJob::where('order_id', $providerOrder->id)->count() === 1 + && ($providerPolicy['catalog_revision'] ?? null) === 2 + && count($providerPolicy['rules'] ?? []) === 9, 'Provider callback did not settle an opening invoice exactly once.'); // A blank optional label is normalized before hashing, but generated only diff --git a/web/tests/CloudFirewallUiContractTest.php b/web/tests/CloudFirewallUiContractTest.php index d4764b22..7afe3e1a 100644 --- a/web/tests/CloudFirewallUiContractTest.php +++ b/web/tests/CloudFirewallUiContractTest.php @@ -18,7 +18,7 @@ $assert(str_contains($template, 'data-instance-setting-tab="firewall"') && str_contains($template, 'id="vm-firewall-rules"'), 'Instance settings must expose the integrated firewall tab and whole-policy editor.'); -$assert(str_contains($assets, "venix_asset_version value='2026100504'"), +$assert(str_contains($assets, "venix_asset_version value='2026100505'"), 'Shared Venix asset cache key must publish the firewall JavaScript and CSS.'); $assert(str_contains($template, '反欺骗保护始终开启') diff --git a/web/tests/CloudPlatformTestNetworkPolicyTest.php b/web/tests/CloudPlatformTestNetworkPolicyTest.php new file mode 100644 index 00000000..9f61bc94 --- /dev/null +++ b/web/tests/CloudPlatformTestNetworkPolicyTest.php @@ -0,0 +1,211 @@ +httpStatus === $status, + $message . ' Unexpected status: ' . $error->httpStatus); + return; + } + throw new RuntimeException($message); +}; + +$capsule = new Capsule(); +$capsule->addConnection([ + 'driver' => 'sqlite', 'database' => ':memory:', +], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); +$schema->create('cloud_platform_test_policy_state', static function ( + Blueprint $table): void { + $table->integer('id')->primary(); + $table->integer('revision')->default(0); + $table->integer('updated_by')->nullable(); + $table->integer('updated_at')->default(0); +}); +$schema->create('cloud_platform_test_policy_rules', static function ( + Blueprint $table): void { + $table->increments('id'); + $table->string('rule_key', 32)->unique(); + $table->string('service', 120); + $table->string('protocol', 8); + $table->integer('port_from'); + $table->integer('port_to'); + $table->string('direction', 8); + $table->string('reason', 500); + $table->integer('created_by'); + $table->integer('updated_by'); + $table->integer('deleted_by')->nullable(); + $table->integer('deleted_at')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$state = new CloudPlatformTestPolicyState(); +$state->id = 1; +$state->revision = 0; +$state->updated_by = null; +$state->updated_at = 0; +$state->save(); + +$manager = [ + 'user_id' => 1, 'is_admin' => true, + 'is_super_admin' => true, 'can_manage' => true, +]; +$regularAdmin = [ + 'user_id' => 2, 'is_admin' => true, + 'is_super_admin' => false, 'can_manage' => false, +]; +$input = [ + 'expected_revision' => 0, + 'service' => 'Temporary web test', + 'protocol' => 'tcp', + 'port' => '8080', + 'direction' => 'ingress', + 'reason' => 'Verify one future-instance snapshot.', +]; + +$empty = Policy::page(); +$defaultSnapshot = Policy::snapshotForProvisioning(); +$assert($empty['revision'] === 0 && $empty['rules'] === [] + && $empty['base_expanded_rules'] === 26 + && $empty['available_expanded_rules'] === 44 + && $defaultSnapshot['catalog_revision'] === 0 + && count($defaultSnapshot['rules']) === 9 + && $defaultSnapshot['digest'] + === 'df7199f5f6ab5419403347be0c6fa7aee0009716d8b2111a36f8644ed59dc5bf', + 'The empty catalog does not match the cross-language baseline snapshot.'); + +$lineTerminatorRules = $defaultSnapshot['rules']; +$lineTerminatorRules[] = [ + 'id' => 'test-' . str_repeat('1', 32), + 'label' => "Line\u{2028}separator", + 'category' => 'test', + 'protocols' => ['tcp'], + 'port_from' => 8080, + 'port_to' => 8080, + 'directions' => ['ingress'], + 'reason' => "Paragraph\u{2029}separator", +]; +$lineTerminatorSnapshot = [ + 'schema_version' => 1, + 'base_policy_version' => 1, + 'catalog_revision' => 7, + 'rules' => $lineTerminatorRules, + 'digest' => 'ffb4b8b3e09189d55180b280cde172e1dbbd83ef0965d27e2f8210cc6b20bb2f', +]; +$assert(Policy::assertSnapshot($lineTerminatorSnapshot) + === $lineTerminatorSnapshot, + 'PHP snapshot encoding drifted from Python for U+2028/U+2029 text.'); + +$expect(static fn () => Policy::create($input, $regularAdmin), 403, + 'A regular administrator changed the global test catalog.'); + +$created = Policy::create($input, $manager); +$ruleKey = (string) ($created['rules'][0]['id'] ?? ''); +$assert($created['revision'] === 1 + && preg_match('/^[a-f0-9]{32}$/D', $ruleKey) === 1 + && $created['rules'][0]['port'] === '8080' + && $created['available_expanded_rules'] === 43, + 'Creating a test rule lost its revision, identity or expanded budget.'); +$sealed = Policy::snapshotForProvisioning(); +$assert($sealed['catalog_revision'] === 1 + && count($sealed['rules']) === 10 + && $sealed['rules'][9]['id'] === 'test-' . $ruleKey + && Policy::assertSnapshot($sealed) === $sealed, + 'The provisioning snapshot did not seal the active test rule.'); + +$expect(static fn () => Policy::update($ruleKey, array_replace($input, [ + 'expected_revision' => 0, +]), $manager), 409, 'A stale administrator revision overwrote the catalog.'); +$expect(static fn () => Policy::create(array_replace($input, [ + 'expected_revision' => 1, + 'service' => 'SMTP submission must remain open', + 'port' => '587', +]), $manager), 422, 'TCP 587 was accepted into the restricted test catalog.'); +$expect(static fn () => Policy::create(array_replace($input, [ + 'expected_revision' => 1, + 'service' => 'Overlaps the static SMTP rule', + 'port' => '25', + 'direction' => 'egress', +]), $manager), 422, 'A test rule overlapped the immutable platform baseline.'); + +$updated = Policy::update($ruleKey, [ + 'expected_revision' => 1, + 'service' => 'Temporary dual-stack protocol test', + 'protocol' => 'tcp_udp', + 'port' => '8080-8081', + 'direction' => 'both', + 'reason' => 'Exercise all protocol and direction combinations.', +], $manager); +$assert($updated['revision'] === 2 + && $updated['rules'][0]['protocol'] === 'tcp_udp' + && $updated['rules'][0]['direction'] === 'both' + && $updated['rules'][0]['port'] === '8080–8081' + && $updated['available_expanded_rules'] === 40, + 'Editing a rule did not replace its complete typed definition.'); + +$deleted = Policy::delete($ruleKey, ['expected_revision' => 2], $manager); +$afterDelete = Policy::snapshotForProvisioning(); +$assert($deleted['revision'] === 3 && $deleted['rules'] === [] + && $afterDelete['catalog_revision'] === 3 + && count($afterDelete['rules']) === 9 + && $afterDelete['digest'] !== $sealed['digest'] + && Policy::assertSnapshot($sealed) === $sealed + && CloudPlatformTestPolicyRule::count() === 1 + && CloudPlatformTestPolicyRule::first()->deleted_at !== null, + 'Deleting a catalog rule altered a sealed historical snapshot or erased audit data.'); + +$sizeRevision = (int) $deleted['revision']; +$sizeAccepted = 0; +$sizeRejected = false; +for ($index = 0; $index < 44; $index++) { + try { + $catalog = Policy::create([ + 'expected_revision' => $sizeRevision, + 'service' => str_repeat('S', 116) . sprintf('%04d', $index), + 'protocol' => 'tcp', + 'port' => (string) (30000 + $index), + 'direction' => 'ingress', + 'reason' => str_repeat('R', 500), + ], $manager); + $sizeRevision = (int) $catalog['revision']; + $sizeAccepted++; + } catch (CloudError $error) { + $assert($error->httpStatus === 422 + && str_contains($error->getMessage(), '32 KiB'), + 'An unrelated validation error masked the snapshot byte limit.'); + $sizeRejected = true; + break; + } +} +$afterSizeRejection = Policy::page(); +$boundedSnapshot = Policy::snapshotForProvisioning(); +$assert($sizeRejected + && $afterSizeRejection['revision'] === $sizeRevision + && count($afterSizeRejection['rules']) === $sizeAccepted + && Policy::assertSnapshot($boundedSnapshot) === $boundedSnapshot, + 'An oversized catalog was committed or corrupted the last valid snapshot.'); + +$tampered = $sealed; +$tampered['digest'] = str_repeat('0', 64); +$expect(static fn () => Policy::assertSnapshot($tampered), 409, + 'A tampered historical snapshot passed strict validation.'); + +echo "Platform test policy CRUD, validation and immutable snapshot contracts passed.\n";