1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 08:56:07 +00:00

fix(nwfilters): a rule is deleted and added exactly as clicked and entered

- Deleting a rule removes the row clicked, by its position, instead of the
  first rule with the same action, direction and priority; a filter changed
  since the page was read is refused instead of losing another rule.
- An added rule is added as entered, with all its attributes. It was merged
  into a rule with the same action, direction and priority, where libvirt
  keeps only the first protocol, so the new rule was silently dropped.
- A new filter shows in the list after it is created.
This commit is contained in:
catborise 2026-10-26 14:20:03 +03:00
parent 953c296324
commit 79e3f91169
7 changed files with 71 additions and 46 deletions

View file

@ -21,7 +21,6 @@
<textarea id="rule_editor"></textarea>
</div>
</div>
<p class="text-muted">{% trans 'If there is a rule which has same attributes it replaces that rule' %}...</p>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{% trans "Close" %}</button>
<button type="submit" class="btn btn-primary" name="add_nwfilter_rule">{% trans "Add" %}</button>

View file

@ -145,6 +145,7 @@
<td>{{ rule.directives }}</td>
<td>
<form action="" method="post" role="form" aria-label="Delete NWFilter rule">{% csrf_token %}
<input type="hidden" name="index" value="{{ rule.index }}">
<input type="hidden" name="action" value="{{ rule.action }}">
<input type="hidden" name="direction" value="{{ rule.direction }}">
<input type="hidden" name="priority" value="{{ rule.priority }}">

View file

