feat: add automatic guest network interface firewall enablement during policy apply operations

Add network_firewall_enabled_value helper to parse and inject firewall=1 into Proxmox network interface config strings, implement enable_guest_firewall_interfaces to update VM/LXC config with firewall=1 on all netX interfaces before writing rules, extend workload_config_url to build config endpoint paths for qemu/lxc guests, add interfaces_enabled field to apply_rules response showing which interfaces were
This commit is contained in:
2026-07-09 19:40:31 +02:00
parent 5302a8bc82
commit 1b81847fc6
3 changed files with 58 additions and 4 deletions
+1 -1
View File
@@ -78,7 +78,7 @@ Minimum practical write privileges for VM/LXC-level firewall rules:
- `VM.Audit` so NexaFabric can resolve guests and inspect existing rules. - `VM.Audit` so NexaFabric can resolve guests and inspect existing rules.
- `VM.Config.Options` so NexaFabric can enable the guest firewall option before writing rules. - `VM.Config.Options` so NexaFabric can enable the guest firewall option before writing rules.
- `VM.Config.Network` on `/vms` or on the narrow VM/LXC paths you want NexaFabric to manage. - `VM.Config.Network` on `/vms` or on the narrow VM/LXC paths you want NexaFabric to manage, so NexaFabric can set `firewall=1` on guest network interfaces before writing rules.
NexaFabric writes only rules that carry a `NexaFabric policy=...` comment marker. During apply it removes and replaces its own marked rules for the selected policy, leaving manually created Proxmox firewall rules untouched. NexaFabric writes only rules that carry a `NexaFabric policy=...` comment marker. During apply it removes and replaces its own marked rules for the selected policy, leaving manually created Proxmox firewall rules untouched.
+46
View File
@@ -139,9 +139,29 @@ class ProxmoxProvider(Provider):
vmid = target["vmid"] vmid = target["vmid"]
return f"{connection.api_url.rstrip('/')}/api2/json/nodes/{node}/{kind}/{vmid}/firewall/options" return f"{connection.api_url.rstrip('/')}/api2/json/nodes/{node}/{kind}/{vmid}/firewall/options"
def workload_config_url(self, connection: ProviderConnection, target: dict[str, Any]) -> str:
kind = "lxc" if target.get("kind") == "lxc" else "qemu"
node = target["node"]
vmid = target["vmid"]
return f"{connection.api_url.rstrip('/')}/api2/json/nodes/{node}/{kind}/{vmid}/config"
def policy_marker(self, rule: dict[str, Any]) -> str: def policy_marker(self, rule: dict[str, Any]) -> str:
return f"NexaFabric policy={rule.get('policy_id')}" return f"NexaFabric policy={rule.get('policy_id')}"
def network_firewall_enabled_value(self, value: str) -> str:
parts = [part for part in value.split(",") if part]
found = False
updated = []
for part in parts:
if part.startswith("firewall="):
updated.append("firewall=1")
found = True
else:
updated.append(part)
if not found:
updated.append("firewall=1")
return ",".join(updated)
async def delete_existing_policy_rules( async def delete_existing_policy_rules(
self, self,
client: httpx.AsyncClient, client: httpx.AsyncClient,
@@ -173,6 +193,29 @@ class ProxmoxProvider(Provider):
response.raise_for_status() response.raise_for_status()
return response.json().get("data") return response.json().get("data")
async def enable_guest_firewall_interfaces(
self,
client: httpx.AsyncClient,
headers: dict[str, str],
connection: ProviderConnection,
target: dict[str, Any],
) -> list[dict[str, Any]]:
config_url = self.workload_config_url(connection, target)
response = await client.get(config_url, headers=headers)
response.raise_for_status()
config = response.json().get("data", {})
changes: dict[str, str] = {}
for key, value in config.items():
if not key.startswith("net") or not isinstance(value, str):
continue
enabled_value = self.network_firewall_enabled_value(value)
if enabled_value != value:
changes[key] = enabled_value
if changes:
update_response = await client.put(config_url, headers=headers, data=changes)
update_response.raise_for_status()
return [{"interface": key, "firewall": 1} for key in sorted(changes)]
async def apply_rules(self, connection: ProviderConnection, rules: list[dict[str, Any]]) -> dict[str, Any]: async def apply_rules(self, connection: ProviderConnection, rules: list[dict[str, Any]]) -> dict[str, Any]:
if connection.read_only: if connection.read_only:
return {"applied": False, "reason": "Cluster is read-only", "rules": rules} return {"applied": False, "reason": "Cluster is read-only", "rules": rules}
@@ -195,6 +238,7 @@ class ProxmoxProvider(Provider):
applied_rules = [] applied_rules = []
deleted_rules = [] deleted_rules = []
enabled_targets = [] enabled_targets = []
enabled_interfaces = []
audit_only_rules = [] audit_only_rules = []
async with httpx.AsyncClient(verify=connection.verify_tls, timeout=20) as client: async with httpx.AsyncClient(verify=connection.verify_tls, timeout=20) as client:
for target_rules in grouped.values(): for target_rules in grouped.values():
@@ -204,6 +248,7 @@ class ProxmoxProvider(Provider):
deleted_rules.extend(await self.delete_existing_policy_rules(client, headers, rules_url, marker)) deleted_rules.extend(await self.delete_existing_policy_rules(client, headers, rules_url, marker))
if any(not rule.get("audit_only") for rule in target_rules): if any(not rule.get("audit_only") for rule in target_rules):
enabled_targets.append({"target": target, "result": await self.enable_guest_firewall(client, headers, connection, target)}) enabled_targets.append({"target": target, "result": await self.enable_guest_firewall(client, headers, connection, target)})
enabled_interfaces.append({"target": target, "interfaces": await self.enable_guest_firewall_interfaces(client, headers, connection, target)})
for rule in target_rules: for rule in target_rules:
if rule.get("audit_only"): if rule.get("audit_only"):
@@ -231,6 +276,7 @@ class ProxmoxProvider(Provider):
"rules_written": len(applied_rules), "rules_written": len(applied_rules),
"rules_deleted": len(deleted_rules), "rules_deleted": len(deleted_rules),
"firewall_enabled": enabled_targets, "firewall_enabled": enabled_targets,
"interfaces_enabled": enabled_interfaces,
"audit_only": audit_only_rules, "audit_only": audit_only_rules,
"rules": applied_rules, "rules": applied_rules,
} }
+11 -3
View File
@@ -31,7 +31,9 @@ class FakeAsyncClient:
async def __aexit__(self, *_: object) -> None: async def __aexit__(self, *_: object) -> None:
return None return None
async def get(self, _: str, **__: object) -> FakeResponse: async def get(self, url: str, **__: object) -> FakeResponse:
if url.endswith("/config"):
return FakeResponse({"net0": "virtio=AA:BB:CC:DD:EE:FF,bridge=vmbr0,firewall=0", "name": "web"})
return FakeResponse( return FakeResponse(
[ [
{"pos": 0, "comment": "manual rule"}, {"pos": 0, "comment": "manual rule"},
@@ -83,8 +85,14 @@ async def test_apply_rules_replaces_only_marked_nexafabric_rules(monkeypatch: py
assert result["applied"] is True assert result["applied"] is True
assert result["rules_deleted"] == 1 assert result["rules_deleted"] == 1
assert FakeAsyncClient.deleted_urls == ["https://pve.example:8006/api2/json/nodes/pve1/qemu/100/firewall/rules/1"] assert FakeAsyncClient.deleted_urls == ["https://pve.example:8006/api2/json/nodes/pve1/qemu/100/firewall/rules/1"]
assert FakeAsyncClient.put_urls == ["https://pve.example:8006/api2/json/nodes/pve1/qemu/100/firewall/options"] assert FakeAsyncClient.put_urls == [
assert FakeAsyncClient.put_payloads == [{"enable": 1}] "https://pve.example:8006/api2/json/nodes/pve1/qemu/100/firewall/options",
"https://pve.example:8006/api2/json/nodes/pve1/qemu/100/config",
]
assert FakeAsyncClient.put_payloads == [
{"enable": 1},
{"net0": "virtio=AA:BB:CC:DD:EE:FF,bridge=vmbr0,firewall=1"},
]
assert FakeAsyncClient.posted_payloads == [ assert FakeAsyncClient.posted_payloads == [
{ {
"type": "in", "type": "in",