lvi-api-client 0.2.12__tar.gz → 0.2.13__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lvi-api-client
3
- Version: 0.2.12
3
+ Version: 0.2.13
4
4
  Summary: LogicVein API Client Library
5
5
  Requires-Python: >=3.8
6
6
  Description-Content-Type: text/markdown
@@ -0,0 +1 @@
1
+ 0.2.13
@@ -99,8 +99,7 @@ def _prepare_rule_set_xml(
99
99
  if not config or (config_path is not None and config != config_path):
100
100
  raise ValueError(f"Rule set XML has config {config!r}, not {config_path!r}")
101
101
 
102
- element = root.find("networks")
103
- stated = [part.strip() for part in (element.text or "").split(",") if part.strip()] if element is not None else []
102
+ stated = _rule_set_networks(root)
104
103
  wanted = list(networks) if networks else (stated or ["*"])
105
104
  if any("," in network or not network.strip() for network in wanted):
106
105
  raise ValueError(f"Network names cannot be blank or contain a comma: {wanted}")
@@ -110,6 +109,22 @@ def _prepare_rule_set_xml(
110
109
  return _write_rule_set_networks(rule_set_xml, root, wanted), config, wanted
111
110
 
112
111
 
112
+ def _rule_set_networks(root: ElementTree.Element) -> List[str]:
113
+ """Return the networks a parsed rule set document names.
114
+
115
+ Args:
116
+ root: The parsed document.
117
+
118
+ Returns:
119
+ List[str]: The names in its networks element, ``["*"]`` meaning all networks, or an
120
+ empty list if it has none.
121
+ """
122
+ element = root.find("networks")
123
+ if element is None:
124
+ return []
125
+ return [part.strip() for part in (element.text or "").split(",") if part.strip()]
126
+
127
+
113
128
  def _write_rule_set_networks(rule_set_xml: str, root: ElementTree.Element, networks: List[str]) -> str:
114
129
  """Replace a rule set document's networks, editing only that element's text.
115
130
 
@@ -2594,20 +2609,84 @@ class LogicVeinAPIClient:
2594
2609
  def delete_managed_network(self, network_name: str) -> bool:
2595
2610
  """Delete a managed network from the LogicVein server.
2596
2611
 
2597
- An alert policy whose only network this is goes with it.
2612
+ A compliance rule set scoped to this network alone would be left with no network,
2613
+ and the server can then neither read, repair nor delete it, so this refuses while
2614
+ one exists: re-scope or delete it first. Errors from the API calls propagate as
2615
+ they are.
2616
+
2617
+ The server deletes the rest of what belongs only to this network with it: its
2618
+ compliance policies and their violations, its tags, users' access to it, and an
2619
+ alert policy whose only network this is. Alert policies, monitor sets, monitor
2620
+ templates and jobs that also belong to other networks lose this one.
2598
2621
 
2599
2622
  Args:
2600
2623
  network_name (str): The name of the managed network to delete.
2601
2624
 
2602
2625
  Returns:
2603
2626
  bool: True if the network was deleted successfully, otherwise False.
2627
+
2628
+ Raises:
2629
+ ValueError: A rule set is scoped to this network alone, or the rule sets could
2630
+ not be read to tell.
2604
2631
  """
2632
+ stranded = self.get_rule_sets_scoped_only_to(network_name)
2633
+ if stranded:
2634
+ raise ValueError(
2635
+ f"Rule sets scoped only to network {network_name!r} would be left with no network, "
2636
+ f"which the server cannot read or delete afterwards: {', '.join(stranded)}. "
2637
+ "Re-scope or delete them first."
2638
+ )
2639
+
2605
2640
  response = self.call("Networks.deleteManagedNetwork", networkName=network_name)
2606
2641
 
2607
2642
  if response and isinstance(response, dict) and "result" in response and response["result"] in (None, "None"):
2608
2643
  return True
2609
2644
  return False
2610
2645
 
2646
+ def get_rule_sets_scoped_only_to(self, network_name: str) -> List[str]:
2647
+ """Name the rule sets whose only network is this one.
2648
+
2649
+ ``delete_managed_network`` refuses while there are any; call this to check first,
2650
+ as a dry run would. A strict read: an answer that cannot be read raises, rather than reading as none.
2651
+ Errors from the API calls themselves propagate as they are.
2652
+
2653
+ Args:
2654
+ network_name: The managed network's name.
2655
+
2656
+ Returns:
2657
+ List[str]: Each such rule set as ``name (id)``.
2658
+
2659
+ Raises:
2660
+ ValueError: The rule sets could not be read, or one rule set's document could not be
2661
+ read or names no networks.
2662
+ """
2663
+ response = self.call("Compliance.getRuleSets", networks=[network_name])
2664
+ listed = response.get("result") if isinstance(response, dict) else None
2665
+ if not isinstance(listed, list):
2666
+ raise ValueError(f"Compliance.getRuleSets did not answer with a list of rule sets for {network_name!r}")
2667
+
2668
+ stranded = []
2669
+ for rule_set in listed:
2670
+ if not isinstance(rule_set, dict) or not isinstance(rule_set.get("ruleSetId"), int):
2671
+ raise ValueError(f"Compliance.getRuleSets answered a rule set with no ID: {rule_set!r}")
2672
+ document = rule_set.get("ruleSetXml")
2673
+ if not isinstance(document, str) or not document: # The list usually leaves the document out.
2674
+ fetched = self.get_rule_set(rule_set["ruleSetId"])
2675
+ document = fetched.get("ruleSetXml") if isinstance(fetched, dict) else None
2676
+ if not isinstance(document, str) or not document:
2677
+ raise ValueError(f"Rule set {rule_set['ruleSetId']} could not be read")
2678
+ try:
2679
+ root = ElementTree.fromstring(document)
2680
+ except ElementTree.ParseError as error:
2681
+ raise ValueError(f"Rule set {rule_set['ruleSetId']} has malformed XML: {error}") from error
2682
+ networks = _rule_set_networks(root) if root.tag == "rule-set" else []
2683
+ if not networks: # Its scope is unknown, so it cannot be shown safe.
2684
+ raise ValueError(f"Rule set {rule_set['ruleSetId']} has no rule-set document naming its networks")
2685
+ # Network names are case-insensitive on the server.
2686
+ if networks and all(network.casefold() == network_name.casefold() for network in networks):
2687
+ stranded.append(f"{rule_set.get('ruleSetName')} ({rule_set['ruleSetId']})")
2688
+ return stranded
2689
+
2611
2690
  def update_managed_network(
2612
2691
  self,
2613
2692
  network_name: str,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lvi-api-client
3
- Version: 0.2.12
3
+ Version: 0.2.13
4
4
  Summary: LogicVein API Client Library
5
5
  Requires-Python: >=3.8
6
6
  Description-Content-Type: text/markdown
@@ -1178,15 +1178,6 @@ class TestNetworkManagementMethods:
1178
1178
  assert network is not None
1179
1179
  assert network["name"] == "Production"
1180
1180
 
1181
- def test_delete_managed_network(self, client, mock_response):
1182
- """Test deleting a managed network."""
1183
- mock_response.json.return_value = {"jsonrpc": "2.0", "id": "test-id", "result": None}
1184
- client.lvi_client.post = Mock(return_value=mock_response)
1185
-
1186
- result = client.delete_managed_network("Test Network")
1187
-
1188
- assert result is True
1189
-
1190
1181
 
1191
1182
  class TestJobSchedulerMethods:
1192
1183
  """Test job scheduler methods."""
@@ -2043,15 +2034,6 @@ class TestNetworkManagementEdgeCases:
2043
2034
 
2044
2035
  assert networks == []
2045
2036
 
2046
- def test_delete_managed_network_failure(self, client, mock_response):
2047
- """Test delete_managed_network when it fails."""
2048
- mock_response.json.return_value = {"jsonrpc": "2.0", "id": "test-id", "result": {"error": "Failed"}}
2049
- client.lvi_client.post = Mock(return_value=mock_response)
2050
-
2051
- result = client.delete_managed_network("Test")
2052
-
2053
- assert result is False
2054
-
2055
2037
  def test_update_managed_network_failure(self, client, mock_response):
2056
2038
  """Test update_managed_network when it fails."""
2057
2039
  mock_response.json.return_value = {"jsonrpc": "2.0", "id": "test-id", "result": {"error": "Failed"}}
@@ -24,6 +24,8 @@ class FakeServer:
24
24
  request = json.loads(data)
25
25
  self.requests.append((request["method"], request["params"]))
26
26
  result = self.results.get(request["method"])
27
+ if callable(result):
28
+ result = result(request["params"])
27
29
  response = Mock(ok=True)
28
30
  response.json.return_value = {"jsonrpc": "2.0", "id": request["id"], "result": result}
29
31
  return response
@@ -789,3 +791,79 @@ class TestStrictViolationReads:
789
791
  client, _ = connect()
790
792
  with patch.object(client, "call", return_value="<html>login</html>"):
791
793
  assert self.read(client, which) == []
794
+
795
+
796
+ def rule_set_xml(networks):
797
+ """A rule set document scoped to the given networks text."""
798
+ return (
799
+ '<rule-set adapter="Cisco::IOS" config="/running-config"><name>r</name>'
800
+ f"<networks><![CDATA[{networks}]]></networks><rule/></rule-set>"
801
+ )
802
+
803
+
804
+ class TestDeletingANetwork:
805
+ """A rule set scoped to a deleted network alone is left unreadable and undeletable (issue #9)."""
806
+
807
+ @staticmethod
808
+ def listing(*scopes):
809
+ """List rule sets 1, 2, ... with these networks; None leaves the document out, as the list usually does."""
810
+ return [
811
+ {"ruleSetId": i, "ruleSetName": f"r{i}", "ruleSetXml": None if scope is None else rule_set_xml(scope)}
812
+ for i, scope in enumerate(scopes, 1)
813
+ ]
814
+
815
+ def test_a_network_with_no_rule_set_of_its_own_is_deleted(self, connect):
816
+ documents = {1: rule_set_xml("*")}
817
+ client, server = connect(
818
+ {
819
+ "Compliance.getRuleSets": self.listing(None, "Lab,Default"),
820
+ "Compliance.getRuleSet": lambda params: {"ruleSetXml": documents[params["ruleSetId"]]},
821
+ "Networks.deleteManagedNetwork": None,
822
+ }
823
+ )
824
+ assert client.delete_managed_network("Lab") is True
825
+ assert server.sent("Compliance.getRuleSets") == {"networks": ["Lab"]}
826
+ assert server.sent("Compliance.getRuleSet") == {"ruleSetId": 1}
827
+ assert server.sent("Networks.deleteManagedNetwork") == {"networkName": "Lab"}
828
+
829
+ @pytest.mark.parametrize("scope", ["Lab", "lab", "LAB,Lab"])
830
+ def test_a_rule_set_scoped_to_the_network_alone_stops_the_delete(self, connect, scope):
831
+ client, server = connect({"Compliance.getRuleSets": self.listing("*", scope)})
832
+ with pytest.raises(ValueError, match=r"r2 \(2\)"):
833
+ client.delete_managed_network("Lab")
834
+ assert "Networks.deleteManagedNetwork" not in [method for method, _ in server.requests]
835
+
836
+ @pytest.mark.parametrize(
837
+ "listing, document",
838
+ [
839
+ (None, None),
840
+ ({"ruleSets": []}, None),
841
+ ([{"ruleSetName": "r1"}], None),
842
+ ([{"ruleSetId": 1, "ruleSetXml": None}], None),
843
+ ([{"ruleSetId": 1, "ruleSetXml": None}], {}),
844
+ ([{"ruleSetId": 1, "ruleSetXml": "<rule-set"}], None),
845
+ ([{"ruleSetId": 1, "ruleSetXml": "<html>login</html>"}], None),
846
+ ([{"ruleSetId": 1, "ruleSetXml": '<rule-set adapter="a" config="c"><name>r</name></rule-set>'}], None),
847
+ ([{"ruleSetId": 1, "ruleSetXml": rule_set_xml(" , ")}], None),
848
+ ],
849
+ )
850
+ def test_rule_sets_that_cannot_be_read_stop_the_delete(self, connect, listing, document):
851
+ client, server = connect(
852
+ {
853
+ "Compliance.getRuleSets": listing,
854
+ "Compliance.getRuleSet": document,
855
+ "Networks.deleteManagedNetwork": None,
856
+ }
857
+ )
858
+ with pytest.raises(ValueError):
859
+ client.delete_managed_network("Lab")
860
+ assert "Networks.deleteManagedNetwork" not in [method for method, _ in server.requests]
861
+
862
+ def test_a_failed_delete_reads_as_not_deleted(self, connect):
863
+ client, _ = connect({"Compliance.getRuleSets": [], "Networks.deleteManagedNetwork": {"error": "Failed"}})
864
+ assert client.delete_managed_network("Lab") is False
865
+
866
+ def test_the_check_is_available_on_its_own_and_deletes_nothing(self, connect):
867
+ client, server = connect({"Compliance.getRuleSets": self.listing("Lab", "*", "Lab,Default")})
868
+ assert client.get_rule_sets_scoped_only_to("Lab") == ["r1 (1)"]
869
+ assert [method for method, _ in server.requests] == ["Compliance.getRuleSets"]
@@ -1 +0,0 @@
1
- 0.2.12
File without changes