@ -41,7 +41,9 @@ class FilterRowTests(TestCase):
@patch("nwfilters.views.wvmInstances")
def test_filter_list_actions(self, instances):
instances.return_value.get_instances.return_value = []
self.client.post(self.list_url, {"create_nwfilter": "", "nwfilter_xml": NEW})
# the list is read again, so the new filter shows
self.assertRedirects(self.client.post(self.list_url, {"create_nwfilter": "", "nwfilter_xml": NEW}),
self.list_url, fetch_redirect_response=False)
self.client.post(self.list_url, {"cln_nwfilter": "", "nwfiltername": "web", "cln_name": "web-copy"})
self.client.post(self.list_url, {"del_nwfilter": "", "nwfiltername": "web"})
self.assertEqual(rows(), [
@ -84,7 +86,7 @@ class FilterRowTests(TestCase):
self.client.post(self.url, {"edit_nwfilter": "", "edit_xml": XML})
self.client.post(self.url, {"add_nwfilter_rule": "",
"nwfilterrule_xml": "<rule action='accept' direction='in' priority='500'><all/></rule>"})
self.client.post(self.url, {"del_nwfilter_rule": "", "action": "drop", "direction": "in", "priority": "900"})
self.client.post(self.url, {"del_nwfilter_rule": "", "index": "0", "action": "drop", "direction": "in", "priority": "900"})
self.client.post(self.url, {"add_nwfilter_ref": "", "nwfilters_select": "no-spoofing"})
self.client.post(self.url, {"del_nwfilter_ref": "", "ref": "clean-traffic"})
self.assertEqual(rows(), [

View file

@ -41,7 +41,7 @@ class FilterRedefineTests(TestCase):
return etree.fromstring(self.wvm.nwfilterDefineXML.call_args.args[0]), response
def test_a_rule_is_removed_in_place(self):
tree, _ = self.defined({"del_nwfilter_rule": "", "action": "drop", "direction": "in", "priority": "900"})
tree, _ = self.defined({"del_nwfilter_rule": "", "index": "1", "action": "drop", "direction": "in", "priority": "900"})
self.assertEqual(tree.findtext("uuid"), UUID)
self.assertEqual([r.get("action") for r in tree.findall("rule")], ["accept"])
@ -53,7 +53,8 @@ class FilterRedefineTests(TestCase):
rule = "<rule action='accept' direction='in' priority='500'><udp dstportstart='53'/></rule>"
tree, response = self.defined({"add_nwfilter_rule": "", "nwfilterrule_xml": rule})
self.assertEqual(tree.findtext("uuid"), UUID)
self.assertEqual(tree.xpath("rule[@priority='500']/*/@dstportstart"), ["22", "53"])
# a rule of its own: libvirt keeps one protocol per rule
self.assertEqual([rule.xpath("*/@dstportstart") for rule in tree.findall("rule")], [["22"], [], ["53"]])
self.assertRedirects(response, self.url, fetch_redirect_response=False)
def test_a_reference_is_added_in_place(self):
@ -71,5 +72,41 @@ class FilterRedefineTests(TestCase):
def test_a_refused_definition_is_reported_not_undone(self):
self.wvm.nwfilterDefineXML.side_effect = libvirtError("XML error: Invalid value for attribute 'action'")
_, response = self.defined({"del_nwfilter_rule": "", "action": "drop", "direction": "in", "priority": "900"})
_, response = self.defined({"del_nwfilter_rule": "", "index": "1", "action": "drop", "direction": "in", "priority": "900"})
self.assertIn("Invalid value for attribute 'action'", " ".join(str(m) for m in get_messages(response.wsgi_request)))
class RuleDeleteTests(TestCase):
"""Rules sharing action, direction and priority: the one clicked goes."""
def setUp(self):
patcher = patch("vrtManager.connection.connection_manager.get_connection")
self.wvm = patcher.start().return_value
self.addCleanup(patcher.stop)
nwfilter = self.wvm.nwfilterLookupByName.return_value
nwfilter.XMLDesc.return_value = (
f"<filter name='web' chain='root'><uuid>{UUID}</uuid>"
"<rule action='accept' direction='in' priority='500'><tcp dstportstart='22'/></rule>"
"<rule action='accept' direction='in' priority='500'><tcp dstportstart='80'/></rule></filter>")
nwfilter.name.return_value = "web"
nwfilter.UUIDString.return_value = UUID
self.wvm.listNWFilters.return_value = ["web"]
compute = Compute.objects.create(name="nwf", hostname="localhost", login="", password="", type=4)
self.client.force_login(get_user_model().objects.create_superuser("nwf", "nwf@example.com", "pw"))
self.url = reverse("nwfilter", args=[compute.id, "web"])
def delete(self, index, priority="500"):
return self.client.post(self.url, {"del_nwfilter_rule": "", "index": index, "action": "accept",
"direction": "in", "priority": priority})
def test_the_second_of_two_alike_rules_is_deleted(self):
self.delete("1")
tree = etree.fromstring(self.wvm.nwfilterDefineXML.call_args.args[0])
self.assertEqual(tree.xpath("rule/*/@dstportstart"), ["22"])
def test_a_rule_that_is_no_longer_there_is_not_deleted(self):
for index, priority in (("2", "500"), ("1", "900")):
with self.subTest(index=index):
response = self.delete(index, priority)
self.assertIn("reload the page", " ".join(str(m) for m in get_messages(response.wsgi_request)))
self.wvm.nwfilterDefineXML.assert_not_called()

View file

@ -61,6 +61,8 @@ def nwfilters(request, compute_id):
conn.create_nwfilter(xml)
except libvirtError as lib_err:
messages.error(request, lib_err)
else:
return HttpResponseRedirect(request.get_full_path())
if "del_nwfilter" in request.POST:
name = request.POST.get("nwfiltername", "")
@ -171,12 +173,13 @@ def nwfilter(request, compute_id, nwfltr):
conn.create_nwfilter(new_xml)
if "del_nwfilter_rule" in request.POST:
index = int(request.POST.get("index", ""))
action = request.POST.get("action", "")
direction = request.POST.get("direction", "")
priority = request.POST.get("priority", "")
with audit(request, compute, subject, "delete rule"):
conn.create_nwfilter(nwfilter.delete_rule(action, direction, priority))
conn.create_nwfilter(nwfilter.delete_rule(index, action, direction, priority))
if "del_nwfilter_ref" in request.POST:
ref_name = request.POST.get("ref")

View file

@ -51,7 +51,7 @@ class wvmNWFilter(wvmConnect):
rules = []
tree = ElementTree.fromstring(self._XMLDesc(0))
for r in tree.findall("./rule"):
for index, r in enumerate(tree.findall("./rule")):
rule_action = r.get("action")
rule_direction = r.get("direction")
rule_priority = r.get("priority")
@ -62,6 +62,7 @@ class wvmNWFilter(wvmConnect):
rule_directives = ElementTree.tostring(rule_directives).decode()
rule_info = {
"index": index,
"action": rule_action,
"direction": rule_direction,
"priority": rule_priority,
@ -81,22 +82,16 @@ class wvmNWFilter(wvmConnect):
break
return ElementTree.tostring(tree).decode()
@staticmethod
def _rules(tree, action, direction, priority):
# compared, not put into an XPath predicate: the values come from forms
return [
rule
for rule in tree.findall("./rule")
if (rule.get("action"), rule.get("direction"), rule.get("priority")) == (action, direction, priority)
]
def delete_rule(self, action, direction, priority):
def delete_rule(self, index, action, direction, priority):
"""The filter without its rule at index (several rules may share
action, direction and priority); those must still match, so a filter
changed since the page was read loses no other rule."""
tree = ElementTree.fromstring(self._XMLDesc(0))
rule_tree = self._rules(tree, action, direction, priority)
if rule_tree:
tree.remove(rule_tree[0])
rules = tree.findall("./rule")
if index >= len(rules) or (rules[index].get("action"), rules[index].get("direction"),
rules[index].get("priority")) != (action, direction, priority):
raise ValueError("The filter has changed; reload the page and try again")
tree.remove(rules[index])
return ElementTree.tostring(tree).decode()
def add_ref(self, name):
@ -107,23 +102,11 @@ class wvmNWFilter(wvmConnect):
return ElementTree.tostring(tree).decode()
def add_rule(self, xml):
"""The filter with the rule added as entered; libvirt keeps one
protocol per rule, so it is never merged into another rule."""
tree = ElementTree.fromstring(self._XMLDesc(0))
rule = ElementTree.fromstring(xml)
rule_action = rule.get("action")
rule_direction = rule.get("direction")
rule_priority = rule.get("priority")
rule_directives = rule.find("./")
rule_tree = self._rules(tree, rule_action, rule_direction, rule_priority)
if rule_tree:
rule_tree[0].append(rule_directives)
else:
element = ElementTree.Element("rule")
element.attrib["action"] = rule_action
element.attrib["direction"] = rule_direction
element.attrib["priority"] = rule_priority
element.append(rule_directives)
tree.append(element)
if rule.tag != "rule":
raise ValueError("Enter one <rule> element")
tree.append(rule)
return ElementTree.tostring(tree).decode()

View file

@ -44,15 +44,15 @@ class XPathValueTests(unittest.TestCase):
nwf = wvmNWFilter.__new__(wvmNWFilter)
nwf._XMLDesc = lambda flags: FILTER
# values with quotes or brackets are compared, not parsed as XPath
self.assertEqual(nwf.delete_rule("drop'][@priority='2", "in", "1").count("<rule "), 2)
self.assertEqual(nwf.delete_rule("it's", "in", "1").count("<rule "), 2)
kept = nwf.delete_rule("drop", "in", "2")
for action in ("drop'][@priority='2", "it's"):
with self.subTest(action=action), self.assertRaises(ValueError):
nwf.delete_rule(0, action, "in", "1")
kept = nwf.delete_rule(1, "drop", "in", "2")
self.assertEqual(kept.count("<rule "), 1)
self.assertIn("priority=\"1\"", kept)
# add_rule appends to the matching rule only
# add_rule adds a rule of its own
added = nwf.add_rule("<rule action='drop' direction='in' priority='2'><icmp/></rule>")
self.assertEqual(added.count("<rule "), 2)
self.assertIn("<icmp", added.split('priority="2"')[1])
self.assertEqual(added.count("<rule "), 3)
def test_qos_direction_must_be_known(self):
net = wvmNetwork.__new__(wvmNetwork)