diff --git a/src/deployment/.gitignore b/src/deployment/.gitignore new file mode 100644 index 0000000000..21ef600e0c --- /dev/null +++ b/src/deployment/.gitignore @@ -0,0 +1,73 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# pyenv +.python-version + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# mypy +.mypy_cache/ + +test-cov.xml +test-output.xml \ No newline at end of file diff --git a/src/deployment/deploy.py b/src/deployment/deploy.py index 6b40bfeba8..251d27a362 100644 --- a/src/deployment/deploy.py +++ b/src/deployment/deploy.py @@ -47,15 +47,16 @@ ) from msrest.serialization import TZ_UTC -from configuration import ( +from deploylib.configuration import ( InstanceConfigClient, + NetworkSecurityConfig, parse_rules, update_admins, update_allowed_aad_tenants, update_nsg, ) -from data_migration import migrate -from registration import ( +from deploylib.data_migration import migrate +from deploylib.registration import ( GraphQueryError, OnefuzzAppRole, add_application_password, @@ -624,18 +625,18 @@ def set_instance_config(self) -> None: with open(self.nsg_config, "r") as template_handle: config_template = json.load(template_handle) - if ( - not config_template["proxy_nsg_config"] - and not config_template["proxy_nsg_config"]["allowed_ips"] - and not config_template["proxy_nsg_config"]["allowed_service_tags"] - ): + try: + config = NetworkSecurityConfig(config_template) + rules = parse_rules(config) + except Exception as ex: + logging.info( + "An Exception was encountered while parsing nsg_config file: %s", ex + ) raise Exception( "proxy_nsg_config and sub-values were not properly included in config." + "Please submit a configuration resembling" + " { 'proxy_nsg_config': { 'allowed_ips': [], 'allowed_service_tags': [] } }" ) - proxy_config = config_template["proxy_nsg_config"] - rules = parse_rules(proxy_config) update_nsg(config_client, rules) diff --git a/src/deployment/deploylib/__init__.py b/src/deployment/deploylib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/deployment/configuration.py b/src/deployment/deploylib/configuration.py similarity index 65% rename from src/deployment/configuration.py rename to src/deployment/deploylib/configuration.py index 43861c7b4a..cdeecd0767 100644 --- a/src/deployment/configuration.py +++ b/src/deployment/deploylib/configuration.py @@ -6,7 +6,7 @@ import ipaddress import json import logging -from typing import Dict, List, Optional +from typing import Any, Dict, List, Optional from uuid import UUID from azure.cosmosdb.table.tableservice import TableService @@ -49,6 +49,67 @@ def create_if_missing(self, table_service: TableService) -> None: self.enable_storage_client_logging() +class NetworkSecurityConfig: + allowed_ips: List[str] + allowed_service_tags: List[str] + + def __init__(self, config: Any): + self.parse_nsg_json(config) + + def parse_nsg_json(self, config: Any) -> None: + if not isinstance(config, Dict): + raise Exception( + "Configuration is not a Dictionary. Please provide Valid Config." + ) + if len(config.keys()) == 0: + raise Exception( + "Empty Configuration File Provided. Please Provide Valid Config." + ) + if None in config.keys() or "proxy_nsg_config" not in config.keys(): + raise Exception( + "proxy_nsg_config not provided as valid key. Please Provide Valid Config." + ) + proxy_config = config["proxy_nsg_config"] + if not isinstance(proxy_config, Dict): + raise Exception( + "Inner Configuration is not a Dictionary. Please provide Valid Config." + ) + if len(proxy_config.keys()) == 0: + raise Exception( + "Empty Inner Configuration File Provided. Please Provide Valid Config." + ) + if ( + None in proxy_config.keys() + or "allowed_ips" not in proxy_config.keys() + or "allowed_service_tags" not in proxy_config.keys() + ): + raise Exception( + "allowed_ips and allowed_service_tags not provided. Please Provide Valid Config." + ) + if not isinstance(proxy_config["allowed_ips"], List) or not isinstance( + proxy_config["allowed_service_tags"], List + ): + raise Exception( + "allowed_ips and allowed_service_tags are not a list. Please Provide Valid Config." + ) + + if ( + len(proxy_config["allowed_ips"]) != 0 + and not all(isinstance(x, str) for x in proxy_config["allowed_ips"]) + ) or ( + len(proxy_config["allowed_ips"]) != 0 + and not all( + isinstance(x, str) for x in proxy_config["allowed_service_tags"] + ) + ): + raise Exception( + "allowed_ips and allowed_service_tags are not a list of strings. Please Provide Valid Config." + ) + + self.allowed_ips = proxy_config["allowed_ips"] + self.allowed_service_tags = proxy_config["allowed_service_tags"] + + class NsgRule: rule: str @@ -117,9 +178,10 @@ def update_admins(config_client: InstanceConfigClient, admins: List[UUID]) -> No ) -def parse_rules(proxy_config: Dict[str, str]) -> List[NsgRule]: - allowed_ips = proxy_config["allowed_ips"] - allowed_service_tags = proxy_config["allowed_service_tags"] +def parse_rules(proxy_config: NetworkSecurityConfig) -> List[NsgRule]: + + allowed_ips = proxy_config.allowed_ips + allowed_service_tags = proxy_config.allowed_service_tags nsg_rules = [] if "*" in allowed_ips: @@ -166,7 +228,3 @@ def update_nsg( "proxy_nsg_config": json.dumps(nsg_config), }, ) - - -if __name__ == "__main__": - pass diff --git a/src/deployment/data_migration.py b/src/deployment/deploylib/data_migration.py similarity index 100% rename from src/deployment/data_migration.py rename to src/deployment/deploylib/data_migration.py diff --git a/src/deployment/registration.py b/src/deployment/deploylib/registration.py similarity index 100% rename from src/deployment/registration.py rename to src/deployment/deploylib/registration.py diff --git a/src/deployment/set_admins.py b/src/deployment/deploylib/set_admins.py similarity index 97% rename from src/deployment/set_admins.py rename to src/deployment/deploylib/set_admins.py index 20eea27d49..92e67d92bc 100644 --- a/src/deployment/set_admins.py +++ b/src/deployment/deploylib/set_admins.py @@ -10,7 +10,7 @@ from azure.cosmosdb.table.tableservice import TableService from azure.mgmt.storage import StorageManagementClient -from configuration import ( +from deploylib.configuration import ( InstanceConfigClient, update_admins, update_allowed_aad_tenants, diff --git a/src/deployment/deploylib/tests/README.md b/src/deployment/deploylib/tests/README.md new file mode 100644 index 0000000000..2867e6cb73 --- /dev/null +++ b/src/deployment/deploylib/tests/README.md @@ -0,0 +1,7 @@ +# Deployment tests. + +- `test_deploy_config.py` + + Requires the deployment packages and scripts from OneFuzz. + + `test_deploy_config.py` validates that the Deploy script takes properly formatted json configuration.. diff --git a/src/deployment/deploylib/tests/__init__.py b/src/deployment/deploylib/tests/__init__.py new file mode 100644 index 0000000000..d2effe12b0 --- /dev/null +++ b/src/deployment/deploylib/tests/__init__.py @@ -0,0 +1,4 @@ +#!/usr/bin/env python +# +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. diff --git a/src/deployment/deploylib/tests/test_deploy_config.py b/src/deployment/deploylib/tests/test_deploy_config.py new file mode 100644 index 0000000000..1bc816802e --- /dev/null +++ b/src/deployment/deploylib/tests/test_deploy_config.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python +# +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import unittest +from typing import Any, List + +from deploylib.configuration import NetworkSecurityConfig + + +class TestNetworkSecurityConfig: + allowed_ips: List[str] + allowed_service_tags: List[str] + + +class DeployTests(unittest.TestCase): + def test_config(self) -> None: + ## Test Invalid Configs + # Test Dictionary + invalid_config: Any = "" + with self.assertRaises(Exception): + NetworkSecurityConfig(invalid_config) + # Test Empty Dic + invalid_config = {} + with self.assertRaises(Exception): + NetworkSecurityConfig(invalid_config) + # Test Invalid Outer Keys + invalid_config = {"": ""} + with self.assertRaises(Exception): + NetworkSecurityConfig(invalid_config) + # Test Inner Dictionary + invalid_config = {"proxy_nsg_config": ""} + with self.assertRaises(Exception): + NetworkSecurityConfig(invalid_config) + # Test Inner Keys + invalid_config = {"proxy_nsg_config": {}} + with self.assertRaises(Exception): + NetworkSecurityConfig(invalid_config) + # Test Inner Keys + invalid_config = {"proxy_nsg_config": {"allowed_ips": ""}} + with self.assertRaises(Exception): + NetworkSecurityConfig(invalid_config) + # Test Inner Dict Values (lists) + invalid_config = { + "proxy_nsg_config": {"allowed_ips": [], "allowed_service_tags": ""} + } + with self.assertRaises(Exception): + NetworkSecurityConfig(invalid_config) + # Test List Values + invalid_config = { + "proxy_nsg_config": { + "allowed_ips": [1, 2], + "allowed_service_tags": ["10.0.0.0"], + } + } + with self.assertRaises(Exception): + NetworkSecurityConfig(invalid_config) + + ## Test Valid Configs + # Test Empty Lists + valid_config: Any = { + "proxy_nsg_config": {"allowed_ips": [], "allowed_service_tags": []} + } + NetworkSecurityConfig(valid_config) + # Test Wild Card Lists + valid_config = { + "proxy_nsg_config": {"allowed_ips": ["*"], "allowed_service_tags": []} + } + NetworkSecurityConfig(valid_config) + # Test IPs Lists + valid_config = { + "proxy_nsg_config": { + "allowed_ips": ["10.0.0.1", "10.0.0.2"], + "allowed_service_tags": [], + } + } + NetworkSecurityConfig(valid_config) + # Test Tags Lists + valid_config = { + "proxy_nsg_config": { + "allowed_ips": ["10.0.0.1", "10.0.0.2"], + "allowed_service_tags": ["Internet"], + } + } + NetworkSecurityConfig(valid_config) + + +if __name__ == "__main__": + unittest.main()