Fix Bug 2307 - Invalid references of vdu-id, monitoring-param, storage and compute...
[osm/NBI.git] / osm_nbi / tests / test_descriptor_topics.py
index a56916e..8ab74b8 100755 (executable)
@@ -27,11 +27,22 @@ from copy import deepcopy
 from time import time
 from osm_common import dbbase, fsbase, msgbase
 from osm_nbi import authconn
-from osm_nbi.tests.test_pkg_descriptors import db_vnfds_text, db_nsds_text
+from osm_nbi.tests.test_pkg_descriptors import (
+    db_vnfds_text,
+    db_nsds_text,
+    vnfd_exploit_text,
+    vnfd_exploit_fixed_text,
+    db_sfc_nsds_text,
+)
 from osm_nbi.descriptor_topics import VnfdTopic, NsdTopic
 from osm_nbi.engine import EngineException
 from osm_common.dbbase import DbException
 import yaml
+import tempfile
+import collections
+import collections.abc
+
+collections.MutableSequence = collections.abc.MutableSequence
 
 test_name = "test-user"
 db_vnfd_content = yaml.safe_load(db_vnfds_text)[0]
@@ -46,11 +57,23 @@ fake_session = {
     "public": False,
     "allow_show_user_project_role": True,
 }
+UUID = "00000000-0000-0000-0000-000000000000"
+
+
+def admin_value():
+    return {"projects_read": []}
+
 
+def setup_mock_fs(fs):
+    fs.path = ""
+    fs.get_params.return_value = {}
+    fs.file_exists.return_value = False
+    fs.file_open.side_effect = lambda path, mode: tempfile.TemporaryFile(mode="a+b")
 
-def norm(str):
+
+def norm(s: str):
     """Normalize string for checking"""
-    return " ".join(str.strip().split()).lower()
+    return " ".join(s.strip().split()).lower()
 
 
 def compare_desc(tc, d1, d2, k):
@@ -94,7 +117,7 @@ class Test_VnfdTopic(TestCase):
         self.topic.check_quota = Mock(return_value=None)  # skip quota
 
     @contextmanager
-    def assertNotRaises(self, exception_type):
+    def assertNotRaises(self, exception_type=Exception):
         try:
             yield None
         except exception_type:
@@ -106,12 +129,7 @@ class Test_VnfdTopic(TestCase):
         return old_desc, new_desc
 
     def prepare_vnfd_creation(self):
-        self.fs.path = ""
-        self.fs.get_params.return_value = {}
-        self.fs.file_exists.return_value = False
-        self.fs.file_open.side_effect = lambda path, mode: open(
-            "/tmp/" + str(uuid4()), "a+b"
-        )
+        setup_mock_fs(self.fs)
         test_vnfd = deepcopy(db_vnfd_content)
         did = db_vnfd_content["_id"]
         self.db.create.return_value = did
@@ -121,6 +139,16 @@ class Test_VnfdTopic(TestCase):
         ]
         return did, test_vnfd
 
+    def prepare_vnfd(self, vnfd_text):
+        setup_mock_fs(self.fs)
+        test_vnfd = yaml.safe_load(vnfd_text)
+        self.db.create.return_value = UUID
+        self.db.get_one.side_effect = [
+            {"_id": UUID, "_admin": admin_value()},
+            None,
+        ]
+        return UUID, test_vnfd
+
     def prepare_test_vnfd(self, test_vnfd):
         del test_vnfd["_id"]
         del test_vnfd["_admin"]
@@ -216,6 +244,26 @@ class Test_VnfdTopic(TestCase):
         self.assertEqual(admin["revision"], 1, "Wrong revision number")
         compare_desc(self, test_vnfd, db_args[2], "VNFD")
 
+    @patch("osm_nbi.descriptor_topics.shutil")
+    @patch("osm_nbi.descriptor_topics.os.rename")
+    def test_new_vnfd_exploit(self, mock_rename, mock_shutil):
+        id, test_vnfd = self.prepare_vnfd(vnfd_exploit_text)
+
+        with self.assertRaises(EngineException):
+            self.topic.upload_content(
+                fake_session, id, test_vnfd, {}, {"Content-Type": []}
+            )
+
+    @patch("osm_nbi.descriptor_topics.shutil")
+    @patch("osm_nbi.descriptor_topics.os.rename")
+    def test_new_vnfd_valid_helm_chart(self, mock_rename, mock_shutil):
+        id, test_vnfd = self.prepare_vnfd(vnfd_exploit_fixed_text)
+
+        with self.assertNotRaises():
+            self.topic.upload_content(
+                fake_session, id, test_vnfd, {}, {"Content-Type": []}
+            )
+
     @patch("osm_nbi.descriptor_topics.shutil")
     @patch("osm_nbi.descriptor_topics.os.rename")
     def test_new_vnfd_check_pyangbind_validation_additional_properties(
@@ -228,10 +276,12 @@ class Test_VnfdTopic(TestCase):
         )
         test_vnfd["_id"] = did
         test_vnfd["extra-property"] = 0
