diff options
Diffstat (limited to 'old/python_moonclient')
58 files changed, 5195 insertions, 0 deletions
diff --git a/old/python_moonclient/.gitignore b/old/python_moonclient/.gitignore new file mode 100644 index 00000000..9c29724f --- /dev/null +++ b/old/python_moonclient/.gitignore @@ -0,0 +1,106 @@ +# 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/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +/tests/unit_python/database.db diff --git a/old/python_moonclient/Changelog b/old/python_moonclient/Changelog new file mode 100644 index 00000000..7cd14340 --- /dev/null +++ b/old/python_moonclient/Changelog @@ -0,0 +1,78 @@ +# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors +# This software is distributed under the terms and conditions of the 'Apache-2.0' +# license which can be found in the file 'LICENSE' in this package distribution +# or at 'http://www.apache.org/licenses/LICENSE-2.0'. + + +CHANGES +======= + +0.1.0 +----- +- First version of the python-moonclient + +1.0.0 +----- +- First public version of the python-moonclient + +1.0.1 +----- +- Fix a bug in configuration + +1.1.0 +----- +- Add some commands: + - moon_get_pdp + - moon_delete_pdp + - moon_delete_policy + - moon_map_pdp_to_project +- Update some commands: + - moon_create_pdp + - moon_send_authz_to_wrapper +- Fix a bug in pdp library + +1.2.0 +----- +- Add some commands: + - moon_get_slaves + - moon_set_slave + - moon_delete_slave + +1.3.0 +----- +- Base the cli on cliff library +- Commands are: + - moon authz send + - moon pdp create + - moon pdp delete + - moon pdp list + - moon pdp map + - moon policy delete + - moon policy list + - moon project list + - moon slave delete + - moon slave list + - moon slave set + +1.4.0 +----- +- Add some commands: + - moon import + - moon export + - moon subject category create + - moon subject category list + - moon object category list + - moon action category list + - moon subject data create + - moon subject data list + - moon object data list + - moon action data list + - moon metarule list + +1.4.1 +----- +- Update exception during configuration + +1.4.2 +----- +- apply PyLint rules
\ No newline at end of file diff --git a/old/python_moonclient/LICENSE b/old/python_moonclient/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/old/python_moonclient/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/old/python_moonclient/MANIFEST.in b/old/python_moonclient/MANIFEST.in new file mode 100644 index 00000000..2a5ac509 --- /dev/null +++ b/old/python_moonclient/MANIFEST.in @@ -0,0 +1,10 @@ +# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors +# This software is distributed under the terms and conditions of the 'Apache-2.0' +# license which can be found in the file 'LICENSE' in this package distribution +# or at 'http://www.apache.org/licenses/LICENSE-2.0'. + +include README.md +include LICENSE +include Changelog +include setup.py +include requirements.txt diff --git a/old/python_moonclient/README.md b/old/python_moonclient/README.md new file mode 100644 index 00000000..1a9731e7 --- /dev/null +++ b/old/python_moonclient/README.md @@ -0,0 +1,33 @@ +# python-moonclient +This package contains the core module for the Moon project. +It is designed to provide authorization feature to all OpenStack components. + +For any other information, refer to the parent project: + + https://git.opnfv.org/moon + +python_moonutilities is a common Python lib for other Moon Python packages + +## Build +### Build Python Package +```bash +cd ${MOON_HOME}/python_moonclient +python3 setup.py sdist bdist_wheel +``` + +### Push Python Package to PIP +```bash +cd ${MOON_HOME}/python_moonclient +gpg --detach-sign -u "${GPG_ID}" -a dist/python_moonclient-X.Y.Z-py3-none-any.whl +gpg --detach-sign -u "${GPG_ID}" -a dist/python_moonclient-X.Y.Z.tar.gz +twine upload dist/python_moonclient-X.Y.Z-py3-none-any.whl dist/python_moonclient-X.Y.Z-py3-none-any.whl.asc +twine upload dist/python_moonclient-X.Y.Z.tar.gz dist/python_moonclient-X.Y.Z.tar.gz.asc +``` + +## Test +### Python Unit Test +launch Docker for Python unit tests +```bash +cd ${MOON_HOME}/python_moonclient +docker run --rm --volume $(pwd):/data wukongsun/moon_python_unit_test:latest +``` diff --git a/old/python_moonclient/python_moonclient/__init__.py b/old/python_moonclient/python_moonclient/__init__.py new file mode 100644 index 00000000..bbd31082 --- /dev/null +++ b/old/python_moonclient/python_moonclient/__init__.py @@ -0,0 +1,6 @@ +# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors +# This software is distributed under the terms and conditions of the 'Apache-2.0' +# license which can be found in the file 'LICENSE' in this package distribution +# or at 'http://www.apache.org/licenses/LICENSE-2.0'. + +__version__ = "1.4.2" diff --git a/old/python_moonclient/python_moonclient/cli/__init__.py b/old/python_moonclient/python_moonclient/cli/__init__.py new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/old/python_moonclient/python_moonclient/cli/__init__.py diff --git a/old/python_moonclient/python_moonclient/cli/authz.py b/old/python_moonclient/python_moonclient/cli/authz.py new file mode 100644 index 00000000..4edc307f --- /dev/null +++ b/old/python_moonclient/python_moonclient/cli/authz.py @@ -0,0 +1,55 @@ +import logging + +from importlib.machinery import SourceFileLoader +from cliff.command import Command + +from python_moonclient.core import models, policies, pdp, authz +from python_moonclient.cli.parser import Parser +from python_moonclient.cli.projects import ProjectsUtils + +LOGGER = logging.getLogger("moonclient.cli.authz") + + +class SendAuthz(Command): + """send authorizations to wrapper""" + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + Parser.add_filename_argument(parser) + Parser.add_id_or_name_project_argument(parser) + Parser.add_authz_arguments(parser) + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + if parsed_args.filename: + LOGGER.info("Loading: {}".format(parsed_args.filename)) + m = SourceFileLoader("scenario", parsed_args.filename) + scenario = m.load_module() + + keystone_project_id = ProjectsUtils.get_project_id(pdp, parsed_args.id_project, + parsed_args.name_project) + if keystone_project_id is None: + LOGGER.error("Project not found !") + + keystone_project_id = pdp.get_keystone_id(keystone_project_id) + time_data = authz.send_requests( + scenario, + parsed_args.authz_host, + parsed_args.authz_port, + keystone_project_id, + request_second=parsed_args.request_second, + limit=parsed_args.limit, + dry_run=parsed_args.dry_run, + stress_test=parsed_args.stress_test, + destination=parsed_args.destination + ) + if not parsed_args.dry_run: + authz.save_data(parsed_args.write, time_data) diff --git a/old/python_moonclient/python_moonclient/cli/export.py b/old/python_moonclient/python_moonclient/cli/export.py new file mode 100644 index 00000000..4ea5cf4f --- /dev/null +++ b/old/python_moonclient/python_moonclient/cli/export.py @@ -0,0 +1,32 @@ +import json + +from python_moonclient.core import models, policies, pdp, json_export +from python_moonclient.cli.parser import Parser + +from cliff.command import Command + + +class Export(Command): + """dump the complete moon database into a json file""" + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_filename_argument(parser) + Parser.add_common_options(parser) + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + json_export.init(consul_host, consul_port) + res = json_export.export_to_json() + if "content" in res: + json_file = open(parsed_args.filename, "w") + json.dump(res["content"], json_file) + return "Export ok!" + + return "Unexpected results : the returned json does not have the correct syntax" diff --git a/old/python_moonclient/python_moonclient/cli/import.py b/old/python_moonclient/python_moonclient/cli/import.py new file mode 100644 index 00000000..efefc304 --- /dev/null +++ b/old/python_moonclient/python_moonclient/cli/import.py @@ -0,0 +1,28 @@ +from python_moonclient.core import models, policies, pdp, json_import +from python_moonclient.cli.parser import Parser +from python_moonclient.cli.projects import ProjectsUtils + +from cliff.command import Command + + +class Import(Command): + """import a json file describing pdps """ + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + Parser.add_filename_argument(parser) + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + json_import.init(consul_host, consul_port) + res = json_import.import_json(parsed_args.filename) + if "message" in res: + return res["message"] + return res diff --git a/old/python_moonclient/python_moonclient/cli/models.py b/old/python_moonclient/python_moonclient/cli/models.py new file mode 100644 index 00000000..369d9027 --- /dev/null +++ b/old/python_moonclient/python_moonclient/cli/models.py @@ -0,0 +1,159 @@ +import logging +from importlib.machinery import SourceFileLoader +from cliff.lister import Lister +from cliff.command import Command +from python_moonclient.core import models, policies, pdp +from python_moonclient.cli.parser import Parser +from python_moonclient.cli.projects import ProjectsUtils + +LOGGER = logging.getLogger("moonclient.cli.pdps") + + +class ModelUtils: + def __init__(self): + pass + + @staticmethod + def get_model_id(model, parsed_id, parsed_name): + modelz = models.check_model() + for _model_key, _model_value in modelz["models"].items(): + if _model_key == parsed_id or _model_value['name'] == parsed_name: + # LOGGER.info( + # "Found pdp : [key='{}' , name='{}']".format(_pdp_key, _pdp_value['name'])) + return _model_key + return None + + @staticmethod + def get_model_name(pdp, parsed_id, parsed_name): + modelz = models.check_model() + for _model_key, _model_value in modelz["models"].items(): + if _model_key == parsed_id or _model_value['name'] == parsed_name: + # LOGGER.info( + # "Found pdp : [key='{}' , name='{}']".format(_pdp_key, _pdp_value['name'])) + return _model_value['name'] + return None + + +class Models(Lister): + """show the list of existing pdps """ + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + modelz = models.check_model() + + return (('Key', 'Name'), + ((_model_key, _model_value['name']) for _model_key, _model_value in + modelz["models"].items()) + ) + + +class SubjectCategories(Lister): + """show the list of existing categories """ + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + subject_categories = models.check_subject_category() + print(subject_categories) + return (('Key', 'Name'), + ((_model_key, _model_value['name']) for _model_key, _model_value in + subject_categories["subject_categories"].items()) + ) + + +class ObjectCategories(Lister): + """show the list of existing categories """ + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + object_categories = models.check_object_category() + print(object_categories) + return (('Key', 'Name'), + ((_model_key, _model_value['name']) for _model_key, _model_value in + object_categories["object_categories"].items()) + ) + + +class ActionCategories(Lister): + """show the list of existing categories """ + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + action_categories = models.check_action_category() + print(action_categories) + return (('Key', 'Name'), + ((_model_key, _model_value['name']) for _model_key, _model_value in + action_categories["action_categories"].items()) + ) + + +class SubjectCategoryAdd(Command): + """show the list of existing categories """ + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + Parser.add_name_argument(parser) + + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + subject_category_id = models.add_subject_category(parsed_args.name) + if subject_category_id is not None: + print("Subject category created with id {}".format(subject_category_id)) + else: + print("Error while creating subject category") + # subject_categories = models.check_subject_category(subject_category_id) diff --git a/old/python_moonclient/python_moonclient/cli/parser.py b/old/python_moonclient/python_moonclient/cli/parser.py new file mode 100644 index 00000000..e71cd6c9 --- /dev/null +++ b/old/python_moonclient/python_moonclient/cli/parser.py @@ -0,0 +1,98 @@ +class Parser: + + @staticmethod + def add_common_options(parser): + parser.add_argument('--consul-host', + help='Set the name of the consul server (default: 127.0.0.1)', + default="127.0.0.1") + parser.add_argument('--consul-port', + help='Set the port of the consult server (default: 30005)', + default="30005") + parser.add_argument("--verbose", "-v", action='store_true', help="verbose mode") + parser.add_argument("--debug", "-d", action='store_true', help="debug mode") + + @staticmethod + def add_filename_argument(parser): + parser.add_argument('filename', help='configuration filename in json format') + + @staticmethod + def add_name_argument(parser): + Parser._add_name_argument(parser) + + @staticmethod + def add_policy_argument(parser): + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument('--policy-name', help='name of the policy') + group.add_argument('--policy-id', help='id of the policy') + + @staticmethod + def add_category_argument(parser): + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument('--category-name', help='name of the category') + group.add_argument('--category-id', help='id of the category') + + @staticmethod + def add_id_or_name_argument(parser): + group = parser.add_mutually_exclusive_group(required=True) + Parser._add_id_argument(group) + Parser._add_name_argument(group) + + @staticmethod + def _add_id_argument(parser): + parser.add_argument('--id', help='id of the element') + + @staticmethod + def _add_name_argument(parser): + parser.add_argument('--name', help='name of the element') + + @staticmethod + def add_id_or_name_pdp_argument(parser): + group = parser.add_mutually_exclusive_group(required=True) + Parser._add_id_pdp_argument(group) + Parser._add_name_pdp_argument(group) + + @staticmethod + def _add_id_pdp_argument(parser): + parser.add_argument('--id-pdp', help='id of the pdp') + + @staticmethod + def _add_name_pdp_argument(parser): + parser.add_argument('--name-pdp', help='name of the pdp') + + @staticmethod + def add_id_or_name_project_argument(parser): + group = parser.add_mutually_exclusive_group(required=True) + Parser._add_id_project_argument(group) + Parser._add_name_project_argument(group) + + @staticmethod + def _add_id_project_argument(parser): + parser.add_argument('--id-project', help='id of the project') + + @staticmethod + def _add_name_project_argument(parser): + parser.add_argument('--name-project', help='name of the project') + + @staticmethod + def add_authz_arguments(parser): + parser.add_argument("--dry-run", "-n", action='store_true', + help="Dry run", dest="dry_run") + parser.add_argument("--destination", + help="Set the type of output needed " + "(default: wrapper, other possible type: " + "interface).", + default="wrapper") + parser.add_argument("--authz-host", + help="Set the name of the authz server to test" + "(default: 127.0.0.1).", + default="127.0.0.1") + parser.add_argument("--authz-port", + help="Set the port of the authz server to test" + "(default: 31002).", + default="31002") + parser.add_argument("--stress-test", "-s", action='store_true', + dest='stress_test', + help="Execute stressing tests (warning delta measures " + "will be false, implies -t)") + parser.add_argument("--write", "-w", help="Write test data to a JSON file", + default="/tmp/data.json") diff --git a/old/python_moonclient/python_moonclient/cli/pdps.py b/old/python_moonclient/python_moonclient/cli/pdps.py new file mode 100644 index 00000000..a4f7bba0 --- /dev/null +++ b/old/python_moonclient/python_moonclient/cli/pdps.py @@ -0,0 +1,190 @@ +import logging +from importlib.machinery import SourceFileLoader +from cliff.lister import Lister +from cliff.command import Command + +from python_moonclient.core import models, policies, pdp +from python_moonclient.cli.parser import Parser +from python_moonclient.cli.projects import ProjectsUtils + +LOGGER = logging.getLogger("moonclient.cli.pdps") + + +class PdpUtils: + def __init__(self): + pass + + @staticmethod + def get_pdp_id(pdp, parsed_id, parsed_name): + pdps = pdp.check_pdp() + for _pdp_key, _pdp_value in pdps["pdps"].items(): + if _pdp_key == parsed_id or _pdp_value['name'] == parsed_name: + # LOGGER.info( + # "Found pdp : [key='{}' , name='{}']".format(_pdp_key, _pdp_value['name'])) + return _pdp_key + return None + + @staticmethod + def get_pdp_name(pdp, parsed_id, parsed_name): + pdps = pdp.check_pdp() + for _pdp_key, _pdp_value in pdps["pdps"].items(): + if _pdp_key == parsed_id or _pdp_value['name'] == parsed_name: + # LOGGER.info( + # "Found pdp : [key='{}' , name='{}']".format(_pdp_key, _pdp_value['name'])) + return _pdp_value['name'] + return None + + +class Pdps(Lister): + """show the list of existing pdps """ + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + pdps = pdp.check_pdp() + + return (('Key', 'Name', 'Project id'), + ((_pdp_key, _pdp_value['name'], _pdp_value['keystone_project_id']) for + _pdp_key, _pdp_value in pdps["pdps"].items()) + ) + + +class CreatePdp(Command): + """create a new pdp from a json file and returns the newly created pdp id""" + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + Parser.add_filename_argument(parser) + return parser + + def take_action(self, parsed_args): + + requests_log = logging.getLogger("requests.packages.urllib3") + requests_log.setLevel(logging.WARNING) + requests_log.propagate = True + + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + # project_id = args.keystone_pid + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + if parsed_args.filename: + LOGGER.info("Loading: {}".format(parsed_args.filename)) + m = SourceFileLoader("scenario", parsed_args.filename) + scenario = m.load_module() + + _models = models.check_model() + for _model_id, _model_value in _models['models'].items(): + if _model_value['name'] == scenario.model_name: + model_id = _model_id + meta_rule_list = _model_value['meta_rules'] + models.create_model(scenario, model_id) + break + else: + model_id, meta_rule_list = models.create_model(scenario) + policy_id = policies.create_policy(scenario, model_id, meta_rule_list) + pdp_id = pdp.create_pdp(scenario, policy_id=policy_id) + pdp_name = PdpUtils.get_pdp_name(pdp, pdp_id, None) + LOGGER.info("Pdp created : [id='{}', name='{}']".format(pdp_id, pdp_name)) + + +class DeletePdp(Command): + """delete an existing pdp""" + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + Parser.add_id_or_name_argument(parser) + return parser + + def take_action(self, parsed_args): + + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + _search = PdpUtils.get_pdp_id(pdp, parsed_args.id, parsed_args.name) + _pdp_key = _search + if _pdp_key is None: + LOGGER.error("Error pdp not found ") + return + + # if parsed_args.id: + # logger.info("Deleting: {}".format(parsed_args.id)) + # _search = parsed_args.id + # if parsed_args.name: + # logger.info("Deleting: {}".format(parsed_args.name)) + # _search = parsed_args.name + + # pdps = pdp.check_pdp() + # for _pdp_key, _pdp_value in pdps["pdps"].items(): + # if _pdp_key == _search or _pdp_value['name'] == _search: + LOGGER.info("Found {}".format(_pdp_key)) + pdp.delete_pdp(_pdp_key) + + pdps = pdp.check_pdp() + LOGGER.info("Listing all PDP:") + for _pdp_key, _pdp_value in pdps["pdps"].items(): + if _pdp_key == _search: # or _pdp_value['name'] == _search: + LOGGER.error("Error in deleting {}".format(_search)) + + return (('Key', 'Name', 'Project id'), + ((_pdp_key, _pdp_value['name'], _pdp_value['keystone_project_id']) for + _pdp_key, _pdp_value in + pdps["pdps"].items()) + ) + + +class MapPdp(Command): + """map an existing pdp to a keystone project""" + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + Parser.add_id_or_name_pdp_argument(parser) + Parser.add_id_or_name_project_argument(parser) + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + # _pdp_key = PdpUtils.get_pdp_id(pdp, parsed_args.id_pdp, parsed_args.name_pdp) + _pdp_name = PdpUtils.get_pdp_name(pdp, parsed_args.id_pdp, parsed_args.name_pdp) + if _pdp_name is None: + LOGGER.error("Error pdp not found ") + return + + # _project_key = ProjectsUtils.get_project_id( + # pdp, parsed_args.id_project, parsed_args.name_project) + _project_name = ProjectsUtils.get_project_name(pdp, parsed_args.id_project, + parsed_args.name_project) + if _project_name is None: + LOGGER.error("Error project not found ") + return + + LOGGER.info("Mapping: {}=>{}".format(_pdp_name, _project_name)) + + # pdp.map_to_keystone(pdp_id=parsed_args.id_pdp, keystone_project_id=parsed_args.id_project) + pdp.map_to_keystone(pdp_id=_pdp_name, keystone_project_id=_project_name) diff --git a/old/python_moonclient/python_moonclient/cli/policies.py b/old/python_moonclient/python_moonclient/cli/policies.py new file mode 100644 index 00000000..af8e959b --- /dev/null +++ b/old/python_moonclient/python_moonclient/cli/policies.py @@ -0,0 +1,264 @@ +import logging +from cliff.command import Command +from cliff.lister import Lister + +from python_moonclient.cli.parser import Parser + +from python_moonclient.core import models, policies, pdp + +LOGGER = logging.getLogger("moonclient.cli.pdps") + + +class PoliciesUtils: + def __init__(self): + pass + + @staticmethod + def get_policy_id(policies, parsed_id, parsed_name): + _policies = policies.check_policy() + for _policy_key, _policy_value in _policies["policies"].items(): + if _policy_key == parsed_id or _policy_value['name'] == parsed_name: + # logger.info("Found {}".format(_policy_key)) + return _policy_key + return None + + @staticmethod + def get_policy_name(policies, parsed_id, parsed_name): + _policies = policies.check_policy() + for _policy_key, _policy_value in _policies["policies"].items(): + if _policy_key == parsed_id or _policy_value['name'] == parsed_name: + # logger.info("Found {}".format(_policy_key)) + return _policy_value['name'] + return None + + +class Policies(Lister): + """show the list of existing policies""" + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + _policies = policies.check_policy() + + return (('Key', 'Name'), + ((_policy_key, _policy_value['name']) for _policy_key, _policy_value in + _policies["policies"].items()) + ) + + +class Subjects(Lister): + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + Parser.add_id_or_name_argument(parser) + Parser.add_policy_argument(parser) + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + _policies = policies.check_subject(parsed_args.id, parsed_args.policy_id) + + return (('Key', 'Name'), + ((_policy_key, _policy_value['name']) for _policy_key, _policy_value in + _policies["policies"].items()) + ) + + +class DeletePolicy(Command): + """delete an existing policy""" + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + Parser.add_id_or_name_argument(parser) + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + policy_id = PoliciesUtils.get_policy_id(policies, parsed_args.id, parsed_args.name) + policy_name = PoliciesUtils.get_policy_name(policies, parsed_args.id, parsed_args.name) + + LOGGER.info("Deleting: {}".format(policy_name)) + pdp.delete_pdp(policy_id) + + _policies = policies.check_policy() + # logger.info("Listing all Policies:") + for _policy_key, _policy_value in _policies["policies"].items(): + # print(" {} {}".format(_policy_key, _policy_value['name'])) + if _policy_key == policy_id: + LOGGER.error("Error in deleting {}".format(policy_id)) + + return (('Key', 'Value'), + ((_policy_key, _policy_value) for _policy_key, _policy_value in + _policies["policies"].items()) + ) + + +class SubjectDatas(Lister): + """list the subject data """ + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + Parser.add_policy_argument(parser) + Parser.add_category_argument(parser) + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + subject_data = policies.check_subject_data(parsed_args.policy_id, None, + parsed_args.category_id) + if len(subject_data["subject_data"]) == 0: + return (('Key', 'Name'), ()) + + return (('Key', 'Name'), + ((_subject_key, subject_data["subject_data"][0]["data"][_subject_key]['name']) for + _subject_key in subject_data["subject_data"][0]["data"].keys()) + ) + + +class ObjectDatas(Lister): + """list the object data""" + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + Parser.add_policy_argument(parser) + Parser.add_category_argument(parser) + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + object_datas = policies.check_object_data(parsed_args.policy_id, None, + parsed_args.category_id) + + if len(object_datas["object_data"]) == 0: + return (('Key', 'Name'), ()) + object_data = object_datas["object_data"][0]["data"] + res = (('Key', 'Name'), + ((_object_key, object_data[_object_key]["value"]['name']) for _object_key in + list(object_data)) + ) + return res + + +class ActionDatas(Lister): + """list the action data""" + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + Parser.add_policy_argument(parser) + Parser.add_category_argument(parser) + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + action_datas = policies.check_action_data(parsed_args.policy_id, None, + parsed_args.category_id) + + if len(action_datas["action_data"]) == 0: + return (('Key', 'Name'), ()) + action_data = action_datas["action_data"][0]["data"] + res = (('Key', 'Name'), + ((_action_key, action_data[_action_key]["value"]['name']) for _action_key in + list(action_data)) + ) + return res + + +class MetaRules(Lister): + """list the meta rules""" + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + metarule_datas = policies.check_meta_rule() + + if len(metarule_datas["meta_rules"]) == 0: + return (('Key', 'Name'), ()) + + metarule_data = metarule_datas["meta_rules"] + res = (('Key', 'Name'), + ((_key, metarule_data[_key]['name']) for _key in list(metarule_data)) + ) + return res + + +class CreateSubjectData(Command): + """create a subject data according to a policy and a category""" + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + Parser.add_policy_argument(parser) + Parser.add_category_argument(parser) + Parser.add_name_argument(parser) + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + subject_data_id = policies.add_subject_data(parsed_args.policy_id, parsed_args.category_id, + parsed_args.name) + if subject_data_id is not None: + print("Subject category created with id {}".format(subject_data_id)) + else: + print("Error while creating subject category") + subject_data = policies.check_subject_data(parsed_args.policy_id, None, + parsed_args.category_id) + # subject_categories = models.check_subject_category(subject_category_id) diff --git a/old/python_moonclient/python_moonclient/cli/projects.py b/old/python_moonclient/python_moonclient/cli/projects.py new file mode 100644 index 00000000..1caa0ace --- /dev/null +++ b/old/python_moonclient/python_moonclient/cli/projects.py @@ -0,0 +1,54 @@ +import logging +from python_moonclient.core import models, policies, pdp +from python_moonclient.cli.parser import Parser +from cliff.lister import Lister + +LOGGER = logging.getLogger("moonclient.cli.projects") + + +class ProjectsUtils: + def __init__(self): + pass + + @staticmethod + def get_project_id(pdp, parsed_id, parsed_name): + projects = pdp.get_keystone_projects() + for _project_value in projects['projects']: + if _project_value['id'] == parsed_id or _project_value['name'] == parsed_name: + # LOGGER.info( + # "Found project : [key='{}' , name='{}']".format(_project_value['id'], _project_value['name'])) + return _project_value['id'] + return None + + @staticmethod + def get_project_name(pdp, parsed_id, parsed_name): + projects = pdp.get_keystone_projects() + for _project_value in projects['projects']: + if _project_value['id'] == parsed_id or _project_value['name'] == parsed_name: + # LOGGER.info( + # "Found project : [key='{}' , name='{}']".format(_project_value['id'], _project_value['name'])) + return _project_value['name'] + return None + + +class Projects(Lister): + """show the list of projects""" + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + return parser + + def take_action(self, parsed_args): + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + + projects = pdp.get_keystone_projects() + + return (('Id', 'Name'), + ((_project['id'], _project['name']) for _project in projects['projects']) + ) diff --git a/old/python_moonclient/python_moonclient/cli/slaves.py b/old/python_moonclient/python_moonclient/cli/slaves.py new file mode 100644 index 00000000..587e9033 --- /dev/null +++ b/old/python_moonclient/python_moonclient/cli/slaves.py @@ -0,0 +1,120 @@ +import logging +from cliff.lister import Lister +from cliff.command import Command + +from python_moonclient.core import models, policies, pdp, slaves +from python_moonclient.cli.parser import Parser + +LOGGER = logging.getLogger("moonclient.cli.slaves") + + +class SlavesUtils: + def __init__(self): + pass + + @staticmethod + def get_slave_name(slaves, parsed_name): + _slaves = slaves.get_slaves() + for _slave_value in _slaves['slaves']: + if _slave_value['name'] == parsed_name: + LOGGER.info("Found {}".format(_slave_value['name'])) + return _slave_value['name'] + return None + + +class Slaves(Lister): + """show the list of slaves""" + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + return parser + + def take_action(self, parsed_args): + requests_log = logging.getLogger("requests.packages.urllib3") + requests_log.setLevel(logging.WARNING) + requests_log.propagate = True + + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + slaves.init(consul_host, consul_port) + + return (('Name', 'Configured'), + ((value['name'], value['configured']) for value in + slaves.get_slaves().get('slaves', dict())) + ) + + +class SetSlave(Command): + """update an existing slave to a configured state""" + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + Parser.add_name_argument(parser) + return parser + + def take_action(self, parsed_args): + requests_log = logging.getLogger("requests.packages.urllib3") + requests_log.setLevel(logging.WARNING) + requests_log.propagate = True + + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + slaves.init(consul_host, consul_port) + + slave_input_name = parsed_args.name + if parsed_args.name is None: + slave_input_name = "kubernetes-admin@kubernetes" + slaves.set_slave(slave_input_name) + + # if slave_name is None: + # slave_name = "kubernetes-admin@kubernetes" + + # if parsed_args.name: + # slave_name = parsed_args.name + print(" {} (configured=True)".format(slave_input_name)) + + # for value in slaves.set_slave(slave_name).get('slaves', dict()): + # if value['configured']: + # print(" {} (configured)".format(value['name'])) + # else: + # print(" {} (not configured)".format(value['name']))# + + +class DeleteSlave(Command): + """update an existing slave to a unconfigured state""" + + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + Parser.add_common_options(parser) + Parser.add_name_argument(parser) + return parser + + def take_action(self, parsed_args): + requests_log = logging.getLogger("requests.packages.urllib3") + requests_log.setLevel(logging.WARNING) + requests_log.propagate = True + + consul_host = parsed_args.consul_host + consul_port = parsed_args.consul_port + + models.init(consul_host, consul_port) + policies.init(consul_host, consul_port) + pdp.init(consul_host, consul_port) + slaves.init(consul_host, consul_port) + + slave_input_name = parsed_args.name + if parsed_args.name is None: + slave_input_name = "kubernetes-admin@kubernetes" + + slaves.delete_slave(slave_input_name) + print(" {} (configured=False)".format(slave_input_name)) diff --git a/old/python_moonclient/python_moonclient/core/__init__.py b/old/python_moonclient/python_moonclient/core/__init__.py new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/old/python_moonclient/python_moonclient/core/__init__.py diff --git a/old/python_moonclient/python_moonclient/core/authz.py b/old/python_moonclient/python_moonclient/core/authz.py new file mode 100644 index 00000000..d331004c --- /dev/null +++ b/old/python_moonclient/python_moonclient/core/authz.py @@ -0,0 +1,180 @@ +from uuid import uuid4 +import copy +import logging +import threading +import time +import json +import random +import requests + +HOST_MANAGER = None +PORT_MANAGER = None +HOST_KEYSTONE = None +PORT_KEYSTONE = None + +LOCK = threading.Lock() +LOGGER = logging.getLogger("moonclient.core.authz") + + +def _construct_payload(creds, current_rule, enforcer, target): + # Convert instances of object() in target temporarily to + # empty dict to avoid circular reference detection + # errors in jsonutils.dumps(). + temp_target = copy.deepcopy(target) + for key in target.keys(): + element = target.get(key) + if type(element) is object: + temp_target[key] = {} + _data = _json = None + if enforcer: + _data = {'rule': current_rule, + 'target': json.dumps(temp_target), + 'credentials': json.dumps(creds)} + else: + _json = {'rule': current_rule, + 'target': temp_target, + 'credentials': creds} + return _data, _json + + +def _send(url, data=None, stress_test=False): + current_request = dict() + current_request['url'] = url + try: + if stress_test: + current_request['start'] = time.time() + # with LOCK: + res = requests.get(url) + current_request['end'] = time.time() + current_request['delta'] = current_request["end"] - current_request["start"] + else: + with LOCK: + current_request['start'] = time.time() + if data: + data, _ = _construct_payload(data['credentials'], data['rule'], True, + data['target']) + res = requests.post(url, json=data, + headers={'content-type': "application/x-www-form-urlencode"} + ) + else: + res = requests.get(url) + current_request['end'] = time.time() + current_request['delta'] = current_request["end"] - current_request["start"] + except requests.exceptions.ConnectionError: + LOGGER.warning("Unable to connect to server") + return {} + if not stress_test: + try: + j = res.json() + if res.status_code == 200: + LOGGER.warning("\033[1m{}\033[m \033[32mGrant\033[m".format(url)) + elif res.status_code == 401: + LOGGER.warning("\033[1m{}\033[m \033[31mDeny\033[m".format(url)) + else: + LOGGER.error("\033[1m{}\033[m {} {}".format(url, res.status_code, res.text)) + except Exception as e: + if res.text == "True": + LOGGER.warning("\033[1m{}\033[m \033[32mGrant\033[m".format(url)) + elif res.text == "False": + LOGGER.warning("\033[1m{}\033[m \033[31mDeny\033[m".format(url)) + else: + LOGGER.error("\033[1m{}\033[m {} {}".format(url, res.status_code, res.text)) + LOGGER.exception(e) + LOGGER.error(res.text) + else: + if j.get("result"): + # logger.warning("{} \033[32m{}\033[m".format(url, j.get("result"))) + LOGGER.debug("{}".format(j.get("error", ""))) + current_request['result'] = "Grant" + else: + # logger.warning("{} \033[31m{}\033[m".format(url, "Deny")) + LOGGER.debug("{}".format(j)) + current_request['result'] = "Deny" + return current_request + + +class AsyncGet(threading.Thread): + + def __init__(self, url, semaphore=None, **kwargs): + threading.Thread.__init__(self) + self.url = url + self.kwargs = kwargs + self.sema = semaphore + self.result = dict() + self.uuid = uuid4().hex + self.index = kwargs.get("index", 0) + + def run(self): + self.result = _send(self.url, + data=self.kwargs.get("data"), + stress_test=self.kwargs.get("stress_test", False)) + self.result['index'] = self.index + + +def send_requests(scenario, authz_host, authz_port, keystone_project_id, request_second=1, + limit=500, + dry_run=None, stress_test=False, destination="wrapper"): + backgrounds = [] + time_data = list() + start_timing = time.time() + request_cpt = 0 + subjects = tuple(scenario.subjects.keys()) + objects = tuple(scenario.objects.keys()) + actions = tuple(scenario.actions.keys()) + while request_cpt < limit: + rule = (random.choice(subjects), random.choice(objects), random.choice(actions)) + if destination.lower() == "wrapper": + url = "http://{}:{}/authz/oslo".format(authz_host, authz_port) + data = { + 'target': { + "user_id": random.choice(subjects), + "target": { + "name": random.choice(objects) + }, + "project_id": keystone_project_id + }, + 'credentials': None, + 'rule': random.choice(actions) + } + else: + url = "http://{}:{}/authz/{}/{}".format(authz_host, authz_port, keystone_project_id, + "/".join(rule)) + data = None + if dry_run: + LOGGER.info(url) + continue + request_cpt += 1 + if stress_test: + time_data.append(copy.deepcopy(_send(url, stress_test=stress_test))) + else: + background = AsyncGet(url, stress_test=stress_test, data=data, + index=request_cpt) + backgrounds.append(background) + background.start() + if request_second > 0: + if request_cpt % request_second == 0: + if time.time() - start_timing < 1: + while True: + if time.time() - start_timing > 1: + break + start_timing = time.time() + if not stress_test: + for background in backgrounds: + background.join() + if background.result: + time_data.append(copy.deepcopy(background.result)) + return time_data + + +def save_data(filename, time_data): + json.dump(time_data, open(filename, "w")) + + +def get_delta(time_data): + time_delta = list() + time_delta_sum1 = 0 + for item in time_data: + time_delta.append(item['delta']) + time_delta_sum1 += item['delta'] + time_delta_average1 = time_delta_sum1 / len(time_data) + return time_delta, time_delta_average1 diff --git a/old/python_moonclient/python_moonclient/core/check_tools.py b/old/python_moonclient/python_moonclient/core/check_tools.py new file mode 100644 index 00000000..381e92c7 --- /dev/null +++ b/old/python_moonclient/python_moonclient/core/check_tools.py @@ -0,0 +1,458 @@ +from python_moonclient.core.cli_exceptions import MoonCliException + + +def check_optionnal_result(result): + if type(result) is not dict: + raise MoonCliException("Unexpected request result. It should be a dictionnary") + if "result" in result: + check_result(result) + + +def check_result(result): + if type(result) is not dict or "result" not in result: + raise MoonCliException( + "Unexpected request result. It should be a dictionnary with a 'result' entry") + if result["result"] is None: + raise MoonCliException("Unexpected request result. The 'result' entry shall not be null") + + +def _check_generic_in_result(field, result, check_not_null=False): + if type(field) is not str or type(result) is not dict or field not in result: + raise MoonCliException( + "Unexpected request result. It should be a dictionnary with a '{}' entry".format(field)) + if check_not_null is True and result[field] is None: + raise MoonCliException( + "Unexpected request result. The '{}' entry shall not be null".format(field)) + + +def check_slaves_in_result(result): + _check_generic_in_result("slaves", result) + + +def check_pdp_in_result(result): + _check_generic_in_result("pdps", result) + + +def check_model_in_result(result, check_not_null=False): + _check_generic_in_result("models", result) + if check_not_null is True and result["models"] is None: + raise MoonCliException("Unexpected request result. The 'models' entry shall not be null") + + +def check_meta_rule_in_result(result): + _check_generic_in_result("meta_rules", result) + + +def check_rule_in_result(result): + _check_generic_in_result("rules", result) + + +def check_subject_in_result(result): + _check_generic_in_result("subjects", result) + + +def check_subject_category_in_result(result): + _check_generic_in_result("subject_categories", result) + + +def check_object_category_in_result(result): + _check_generic_in_result("object_categories", result) + + +def check_action_category_in_result(result): + _check_generic_in_result("action_categories", result) + + +def check_policy_in_result(result): + _check_generic_in_result("policies", result) + + +def check_object_in_result(result): + _check_generic_in_result("objects", result) + + +def check_action_in_result(result): + _check_generic_in_result("actions", result) + + +def check_subject_assignment_in_result(result): + _check_generic_in_result("subject_assignments", result, True) + + +def check_object_assignment_in_result(result): + _check_generic_in_result("object_assignments", result, True) + + +def check_action_assignment_in_result(result): + _check_generic_in_result("action_assignments", result, True) + + +def check_pdp_id(pdp_id, result): + check_pdp_in_result(result) + if pdp_id not in result['pdps']: + raise MoonCliException("Unexpected request result. Unknown pdp id") + + +def _check_generic_name(field, name, field_elt_id, result, do_check_name=True): + if type(field) is str: + if result[field] is None: + raise MoonCliException( + "Unexpected request result : {} shall not be empty".format(field)) + if field_elt_id not in result[field]: + raise MoonCliException("Unexpected request result. Unknown {} id".format(field)) + if "name" not in result[field][field_elt_id]: + raise MoonCliException( + "Unexpected request result : {} with id {} has no name".format(field, field_elt_id)) + if do_check_name and name != result[field][field_elt_id]["name"]: + raise MoonCliException( + "Unexpected request result : {} with id {} has a bad name. Expected {}".format( + field, field_elt_id, name)) + + +def check_model_name(name, model_id, result, do_check_name): + _check_generic_name("models", name, model_id, result, do_check_name) + + +def check_pdp_name(name, pdp_id, result): + _check_generic_name("pdps", name, pdp_id, result) + + +def check_subject_categories_name(name, category_id, result): + _check_generic_name("subject_categories", name, category_id, result) + + +def check_object_categories_name(name, category_id, result): + _check_generic_name("object_categories", name, category_id, result) + + +def check_action_categories_name(name, category_id, result): + _check_generic_name("action_categories", name, category_id, result) + + +def check_meta_rules_name(name, meta_rule_id, result): + _check_generic_name("meta_rules", name, meta_rule_id, result, False) + + +def check_policy_name(name, policy_id, result): + _check_generic_name("policies", name, policy_id, result) + + +def check_subject_name(name, subject_id, result): + _check_generic_name("subjects", name, subject_id, result) + + +def check_object_name(name, object_id, result): + _check_generic_name("objects", name, object_id, result) + + +def check_action_name(name, action_id, result): + _check_generic_name("actions", name, action_id, result) + + +def check_scat_id_in_dict(scat_id, in_dict): + if scat_id not in in_dict: + raise MoonCliException("Unexpected request result. Subject category not in result") + + +def check_ocat_id_in_dict(ocat_id, in_dict): + if ocat_id not in in_dict: + raise MoonCliException("Unexpected request result. Object category not in result") + + +def check_acat_id_in_dict(acat_id, in_dict): + if acat_id not in in_dict: + raise MoonCliException("Unexpected request result. Action category not in result") + + +def check_policy_id_in_pipeline(policy_id, pipeline): + if policy_id not in pipeline: + raise MoonCliException( + "Unexpected request result. The policy id {} shall be in the pipeline".format( + policy_id)) + + +def _check_generic_policy_in_dict(field, policy_id, in_dict): + if type(field) is str: + if policy_id is not None: + if "policy_list" not in in_dict: + raise MoonCliException( + "Unexpected request result. The policy list of the {} shall not be empty".format( + field)) + if policy_id not in in_dict["policy_list"]: + raise MoonCliException( + "Unexpected request result. The policy with id {} shall be in the {}".format( + policy_id, field)) + + +def check_subject_policy(policy_id, in_dict): + _check_generic_policy_in_dict("subject", policy_id, in_dict) + + +def check_object_policy(policy_id, in_dict): + _check_generic_policy_in_dict("object", policy_id, in_dict) + + +def check_action_policy(policy_id, in_dict): + _check_generic_policy_in_dict("action", policy_id, in_dict) + + +def _check_generic_elt_id(field1, field1_id, field2, field2_id, result): + if type(field1) is str and type(field2) is str: + if result[field1] is None: + raise MoonCliException( + "Unexpected request result: {} shall not be empty".format(field1)) + if field1_id not in result[field1]: + raise MoonCliException("Unexpected request result. Unknown {} with id".format(field1)) + if field2 not in result[field1][field1_id]: + raise MoonCliException( + "Unexpected request result. {} element with id {} has no {} field".format(field1, + field1_id, + field2)) + if field2_id != result[field1][field1_id][field2]: + raise MoonCliException( + "Unexpected request result. {} element with id {} has a bad {} id. Expected {}".format( + field1, field1_id, field2, field2_id)) + + +def check_policy_model_id(model_id, policy_id, result): + _check_generic_elt_id("policies", policy_id, "model_id", model_id, result) + + +def check_pdp_project_id(project_id, pdp_id, result): + _check_generic_elt_id("pdps", pdp_id, "keystone_project_id", project_id, result) + + +def check_subject_description(description, in_dict): + if description is not None: + if "description" not in in_dict: + raise MoonCliException( + "Unexpected request result. The description of the subject shall not be empty") + if description not in in_dict["description"]: + raise MoonCliException( + "Unexpected request result. The description {} shall be in the subject".format( + description)) + + +def check_meta_rules_list_in_model(meta_rule_list, model_id, result): + if result["models"] is None: + raise MoonCliException("Unexpected request result. results shall not be empty") + if model_id not in result['models']: + raise MoonCliException("Unexpected request result. Unknown Model id") + if "meta_rules" not in result['models'][model_id]: + raise MoonCliException( + "Unexpected request result. Meta rules related to model with id {} are empty".format( + model_id)) + if meta_rule_list != result['models'][model_id]["meta_rules"]: + raise MoonCliException( + "Unexpected request result. Meta rule of model with id {} are different from those expected".format( + model_id)) + + +def check_name_in_slaves(name, slaves): + if name is None: + raise MoonCliException("The slave name must be provided !") + names = map(lambda x: x['name'], slaves) + if name not in names: + raise MoonCliException("The slave '{}' was not found !".format(name)) + + +def _check_generic_data_data(field, result): + if type(field) is str: + if field not in result: + raise MoonCliException( + "Unexpected request result. The {} field shall be in result".format(field)) + # if "data" not in resulti[field]: + # raise MoonCliException("Unexpected request result. The data field shall be in result['{}']".format(field)) + + +def _check_id_in_generic_data_data(field, data_id, result): + if type(field) is str: + _check_generic_data_data(field, result) + for _data in result[field]: + if data_id not in list(_data['data'].keys()): + raise MoonCliException( + "Unexpected request result. Data id {} not in {}".format(data_id, field)) + + +def _check_id_not_in_generic_data_data(field, data_id, result): + if type(field) is str: + _check_generic_data_data(field, result) + for _data in result[field]: + if data_id in list(_data['data'].keys()): + raise MoonCliException( + "Unexpected request result. Data id {} shall not be in {}".format(data_id, + field)) + + +def _check_category_in_generic_data_data(field, category_id, result): + _check_generic_data_data(field, result) + for _data in result[field]: + if category_id != _data["category_id"]: + raise MoonCliException( + "Unexpected request result. Category id {} not in {} data".format(category_id, + field)) + + +def check_subject_data_data(result): + _check_generic_data_data("subject_data", result) + + +def check_id_in_subject_data_data(data_id, result): + _check_id_in_generic_data_data("subject_data", data_id, result) + + +def check_id_not_in_subject_data_data(data_id, result): + _check_id_not_in_generic_data_data("subject_data", data_id, result) + + +def check_category_id_in_subject_data_data(category_id, result): + _check_category_in_generic_data_data('subject_data', category_id, result) + + +def check_object_data_data(result): + _check_generic_data_data("object_data", result) + + +def check_id_in_object_data_data(data_id, result): + _check_id_in_generic_data_data("object_data", data_id, result) + + +def check_id_not_in_object_data_data(data_id, result): + _check_id_not_in_generic_data_data("object_data", data_id, result) + + +def check_category_id_in_object_data_data(category_id, result): + _check_category_in_generic_data_data('object_data', category_id, result) + + +def check_action_data_data(result): + _check_generic_data_data("action_data", result) + + +def check_id_in_action_data_data(data_id, result): + _check_id_in_generic_data_data("action_data", data_id, result) + + +def check_id_not_in_action_data_data(data_id, result): + _check_id_not_in_generic_data_data("action_data", data_id, result) + + +def check_category_id_in_action_data_data(category_id, result): + _check_category_in_generic_data_data('action_data', category_id, result) + + +def _check_generic_assignments(field, field_id_name, field_id, field_cat_id, field_data_id, result): + if type(field) is str and type(field_id_name) is str: + for key in result[field]: + if field_id_name not in result[field][key]: + raise MoonCliException( + "Unexpected request result. subject_id not in result[{}] data".format(field)) + if "category_id" not in result[field][key]: + raise MoonCliException( + "Unexpected request result. category_id not in result[{}] data".format(field)) + if "assignments" not in result[field][key]: + raise MoonCliException( + "Unexpected request result. assignments not in result[{}] data".format(field)) + if result[field][key][field_id_name] == field_id and \ + result[field][key]["category_id"] == field_cat_id: + if field_data_id not in result[field][key]["assignments"]: + raise MoonCliException( + "Unexpected request result. {} data with id {} not in result[{}][]['assignements'] data".format( + field, field_data_id, field)) + + +def check_subject_assignements(subject_id, subject_act_id, subject_data_id, result): + _check_generic_assignments("subject_assignments", "subject_id", subject_id, subject_act_id, + subject_data_id, result) + + +def check_object_assignements(object_id, object_act_id, object_data_id, result): + _check_generic_assignments("object_assignments", "object_id", object_id, object_act_id, + object_data_id, result) + + +def check_action_assignements(action_id, action_act_id, action_data_id, result): + _check_generic_assignments("action_assignments", "action_id", action_id, action_act_id, + action_data_id, result) + + +def _check_not_generic_assignments(field, field_id_name, field_id, field_cat_id, field_data_id, + result): + if type(field) is str and type(field_id_name) is str: + for key in result[field]: + if field_id_name not in result[field][key]: + raise MoonCliException( + "Unexpected request result. subject_id not in result[{}] data".format(field)) + if "category_id" not in result[field][key]: + raise MoonCliException( + "Unexpected request result. category_id not in result[{}] data".format(field)) + if "assignments" not in result[field][key]: + raise MoonCliException( + "Unexpected request result. assignments not in result[{}] data".format(field)) + if result[field][key]['subject_id'] == field_id and \ + result[field][key]["category_id"] == field_cat_id: + if field_data_id in result[field][key]["assignments"]: + raise MoonCliException( + "Unexpected request result. {} data with id {} shall not be in result[{}][]['assignements'] data".format( + field, field_data_id, field)) + + +def check_not_subject_assignements(subject_id, subject_act_id, subject_data_id, result): + _check_not_generic_assignments("subject_assignments", "subject_id", subject_id, subject_act_id, + subject_data_id, result) + + +def check_not_object_assignements(object_id, object_act_id, object_data_id, result): + _check_not_generic_assignments("object_assignments", "object_id", object_id, object_act_id, + object_data_id, result) + + +def check_not_action_assignements(action_id, action_act_id, action_data_id, result): + _check_not_generic_assignments("action_assignments", "action_id", action_id, action_act_id, + action_data_id, result) + + +def check_policy_id_in_dict(policy_id, in_dict): + if "policy_id" not in in_dict: + raise MoonCliException("Unexpected request result. policy_id not in result") + if policy_id != in_dict["policy_id"]: + raise MoonCliException( + "Unexpected request result. Bad policy id in result, expected {}".format(policy_id)) + + +def check_meta_rule_id_in_dict(meta_rule_id, in_dict): + if "meta_rule_id" not in in_dict: + raise MoonCliException("Unexpected request result. meta_rule_id not in result") + if meta_rule_id != in_dict["meta_rule_id"]: + raise MoonCliException( + "Unexpected request result. Bad meta rule id in result, expected {}".format( + meta_rule_id)) + + +def check_rule_in_dict(rule, in_dict): + if "rule" not in in_dict: + raise MoonCliException("Unexpected request result. rule not in result") + if rule != in_dict["rule"]: + raise MoonCliException( + "Unexpected request result. Bad rule in result, expected {}".format(rule)) + + +def check_rule_id_in_list(meta_rule_id, rule_id, rule, in_dict): + for item in in_dict: + if "meta_rule_id" not in item: + raise MoonCliException("Unexpected request result. meta_rule_id field not in result") + if meta_rule_id == item["meta_rule_id"]: + if rule_id == item["id"]: + if rule != item["rule"]: + raise MoonCliException( + "Unexpected request result. Bad rule in result, expected {}".format(rule)) + + +def check_rule_id_not_in_list(rule_id, in_dict): + found_rule = False + for item in in_dict: + if rule_id == item["id"]: + found_rule = True + if found_rule is True: + raise MoonCliException( + "Unexpected request result. Rule with id {} shall not be in result".format(rule_id)) diff --git a/old/python_moonclient/python_moonclient/core/cli_exceptions.py b/old/python_moonclient/python_moonclient/core/cli_exceptions.py new file mode 100644 index 00000000..01fd23e0 --- /dev/null +++ b/old/python_moonclient/python_moonclient/core/cli_exceptions.py @@ -0,0 +1,4 @@ +class MoonCliException(Exception): + def __init__(self, message): + # Call the base class constructor with the parameters it needs + super(MoonCliException, self).__init__(message) diff --git a/old/python_moonclient/python_moonclient/core/config.py b/old/python_moonclient/python_moonclient/core/config.py new file mode 100644 index 00000000..c123499b --- /dev/null +++ b/old/python_moonclient/python_moonclient/core/config.py @@ -0,0 +1,64 @@ +import base64 +import json +import requests + + +def get_configuration(consul_host, consul_port, key): + url = "http://{}:{}/v1/kv/{}".format(consul_host, consul_port, key) + req = requests.get(url) + if req.status_code != 200: + raise Exception("Exception when retrieving configuration from Consul: {} {}".format( + req.status_code, req.text + )) + data = req.json() + if len(data) == 1: + data = data[0] + return {data["Key"]: json.loads(base64.b64decode(data["Value"]).decode("utf-8"))} + return [ + {item["Key"]: json.loads(base64.b64decode(item["Value"]).decode("utf-8"))} + for item in data + ] + + +def get_config_data(consul_host, consul_port): + conf_data = dict() + conf_data['manager_host'] = get_configuration( + consul_host, consul_port, + 'components/manager')['components/manager']['external']['hostname'] + conf_data['manager_port'] = get_configuration( + consul_host, consul_port, + 'components/manager')['components/manager']['external']['port'] + try: + requests.get("http://{}:{}/".format( + conf_data['manager_host'], + conf_data['manager_port'] + ), + timeout=2) + except requests.exceptions.ConnectionError: + conf_data['manager_host'] = get_configuration(consul_host, consul_port, + 'components/manager')[ + 'components/manager']['hostname'] + conf_data['manager_port'] = get_configuration(consul_host, consul_port, + 'components/manager')[ + 'components/manager']['port'] + + conf_data['keystone_host'] = get_configuration( + consul_host, consul_port, + 'openstack/keystone')['openstack/keystone']['external']['url'] + try: + requests.get(conf_data['keystone_host'], timeout=2) + except requests.exceptions.ConnectionError: + conf_data['keystone_host'] = get_configuration( + consul_host, consul_port, + 'openstack/keystone')['openstack/keystone']['url'] + + conf_data['keystone_user'] = get_configuration(consul_host, consul_port, + 'openstack/keystone')['openstack/keystone'][ + 'user'] + conf_data['keystone_password'] = get_configuration(consul_host, consul_port, + 'openstack/keystone')['openstack/keystone'][ + 'password'] + conf_data['keystone_project'] = get_configuration(consul_host, consul_port, + 'openstack/keystone')['openstack/keystone'][ + 'project'] + return conf_data diff --git a/old/python_moonclient/python_moonclient/core/json_export.py b/old/python_moonclient/python_moonclient/core/json_export.py new file mode 100644 index 00000000..edaeb177 --- /dev/null +++ b/old/python_moonclient/python_moonclient/core/json_export.py @@ -0,0 +1,26 @@ +import logging +import copy +import requests +from python_moonclient.core import config + +LOGGER = logging.getLogger("moonclient.core.export_json") + +URL = None +HEADERS = None + + +def init(consul_host, consul_port): + conf_data = config.get_config_data(consul_host, consul_port) + global URL, HEADERS + URL = "http://{}:{}".format( + conf_data['manager_host'], + conf_data['manager_port']) + URL = URL + "{}" + HEADERS = {"content-type": "application/json"} + + +def export_to_json(): + req = requests.get(URL.format("/export")) + req.raise_for_status() + result = req.json() + return result diff --git a/old/python_moonclient/python_moonclient/core/json_import.py b/old/python_moonclient/python_moonclient/core/json_import.py new file mode 100644 index 00000000..b65ec39b --- /dev/null +++ b/old/python_moonclient/python_moonclient/core/json_import.py @@ -0,0 +1,29 @@ +import logging +import requests +import copy +from python_moonclient.core import config + +LOGGER = logging.getLogger("moonclient.core.import_json") + +URL = None +HEADERS = None + + +def init(consul_host, consul_port): + conf_data = config.get_config_data(consul_host, consul_port) + global URL, HEADERS + URL = "http://{}:{}".format( + conf_data['manager_host'], + conf_data['manager_port']) + URL = URL + "{}" + HEADERS = {"content-type": "application/json"} + + +def import_json(file_name): + files = {'file': open(file_name, 'rb')} + req = requests.post(URL.format("/import"), files=files) + result = req.json() + if isinstance(result, dict) and "message" in result: + req.reason = result["message"] + req.raise_for_status() + return result diff --git a/old/python_moonclient/python_moonclient/core/models.py b/old/python_moonclient/python_moonclient/core/models.py new file mode 100644 index 00000000..8d3c8858 --- /dev/null +++ b/old/python_moonclient/python_moonclient/core/models.py @@ -0,0 +1,279 @@ +import logging +import copy +import requests +from python_moonclient.core import config +from python_moonclient.core.check_tools import * + +LOGGER = logging.getLogger("moonclient.core.models") + +URL = None +HEADERS = None + +model_template = { + "name": "test_model", + "description": "test", + "meta_rules": [] +} + +category_template = { + "name": "name of the category", + "description": "description of the category" +} + +meta_rule_template = { + "name": "test_meta_rule", + "subject_categories": [], + "object_categories": [], + "action_categories": [] +} + + +def init(consul_host, consul_port): + conf_data = config.get_config_data(consul_host, consul_port) + global URL, HEADERS + URL = "http://{}:{}".format( + conf_data['manager_host'], + conf_data['manager_port']) + URL = URL + "{}" + HEADERS = {"content-type": "application/json"} + + +def check_model(model_id=None, do_check_model_name=True): + req = requests.get(URL.format("/models")) + req.raise_for_status() + result = req.json() + check_model_in_result(result) + if model_id: + check_model_name(model_template["name"], model_id, result, do_check_model_name) + return result + + +def add_model(name=None): + if name: + model_template['name'] = name + req = requests.post(URL.format("/models"), json=model_template, headers=HEADERS) + req.raise_for_status() + result = req.json() + check_model_in_result(result) + model_id = list(result['models'].keys())[0] + check_model_name(model_template["name"], model_id, result, True) + return model_id + + +def delete_model(model_id): + req = requests.delete(URL.format("/models/{}".format(model_id))) + req.raise_for_status() + result = req.json() + check_result(result) + + +def add_subject_category(name="subject_cat_1"): + category_template["name"] = name + req = requests.post(URL.format("/subject_categories"), json=category_template, headers=HEADERS) + req.raise_for_status() + result = req.json() + + check_subject_category_in_result(result) + category_id = list(result['subject_categories'].keys())[0] + check_optionnal_result(result) + check_subject_categories_name(category_template["name"], category_id, result) + return category_id + + +def check_subject_category(category_id=None): + req = requests.get(URL.format("/subject_categories")) + req.raise_for_status() + result = req.json() + + check_subject_category_in_result(result) + check_optionnal_result(result) + if category_id is not None: + check_subject_categories_name(category_template["name"], category_id, result) + return result + + +def delete_subject_category(category_id): + req = requests.delete(URL.format("/subject_categories/{}".format(category_id))) + req.raise_for_status() + result = req.json() + check_optionnal_result(result) + + +def add_object_category(name="object_cat_1"): + category_template["name"] = name + req = requests.post(URL.format("/object_categories"), json=category_template, headers=HEADERS) + req.raise_for_status() + result = req.json() + check_object_category_in_result(result) + category_id = list(result['object_categories'].keys())[0] + check_optionnal_result(result) + check_object_categories_name(category_template["name"], category_id, result) + return category_id + + +def check_object_category(category_id=None): + req = requests.get(URL.format("/object_categories")) + req.raise_for_status() + result = req.json() + check_object_category_in_result(result) + check_optionnal_result(result) + if category_id is not None: + check_object_categories_name(category_template["name"], category_id, result) + return result + + +def delete_object_category(category_id): + req = requests.delete(URL.format("/object_categories/{}".format(category_id))) + req.raise_for_status() + result = req.json() + check_optionnal_result(result) + + +def add_action_category(name="action_cat_1"): + category_template["name"] = name + req = requests.post(URL.format("/action_categories"), json=category_template, headers=HEADERS) + req.raise_for_status() + result = req.json() + check_action_category_in_result(result) + category_id = list(result['action_categories'].keys())[0] + check_optionnal_result(result) + check_action_categories_name(category_template["name"], category_id, result) + return category_id + + +def check_action_category(category_id=None): + req = requests.get(URL.format("/action_categories")) + req.raise_for_status() + result = req.json() + print(result) + check_action_category_in_result(result) + check_optionnal_result(result) + if category_id is not None: + check_action_categories_name(category_template["name"], category_id, result) + return result + + +def delete_action_category(category_id): + req = requests.delete(URL.format("/action_categories/{}".format(category_id))) + req.raise_for_status() + result = req.json() + check_optionnal_result(result) + + +def add_categories_and_meta_rule(name="test_meta_rule"): + scat_id = add_subject_category() + ocat_id = add_object_category() + acat_id = add_action_category() + _meta_rule_template = copy.deepcopy(meta_rule_template) + _meta_rule_template["name"] = name + _meta_rule_template["subject_categories"].append(scat_id) + _meta_rule_template["object_categories"].append(ocat_id) + _meta_rule_template["action_categories"].append(acat_id) + req = requests.post(URL.format("/meta_rules"), json=_meta_rule_template, headers=HEADERS) + req.raise_for_status() + result = req.json() + check_meta_rule_in_result(result) + meta_rule_id = list(result['meta_rules'].keys())[0] + check_optionnal_result(result) + check_meta_rules_name(_meta_rule_template["name"], meta_rule_id, result) + return meta_rule_id, scat_id, ocat_id, acat_id + + +def add_meta_rule(name="test_meta_rule", scat=[], ocat=[], acat=[]): + _meta_rule_template = copy.deepcopy(meta_rule_template) + _meta_rule_template["name"] = name + _meta_rule_template["subject_categories"] = [] + _meta_rule_template["subject_categories"].extend(scat) + _meta_rule_template["object_categories"] = [] + _meta_rule_template["object_categories"].extend(ocat) + _meta_rule_template["action_categories"] = [] + _meta_rule_template["action_categories"].extend(acat) + req = requests.post(URL.format("/meta_rules"), json=_meta_rule_template, headers=HEADERS) + req.raise_for_status() + result = req.json() + check_meta_rule_in_result(result) + meta_rule_id = list(result['meta_rules'].keys())[0] + check_optionnal_result(result) + check_meta_rules_name(_meta_rule_template["name"], meta_rule_id, result) + return meta_rule_id + + +def check_meta_rule(meta_rule_id, scat_id=None, ocat_id=None, acat_id=None): + req = requests.get(URL.format("/meta_rules")) + req.raise_for_status() + result = req.json() + check_meta_rule_in_result(result) + check_optionnal_result(result) + if not meta_rule_id: + return result + check_meta_rules_name(None, meta_rule_id, result) + if scat_id: + check_scat_id_in_dict(scat_id, result['meta_rules'][meta_rule_id]["subject_categories"]) + if ocat_id: + check_ocat_id_in_dict(ocat_id, result['meta_rules'][meta_rule_id]["object_categories"]) + if acat_id: + check_acat_id_in_dict(acat_id, result['meta_rules'][meta_rule_id]["action_categories"]) + return result + + +def delete_meta_rule(meta_rule_id): + req = requests.delete(URL.format("/meta_rules/{}".format(meta_rule_id))) + req.raise_for_status() + result = req.json() + check_optionnal_result(result) + + +def add_meta_rule_to_model(model_id, meta_rule_id): + model = check_model(model_id, do_check_model_name=False)['models'] + meta_rule_list = model[model_id]["meta_rules"] + if meta_rule_id not in meta_rule_list: + meta_rule_list.append(meta_rule_id) + req = requests.patch(URL.format("/models/{}".format(model_id)), + json={"meta_rules": meta_rule_list}, + headers=HEADERS) + req.raise_for_status() + result = req.json() + check_model_in_result(result) + model_id = list(result['models'].keys())[0] + check_optionnal_result(result) + check_meta_rules_list_in_model(meta_rule_list, model_id, result) + + +def create_model(scenario, model_id=None): + LOGGER.info("Creating model {}".format(scenario.model_name)) + if not model_id: + LOGGER.info("Add model") + model_id = add_model(name=scenario.model_name) + LOGGER.info("Add subject categories") + for cat in scenario.subject_categories: + scenario.subject_categories[cat] = add_subject_category(name=cat) + LOGGER.info("Add object categories") + for cat in scenario.object_categories: + scenario.object_categories[cat] = add_object_category(name=cat) + LOGGER.info("Add action categories") + for cat in scenario.action_categories: + scenario.action_categories[cat] = add_action_category(name=cat) + sub_cat = [] + ob_cat = [] + act_cat = [] + meta_rule_list = [] + for item_name, item_value in scenario.meta_rule.items(): + for item in item_value["value"]: + if item in scenario.subject_categories: + sub_cat.append(scenario.subject_categories[item]) + elif item in scenario.object_categories: + ob_cat.append(scenario.object_categories[item]) + elif item in scenario.action_categories: + act_cat.append(scenario.action_categories[item]) + meta_rules = check_meta_rule(meta_rule_id=None) + for _meta_rule_id, _meta_rule_value in meta_rules['meta_rules'].items(): + if _meta_rule_value['name'] == item_name: + meta_rule_id = _meta_rule_id + break + else: + LOGGER.info("Add meta rule") + meta_rule_id = add_meta_rule(item_name, sub_cat, ob_cat, act_cat) + item_value["id"] = meta_rule_id + if meta_rule_id not in meta_rule_list: + meta_rule_list.append(meta_rule_id) + return model_id, meta_rule_list diff --git a/old/python_moonclient/python_moonclient/core/pdp.py b/old/python_moonclient/python_moonclient/core/pdp.py new file mode 100644 index 00000000..f67a4d01 --- /dev/null +++ b/old/python_moonclient/python_moonclient/core/pdp.py @@ -0,0 +1,194 @@ +import sys +import logging +import requests +from python_moonclient.core import config +from python_moonclient.core.check_tools import * + +LOGGER = logging.getLogger("python_moonclient.core.pdp") + +URL = None +HEADERS = None +KEYSTONE_USER = None +KEYSTONE_PASSWORD = None +KEYSTONE_PROJECT = None +KEYSTONE_SERVER = None + +pdp_template = { + "name": "test_pdp", + "security_pipeline": [], + "keystone_project_id": None, + "description": "test", +} + + +def init(consul_host, consul_port): + conf_data = config.get_config_data(consul_host, consul_port) + global URL, HEADERS, KEYSTONE_USER, KEYSTONE_PASSWORD, KEYSTONE_PROJECT, KEYSTONE_SERVER + URL = "http://{}:{}".format( + conf_data['manager_host'], + conf_data['manager_port']) + # URL = URL + "{}" + HEADERS = {"content-type": "application/json"} + KEYSTONE_USER = conf_data['keystone_user'] + KEYSTONE_PASSWORD = conf_data['keystone_password'] + KEYSTONE_PROJECT = conf_data['keystone_project'] + KEYSTONE_SERVER = conf_data['keystone_host'] + + +def get_keystone_projects(): + global HEADERS + HEADERS = { + "Content-Type": "application/json" + } + + data_auth = { + "auth": { + "identity": { + "methods": [ + "password" + ], + "password": { + "user": { + "name": KEYSTONE_USER, + "domain": { + "name": "Default" + }, + "password": KEYSTONE_PASSWORD + } + } + } + } + } + + req = requests.post("{}/auth/tokens".format(KEYSTONE_SERVER), json=data_auth, headers=HEADERS) + LOGGER.debug("{}/auth/tokens".format(KEYSTONE_SERVER)) + LOGGER.debug(req.text) + req.raise_for_status() + token = req.headers['X-Subject-Token'] + HEADERS['X-Auth-Token'] = token + req = requests.get("{}/projects".format(KEYSTONE_SERVER), headers=HEADERS) + if req.status_code not in (200, 201): + data_auth["auth"]["scope"] = { + "project": { + "name": KEYSTONE_PROJECT, + "domain": { + "id": "default" + } + } + } + req = requests.post("{}/auth/tokens".format(KEYSTONE_SERVER), json=data_auth, + headers=HEADERS) + req.raise_for_status() + token = req.headers['X-Subject-Token'] + HEADERS['X-Auth-Token'] = token + req = requests.get("{}/projects".format(KEYSTONE_SERVER), headers=HEADERS) + req.raise_for_status() + return req.json() + + +def get_keystone_id(pdp_name): + keystone_project_id = None + for pdp_key, pdp_value in check_pdp()["pdps"].items(): + if pdp_name: + if pdp_name != pdp_value["name"]: + continue + if pdp_value['security_pipeline'] and pdp_value["keystone_project_id"]: + LOGGER.debug( + "Found pdp with keystone_project_id={}".format(pdp_value["keystone_project_id"])) + keystone_project_id = pdp_value["keystone_project_id"] + + if not keystone_project_id: + LOGGER.error("Cannot find PDP with keystone project ID") + sys.exit(1) + return keystone_project_id + + +def check_pdp(pdp_id=None, keystone_project_id=None, moon_url=None): + _url = URL + if moon_url: + _url = moon_url + req = requests.get(_url + "/pdp") + req.raise_for_status() + result = req.json() + check_pdp_in_result(result) + if pdp_id: + check_pdp_name(pdp_template["name"], pdp_id, result) + if keystone_project_id: + check_pdp_project_id(keystone_project_id, pdp_id, result) + return result + + +def add_pdp(name="test_pdp", policy_id=None): + pdp_template['name'] = name + if policy_id: + pdp_template['security_pipeline'].append(policy_id) + req = requests.post(URL + "/pdp", json=pdp_template, headers=HEADERS) + LOGGER.debug(req.status_code) + LOGGER.debug(req) + req.raise_for_status() + result = req.json() + check_pdp_in_result(result) + pdp_id = list(result['pdps'].keys())[0] + check_pdp_name(pdp_template["name"], pdp_id, result) + return pdp_id + + +def update_pdp(pdp_id, policy_id=None): + req = requests.get(URL + "/pdp/{}".format(pdp_id)) + req.raise_for_status() + result = req.json() + check_pdp_id(pdp_id, result) + pipeline = result['pdps'][pdp_id]["security_pipeline"] + if policy_id not in pipeline: + pipeline.append(policy_id) + req = requests.patch(URL + "/pdp/{}".format(pdp_id), + json={"security_pipeline": pipeline}) + req.raise_for_status() + result = req.json() + check_pdp_id(pdp_id, result) + + req = requests.get(URL + "/pdp/{}".format(pdp_id)) + req.raise_for_status() + result = req.json() + check_pdp_id(pdp_id, result) + check_policy_id_in_pipeline(pdp_id, pipeline) + + +def map_to_keystone(pdp_id, keystone_project_id): + req = requests.patch(URL + "/pdp/{}".format(pdp_id), + json={"keystone_project_id": keystone_project_id}, + headers=HEADERS) + req.raise_for_status() + result = req.json() + check_pdp_id(pdp_id, result) + # assert "name" in result['pdps'][pdp_id] + # assert pdp_template["name"] == result['pdps'][pdp_id]["name"] + return pdp_id + + +def delete_pdp(pdp_id): + req = requests.delete(URL + "/pdp/{}".format(pdp_id)) + req.raise_for_status() + result = req.json() + check_result(result) + + +def create_pdp(scenario, policy_id=None, project_id=None): + LOGGER.info("Creating PDP {}".format(scenario.pdp_name)) + projects = get_keystone_projects() + # if not project_id: + # for _project in projects['projects']: + # if _project['name'] == "admin": + # project_id = _project['id'] + # assert project_id + pdps = check_pdp()["pdps"] + for pdp_id, pdp_value in pdps.items(): + if scenario.pdp_name == pdp_value["name"]: + update_pdp(pdp_id, policy_id=policy_id) + LOGGER.debug( + "Found existing PDP named {} (will add policy {})".format(scenario.pdp_name, + policy_id)) + return pdp_id + _pdp_id = add_pdp(name=scenario.pdp_name, policy_id=policy_id) + # map_to_keystone(pdp_id=_pdp_id, keystone_project_id=project_id) + return _pdp_id diff --git a/old/python_moonclient/python_moonclient/core/policies.py b/old/python_moonclient/python_moonclient/core/policies.py new file mode 100644 index 00000000..b9b05dd8 --- /dev/null +++ b/old/python_moonclient/python_moonclient/core/policies.py @@ -0,0 +1,673 @@ +import logging +import requests +from python_moonclient.core import models, config +from python_moonclient.core.check_tools import * + +LOGGER = logging.getLogger("moonclient.core.policies") + +URL = None +HEADERS = None + +policy_template = { + "name": "test_policy", + "model_id": "", + "genre": "authz", + "description": "test", +} + +subject_template = { + "name": "test_subject", + "description": "test", + "email": "mail", + "password": "my_pass", +} + +object_template = { + "name": "test_subject", + "description": "test" +} + +action_template = { + "name": "test_subject", + "description": "test" +} + +subject_data_template = { + "name": "subject_data1", + "description": "description of the data subject" +} + +object_data_template = { + "name": "object_data1", + "description": "description of the data subject" +} + +action_data_template = { + "name": "action_data1", + "description": "description of the data subject" +} + +subject_assignment_template = { + "id": "", + "category_id": "", + "scope_id": "" +} + + +def init(consul_host, consul_port): + conf_data = config.get_config_data(consul_host, consul_port) + global URL, HEADERS + URL = "http://{}:{}".format( + conf_data['manager_host'], + conf_data['manager_port']) + URL = URL + "{}" + HEADERS = {"content-type": "application/json"} + + +def check_policy(policy_id=None): + req = requests.get(URL.format("/policies")) + req.raise_for_status() + result = req.json() + check_policy_in_result(result) + if policy_id: + check_policy_name(policy_template["name"], policy_id, result) + return result + + +def add_policy(name="test_policy", genre="authz"): + policy_template["name"] = name + policy_template["genre"] = genre + req = requests.post(URL.format("/policies"), json=policy_template, headers=HEADERS) + req.raise_for_status() + result = req.json() + check_policy_in_result(result) + policy_id = list(result['policies'].keys())[0] + check_optionnal_result(result) + check_policy_name(policy_template["name"], policy_id, result) + return policy_id + + +def update_policy(policy_id, model_id): + req = requests.patch(URL.format("/policies/{}".format(policy_id)), + json={"model_id": model_id}, headers=HEADERS) + req.raise_for_status() + result = req.json() + check_policy_in_result(result) + policy_id = list(result['policies'].keys())[0] + check_optionnal_result(result) + check_policy_model_id(model_id, policy_id, result) + + +def delete_policy(policy_id): + req = requests.delete(URL.format("/policies/{}".format(policy_id))) + req.raise_for_status() + result = req.json() + check_result(result) + + +def add_subject(policy_id=None, name="test_subject"): + subject_template['name'] = name + if policy_id: + LOGGER.debug(URL.format("/policies/{}/subjects".format(policy_id))) + req = requests.post(URL.format("/policies/{}/subjects".format(policy_id)), + json=subject_template, headers=HEADERS) + else: + LOGGER.debug(URL.format("/subjects")) + req = requests.post(URL.format("/subjects"), json=subject_template, headers=HEADERS) + LOGGER.debug(req.text) + req.raise_for_status() + result = req.json() + check_subject_in_result(result) + subject_id = list(result['subjects'].keys())[0] + return subject_id + + +def update_subject(subject_id, policy_id=None, description=None): + if policy_id and not description: + req = requests.patch(URL.format("/policies/{}/subjects/{}".format(policy_id, subject_id)), + json={}) + elif policy_id and description: + req = requests.patch(URL.format("/policies/{}/subjects/{}".format(policy_id, subject_id)), + json={"description": description}) + else: + req = requests.patch(URL.format("/subjects/{}".format(subject_id)), + json={"description": description}) + req.raise_for_status() + result = req.json() + check_subject_name(subject_template["name"], subject_id, result) + check_subject_policy(policy_id, result["subjects"][subject_id]) + check_subject_description(description, result["subjects"][subject_id]) + + +def check_subject(subject_id=None, policy_id=None): + if policy_id: + req = requests.get(URL.format("/policies/{}/subjects".format(policy_id))) + else: + req = requests.get(URL.format("/subjects")) + req.raise_for_status() + result = req.json() + check_subject_name(subject_template["name"], subject_id, result) + check_subject_policy(policy_id, result["subjects"][subject_id]) + + +def delete_subject(subject_id, policy_id=None): + if policy_id: + req = requests.delete(URL.format("/policies/{}/subjects/{}".format(policy_id, subject_id))) + else: + req = requests.delete(URL.format("/subjects/{}".format(subject_id))) + req.raise_for_status() + result = req.json() + check_result(result) + + if policy_id: + req = requests.get(URL.format("/policies/{}/subjects".format(policy_id))) + else: + req = requests.get(URL.format("/subjects")) + req.raise_for_status() + result = req.json() + check_subject_in_result(result) + if subject_id in result["subjects"]: + check_subject_name(subject_template["name"], subject_id, result) + check_subject_policy(policy_id, result["subjects"][subject_id]) + + +def add_object(policy_id=None, name="test_object"): + object_template['name'] = name + if policy_id: + req = requests.post(URL.format("/policies/{}/objects".format(policy_id)), + json=object_template, headers=HEADERS) + else: + req = requests.post(URL.format("/objects"), json=object_template, headers=HEADERS) + req.raise_for_status() + result = req.json() + check_object_in_result(result) + object_id = list(result['objects'].keys())[0] + return object_id + + +def update_object(object_id, policy_id): + req = requests.patch(URL.format("/policies/{}/objects/{}".format(policy_id, object_id)), + json={}) + req.raise_for_status() + result = req.json() + check_object_in_result(result) + check_object_name(object_template["name"], object_id, result) + check_object_policy(policy_id, result["objects"][object_id]) + + +def check_object(object_id=None, policy_id=None): + if policy_id: + req = requests.get(URL.format("/policies/{}/objects".format(policy_id))) + else: + req = requests.get(URL.format("/objects")) + req.raise_for_status() + result = req.json() + check_object_in_result(result) + check_object_name(object_template["name"], object_id, result) + if policy_id: + check_object_policy(policy_id, result["objects"][object_id]) + + +def delete_object(object_id, policy_id=None): + if policy_id: + req = requests.delete(URL.format("/policies/{}/objects/{}".format(policy_id, object_id))) + else: + req = requests.delete(URL.format("/objects/{}".format(object_id))) + req.raise_for_status() + result = req.json() + check_result(result) + + if policy_id: + req = requests.get(URL.format("/policies/{}/objects".format(policy_id))) + else: + req = requests.get(URL.format("/objects")) + req.raise_for_status() + result = req.json() + check_object_in_result(result) + if object_id in result["objects"]: + check_object_name(object_template["name"], object_id, result) + if policy_id: + check_object_policy(policy_id, result["objects"][object_id]) + + +def add_action(policy_id=None, name="test_action"): + action_template['name'] = name + if policy_id: + req = requests.post(URL.format("/policies/{}/actions".format(policy_id)), + json=action_template, headers=HEADERS) + else: + req = requests.post(URL.format("/actions"), json=action_template, headers=HEADERS) + req.raise_for_status() + result = req.json() + check_action_in_result(result) + action_id = list(result['actions'].keys())[0] + return action_id + + +def update_action(action_id, policy_id): + req = requests.patch(URL.format("/policies/{}/actions/{}".format(policy_id, action_id)), + json={}) + req.raise_for_status() + result = req.json() + check_action_in_result(result) + check_action_name(action_template["name"], action_id, result) + check_action_policy(policy_id, result["actions"][action_id]) + + +def check_action(action_id=None, policy_id=None): + if policy_id: + req = requests.get(URL.format("/policies/{}/actions".format(policy_id))) + else: + req = requests.get(URL.format("/actions")) + req.raise_for_status() + result = req.json() + check_action_in_result(result) + check_action_name(action_template["name"], action_id, result) + if policy_id: + check_action_policy(policy_id, result["actions"][action_id]) + + +def delete_action(action_id, policy_id=None): + if policy_id: + req = requests.delete(URL.format("/policies/{}/actions/{}".format(policy_id, action_id))) + else: + req = requests.delete(URL.format("/actions/{}".format(action_id))) + req.raise_for_status() + result = req.json() + check_result(result) + + if policy_id: + req = requests.get(URL.format("/policies/{}/actions".format(policy_id))) + else: + req = requests.get(URL.format("/actions")) + req.raise_for_status() + result = req.json() + check_action_in_result(result) + if action_id in result["actions"]: + check_action_name(action_template["name"], action_id, result) + if policy_id: + check_action_policy(policy_id, result["actions"][action_id]) + + +def add_subject_data(policy_id, category_id, name="subject_data1"): + subject_data_template['name'] = name + req = requests.post(URL.format("/policies/{}/subject_data/{}".format(policy_id, category_id)), + json=subject_data_template, headers=HEADERS) + req.raise_for_status() + result = req.json() + check_subject_data_data(result) + subject_id = list(result['subject_data']['data'].keys())[0] + return subject_id + + +def check_subject_data(policy_id, data_id, category_id): + req = requests.get(URL.format("/policies/{}/subject_data/{}".format(policy_id, category_id))) + req.raise_for_status() + result = req.json() + print(result) + if data_id is not None: + check_id_in_subject_data_data(data_id, result) + check_category_id_in_subject_data_data(category_id, result) + return result + + +def delete_subject_data(policy_id, category_id, data_id): + req = requests.delete( + URL.format("/policies/{}/subject_data/{}/{}".format(policy_id, category_id, data_id)), + headers=HEADERS) + req.raise_for_status() + req = requests.get(URL.format("/policies/{}/subject_data/{}".format(policy_id, category_id))) + req.raise_for_status() + result = req.json() + check_id_not_in_subject_data_data(data_id, result) + check_category_id_in_subject_data_data(category_id, result) + + +def add_object_data(policy_id, category_id, name="object_data1"): + object_data_template['name'] = name + req = requests.post(URL.format("/policies/{}/object_data/{}".format(policy_id, category_id)), + json=object_data_template, headers=HEADERS) + req.raise_for_status() + result = req.json() + check_object_data_data(result) + object_id = list(result['object_data']['data'].keys())[0] + return object_id + + +def check_object_data(policy_id, data_id, category_id): + req = requests.get(URL.format("/policies/{}/object_data/{}".format(policy_id, category_id))) + req.raise_for_status() + result = req.json() + if data_id is not None: + check_id_in_object_data_data(data_id, result) + check_category_id_in_object_data_data(category_id, result) + return result + + +def delete_object_data(policy_id, category_id, data_id): + req = requests.delete( + URL.format("/policies/{}/object_data/{}/{}".format(policy_id, category_id, data_id)), + headers=HEADERS) + req.raise_for_status() + req = requests.get(URL.format("/policies/{}/object_data/{}".format(policy_id, category_id))) + req.raise_for_status() + result = req.json() + check_id_not_in_object_data_data(data_id, result) + check_category_id_in_object_data_data(category_id, result) + + +def add_action_data(policy_id, category_id, name="action_data1"): + action_data_template['name'] = name + req = requests.post(URL.format("/policies/{}/action_data/{}".format(policy_id, category_id)), + json=action_data_template, headers=HEADERS) + req.raise_for_status() + result = req.json() + check_action_data_data(result) + action_id = list(result['action_data']['data'].keys())[0] + return action_id + + +def check_action_data(policy_id, data_id, category_id): + req = requests.get(URL.format("/policies/{}/action_data/{}".format(policy_id, category_id))) + req.raise_for_status() + result = req.json() + print(result) + if data_id is not None: + check_id_in_action_data_data(data_id, result) + check_category_id_in_action_data_data(category_id, result) + return result + + +def delete_action_data(policy_id, category_id, data_id): + req = requests.delete( + URL.format("/policies/{}/action_data/{}/{}".format(policy_id, category_id, data_id)), + headers=HEADERS) + req.raise_for_status() + req = requests.get(URL.format("/policies/{}/action_data/{}".format(policy_id, category_id))) + req.raise_for_status() + result = req.json() + check_id_not_in_action_data_data(data_id, result) + check_category_id_in_action_data_data(category_id, result) + + +def add_subject_assignments(policy_id, subject_id, subject_cat_id, subject_data_id): + req = requests.post(URL.format("/policies/{}/subject_assignments".format(policy_id)), + json={ + "id": subject_id, + "category_id": subject_cat_id, + "data_id": subject_data_id + }, headers=HEADERS) + req.raise_for_status() + result = req.json() + check_subject_assignment_in_result(result) + + +def check_subject_assignments(policy_id, subject_id, subject_cat_id, subject_data_id): + req = requests.get(URL.format("/policies/{}/subject_assignments/{}/{}/{}".format( + policy_id, subject_id, subject_cat_id, subject_data_id))) + req.raise_for_status() + result = req.json() + check_subject_assignment_in_result(result) + check_subject_assignements(subject_id, subject_cat_id, subject_data_id, result) + + +def check_object_assignments(policy_id, object_id, object_cat_id, object_data_id): + req = requests.get(URL.format("/policies/{}/object_assignments/{}/{}/{}".format( + policy_id, object_id, object_cat_id, object_data_id))) + req.raise_for_status() + result = req.json() + check_object_assignment_in_result(result) + check_object_assignements(object_id, object_cat_id, object_data_id, result) + + +def check_action_assignments(policy_id, action_id, action_cat_id, action_data_id): + req = requests.get(URL.format("/policies/{}/action_assignments/{}/{}/{}".format( + policy_id, action_id, action_cat_id, action_data_id))) + req.raise_for_status() + result = req.json() + check_action_assignment_in_result(result) + check_action_assignements(action_id, action_cat_id, action_data_id, result) + + +def add_object_assignments(policy_id, object_id, object_cat_id, object_data_id): + req = requests.post(URL.format("/policies/{}/object_assignments".format(policy_id)), + json={ + "id": object_id, + "category_id": object_cat_id, + "data_id": object_data_id + }, headers=HEADERS) + req.raise_for_status() + result = req.json() + check_object_assignment_in_result(result) + + +def add_action_assignments(policy_id, action_id, action_cat_id, action_data_id): + req = requests.post(URL.format("/policies/{}/action_assignments".format(policy_id)), + json={ + "id": action_id, + "category_id": action_cat_id, + "data_id": action_data_id + }, headers=HEADERS) + req.raise_for_status() + result = req.json() + check_action_assignment_in_result(result) + + +def delete_subject_assignment(policy_id, subject_id, subject_cat_id, subject_data_id): + req = requests.delete(URL.format("/policies/{}/subject_assignments/{}/{}/{}".format( + policy_id, subject_id, subject_cat_id, subject_data_id))) + req.raise_for_status() + result = req.json() + check_result(result) + + req = requests.get(URL.format("/policies/{}/subject_assignments/{}/{}/{}".format( + policy_id, subject_id, subject_cat_id, subject_data_id))) + req.raise_for_status() + result = req.json() + check_subject_assignment_in_result(result) + check_not_subject_assignements(subject_id, subject_cat_id, subject_data_id, result) + + +def delete_object_assignment(policy_id, object_id, object_cat_id, object_data_id): + req = requests.delete(URL.format("/policies/{}/object_assignments/{}/{}/{}".format( + policy_id, object_id, object_cat_id, object_data_id))) + req.raise_for_status() + result = req.json() + check_result(result) + + req = requests.get(URL.format("/policies/{}/object_assignments/{}/{}/{}".format( + policy_id, object_id, object_cat_id, object_data_id))) + req.raise_for_status() + result = req.json() + check_object_assignment_in_result(result) + check_not_object_assignements(object_id, object_cat_id, object_data_id, result) + + +def delete_action_assignment(policy_id, action_id, action_cat_id, action_data_id): + req = requests.delete(URL.format("/policies/{}/action_assignments/{}/{}/{}".format( + policy_id, action_id, action_cat_id, action_data_id))) + req.raise_for_status() + result = req.json() + check_result(result) + + req = requests.get(URL.format("/policies/{}/action_assignments/{}/{}/{}".format( + policy_id, action_id, action_cat_id, action_data_id))) + req.raise_for_status() + result = req.json() + check_action_assignment_in_result(result) + check_not_action_assignements(action_id, action_cat_id, action_data_id, result) + + +def add_rule(policy_id, meta_rule_id, rule, + instructions={"chain": [{"security_pipeline": "rbac"}]}): + req = requests.post(URL.format("/policies/{}/rules".format(policy_id)), + json={ + "meta_rule_id": meta_rule_id, + "rule": rule, + "instructions": instructions, + "enabled": True + }, + headers=HEADERS) + req.raise_for_status() + result = req.json() + check_rule_in_result(result) + rule_id = list(result["rules"].keys())[0] + check_policy_id_in_dict(policy_id, result["rules"][rule_id]) + check_meta_rule_id_in_dict(meta_rule_id, result["rules"][rule_id]) + check_rule_in_dict(rule, result["rules"][rule_id]) + return rule_id + + +def check_rule(policy_id, meta_rule_id, rule_id, rule): + req = requests.get(URL.format("/policies/{}/rules".format(policy_id))) + req.raise_for_status() + result = req.json() + check_rule_in_result(result) + check_policy_id_in_dict(policy_id, result["rules"]) + check_rule_id_in_list(meta_rule_id, rule_id, rule, result["rules"]["rules"]) + + +def delete_rule(policy_id, rule_id): + req = requests.delete(URL.format("/policies/{}/rules/{}".format(policy_id, rule_id))) + req.raise_for_status() + result = req.json() + check_result(result) + req = requests.get(URL.format("/policies/{}/rules".format(policy_id))) + req.raise_for_status() + result = req.json() + check_rule_in_result(result) + check_policy_id_in_dict(policy_id, result["rules"]) + check_rule_id_not_in_list(rule_id, result["rules"]["rules"]) + + +def check_meta_rule(): + req = requests.get(URL.format("/meta_rules/")) + req.raise_for_status() + result = req.json() + print(result) + return result + + +def create_policy(scenario, model_id, meta_rule_list): + LOGGER.info("Creating policy {}".format(scenario.policy_name)) + _policies = check_policy() + for _policy_id, _policy_value in _policies["policies"].items(): + if _policy_value['name'] == scenario.policy_name: + policy_id = _policy_id + break + else: + policy_id = add_policy(name=scenario.policy_name, genre=scenario.policy_genre) + + update_policy(policy_id, model_id) + + for meta_rule_id in meta_rule_list: + LOGGER.debug("add_meta_rule_to_model {} {}".format(model_id, meta_rule_id)) + models.add_meta_rule_to_model(model_id, meta_rule_id) + + LOGGER.info("Add subject data") + for subject_cat_name in scenario.subject_data: + for subject_data_name in scenario.subject_data[subject_cat_name]: + data_id = scenario.subject_data[subject_cat_name][subject_data_name] = add_subject_data( + policy_id=policy_id, + category_id=scenario.subject_categories[subject_cat_name], name=subject_data_name) + scenario.subject_data[subject_cat_name][subject_data_name] = data_id + LOGGER.info("Add object data") + for object_cat_name in scenario.object_data: + for object_data_name in scenario.object_data[object_cat_name]: + data_id = scenario.object_data[object_cat_name][object_data_name] = add_object_data( + policy_id=policy_id, + category_id=scenario.object_categories[object_cat_name], name=object_data_name) + scenario.object_data[object_cat_name][object_data_name] = data_id + LOGGER.info("Add action data") + for action_cat_name in scenario.action_data: + for action_data_name in scenario.action_data[action_cat_name]: + data_id = scenario.action_data[action_cat_name][action_data_name] = add_action_data( + policy_id=policy_id, + category_id=scenario.action_categories[action_cat_name], name=action_data_name) + scenario.action_data[action_cat_name][action_data_name] = data_id + + LOGGER.info("Add subjects") + for name in scenario.subjects: + scenario.subjects[name] = add_subject(policy_id, name=name) + LOGGER.info("Add objects") + for name in scenario.objects: + scenario.objects[name] = add_object(policy_id, name=name) + LOGGER.info("Add actions") + for name in scenario.actions: + scenario.actions[name] = add_action(policy_id, name=name) + + LOGGER.info("Add subject assignments") + for subject_name in scenario.subject_assignments: + if type(scenario.subject_assignments[subject_name]) in (list, tuple): + for items in scenario.subject_assignments[subject_name]: + for subject_category_name in items: + subject_id = scenario.subjects[subject_name] + subject_cat_id = scenario.subject_categories[subject_category_name] + for data in scenario.subject_assignments[subject_name]: + subject_data_id = scenario.subject_data[subject_category_name][ + data[subject_category_name]] + add_subject_assignments(policy_id, subject_id, subject_cat_id, + subject_data_id) + else: + for subject_category_name in scenario.subject_assignments[subject_name]: + subject_id = scenario.subjects[subject_name] + subject_cat_id = scenario.subject_categories[subject_category_name] + subject_data_id = scenario.subject_data[subject_category_name][ + scenario.subject_assignments[subject_name][subject_category_name]] + add_subject_assignments(policy_id, subject_id, subject_cat_id, subject_data_id) + + LOGGER.info("Add object assignments") + for object_name in scenario.object_assignments: + if type(scenario.object_assignments[object_name]) in (list, tuple): + for items in scenario.object_assignments[object_name]: + for object_category_name in items: + object_id = scenario.objects[object_name] + object_cat_id = scenario.object_categories[object_category_name] + for data in scenario.object_assignments[object_name]: + object_data_id = scenario.object_data[object_category_name][ + data[object_category_name]] + add_object_assignments(policy_id, object_id, object_cat_id, object_data_id) + else: + for object_category_name in scenario.object_assignments[object_name]: + object_id = scenario.objects[object_name] + object_cat_id = scenario.object_categories[object_category_name] + object_data_id = scenario.object_data[object_category_name][ + scenario.object_assignments[object_name][object_category_name]] + add_object_assignments(policy_id, object_id, object_cat_id, object_data_id) + + LOGGER.info("Add action assignments") + for action_name in scenario.action_assignments: + if type(scenario.action_assignments[action_name]) in (list, tuple): + for items in scenario.action_assignments[action_name]: + for action_category_name in items: + action_id = scenario.actions[action_name] + action_cat_id = scenario.action_categories[action_category_name] + for data in scenario.action_assignments[action_name]: + action_data_id = scenario.action_data[action_category_name][ + data[action_category_name]] + add_action_assignments(policy_id, action_id, action_cat_id, action_data_id) + else: + for action_category_name in scenario.action_assignments[action_name]: + action_id = scenario.actions[action_name] + action_cat_id = scenario.action_categories[action_category_name] + action_data_id = scenario.action_data[action_category_name][ + scenario.action_assignments[action_name][action_category_name]] + add_action_assignments(policy_id, action_id, action_cat_id, action_data_id) + + LOGGER.info("Add rules") + for meta_rule_name in scenario.rules: + meta_rule_value = scenario.meta_rule[meta_rule_name] + for rule in scenario.rules[meta_rule_name]: + data_list = [] + _meta_rule = list(meta_rule_value["value"]) + for data_name in rule["rule"]: + category_name = _meta_rule.pop(0) + if category_name in scenario.subject_categories: + data_list.append(scenario.subject_data[category_name][data_name]) + elif category_name in scenario.object_categories: + data_list.append(scenario.object_data[category_name][data_name]) + elif category_name in scenario.action_categories: + data_list.append(scenario.action_data[category_name][data_name]) + instructions = rule["instructions"] + add_rule(policy_id, meta_rule_value["id"], data_list, instructions) + return policy_id diff --git a/old/python_moonclient/python_moonclient/core/slaves.py b/old/python_moonclient/python_moonclient/core/slaves.py new file mode 100644 index 00000000..77b127c1 --- /dev/null +++ b/old/python_moonclient/python_moonclient/core/slaves.py @@ -0,0 +1,59 @@ +import logging +import requests +from python_moonclient.core import config +from python_moonclient.core.check_tools import * + +LOGGER = logging.getLogger("moonclient.core.slaves") + +URL = None +HEADERS = None + + +def init(consul_host, consul_port): + conf_data = config.get_config_data(consul_host, consul_port) + global URL, HEADERS + URL = "http://{}:{}".format( + conf_data['manager_host'], + conf_data['manager_port']) + URL = URL + "{}" + HEADERS = {"content-type": "application/json"} + + +def get_slaves(): + req = requests.get(URL.format("/slaves")) + req.raise_for_status() + result = req.json() + check_slaves_in_result(result) + return result + + +def set_slave(name): + slaves = get_slaves().get("slaves", []) + check_name_in_slaves(name, slaves) + req = requests.patch(URL.format("/slaves/{}".format(name)), + headers=HEADERS, + json={ + "op": "replace", + "variable": "configured", + "value": True + }) + req.raise_for_status() + result = req.json() + check_slaves_in_result(result) + return get_slaves() + + +def delete_slave(name): + slaves = get_slaves().get("slaves", []) + check_name_in_slaves(name, slaves) + req = requests.patch(URL.format("/slaves/{}".format(name)), + headers=HEADERS, + json={ + "op": "replace", + "variable": "configured", + "value": False + }) + req.raise_for_status() + result = req.json() + check_slaves_in_result(result) + return get_slaves() diff --git a/old/python_moonclient/python_moonclient/moon.py b/old/python_moonclient/python_moonclient/moon.py new file mode 100644 index 00000000..0bd80921 --- /dev/null +++ b/old/python_moonclient/python_moonclient/moon.py @@ -0,0 +1,37 @@ +import sys +import python_moonclient + +from cliff.app import App +from cliff.commandmanager import CommandManager + + +class Moon(App): + + def __init__(self): + super(Moon, self).__init__( + description='Moon client', + version=python_moonclient.__version__, + command_manager=CommandManager('moon'), + deferred_help=True, + ) + + +def main(argv=sys.argv[1:]): + myapp = Moon() + return myapp.run(argv) + + +if __name__ == '__main__': + # import python_moonclient.python_moonclient.core.import_json + # import python_moonclient.python_moonclient.core.models + # import python_moonclient.core.policies.init as init_policy + # import python_moonclient.core.pdp.init as init_pdp + # consul_host = "consul" + # consul_port = "8005" + + # init_model(consul_host, consul_port) + # init_policy.init(consul_host, consul_port) + # init_pdp.init(consul_host, consul_port) + # import_json('/home/fcellier/moon/tests/functional/scenario_available/rbac.json') + + sys.exit(Moon(sys.argv[1:])) diff --git a/old/python_moonclient/requirements.txt b/old/python_moonclient/requirements.txt new file mode 100644 index 00000000..bbcd8cd5 --- /dev/null +++ b/old/python_moonclient/requirements.txt @@ -0,0 +1,4 @@ +werkzeug +flask +requests +cliff diff --git a/old/python_moonclient/setup.py b/old/python_moonclient/setup.py new file mode 100644 index 00000000..4a3a8233 --- /dev/null +++ b/old/python_moonclient/setup.py @@ -0,0 +1,75 @@ +# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors +# This software is distributed under the terms and conditions of the 'Apache-2.0' +# license which can be found in the file 'LICENSE' in this package distribution +# or at 'http://www.apache.org/licenses/LICENSE-2.0'. + +from setuptools import setup, find_packages +import python_moonclient +import python_moonclient.core + +with open('requirements.txt') as f: + required = f.read().splitlines() + + +setup( + + name='python-moonclient', + + version=python_moonclient.__version__, + + packages=find_packages(), + + author='Thomas Duval & Ruan He', + + author_email='thomas.duval@orange.com, ruan.he@orange.com', + + description='client lib for all the Moon components', + + long_description=open('README.md').read(), + + install_requires=required, + + include_package_data=True, + + url='https://git.opnfv.org/cgit/moon', + + classifiers=[ + 'Programming Language :: Python :: 3', + 'Development Status :: 1 - Planning', + 'License :: OSI Approved', + 'Natural Language :: English', + 'Operating System :: OS Independent', + ], + + entry_points={ + 'console_scripts': [ + 'moon = python_moonclient.moon:main' + ], + 'moon': [ + 'pdp_list = python_moonclient.cli.pdps:Pdps', + 'pdp_create = python_moonclient.cli.pdps:CreatePdp', + 'pdp_delete = python_moonclient.cli.pdps:DeletePdp', + 'pdp_map = python_moonclient.cli.pdps:MapPdp', + 'policy_list = python_moonclient.cli.policies:Policies', + 'policy_delete = python_moonclient.cli.policies:DeletePolicy', + 'project_list = python_moonclient.cli.projects:Projects', + 'slave_list = python_moonclient.cli.slaves:Slaves', + 'slave_set = python_moonclient.cli.slaves:SetSlave', + 'slave_delete = python_moonclient.cli.slaves:DeleteSlave', + 'authz_send = python_moonclient.cli.authz:SendAuthz', + 'import = python_moonclient.cli.import:Import', + 'export = python_moonclient.cli.export:Export', + 'model_list = python_moonclient.cli.models:Models', + 'subject_data_list = python_moonclient.cli.policies:SubjectDatas', + 'object_data_list = python_moonclient.cli.policies:ObjectDatas', + 'action_data_list = python_moonclient.cli.policies:ActionDatas', + 'subject_category_list = python_moonclient.cli.models:SubjectCategories', + 'object_category_list = python_moonclient.cli.models:ObjectCategories', + 'action_category_list = python_moonclient.cli.models:ActionCategories', + 'subject_category_create = python_moonclient.cli.models:SubjectCategoryAdd', + 'subject_data_create = python_moonclient.cli.policies:CreateSubjectData', + 'metarule_list = python_moonclient.cli.policies:MetaRules' + ], + } + +) diff --git a/old/python_moonclient/tests/unit_python/__init__.py b/old/python_moonclient/tests/unit_python/__init__.py new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/old/python_moonclient/tests/unit_python/__init__.py diff --git a/old/python_moonclient/tests/unit_python/conf/conf_action_assignments.py b/old/python_moonclient/tests/unit_python/conf/conf_action_assignments.py new file mode 100644 index 00000000..43c4db59 --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_action_assignments.py @@ -0,0 +1,51 @@ +from .conf_all import * + +POST_ACTION_ASSIGNMENT = { + "action_assignments":{ + "1":{ + "policy_id": "1", + "action_id": "2", + "category_id": "1", + "assignments": ["1"] + } + } +} + +POST_OTHER_ACTION_ASSIGNMENT = { + "action_assignments":{ + "2":{ + "policy_id": "1", + "action_id": "2", + "category_id": "1", + "assignments": ["2"] + } + } +} + +DELETE_ACTION_ASSIGNMENT = { + "action_assignments":{ + + } +} + + +def conf_action_assignments(m): + m.register_uri( + 'GET', 'http://manager:30001/policies/2/action_assignments/2/1/1', + [{'headers': {'X-Subject-Token': "111111111"}, 'json': POST_ACTION_ASSIGNMENT}, + {'headers': {'X-Subject-Token': "111111111"}, 'json': DELETE_ACTION_ASSIGNMENT}] + ) + m.register_uri( + 'GET', 'http://manager:30001/policies/2/action_assignments/2/1/2', + headers={'X-Subject-Token': "111111111"}, + json=POST_OTHER_ACTION_ASSIGNMENT + ) + m.register_uri( + 'POST', 'http://manager:30001/policies/2/action_assignments', + headers={'X-Subject-Token': "111111111"}, + json=POST_ACTION_ASSIGNMENT + ) + m.register_uri( + 'DELETE', 'http://manager:30001/policies/2/action_assignments/2/1/1', + json=RESULT_OK + )
\ No newline at end of file diff --git a/old/python_moonclient/tests/unit_python/conf/conf_action_categories.py b/old/python_moonclient/tests/unit_python/conf/conf_action_categories.py new file mode 100644 index 00000000..909befb2 --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_action_categories.py @@ -0,0 +1,32 @@ + + +ACTION_CATEGORIES = { + "action_categories": { + "1": { + "name": "action_cat_1", + "description": "description of the category" + } + } +} + +POST_ACTION_CATEGORIES = { + "action_categories": { + "1": { + "name": "action_cat_1", + "description": "description of the category" + } + } +} + + +def conf_action_categories(m): + m.register_uri( + 'GET', 'http://manager:30001/action_categories', + headers={'X-Subject-Token': "111111111"}, + json=ACTION_CATEGORIES + ) + m.register_uri( + 'POST', 'http://manager:30001/action_categories', + headers={'X-Subject-Token': "111111111"}, + json=POST_ACTION_CATEGORIES + )
\ No newline at end of file diff --git a/old/python_moonclient/tests/unit_python/conf/conf_action_data.py b/old/python_moonclient/tests/unit_python/conf/conf_action_data.py new file mode 100644 index 00000000..fb6f501c --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_action_data.py @@ -0,0 +1,66 @@ +from .conf_all import * + +ACTION_DATA = { + "action_data":[{ + "policy_id": "1", + "category_id": "1", + "data": { + "1": { + "name": "name of the data", + "description": "description of the data" + } + } + }] +} + +POST_ACTION_DATA = { + "action_data":{ + "policy_id": "1", + "category_id": "1", + "data": { + "1": { + "name": "name of the data", + "description": "description of the data" + } + } + } +} + +POST_OTHER_ACTION_DATA = { + "action_data":{ + "policy_id": "1", + "category_id": "1", + "data": { + "2": { + "name": "name of the data", + "description": "description of the data" + } + } + } +} + +DELETE_ACTION_DATA= { + "action_data":[{ + "policy_id": "1", + "category_id": "1", + "data":{} + }] +} + + +def conf_action_data(m): + m.register_uri( + 'POST', 'http://manager:30001/policies/2/action_data/1', + [{'headers': {'X-Subject-Token': "111111111"}, 'json': POST_ACTION_DATA}, + {'headers': {'X-Subject-Token': "111111111"}, 'json': POST_OTHER_ACTION_DATA}] + ) + m.register_uri( + 'GET', 'http://manager:30001/policies/2/action_data/1', + [{'headers': {'X-Subject-Token': "111111111"}, 'json': ACTION_DATA}, + {'headers': {'X-Subject-Token': "111111111"}, 'json': DELETE_ACTION_DATA}] + ) + m.register_uri( + 'DELETE', 'http://manager:30001/policies/2/action_data/1/1', + headers={'X-Subject-Token': "111111111"}, + json=RESULT_OK + )
\ No newline at end of file diff --git a/old/python_moonclient/tests/unit_python/conf/conf_actions.py b/old/python_moonclient/tests/unit_python/conf/conf_actions.py new file mode 100644 index 00000000..4e6784dd --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_actions.py @@ -0,0 +1,111 @@ +from .conf_all import * + +ACTIONS = { + "actions":{ + "1": { + "name": "name of the action", + "keystone_id": "1", + "description": "a description", + "policy_list": ["1"] + } + } +} + +ACTIONS_AFTER_POST = { + "actions":{ + "1": { + "name": "name of the action", + "keystone_id": "1", + "description": "a description", + "policy_list": ["1"] + }, + "2": { + "name": "test_action", + "keystone_id": "1", + "description": "a description", + "policy_list": [] + } + } +} + +ACTIONS_AFTER_PATCH = { + "actions":{ + "1": { + "name": "name of the action", + "keystone_id": "1", + "description": "a description", + "policy_list": ["1"] + }, + "2": { + "name": "test_action", + "keystone_id": "1", + "description": "a description", + "policy_list": ["2"] + } + } +} + + +POST_ACTIONS = { + "actions":{ + "2": { + "name": "test_action", + "keystone_id": "1", + "description": "a description", + "policy_list": [] + } + } +} + +PATCH_ACTIONS = { + "actions":{ + "2": { + "name": "test_action", + "keystone_id": "1", + "description": "a description", + "policy_list": ["2"] + } + } +} + +def conf_actions(m): + m.register_uri( + 'GET', 'http://manager:30001/actions', + headers={'X-Subject-Token': "111111111"}, + json=ACTIONS + ) + m.register_uri( + 'POST', 'http://manager:30001/actions', + headers={'X-Subject-Token': "111111111"}, + json=POST_ACTIONS + ) + m.register_uri( + 'DELETE', 'http://manager:30001/actions/2', + headers={'X-Subject-Token': "111111111"}, + json=RESULT_OK + ) + m.register_uri( + 'PATCH', 'http://manager:30001/policies/2/actions/2', + headers={'X-Subject-Token': "111111111"}, + json=PATCH_ACTIONS + ) + m.register_uri( + 'GET', 'http://manager:30001/policies/2/actions', + headers={'X-Subject-Token': "111111111"}, + json=ACTIONS_AFTER_PATCH + ) + m.register_uri( + 'POST', 'http://manager:30001/policies/2/actions', + headers={'X-Subject-Token': "111111111"}, + json=POST_ACTIONS + ) + m.register_uri( + 'GET', 'http://manager:30001/policies/2/actions/2', + headers={'X-Subject-Token': "111111111"}, + json=PATCH_ACTIONS + ) + m.register_uri( + 'DELETE', 'http://manager:30001/policies/2/actions/2', + headers={'X-Subject-Token': "111111111"}, + json=RESULT_OK + )
\ No newline at end of file diff --git a/old/python_moonclient/tests/unit_python/conf/conf_all.py b/old/python_moonclient/tests/unit_python/conf/conf_all.py new file mode 100644 index 00000000..b87d4fe7 --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_all.py @@ -0,0 +1 @@ +RESULT_OK = {"result": "OK"} diff --git a/old/python_moonclient/tests/unit_python/conf/conf_meta_rules.py b/old/python_moonclient/tests/unit_python/conf/conf_meta_rules.py new file mode 100644 index 00000000..67c14ddf --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_meta_rules.py @@ -0,0 +1,44 @@ +from .conf_all import * + + +META_RULES = { + "meta_rules": { + "1": { + "name": "test_meta_rule", + "algorithm": "name of the meta rule algorithm", + "subject_categories": ["1"], + "object_categories": ["1"], + "action_categories": ["1"] + } + } +} + +POST_META_RULES = { + "meta_rules": { + "1": { + "name": "test_meta_rule", + "algorithm": "name of the meta rule algorithm", + "subject_categories": ["1"], + "object_categories": ["1"], + "action_categories": ["1"] + } + } +} + + +def conf_meta_rules(m): + m.register_uri( + 'GET', 'http://manager:30001/meta_rules', + headers={'X-Subject-Token': "111111111"}, + json=META_RULES + ) + m.register_uri( + 'POST', 'http://manager:30001/meta_rules', + headers={'X-Subject-Token': "111111111"}, + json=POST_META_RULES + ) + m.register_uri( + 'DELETE', 'http://manager:30001/meta_rules/1', + headers={'X-Subject-Token': "111111111"}, + json=RESULT_OK + ) diff --git a/old/python_moonclient/tests/unit_python/conf/conf_models.py b/old/python_moonclient/tests/unit_python/conf/conf_models.py new file mode 100644 index 00000000..930af88f --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_models.py @@ -0,0 +1,94 @@ +from .conf_all import * + + +MODELS = { + "models": { + "1": { + "name": "model 1", + "description": "description model 1", + "meta_rules": [{ + "meta_rule_id": "1" + }, { + "meta_rule_id": "2" + }] + }, + "2": { + "name": "model 2", + "description": "description model 2", + "meta_rules": ["2"] + }, + "3": { + "name": "test_model", + "description": "description model 3", + "meta_rules": ["2"] + } + } +} + +POST_MODEL = { + "models": { + "3": { + "name": "test_model", + "description": "description model 3", + "meta_rules": ["2"] + } + } +} + +PATCH_MODEL = { + "models": { + "3": { + "name": "test_model", + "description": "description model 3", + "meta_rules": ["2", "1"] + } + } +} + + +MODELS_AFTER_POST = { +"models": { + "1": { + "name": "model 1", + "description": "description model 1", + "meta_rules": [{ + "meta_rule_id": "1" + }, { + "meta_rule_id": "2" + }] + }, + "2": { + "name": "model 2", + "description": "description model 2", + "meta_rules": ["2"] + }, + "3": { + "name": "test_model", + "description": "description model 3", + "meta_rules": ["1", "2"] + } + } +} + + +def conf_models(m): + m.register_uri( + 'GET', 'http://manager:30001/models', + [{'json': MODELS, 'headers': {'X-Subject-Token': "111111111"}}, + {'json': MODELS_AFTER_POST, 'headers': {'X-Subject-Token': "111111111"}}] + ) + m.register_uri( + 'POST', 'http://manager:30001/models', + headers={'X-Subject-Token': "111111111"}, + json=POST_MODEL + ) + m.register_uri( + 'PATCH', 'http://manager:30001/models/3', + headers={'X-Subject-Token': "111111111"}, + json=PATCH_MODEL + ) + m.register_uri( + 'DELETE', 'http://manager:30001/models/3', + headers={'X-Subject-Token': "111111111"}, + json=RESULT_OK + )
\ No newline at end of file diff --git a/old/python_moonclient/tests/unit_python/conf/conf_object_assignments.py b/old/python_moonclient/tests/unit_python/conf/conf_object_assignments.py new file mode 100644 index 00000000..9e88e03e --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_object_assignments.py @@ -0,0 +1,51 @@ +from .conf_all import * + +POST_OBJECT_ASSIGNMENT = { + "object_assignments":{ + "1":{ + "policy_id": "1", + "object_id": "2", + "category_id": "1", + "assignments": ["1"] + } + } +} + +POST_OTHER_OBJECT_ASSIGNMENT = { + "object_assignments":{ + "2":{ + "policy_id": "1", + "object_id": "2", + "category_id": "1", + "assignments": ["2"] + } + } +} + +DELETE_OBJECT_ASSIGNMENT = { + "object_assignments":{ + + } +} + + +def conf_object_assignments(m): + m.register_uri( + 'GET', 'http://manager:30001/policies/2/object_assignments/2/1/1', + [{'headers': {'X-Subject-Token': "111111111"}, 'json': POST_OBJECT_ASSIGNMENT}, + {'headers': {'X-Subject-Token': "111111111"}, 'json': DELETE_OBJECT_ASSIGNMENT}] + ) + m.register_uri( + 'GET', 'http://manager:30001/policies/2/object_assignments/2/1/2', + headers={'X-Subject-Token': "111111111"}, + json=POST_OTHER_OBJECT_ASSIGNMENT + ) + m.register_uri( + 'POST', 'http://manager:30001/policies/2/object_assignments', + headers={'X-Subject-Token': "111111111"}, + json=POST_OBJECT_ASSIGNMENT + ) + m.register_uri( + 'DELETE', 'http://manager:30001/policies/2/object_assignments/2/1/1', + json=RESULT_OK + )
\ No newline at end of file diff --git a/old/python_moonclient/tests/unit_python/conf/conf_object_categories.py b/old/python_moonclient/tests/unit_python/conf/conf_object_categories.py new file mode 100644 index 00000000..a942f9c6 --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_object_categories.py @@ -0,0 +1,31 @@ + +OBJECT_CATEGORIES = { + "object_categories": { + "1": { + "name": "object_cat_1", + "description": "description of the category" + } + } +} + +POST_OBJECT_CATEGORIES = { + "object_categories": { + "1": { + "name": "object_cat_1", + "description": "description of the category" + } + } +} + + +def conf_object_categories(m): + m.register_uri( + 'GET', 'http://manager:30001/object_categories', + headers={'X-Subject-Token': "111111111"}, + json=OBJECT_CATEGORIES + ) + m.register_uri( + 'POST', 'http://manager:30001/object_categories', + headers={'X-Subject-Token': "111111111"}, + json=POST_OBJECT_CATEGORIES + ) diff --git a/old/python_moonclient/tests/unit_python/conf/conf_object_data.py b/old/python_moonclient/tests/unit_python/conf/conf_object_data.py new file mode 100644 index 00000000..8fa81d69 --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_object_data.py @@ -0,0 +1,67 @@ + +from .conf_all import * + +OBJECT_DATA = { + "object_data":[{ + "policy_id": "1", + "category_id": "1", + "data": { + "1": { + "name": "name of the data", + "description": "description of the data" + } + } + }] +} + +POST_OBJECT_DATA = { + "object_data":{ + "policy_id": "1", + "category_id": "1", + "data": { + "1": { + "name": "name of the data", + "description": "description of the data" + } + } + } +} + +POST_OTHER_OBJECT_DATA = { + "object_data":{ + "policy_id": "1", + "category_id": "1", + "data": { + "2": { + "name": "name of the data", + "description": "description of the data" + } + } + } +} + +DELETE_OBJECT_DATA= { + "object_data":[{ + "policy_id": "1", + "category_id": "1", + "data":{} + }] +} + + +def conf_object_data(m): + m.register_uri( + 'POST', 'http://manager:30001/policies/2/object_data/1', + [{'headers': {'X-Subject-Token': "111111111"}, 'json': POST_OBJECT_DATA}, + {'headers': {'X-Subject-Token': "111111111"}, 'json': POST_OTHER_OBJECT_DATA}] + ) + m.register_uri( + 'GET', 'http://manager:30001/policies/2/object_data/1', + [{'headers': {'X-Subject-Token': "111111111"}, 'json': OBJECT_DATA}, + {'headers': {'X-Subject-Token': "111111111"}, 'json': DELETE_OBJECT_DATA}] + ) + m.register_uri( + 'DELETE', 'http://manager:30001/policies/2/object_data/1/1', + headers={'X-Subject-Token': "111111111"}, + json=RESULT_OK + ) diff --git a/old/python_moonclient/tests/unit_python/conf/conf_objects.py b/old/python_moonclient/tests/unit_python/conf/conf_objects.py new file mode 100644 index 00000000..cf3e7aa4 --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_objects.py @@ -0,0 +1,112 @@ +from .conf_all import * + +OBJECTS = { + "objects":{ + "1": { + "name": "name of the object", + "keystone_id": "1", + "description": "a description", + "policy_list": ["1"] + } + } +} + +OBJECTS_AFTER_POST = { + "objects":{ + "1": { + "name": "name of the object", + "keystone_id": "1", + "description": "a description", + "policy_list": ["1"] + }, + "2": { + "name": "test_object", + "keystone_id": "1", + "description": "a description", + "policy_list": [] + } + } +} + +OBJECTS_AFTER_PATCH = { + "objects":{ + "1": { + "name": "name of the object", + "keystone_id": "1", + "description": "a description", + "policy_list": ["1"] + }, + "2": { + "name": "test_object", + "keystone_id": "1", + "description": "a description", + "policy_list": ["2"] + } + } +} + + +POST_OBJECTS = { + "objects":{ + "2": { + "name": "test_object", + "keystone_id": "1", + "description": "a description", + "policy_list": [] + } + } +} + +PATCH_OBJECTS = { + "objects":{ + "2": { + "name": "test_object", + "keystone_id": "1", + "description": "a description", + "policy_list": ["2"] + } + } +} + +def conf_objects(m): + m.register_uri( + 'GET', 'http://manager:30001/objects', + [{'json': OBJECTS, 'headers': {'X-Subject-Token': "111111111"}}, + {'json': OBJECTS_AFTER_POST, 'headers': {'X-Subject-Token': "111111111"}}, + {'json': OBJECTS, 'headers': {'X-Subject-Token': "111111111"}}] + ) + m.register_uri( + 'POST', 'http://manager:30001/objects', + headers={'X-Subject-Token': "111111111"}, + json=POST_OBJECTS + ) + m.register_uri( + 'DELETE', 'http://manager:30001/objects/2', + headers={'X-Subject-Token': "111111111"}, + json=RESULT_OK + ) + m.register_uri( + 'PATCH', 'http://manager:30001/policies/2/objects/2', + headers={'X-Subject-Token': "111111111"}, + json=PATCH_OBJECTS + ) + m.register_uri( + 'GET', 'http://manager:30001/policies/2/objects', + headers={'X-Subject-Token': "111111111"}, + json=OBJECTS_AFTER_PATCH + ) + m.register_uri( + 'POST', 'http://manager:30001/policies/2/objects', + headers={'X-Subject-Token': "111111111"}, + json=POST_OBJECTS + ) + m.register_uri( + 'GET', 'http://manager:30001/policies/2/objects/2', + headers={'X-Subject-Token': "111111111"}, + json=PATCH_OBJECTS + ) + m.register_uri( + 'DELETE', 'http://manager:30001/policies/2/objects/2', + headers={'X-Subject-Token': "111111111"}, + json=RESULT_OK + ) diff --git a/old/python_moonclient/tests/unit_python/conf/conf_pdps.py b/old/python_moonclient/tests/unit_python/conf/conf_pdps.py new file mode 100644 index 00000000..1090fccb --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_pdps.py @@ -0,0 +1,95 @@ +from .conf_all import * + +PDPS = { + "pdps": { + "1": { + "name": "...", + "security_pipeline": [], + "keystone_project_id": "", + "description": "...", + } + } + } + + +POST_PDP = { + "pdps": { + "2": { + "name": "test_pdp", + "security_pipeline": [], + "keystone_project_id": "", + "description": "..." + } + } + } + +PATCH_PDP = { + "pdps": { + "2": { + "name": "test_pdp", + "security_pipeline": [], + "keystone_project_id": "0c4e939acacf4376bdcd1129f1a054ad", + "description": "..." + } + } + } + +PDPS_AFTER_POST = { + "pdps": { + "1": { + "name": "...", + "security_pipeline": [], + "keystone_project_id": "", + "description": "...", + }, + + "2": { + "name": "test_pdp", + "security_pipeline": [], + "keystone_project_id": "", + "description": "...", + } + } + } + +PDPS_AFTER_PATCH = { + "pdps": { + "1": { + "name": "...", + "security_pipeline": [], + "keystone_project_id": "", + "description": "...", + }, + + "2": { + "name": "test_pdp", + "security_pipeline": [], + "keystone_project_id": "0c4e939acacf4376bdcd1129f1a054ad", + "description": "...", + } + } + } + +def conf_pdps(m): + m.register_uri( + 'GET', 'http://manager:30001/pdp', + [{'json': PDPS, 'headers': {'X-Subject-Token': "111111111"}}, + {'json': PDPS_AFTER_POST, 'headers': {'X-Subject-Token': "111111111"}}, + {'json': PDPS_AFTER_PATCH, 'headers': {'X-Subject-Token': "111111111"}}, + {'json': PDPS, 'headers': {'X-Subject-Token': "111111111"}}] + ) + m.register_uri( + 'POST', 'http://manager:30001/pdp', + headers={'X-Subject-Token': "111111111"}, + json=POST_PDP + ) + m.register_uri( + 'PATCH', 'http://manager:30001/pdp/2', + headers={'X-Subject-Token': "111111111"}, + json=PATCH_PDP + ) + m.register_uri( + 'DELETE', 'http://manager:30001/pdp/2', + headers={'X-Subject-Token': "111111111"}, + json=RESULT_OK + )
\ No newline at end of file diff --git a/old/python_moonclient/tests/unit_python/conf/conf_policies.py b/old/python_moonclient/tests/unit_python/conf/conf_policies.py new file mode 100644 index 00000000..bf6883bc --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_policies.py @@ -0,0 +1,78 @@ +from .conf_all import * + +POLICIES = { + "policies":{ + "1": { + "name": "test_policy", + "model_id": "1", + "genre": "authz", + "description": "Description of the policy", + } + } +} + +POLICIES_AFTER_POST= { + "policies":{ + "1": { + "name": "test_policy", + "model_id": "1", + "genre": "authz", + "description": "Description of the policy", + }, + "2": { + "name": "test_policy", + "model_id": "", + "genre": "", + "description": "Description of the policy", + } + } +} + + +POST_POLICIES ={ + "policies":{ + "2": { + "name": "test_policy", + "model_id": "", + "genre": "", + "description": "Description of the policy", + } + } +} + + +PATCH_POLICIES ={ + "policies":{ + "2": { + "name": "test_policy", + "model_id": "3", + "genre": "authz", + "description": "Description of the policy", + } + } +} + + +def conf_policies(m): + m.register_uri( + 'GET', 'http://manager:30001/policies', + [{'json': POLICIES, 'headers': {'X-Subject-Token': "111111111"}}, + {'json': POLICIES_AFTER_POST, 'headers': {'X-Subject-Token': "111111111"}}, + {'json': POLICIES, 'headers': {'X-Subject-Token': "111111111"}}] + + ) + m.register_uri( + 'POST', 'http://manager:30001/policies', + headers={'X-Subject-Token': "111111111"}, + json=POST_POLICIES + ) + m.register_uri( + 'PATCH', 'http://manager:30001/policies/2', + headers={'X-Subject-Token': "111111111"}, + json=PATCH_POLICIES + ) + m.register_uri( + 'DELETE', 'http://manager:30001/policies/2', + headers={'X-Subject-Token': "111111111"}, + json=RESULT_OK + )
\ No newline at end of file diff --git a/old/python_moonclient/tests/unit_python/conf/conf_projects.py b/old/python_moonclient/tests/unit_python/conf/conf_projects.py new file mode 100644 index 00000000..63be05e0 --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_projects.py @@ -0,0 +1,44 @@ + + +PROJECTS = { + "projects": [ + { + "is_domain": False, + "description": None, + "domain_id": "admin", + "enabled": True, + "id": "0c4e939acacf4376bdcd1129f1a054ad", + "links": { + "self": "http://example.com/identity/v3/projects/0c4e939acacf4376bdcd1129f1a054ad" + }, + "name": "admin", + "parent_id": None, + "tags": [] + }, + { + "is_domain": False, + "description": None, + "domain_id": "default", + "enabled": True, + "id": "0cbd49cbf76d405d9c86562e1d579bd3", + "links": { + "self": "http://example.com/identity/v3/projects/0cbd49cbf76d405d9c86562e1d579bd3" + }, + "name": "demo", + "parent_id": None, + "tags": [] + } + ] +} + + +def conf_projects(m): + m.register_uri( + 'GET', 'http://keystone:5000/v3/projects', + headers={'X-Subject-Token': "111111111"}, + json=PROJECTS + ) + m.register_uri( + 'POST', 'http://keystone:5000/v3/auth/tokens', + headers={'X-Subject-Token': "111111111"} + ) diff --git a/old/python_moonclient/tests/unit_python/conf/conf_rules.py b/old/python_moonclient/tests/unit_python/conf/conf_rules.py new file mode 100644 index 00000000..30b8c682 --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_rules.py @@ -0,0 +1,46 @@ +from .conf_all import * + +RULES = { + "rules":{ + "policy_id": "2", + "rules": [{ + "meta_rule_id": "1", + "id": "1", + "rule": ["1", "1", "1"] + }] + } +} + +POST_RULES = { + "rules":{ + "1":{ + "policy_id": "2", + "meta_rule_id": "1", + "rule": ["1", "1", "1"] + } + } +} + +DELETE_RULES = { + "rules":{ + "policy_id": "2", + "rules": [] + } +} + + +def conf_rule_assignments(m): + m.register_uri( + 'GET', 'http://manager:30001/policies/2/rules', + [{'headers': {'X-Subject-Token': "111111111"}, 'json': RULES}, + {'headers': {'X-Subject-Token': "111111111"}, 'json': DELETE_RULES}] + ) + m.register_uri( + 'POST', 'http://manager:30001/policies/2/rules', + [{'headers': {'X-Subject-Token': "111111111"}, 'json': POST_RULES}] + ) + m.register_uri( + 'DELETE', 'http://manager:30001/policies/2/rules/1', + headers={'X-Subject-Token': "111111111"}, + json=RESULT_OK + )
\ No newline at end of file diff --git a/old/python_moonclient/tests/unit_python/conf/conf_subject_assignments.py b/old/python_moonclient/tests/unit_python/conf/conf_subject_assignments.py new file mode 100644 index 00000000..92b689c0 --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_subject_assignments.py @@ -0,0 +1,51 @@ +from .conf_all import * + +POST_SUBJECT_ASSIGNMENT = { + "subject_assignments":{ + "1":{ + "policy_id": "1", + "subject_id": "2", + "category_id": "1", + "assignments": ["1"] + } + } +} + +DELETE_SUBJECT_ASSIGNMENT = { + "subject_assignments":{ + + } +} + +POST_OTHER_SUBJECT_ASSIGNMENT = { + "subject_assignments":{ + "2":{ + "policy_id": "1", + "subject_id": "2", + "category_id": "1", + "assignments": ["2"] + } + } +} + + +def conf_subject_assignments(m): + m.register_uri( + 'GET', 'http://manager:30001/policies/2/subject_assignments/2/1/1', + [{'headers': {'X-Subject-Token': "111111111"}, 'json': POST_SUBJECT_ASSIGNMENT}, + {'headers': {'X-Subject-Token': "111111111"}, 'json': DELETE_SUBJECT_ASSIGNMENT}] + ) + m.register_uri( + 'GET', 'http://manager:30001/policies/2/subject_assignments/2/1/2', + headers={'X-Subject-Token': "111111111"}, + json=POST_OTHER_SUBJECT_ASSIGNMENT + ) + m.register_uri( + 'POST', 'http://manager:30001/policies/2/subject_assignments', + headers={'X-Subject-Token': "111111111"}, + json=POST_SUBJECT_ASSIGNMENT + ) + m.register_uri( + 'DELETE', 'http://manager:30001/policies/2/subject_assignments/2/1/1', + json=RESULT_OK + )
\ No newline at end of file diff --git a/old/python_moonclient/tests/unit_python/conf/conf_subject_categories.py b/old/python_moonclient/tests/unit_python/conf/conf_subject_categories.py new file mode 100644 index 00000000..e59a458a --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_subject_categories.py @@ -0,0 +1,30 @@ + +SUBJECT_CATEGORIES = { + "subject_categories": { + "1": { + "name": "subject_cat_1", + "description": "description of the category" + } + } +} + +POST_SUBJECT_CATEGORIES = { + "subject_categories": { + "1": { + "name": "subject_cat_1", + "description": "description of the category" + } + } +} + +def conf_subject_categories(m): + m.register_uri( + 'GET', 'http://manager:30001/subject_categories', + headers={'X-Subject-Token': "111111111"}, + json=SUBJECT_CATEGORIES + ) + m.register_uri( + 'POST', 'http://manager:30001/subject_categories', + headers={'X-Subject-Token': "111111111"}, + json=POST_SUBJECT_CATEGORIES + ) diff --git a/old/python_moonclient/tests/unit_python/conf/conf_subject_data.py b/old/python_moonclient/tests/unit_python/conf/conf_subject_data.py new file mode 100644 index 00000000..19db217d --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_subject_data.py @@ -0,0 +1,67 @@ +from .conf_all import * + +SUBJECT_DATA = { + "subject_data":[{ + "policy_id": "1", + "category_id": "1", + "data": { + "1": { + "name": "name of the data", + "description": "description of the data" + } + } + }] +} + +POST_SUBJECT_DATA = { + "subject_data":{ + "policy_id": "1", + "category_id": "1", + "data": { + "1": { + "name": "name of the data", + "description": "description of the data" + } + } + } +} + + +POST_OTHER_SUBJECT_DATA = { + "subject_data":{ + "policy_id": "1", + "category_id": "1", + "data": { + "2": { + "name": "name of the data", + "description": "description of the data" + } + } + } +} + +DELETE_SUBJECT_DATA= { + "subject_data":[{ + "policy_id": "1", + "category_id": "1", + "data":{} + }] +} + + +def conf_subject_data(m): + m.register_uri( + 'POST', 'http://manager:30001/policies/2/subject_data/1', + [{'headers': {'X-Subject-Token': "111111111"}, 'json': POST_SUBJECT_DATA}, + {'headers': {'X-Subject-Token': "111111111"}, 'json': POST_OTHER_SUBJECT_DATA}] + ) + m.register_uri( + 'GET', 'http://manager:30001/policies/2/subject_data/1', + [{'headers': {'X-Subject-Token': "111111111"}, 'json': SUBJECT_DATA}, + {'headers': {'X-Subject-Token': "111111111"}, 'json': DELETE_SUBJECT_DATA}] + ) + m.register_uri( + 'DELETE', 'http://manager:30001/policies/2/subject_data/1/1', + headers={'X-Subject-Token': "111111111"}, + json=RESULT_OK + )
\ No newline at end of file diff --git a/old/python_moonclient/tests/unit_python/conf/conf_subjects.py b/old/python_moonclient/tests/unit_python/conf/conf_subjects.py new file mode 100644 index 00000000..bde6093f --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conf/conf_subjects.py @@ -0,0 +1,112 @@ +from .conf_all import * + +SUBJECTS = { + "subjects":{ + "1": { + "name": "name of the subject", + "keystone_id": "1", + "description": "a description", + "policy_list": ["1"] + } + } +} + +SUBJECTS_AFTER_POST= { + "subjects":{ + "1": { + "name": "name of the subject", + "keystone_id": "1", + "description": "a description", + "policy_list": ["1"] + }, + "2": { + "name": "test_subject", + "keystone_id": "1", + "description": "a description", + "policy_list": [] + } + } +} + +SUBJECTS_AFTER_PATCH= { + "subjects":{ + "1": { + "name": "name of the subject", + "keystone_id": "1", + "description": "a description", + "policy_list": ["1"] + }, + "2": { + "name": "test_subject", + "keystone_id": "1", + "description": "a description", + "policy_list": ["2"] + } + } +} + +POST_SUBJECTS = { + "subjects":{ + "2": { + "name": "test_subject", + "keystone_id": "1", + "description": "a description", + "policy_list": [] + } + } +} + + +PATCH_SUBJECTS = { + "subjects":{ + "2": { + "name": "test_subject", + "keystone_id": "1", + "description": "a description", + "policy_list": ["2"] + } + } +} + +def conf_subjects(m): + m.register_uri( + 'GET', 'http://manager:30001/subjects', + [{'json': SUBJECTS, 'headers': {'X-Subject-Token': "111111111"}}, + {'json': SUBJECTS_AFTER_POST, 'headers': {'X-Subject-Token': "111111111"}}, + {'json': SUBJECTS, 'headers': {'X-Subject-Token': "111111111"}}] + ) + m.register_uri( + 'POST', 'http://manager:30001/subjects', + headers={'X-Subject-Token': "111111111"}, + json=POST_SUBJECTS + ) + m.register_uri( + 'DELETE', 'http://manager:30001/subjects/2', + headers={'X-Subject-Token': "111111111"}, + json=RESULT_OK + ) + m.register_uri( + 'PATCH', 'http://manager:30001/policies/2/subjects/2', + headers={'X-Subject-Token': "111111111"}, + json=PATCH_SUBJECTS + ) + m.register_uri( + 'GET', 'http://manager:30001/policies/2/subjects', + headers={'X-Subject-Token': "111111111"}, + json=SUBJECTS_AFTER_PATCH + ) + m.register_uri( + 'POST', 'http://manager:30001/policies/2/subjects', + headers={'X-Subject-Token': "111111111"}, + json=POST_SUBJECTS + ) + m.register_uri( + 'GET', 'http://manager:30001/policies/2/subjects/2', + headers={'X-Subject-Token': "111111111"}, + json=PATCH_SUBJECTS + ) + m.register_uri( + 'DELETE', 'http://manager:30001/policies/2/subjects/2', + headers={'X-Subject-Token': "111111111"}, + json=RESULT_OK + )
\ No newline at end of file diff --git a/old/python_moonclient/tests/unit_python/conftest.py b/old/python_moonclient/tests/unit_python/conftest.py new file mode 100644 index 00000000..bd3e5f4d --- /dev/null +++ b/old/python_moonclient/tests/unit_python/conftest.py @@ -0,0 +1,52 @@ +import pytest +import requests_mock +from . import mock_config + +from .conf.conf_projects import * +from .conf.conf_models import * +from .conf.conf_pdps import * +from .conf.conf_action_categories import * +from .conf.conf_object_categories import * +from .conf.conf_subject_categories import * +from .conf.conf_meta_rules import * +from .conf.conf_action_assignments import * +from .conf.conf_object_assignments import * +from .conf.conf_subject_assignments import * +from .conf.conf_policies import * +from .conf.conf_subjects import * +from .conf.conf_objects import * +from .conf.conf_actions import * +from .conf.conf_subject_data import * +from .conf.conf_object_data import * +from .conf.conf_action_data import * +from .conf.conf_rules import * + + +@pytest.fixture(autouse=True) +def no_requests(monkeypatch): + """ Modify the response from Requests module + """ + with requests_mock.Mocker(real_http=True) as m: + mock_config.register_consul(m) + + conf_projects(m) + conf_models(m) + conf_pdps(m) + conf_action_categories(m) + conf_object_categories(m) + conf_subject_categories(m) + conf_meta_rules(m) + conf_policies(m) + conf_subjects(m) + conf_objects(m) + conf_actions(m) + conf_object_data(m) + conf_subject_data(m) + conf_action_data(m) + conf_action_assignments(m) + conf_object_assignments(m) + conf_subject_assignments(m) + conf_rule_assignments(m) + yield m + + diff --git a/old/python_moonclient/tests/unit_python/mock_config.py b/old/python_moonclient/tests/unit_python/mock_config.py new file mode 100644 index 00000000..b6c42d76 --- /dev/null +++ b/old/python_moonclient/tests/unit_python/mock_config.py @@ -0,0 +1,64 @@ +from . import utilities + + +components_manager_mock = { + "port": 8082, + "bind": "0.0.0.0", + "hostname": "manager", + "container": "wukongsun/moon_manager:v4.3.1", + "external": { + "port": 30001, + "hostname": "88.88.88.2" + } +} + + +openstack_keystone_mock = { + "url": "http://keystone:5000/v3", + "user": "admin", + "password": "p4ssw0rd", + "domain": "default", + "project": "admin", + "check_token": False, + "certificate": False, + "external": { + "url": "http://88.88.88.2:30006/v3" + } +} + + +def register_consul(m): + for component in utilities.COMPONENTS: + m.register_uri( + 'GET', 'http://consul:8500/v1/kv/{}'.format(component), + json=[{'Key': component, 'Value': utilities.get_b64_conf(component)}] + ) + + m.register_uri( + 'GET', 'http://manager:30001', + json={} + ) + m.register_uri( + 'GET', 'http://keystone:5000/v3', + json={} + ) + m.register_uri( + 'POST', 'http://keystone:5000/v3/auth/tokens', + headers={'X-Subject-Token': "111111111"} + ) + m.register_uri( + 'DELETE', 'http://keystone:5000/v3/auth/tokens', + headers={'X-Subject-Token': "111111111"} + ) + m.register_uri( + 'POST', 'http://keystone:5000/v3/users?name=testuser&domain_id=default', + json={"users": {}} + ) + m.register_uri( + 'GET', 'http://keystone:5000/v3/users?name=testuser&domain_id=default', + json={"users": {}} + ) + m.register_uri( + 'POST', 'http://keystone:5000/v3/users/', + json={"users": [{"id": "1111111111111"}]} + ) diff --git a/old/python_moonclient/tests/unit_python/requirements.txt b/old/python_moonclient/tests/unit_python/requirements.txt new file mode 100644 index 00000000..3c1ad607 --- /dev/null +++ b/old/python_moonclient/tests/unit_python/requirements.txt @@ -0,0 +1,2 @@ +pytest +requests_mock
\ No newline at end of file diff --git a/old/python_moonclient/tests/unit_python/test_config.py b/old/python_moonclient/tests/unit_python/test_config.py new file mode 100644 index 00000000..e4effec6 --- /dev/null +++ b/old/python_moonclient/tests/unit_python/test_config.py @@ -0,0 +1,8 @@ +from python_moonclient.core.cli_exceptions import MoonCliException + + +def test_authz_request(): + from python_moonclient.core import config + conf_data = config.get_config_data("consul", 8500) + if not isinstance(conf_data, dict): + raise MoonCliException("Unexpected error : the conf data is not a dictionnary") diff --git a/old/python_moonclient/tests/unit_python/test_models.py b/old/python_moonclient/tests/unit_python/test_models.py new file mode 100644 index 00000000..fed889e3 --- /dev/null +++ b/old/python_moonclient/tests/unit_python/test_models.py @@ -0,0 +1,38 @@ +from python_moonclient.core.models import * + + +def test_models(): + init("consul", 8500) + check_model() + model_id = add_model() + check_model(model_id) + delete_model(model_id) + + +def test_meta_data_subject(): + category_id = add_subject_category() + check_subject_category(category_id) + # TODO (asteroide): must implement the deletion of linked data + # delete_subject_category(category_id) + + +def test_meta_data_object(): + category_id = add_object_category() + check_object_category(category_id) + # TODO (asteroide): must implement the deletion of linked data + # delete_object_category(category_id) + + +def test_meta_data_action(): + category_id = add_action_category() + check_action_category(category_id) + # TODO (asteroide): must implement the deletion of linked data + # delete_action_category(category_id) + + +def test_meta_rule(): + meta_rule_id, scat_id, ocat_id, acat_id = add_categories_and_meta_rule() + check_meta_rule(meta_rule_id, scat_id, ocat_id, acat_id) + delete_meta_rule(meta_rule_id) + + diff --git a/old/python_moonclient/tests/unit_python/test_pdp.py b/old/python_moonclient/tests/unit_python/test_pdp.py new file mode 100644 index 00000000..e979aeae --- /dev/null +++ b/old/python_moonclient/tests/unit_python/test_pdp.py @@ -0,0 +1,17 @@ +from python_moonclient.core.pdp import * + +def test_pdp(): + init("consul", 8500) + projects = get_keystone_projects() + admin_project_id = None + for _project in projects['projects']: + if _project['name'] == "admin": + admin_project_id = _project['id'] + if admin_project_id is None: + raise MoonCliException("Unexpected results, could not find the admin project") + check_pdp() + pdp_id = add_pdp() + check_pdp(pdp_id) + map_to_keystone(pdp_id=pdp_id, keystone_project_id=admin_project_id) + check_pdp(pdp_id=pdp_id, keystone_project_id=admin_project_id) + delete_pdp(pdp_id) diff --git a/old/python_moonclient/tests/unit_python/test_policies.py b/old/python_moonclient/tests/unit_python/test_policies.py new file mode 100644 index 00000000..9ab9003e --- /dev/null +++ b/old/python_moonclient/tests/unit_python/test_policies.py @@ -0,0 +1,161 @@ +from python_moonclient.core.policies import * +from python_moonclient.core.models import * +from python_moonclient.core import policies +from python_moonclient.core import models + + +def test_policies(): + policies.init("consul", 8500) + models.init("consul", 8500) + check_policy() + policy_id = add_policy() + check_policy(policy_id) + delete_policy(policy_id) + + +def test_subjects(): + policy_id = add_policy() + subject_id = add_subject() + + update_subject(subject_id=subject_id, policy_id=policy_id) + + check_subject(subject_id=subject_id, policy_id=policy_id) + + delete_subject(subject_id, policy_id=policy_id) + delete_subject(subject_id) + + +def test_objects(): + policy_id = add_policy() + object_id = add_object() + + update_object(object_id=object_id, policy_id=policy_id) + check_object(object_id=object_id, policy_id=policy_id) + + delete_object(object_id=object_id, policy_id=policy_id) + delete_object(object_id=object_id) + + +def test_actions(): + policy_id = add_policy() + action_id = add_action() + + update_action(action_id=action_id, policy_id=policy_id) + check_action(action_id=action_id, policy_id=policy_id) + + delete_action(action_id=action_id, policy_id=policy_id) + delete_action(action_id=action_id) + + +def test_subject_data(): + policy_id = add_policy() + + model_id = add_model() + + update_policy(policy_id, model_id) + + meta_rule_id, subject_cat_id, object_cat_id, action_cat_id = add_categories_and_meta_rule() + add_meta_rule_to_model(model_id, meta_rule_id) + + subject_data_id = add_subject_data(policy_id=policy_id, category_id=subject_cat_id) + check_subject_data(policy_id=policy_id, data_id=subject_data_id, category_id=subject_cat_id) + delete_subject_data(policy_id=policy_id, data_id=subject_data_id, category_id=subject_cat_id) + + +def test_object_data(): + policy_id = add_policy() + + model_id = add_model() + + update_policy(policy_id, model_id) + + meta_rule_id, object_cat_id, object_cat_id, action_cat_id = add_categories_and_meta_rule() + add_meta_rule_to_model(model_id, meta_rule_id) + + object_data_id = add_object_data(policy_id=policy_id, category_id=object_cat_id) + check_object_data(policy_id=policy_id, data_id=object_data_id, category_id=object_cat_id) + delete_object_data(policy_id=policy_id, data_id=object_data_id, category_id=object_cat_id) + print('ok') + +def test_action_data(): + policy_id = add_policy() + + model_id = add_model() + + update_policy(policy_id, model_id) + + meta_rule_id, action_cat_id, action_cat_id, action_cat_id = add_categories_and_meta_rule() + add_meta_rule_to_model(model_id, meta_rule_id) + + action_data_id = add_action_data(policy_id=policy_id, category_id=action_cat_id) + check_action_data(policy_id=policy_id, data_id=action_data_id, category_id=action_cat_id) + delete_action_data(policy_id=policy_id, data_id=action_data_id, category_id=action_cat_id) + + +def test_assignments(): + policy_id = add_policy() + + model_id = add_model() + + update_policy(policy_id, model_id) + + meta_rule_id, subject_cat_id, object_cat_id, action_cat_id = add_categories_and_meta_rule() + add_meta_rule_to_model(model_id, meta_rule_id) + + subject_data_id = add_subject_data(policy_id=policy_id, category_id=subject_cat_id) + subject_data_id_bis = add_subject_data(policy_id=policy_id, category_id=subject_cat_id) + object_data_id = add_object_data(policy_id=policy_id, category_id=object_cat_id) + object_data_id_bis = add_object_data(policy_id=policy_id, category_id=object_cat_id) + action_data_id = add_action_data(policy_id=policy_id, category_id=action_cat_id) + action_data_id_bis = add_action_data(policy_id=policy_id, category_id=action_cat_id) + + subject_id = add_subject(policy_id) + object_id = add_object(policy_id) + action_id = add_action(policy_id) + + add_subject_assignments(policy_id, subject_id, subject_cat_id, subject_data_id) + add_subject_assignments(policy_id, subject_id, subject_cat_id, subject_data_id_bis) + add_object_assignments(policy_id, object_id, object_cat_id, object_data_id) + add_object_assignments(policy_id, object_id, object_cat_id, object_data_id_bis) + add_action_assignments(policy_id, action_id, action_cat_id, action_data_id) + add_action_assignments(policy_id, action_id, action_cat_id, action_data_id_bis) + + check_subject_assignments(policy_id, subject_id, subject_cat_id, subject_data_id) + check_subject_assignments(policy_id, subject_id, subject_cat_id, subject_data_id_bis) + check_object_assignments(policy_id, object_id, object_cat_id, object_data_id) + check_object_assignments(policy_id, object_id, object_cat_id, object_data_id_bis) + check_action_assignments(policy_id, action_id, action_cat_id, action_data_id) + check_action_assignments(policy_id, action_id, action_cat_id, action_data_id_bis) + + delete_subject_assignment(policy_id, subject_id, subject_cat_id, subject_data_id) + delete_object_assignment(policy_id, object_id, object_cat_id, object_data_id) + delete_action_assignment(policy_id, action_id, action_cat_id, action_data_id) + + +def test_rule(): + policy_id = add_policy() + + model_id = add_model() + + update_policy(policy_id, model_id) + + meta_rule_id, subject_cat_id, object_cat_id, action_cat_id = add_categories_and_meta_rule() + add_meta_rule_to_model(model_id, meta_rule_id) + + subject_data_id = add_subject_data(policy_id=policy_id, category_id=subject_cat_id) + object_data_id = add_object_data(policy_id=policy_id, category_id=object_cat_id) + action_data_id = add_action_data(policy_id=policy_id, category_id=action_cat_id) + + subject_id = add_subject(policy_id) + object_id = add_object(policy_id) + action_id = add_action(policy_id) + + add_subject_assignments(policy_id, subject_id, subject_cat_id, subject_data_id) + add_object_assignments(policy_id, object_id, object_cat_id, object_data_id) + add_action_assignments(policy_id, action_id, action_cat_id, action_data_id) + + rule_id = add_rule(policy_id, meta_rule_id, [subject_data_id, object_data_id, action_data_id]) + check_rule(policy_id, meta_rule_id, rule_id, [subject_data_id, object_data_id, action_data_id]) + + delete_rule(policy_id, rule_id) + diff --git a/old/python_moonclient/tests/unit_python/utilities.py b/old/python_moonclient/tests/unit_python/utilities.py new file mode 100644 index 00000000..ae2932c7 --- /dev/null +++ b/old/python_moonclient/tests/unit_python/utilities.py @@ -0,0 +1,153 @@ +import base64 +import json + +CONF = { + "openstack": { + "keystone": { + "url": "http://keystone:5000/v3", + "user": "admin", + "check_token": False, + "password": "p4ssw0rd", + "domain": "default", + "certificate": False, + "project": "admin", + "external": { + "url": "http://keystone:5000/v3", + } + } + }, + "components": { + "wrapper": { + "bind": "0.0.0.0", + "port": 8080, + "container": "wukongsun/moon_wrapper:v4.3", + "timeout": 5, + "hostname": "wrapper" + }, + "manager": { + "bind": "0.0.0.0", + "port": 8082, + "container": "wukongsun/moon_manager:v4.3", + "hostname": "manager", + "external": { + "hostname": "manager", + "port": 30001 + } + }, + "port_start": 31001, + "orchestrator": { + "bind": "0.0.0.0", + "port": 8083, + "container": "wukongsun/moon_orchestrator:v4.3", + "hostname": "orchestrator" + }, + "interface": { + "bind": "0.0.0.0", + "port": 8080, + "container": "wukongsun/moon_interface:v4.3", + "hostname": "interface" + } + }, + "plugins": { + "session": { + "port": 8082, + "container": "asteroide/session:latest" + }, + "authz": { + "port": 8081, + "container": "wukongsun/moon_authz:v4.3" + } + }, + "logging": { + "handlers": { + "file": { + "filename": "/tmp/moon.log", + "class": "logging.handlers.RotatingFileHandler", + "level": "DEBUG", + "formatter": "custom", + "backupCount": 3, + "maxBytes": 1048576 + }, + "console": { + "class": "logging.StreamHandler", + "formatter": "brief", + "level": "INFO", + "stream": "ext://sys.stdout" + } + }, + "formatters": { + "brief": { + "format": "%(levelname)s %(name)s %(message)-30s" + }, + "custom": { + "format": "%(asctime)-15s %(levelname)s %(name)s %(message)s" + } + }, + "root": { + "handlers": [ + "console" + ], + "level": "ERROR" + }, + "version": 1, + "loggers": { + "moon": { + "handlers": [ + "console", + "file" + ], + "propagate": False, + "level": "DEBUG" + } + } + }, + "slave": { + "name": None, + "master": { + "url": None, + "login": None, + "password": None + } + }, + "docker": { + "url": "tcp://172.88.88.1:2376", + "network": "moon" + }, + "database": { + "url": "sqlite:///database.db", + # "url": "mysql+pymysql://moon:p4sswOrd1@db/moon", + "driver": "sql" + }, + "messenger": { + "url": "rabbit://moon:p4sswOrd1@messenger:5672/moon" + } +} + +COMPONENTS = ( + "logging", + "openstack/keystone", + "database", + "slave", + "components/manager", + "components/orchestrator", + "components/interface", + "components/wrapper", +) + + +def get_b64_conf(component=None): + if component == "components": + return base64.b64encode( + json.dumps(CONF["components"]).encode('utf-8')+b"\n").decode('utf-8') + elif component in CONF: + return base64.b64encode( + json.dumps( + CONF[component]).encode('utf-8')+b"\n").decode('utf-8') + elif not component: + return base64.b64encode( + json.dumps(CONF).encode('utf-8')+b"\n").decode('utf-8') + elif "/" in component: + key1, _, key2 = component.partition("/") + return base64.b64encode( + json.dumps( + CONF[key1][key2]).encode('utf-8')+b"\n").decode('utf-8') |