-        self.db.get_one.side_effect = lambda table, filter, fail_on_empty=None, fail_on_more=None: {
-            "_id": did,
-            "_admin": deepcopy(db_vnfd_content["_admin"]),
-        }
+        self.db.get_one.side_effect = (
+            lambda table, filter, fail_on_empty=None, fail_on_more=None: {
+                "_id": did,
+                "_admin": deepcopy(db_vnfd_content["_admin"]),
+            }
+        )
 
         with self.assertRaises(
             EngineException, msg="Accepted VNFD with an additional property"
@@ -529,6 +579,49 @@ class Test_VnfdTopic(TestCase):
             "Wrong exception text",
         )
 
+    @patch("osm_nbi.descriptor_topics.shutil")
+    @patch("osm_nbi.descriptor_topics.os.rename")
+    def test_new_vnfd_check_input_validation_scaling_criteria_vdu_id(
+        self, mock_rename, mock_shutil
+    ):
+        """Testing input validation during new vnfd creation
+        for scaling criteria with invalid vdu-id"""
+        did, test_vnfd = self.prepare_vnfd_creation()
+        test_vnfd = self.prepare_test_vnfd(test_vnfd)
+        test_vnfd["df"][0]["scaling-aspect"][0]["aspect-delta-details"]["deltas"][0][
+            "vdu-delta"
+        ][0]["id"] = "vdudelta1"
+        affected_df = test_vnfd["df"][0]
+        sa = affected_df["scaling-aspect"][0]
+        delta = sa["aspect-delta-details"]["deltas"][0]
+        vdu_delta = delta["vdu-delta"][0]
+
+        with self.assertRaises(
+            EngineException, msg="Accepted invalid Scaling Group Policy Criteria"
+        ) as e:
+            self.topic.upload_content(
+                fake_session, did, test_vnfd, {}, {"Content-Type": []}
+            )
+        self.assertEqual(
+            e.exception.http_code,
+            HTTPStatus.UNPROCESSABLE_ENTITY,
+            "Wrong HTTP status code",
+        )
+        self.assertIn(
+            norm(
+                "df[id='{}']:scaling-aspect[id='{}']:aspect-delta-details"
+                "[delta='{}']: "
+                "vdu-id='{}' not defined in vdu".format(
+                    affected_df["id"],
+                    sa["id"],
+                    delta["id"],
+                    vdu_delta["id"],
+                )
+            ),
+            norm(str(e.exception)),
+            "Wrong exception text",
+        )
+
     @patch("osm_nbi.descriptor_topics.shutil")
     @patch("osm_nbi.descriptor_topics.os.rename")
     def test_new_vnfd_check_input_validation_scaling_criteria_monitoring_param_ref(
@@ -649,6 +742,157 @@ class Test_VnfdTopic(TestCase):
             "Wrong exception text",
         )
 
+    @patch("osm_nbi.descriptor_topics.shutil")
+    @patch("osm_nbi.descriptor_topics.os.rename")
+    def test_new_vnfd_check_input_validation_healing_criteria_vdu_id(
+        self, mock_rename, mock_shutil
+    ):
+        """Testing input validation during new vnfd creation
+        for healing criteria with invalid vdu-id"""
+        did, test_vnfd = self.prepare_vnfd_creation()
+        test_vnfd = self.prepare_test_vnfd(test_vnfd)
+        test_vnfd["df"][0]["healing-aspect"][0]["healing-policy"][0][
+            "vdu-id"
+        ] = "vduid1"
+        affected_df = test_vnfd["df"][0]
+        ha = affected_df["healing-aspect"][0]
+        hp = ha["healing-policy"][0]
+        hp_vdu_id = hp["vdu-id"]
+
+        with self.assertRaises(
+            EngineException, msg="Accepted invalid Healing Group Policy Criteria"
+        ) as e:
+            self.topic.upload_content(
+                fake_session, did, test_vnfd, {}, {"Content-Type": []}
+            )
+        self.assertEqual(
+            e.exception.http_code,
+            HTTPStatus.UNPROCESSABLE_ENTITY,
+            "Wrong HTTP status code",
+        )
+        self.assertIn(
+            norm(
+                "df[id='{}']:healing-aspect[id='{}']:healing-policy"
+                "[name='{}']: "
+                "vdu-id='{}' not defined in vdu".format(
+                    affected_df["id"],
+                    ha["id"],
+                    hp["event-name"],
+                    hp_vdu_id,
+                )
+            ),
+            norm(str(e.exception)),
+            "Wrong exception text",
+        )
+
+    @patch("osm_nbi.descriptor_topics.shutil")
+    @patch("osm_nbi.descriptor_topics.os.rename")
+    def test_new_vnfd_check_input_validation_alarm_criteria_monitoring_param_ref(
+        self, mock_rename, mock_shutil
+    ):
+        """Testing input validation during new vnfd creation
+        for alarm with invalid monitoring parameter reference"""
+        did, test_vnfd = self.prepare_vnfd_creation()
+        test_vnfd = self.prepare_test_vnfd(test_vnfd)
+        test_vnfd["vdu"][1]["alarm"][0]["vnf-monitoring-param-ref"] = "unit_test_alarm"
+        vdu = test_vnfd["vdu"][1]
+        alarm = vdu["alarm"][0]
+        alarm_monitoring_param = alarm["vnf-monitoring-param-ref"]
+
+        with self.assertRaises(
+            EngineException, msg="Accepted invalid Alarm Criteria"
+        ) as e:
+            self.topic.upload_content(
+                fake_session, did, test_vnfd, {}, {"Content-Type": []}
+            )
+        self.assertEqual(
+            e.exception.http_code,
+            HTTPStatus.UNPROCESSABLE_ENTITY,
+            "Wrong HTTP status code",
+        )
+        self.assertIn(
+            norm(
+                "vdu[id='{}']:alarm[id='{}']:"
+                "vnf-monitoring-param-ref='{}' not defined in any monitoring-param".format(
+                    vdu["id"],
+                    alarm["alarm-id"],
+                    alarm_monitoring_param,
+                )
+            ),
+            norm(str(e.exception)),
+            "Wrong exception text",
+        )
+
+    @patch("osm_nbi.descriptor_topics.shutil")
+    @patch("osm_nbi.descriptor_topics.os.rename")
+    def test_new_vnfd_check_input_validation_storage_reference_criteria(
+        self, mock_rename, mock_shutil
+    ):
+        """Testing input validation during new vnfd creation
+        for invalid virtual-storge-desc reference"""
+        did, test_vnfd = self.prepare_vnfd_creation()
+        test_vnfd = self.prepare_test_vnfd(test_vnfd)
+        test_vnfd["vdu"][1]["virtual-storage-desc"] = "unit_test_storage"
+        vdu = test_vnfd["vdu"][1]
+        vsd_ref = vdu["virtual-storage-desc"]
+
+        with self.assertRaises(
+            EngineException, msg="Accepted invalid virtual-storage-desc"
+        ) as e:
+            self.topic.upload_content(
+                fake_session, did, test_vnfd, {}, {"Content-Type": []}
+            )
+        self.assertEqual(
+            e.exception.http_code,
+            HTTPStatus.UNPROCESSABLE_ENTITY,
+            "Wrong HTTP status code",
+        )
+        self.assertIn(
+            norm(
+                "vdu[virtual-storage-desc='{}']"
+                "not defined in vnfd".format(
+                    vsd_ref,
+                )
+            ),
+            norm(str(e.exception)),
+            "Wrong exception text",
+        )
+
+    @patch("osm_nbi.descriptor_topics.shutil")
+    @patch("osm_nbi.descriptor_topics.os.rename")
+    def test_new_vnfd_check_input_validation_compute_reference_criteria(
+        self, mock_rename, mock_shutil
+    ):
+        """Testing input validation during new vnfd creation
+        for invalid virtual-compute-desc reference"""
+        did, test_vnfd = self.prepare_vnfd_creation()
+        test_vnfd = self.prepare_test_vnfd(test_vnfd)
+        test_vnfd["vdu"][1]["virtual-compute-desc"] = "unit_test_compute"
+        vdu = test_vnfd["vdu"][1]
+        vcd_ref = vdu["virtual-compute-desc"]
+
+        with self.assertRaises(
+            EngineException, msg="Accepted invalid virtual-compute-desc"
+        ) as e:
+            self.topic.upload_content(
+                fake_session, did, test_vnfd, {}, {"Content-Type": []}
+            )
+        self.assertEqual(
+            e.exception.http_code,
+            HTTPStatus.UNPROCESSABLE_ENTITY,
+            "Wrong HTTP status code",
+        )
+        self.assertIn(
+            norm(
+                "vdu[virtual-compute-desc='{}']"
+                "not defined in vnfd".format(
+                    vcd_ref,
+                )
+            ),
+            norm(str(e.exception)),
+            "Wrong exception text",
+        )
+
     @patch("osm_nbi.descriptor_topics.shutil")
     @patch("osm_nbi.descriptor_topics.os.rename")
     def test_new_vnfd_check_input_validation_everything_right(
@@ -1441,8 +1685,8 @@ class Test_NsdTopic(TestCase):
         did = db_nsd_content["_id"]
         self.fs.get_params.return_value = {}
         self.fs.file_exists.return_value = False
-        self.fs.file_open.side_effect = lambda path, mode: open(
-            "/tmp/" + str(uuid4()), "a+b"
+        self.fs.file_open.side_effect = lambda path, mode: tempfile.TemporaryFile(
+            mode="a+b"
         )
         self.db.get_one.side_effect = [
             {"_id": did, "_admin": deepcopy(db_nsd_content["_admin"])},
@@ -1944,7 +2188,6 @@ class Test_NsdTopic(TestCase):
             {"ns-configuration": {"config-primitive": [{"name": "del-user"}]}}
         )
 
-
         with self.assertNotRaises(EngineException):
             self.topic._validate_descriptor_changes(
                 old_nsd["_id"], descriptor_name, "/tmp", "/tmp:1"
@@ -2149,6 +2392,61 @@ class Test_NsdTopic(TestCase):
             "Wrong exception text",
         )
 
+    def test_validate_vnffgd_descriptor_on_valid_descriptor(self):
+        indata = yaml.safe_load(db_sfc_nsds_text)[0]
+        vnffgd = indata.get("vnffgd")
+        fg = vnffgd[0]
+        self.topic.validate_vnffgd_data(fg, indata)
+
+    def test_validate_vnffgd_descriptor_not_matching_nfp_position_element(self):
+        indata = yaml.safe_load(db_sfc_nsds_text)[0]
+        vnffgd = indata.get("vnffgd")
+        fg = vnffgd[0]
+        nfpd = fg.get("nfpd")[0]
+        with self.assertRaises(EngineException) as e:
+            fg.update({"nfp-position-element": [{"id": "test1"}]})
+            self.topic.validate_vnffgd_data(fg, indata)
+        self.assertEqual(
+            e.exception.http_code,
+            HTTPStatus.UNPROCESSABLE_ENTITY,
+            "Wrong HTTP status code",
+        )
+        self.assertIn(
+            norm(
+                "Error at vnffgd nfpd[id='{}']:nfp-position-element-id='{}' "
+                "does not match any nfp-position-element".format(nfpd["id"], "test")
+            ),
+            norm(str(e.exception)),
+            "Wrong exception text",
+        )
+
+    def test_validate_vnffgd_descriptor_not_matching_constituent_base_element_id(
+        self,
+    ):
+        indata = yaml.safe_load(db_sfc_nsds_text)[0]
+        vnffgd = indata.get("vnffgd")
+        fg = vnffgd[0]
+        fg["nfpd"][0]["position-desc-id"][0]["cp-profile-id"][0][
+            "constituent-profile-elements"
+        ][0]["constituent-base-element-id"] = "error_vnf"
+        with self.assertRaises(EngineException) as e:
+            self.topic.validate_vnffgd_data(fg, indata)
+        self.assertEqual(
+            e.exception.http_code,
+            HTTPStatus.UNPROCESSABLE_ENTITY,
+            "Wrong HTTP status code",
+        )
+        self.assertIn(
+            norm(
+                "Error at vnffgd constituent_profile[id='{}']:vnfd-id='{}' "
+                "does not match any constituent-base-element-id".format(
+                    "vnf1", "error_vnf"
+                )
+            ),
+            norm(str(e.exception)),
+            "Wrong exception text",
+        )
+
 
 if __name__ == "__main__":
     unittest.main()