aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--moon_authz/Dockerfile13
-rw-r--r--moon_dashboard/.gitignore1
-rw-r--r--moon_dashboard/.gitlab-ci.yml64
-rw-r--r--moon_dashboard/Dockerfile34
-rw-r--r--moon_dashboard/LICENSE0
-rw-r--r--moon_dashboard/MANIFEST.in3
-rw-r--r--moon_dashboard/README.md40
-rw-r--r--moon_dashboard/README.rst39
-rw-r--r--moon_dashboard/babel-django.cfg5
-rw-r--r--moon_dashboard/babel-djangojs.cfg14
-rw-r--r--moon_dashboard/moon/__init__.py0
-rw-r--r--moon_dashboard/moon/dashboard.py13
-rw-r--r--moon_dashboard/moon/enabled/_32000_moon.py19
-rw-r--r--moon_dashboard/moon/model/__init__.py0
-rw-r--r--moon_dashboard/moon/model/panel.py23
-rw-r--r--moon_dashboard/moon/model/templates/model/index.html16
-rw-r--r--moon_dashboard/moon/model/tests.py19
-rw-r--r--moon_dashboard/moon/model/urls.py20
-rw-r--r--moon_dashboard/moon/model/views.py22
-rw-r--r--moon_dashboard/moon/pdp/__init__.py0
-rw-r--r--moon_dashboard/moon/pdp/panel.py23
-rw-r--r--moon_dashboard/moon/pdp/templates/pdp/index.html16
-rw-r--r--moon_dashboard/moon/pdp/tests.py19
-rw-r--r--moon_dashboard/moon/pdp/urls.py20
-rw-r--r--moon_dashboard/moon/pdp/views.py22
-rw-r--r--moon_dashboard/moon/policy/__init__.py0
-rw-r--r--moon_dashboard/moon/policy/panel.py23
-rw-r--r--moon_dashboard/moon/policy/templates/policy/index.html16
-rw-r--r--moon_dashboard/moon/policy/tests.py19
-rw-r--r--moon_dashboard/moon/policy/urls.py20
-rw-r--r--moon_dashboard/moon/policy/views.py22
-rw-r--r--moon_dashboard/moon/static/moon/js/angular-resource.js863
-rwxr-xr-xmoon_dashboard/moon/static/moon/js/import.service.js27
-rwxr-xr-xmoon_dashboard/moon/static/moon/js/moon.module.js29
-rwxr-xr-xmoon_dashboard/moon/static/moon/js/util.service.js136
-rwxr-xr-xmoon_dashboard/moon/static/moon/js/util.service.spec.js86
-rw-r--r--moon_dashboard/moon/static/moon/model/model.controller.js244
-rw-r--r--moon_dashboard/moon/static/moon/model/model.html143
-rwxr-xr-xmoon_dashboard/moon/static/moon/model/model.service.js286
-rwxr-xr-xmoon_dashboard/moon/static/moon/model/model.service.spec.js288
-rw-r--r--moon_dashboard/moon/static/moon/pdp/pdp.controller.js121
-rw-r--r--moon_dashboard/moon/static/moon/pdp/pdp.html41
-rwxr-xr-xmoon_dashboard/moon/static/moon/pdp/pdp.service.js123
-rwxr-xr-xmoon_dashboard/moon/static/moon/pdp/pdp.service.spec.js143
-rw-r--r--moon_dashboard/moon/static/moon/policy/policy.controller.js295
-rw-r--r--moon_dashboard/moon/static/moon/policy/policy.html158
-rwxr-xr-xmoon_dashboard/moon/static/moon/policy/policy.service.js330
-rwxr-xr-xmoon_dashboard/moon/static/moon/policy/policy.service.spec.js336
-rw-r--r--moon_dashboard/moon/static/moon/scss/moon.scss54
-rw-r--r--moon_dashboard/moon/templates/moon/base.html11
-rw-r--r--moon_dashboard/run.sh26
-rw-r--r--moon_dashboard/setup.cfg24
-rw-r--r--moon_dashboard/setup.py14
-rw-r--r--moon_forming/Changelog11
-rw-r--r--moon_forming/Dockerfile8
-rw-r--r--moon_forming/conf2consul.py2
-rw-r--r--moon_interface/Changelog4
-rw-r--r--moon_interface/Dockerfile13
-rw-r--r--moon_interface/moon_interface/__init__.py2
-rw-r--r--moon_interface/moon_interface/authz_requests.py1
-rw-r--r--moon_interface/tests/unit_python/api/test_authz.py6
-rw-r--r--moon_manager/Changelog12
-rw-r--r--moon_manager/Dockerfile13
-rw-r--r--moon_manager/moon_manager/__init__.py2
-rw-r--r--moon_manager/moon_manager/api/assignments.py149
-rw-r--r--moon_manager/moon_manager/api/data.py124
-rw-r--r--moon_manager/moon_manager/api/json_import.py88
-rw-r--r--moon_manager/moon_manager/api/meta_data.py101
-rw-r--r--moon_manager/moon_manager/api/meta_rules.py51
-rw-r--r--moon_manager/moon_manager/api/models.py45
-rw-r--r--moon_manager/moon_manager/api/pdp.py83
-rw-r--r--moon_manager/moon_manager/api/perimeter.py254
-rw-r--r--moon_manager/moon_manager/api/policies.py50
-rw-r--r--moon_manager/moon_manager/api/rules.py37
-rw-r--r--moon_manager/moon_manager/api/slaves.py12
-rw-r--r--moon_manager/moon_manager/http_server.py7
-rw-r--r--moon_manager/tests/unit_python/api/import_export_utilities.py45
-rw-r--r--moon_manager/tests/unit_python/api/test_assignemnt.py161
-rw-r--r--moon_manager/tests/unit_python/api/test_data.py89
-rw-r--r--moon_manager/tests/unit_python/api/test_export.py40
-rw-r--r--moon_manager/tests/unit_python/api/test_import.py78
-rw-r--r--moon_manager/tests/unit_python/api/test_meta_data.py235
-rw-r--r--moon_manager/tests/unit_python/api/test_meta_rules.py175
-rw-r--r--moon_manager/tests/unit_python/api/test_pdp.py55
-rw-r--r--moon_manager/tests/unit_python/api/test_perimeter.py153
-rw-r--r--moon_manager/tests/unit_python/api/test_policies.py19
-rw-r--r--moon_manager/tests/unit_python/api/test_rules.py71
-rw-r--r--moon_manager/tests/unit_python/api/test_unit_models.py61
-rw-r--r--moon_manager/tests/unit_python/api/utilities.py24
-rw-r--r--moon_manager/tests/unit_python/conftest.py12
-rw-r--r--moon_manager/tests/unit_python/helpers/__init__.py0
-rw-r--r--moon_manager/tests/unit_python/helpers/assignment_helper.py49
-rw-r--r--moon_manager/tests/unit_python/helpers/category_helper.py40
-rw-r--r--moon_manager/tests/unit_python/helpers/data_builder.py209
-rw-r--r--moon_manager/tests/unit_python/helpers/data_helper.py99
-rw-r--r--moon_manager/tests/unit_python/helpers/meta_rule_helper.py49
-rw-r--r--moon_manager/tests/unit_python/helpers/model_helper.py51
-rw-r--r--moon_manager/tests/unit_python/helpers/pdp_helper.py23
-rw-r--r--moon_manager/tests/unit_python/helpers/policy_helper.py61
-rw-r--r--moon_manager/tests/unit_python/requirements.txt2
-rw-r--r--moon_orchestrator/Dockerfile13
-rw-r--r--moon_wrapper/Dockerfile13
-rw-r--r--python_moonclient/Changelog4
-rw-r--r--python_moonclient/python_moonclient/__init__.py2
-rw-r--r--python_moonclient/python_moonclient/core/config.py4
-rw-r--r--python_moondb/Changelog33
-rw-r--r--python_moondb/python_moondb/__init__.py3
-rw-r--r--python_moondb/python_moondb/api/model.py43
-rw-r--r--python_moondb/python_moondb/api/pdp.py8
-rw-r--r--python_moondb/python_moondb/api/policy.py59
-rw-r--r--python_moondb/python_moondb/backends/sql.py126
-rw-r--r--python_moondb/python_moondb/migrate_repo/versions/001_moon.py49
-rw-r--r--python_moondb/tests/unit_python/helpers/__init__.py0
-rw-r--r--python_moondb/tests/unit_python/helpers/assignment_helper.py49
-rw-r--r--python_moondb/tests/unit_python/helpers/category_helper.py54
-rw-r--r--python_moondb/tests/unit_python/helpers/data_helper.py98
-rw-r--r--python_moondb/tests/unit_python/helpers/meta_rule_helper.py48
-rw-r--r--python_moondb/tests/unit_python/helpers/mock_data.py144
-rw-r--r--python_moondb/tests/unit_python/helpers/model_helper.py50
-rw-r--r--python_moondb/tests/unit_python/helpers/pdp_helper.py23
-rw-r--r--python_moondb/tests/unit_python/helpers/policy_helper.py61
-rw-r--r--python_moondb/tests/unit_python/models/test_categories.py250
-rw-r--r--python_moondb/tests/unit_python/models/test_meta_rules.py194
-rw-r--r--python_moondb/tests/unit_python/models/test_models.py385
-rw-r--r--python_moondb/tests/unit_python/policies/mock_data.py35
-rwxr-xr-xpython_moondb/tests/unit_python/policies/test_assignments.py299
-rwxr-xr-xpython_moondb/tests/unit_python/policies/test_data.py634
-rwxr-xr-xpython_moondb/tests/unit_python/policies/test_policies.py237
-rw-r--r--python_moondb/tests/unit_python/requirements.txt1
-rwxr-xr-xpython_moondb/tests/unit_python/test_pdp.py108
-rw-r--r--python_moonutilities/Changelog4
-rw-r--r--python_moonutilities/python_moonutilities/__init__.py2
-rw-r--r--python_moonutilities/python_moonutilities/exceptions.py18
-rw-r--r--python_moonutilities/python_moonutilities/security_functions.py2
134 files changed, 8058 insertions, 2194 deletions
diff --git a/moon_authz/Dockerfile b/moon_authz/Dockerfile
index c44d7c23..7081e31c 100644
--- a/moon_authz/Dockerfile
+++ b/moon_authz/Dockerfile
@@ -1,10 +1,15 @@
FROM python:3
+LABEL Name=Authz_plugin
+LABEL Description="Authz plugin for the Moon platform"
+LABEL Maintainer="Thomas Duval"
+LABEL Url="https://wiki.opnfv.org/display/moon/Moon+Project+Proposal"
+
+USER root
+
ADD . /root
WORKDIR /root/
-RUN pip3 install -r requirements.txt
-RUN if [ -d /root/dist ]; then for FILE in $(ls /root/dist/*.tar.gz); do pip install $FILE --upgrade; done; fi
-RUN if [ -d /root/dist ]; then for FILE in $(ls /root/dist/*.whl); do pip install $FILE --upgrade; done; fi
-RUN pip3 install .
+RUN pip3 install --no-cache-dir -r requirements.txt
+RUN pip3 install --no-cache-dir .
CMD ["python3", "-m", "moon_authz"] \ No newline at end of file
diff --git a/moon_dashboard/.gitignore b/moon_dashboard/.gitignore
new file mode 100644
index 00000000..61f2dc9f
--- /dev/null
+++ b/moon_dashboard/.gitignore
@@ -0,0 +1 @@
+**/__pycache__/
diff --git a/moon_dashboard/.gitlab-ci.yml b/moon_dashboard/.gitlab-ci.yml
new file mode 100644
index 00000000..50fd8a4e
--- /dev/null
+++ b/moon_dashboard/.gitlab-ci.yml
@@ -0,0 +1,64 @@
+stages:
+ - lint
+ - build
+ - test
+ - publish
+
+variables:
+ http_proxy: "http://devwatt-proxy.si.fr.intraorange:8080"
+ https_proxy: "http://devwatt-proxy.si.fr.intraorange:8080"
+ no_proxy: dind, gitlab.forge.orange-labs.fr
+ DOCKER_DRIVER: overlay
+ DOCKER_HOST: tcp://dind:2375
+ CONTAINER_RELEASE_IMAGE: moonplatform/$CI_PROJECT_NAME
+ CONTAINER_TAG: dev
+ DOCKER_VERSION: "17.12"
+
+services:
+ - name: dockerproxy-iva.si.francetelecom.fr/docker:$DOCKER_VERSION-dind
+ alias: dind
+image: dockerproxy-iva.si.francetelecom.fr/docker:$DOCKER_VERSION
+
+lint-job:
+ image: dockerfactory-iva.si.francetelecom.fr/docker/orange-dockerfile-lint:0.2.7-alpine3.6-2
+ tags:
+ - rsc
+ - docker
+ - shared
+ stage: lint
+ script:
+ - dockerfile_lint -f Dockerfile
+
+build-job:
+ stage: build
+ tags:
+ - rsc
+ - docker-privileged
+ script:
+ - docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD
+ - docker build -t $CONTAINER_RELEASE_IMAGE:$CONTAINER_TAG --build-arg http_proxy=$http_proxy --build-arg https_proxy=$http_proxy .
+ - docker push $CONTAINER_RELEASE_IMAGE:$CONTAINER_TAG
+
+test-job:
+ stage: test
+ tags:
+ - rsc
+ - docker-privileged
+ script:
+ - docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD
+ - docker run -e http_proxy=$http_proxy -e https_proxy=$http_proxy $CONTAINER_RELEASE_IMAGE:$CONTAINER_TAG curl http://localhost:8000
+
+publish-job:
+ stage: publish
+ tags:
+ - rsc
+ - docker-privileged
+ script:
+ - docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD
+ - FINAL_TAG=$(grep version setup.cfg | cut -d "=" -f 2)
+ - echo FINAL_TAG=$FINAL_TAG
+ - docker pull $CONTAINER_RELEASE_IMAGE:$CONTAINER_TAG
+ - docker tag $CONTAINER_RELEASE_IMAGE:$CONTAINER_TAG $CONTAINER_RELEASE_IMAGE:$FINAL_TAG
+ - docker push $CONTAINER_RELEASE_IMAGE:$FINAL_TAG
+ only:
+ - master
diff --git a/moon_dashboard/Dockerfile b/moon_dashboard/Dockerfile
new file mode 100644
index 00000000..8f997fe1
--- /dev/null
+++ b/moon_dashboard/Dockerfile
@@ -0,0 +1,34 @@
+FROM python:3.5
+
+LABEL Name=Dashboard
+LABEL Description="User interface for the Moon platform"
+LABEL Maintainer="Thomas Duval"
+LABEL Url="https://wiki.opnfv.org/display/moon/Moon+Project+Proposal"
+
+ENV MANAGER_HOST="127.0.0.1"
+ENV MANAGER_PORT=30001
+ENV KEYSTONE_HOST="127.0.0.1"
+ENV KEYSTONE_PORT=30005
+ENV OPENSTACK_HOST="127.0.0.1"
+ENV OPENSTACK_KEYSTONE_URL="http://${KEYSTONE_HOST}:${KEYSTONE_PORT}/v2.0"
+
+USER root
+
+WORKDIR /root/
+ADD . /root
+
+RUN git clone https://git.openstack.org/openstack/horizon
+
+WORKDIR /root/horizon
+
+RUN pip install --no-cache-dir -c http://git.openstack.org/cgit/openstack/requirements/plain/upper-constraints.txt .
+
+RUN cp openstack_dashboard/local/local_settings.py.example openstack_dashboard/local/local_settings.py
+RUN pip install --no-cache-dir tox
+
+WORKDIR /root/
+
+RUN cp -v moon/enabled/_32000_moon.py horizon/openstack_dashboard/local/enabled/_32000_moon.py
+RUN cp -rv moon/ horizon/openstack_dashboard/dashboards/
+
+CMD ["/bin/sh", "/root/run.sh"] \ No newline at end of file
diff --git a/moon_dashboard/LICENSE b/moon_dashboard/LICENSE
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/moon_dashboard/LICENSE
diff --git a/moon_dashboard/MANIFEST.in b/moon_dashboard/MANIFEST.in
new file mode 100644
index 00000000..1f077b06
--- /dev/null
+++ b/moon_dashboard/MANIFEST.in
@@ -0,0 +1,3 @@
+include setup.py
+
+recursive-include myplugin *.js *.html *.scss \ No newline at end of file
diff --git a/moon_dashboard/README.md b/moon_dashboard/README.md
new file mode 100644
index 00000000..fca52b2d
--- /dev/null
+++ b/moon_dashboard/README.md
@@ -0,0 +1,40 @@
+# Moon plugin for Horizon (OpenStack Dashboard)
+
+## Install Horizon
+
+https://docs.openstack.org/horizon/latest/install/index.html
+
+or for developper quick start:
+
+https://docs.openstack.org/horizon/latest/contributor/quickstart.html
+
+
+## Moon plugin
+
+Clone the plugin:
+
+```bash
+git clone https://gitlab.forge.orange-labs.fr/moon/dashboard.git
+```
+
+* ``$plugin`` is the location of moon plugin
+* ``$horizon`` is the location of horizon
+
+Make symbolic link to enabled file:
+
+```bash
+ln -s $plugin/moon/enabled/_32000_moon.py $horizon/openstack_dashboard/local/enabled/_32000_moon.py
+```
+
+Make symbolic link to dashboard folder:
+
+```bash
+ln -s $plugin/moon/ $horizon/openstack_dashboard/dashboards/moon
+```
+
+Finish by restarting the Horizon server.
+
+## Set Moon API endpoint
+
+Set the endpoint in $plugin/moon/moon/static/moon/js/moon.module.js file
+
diff --git a/moon_dashboard/README.rst b/moon_dashboard/README.rst
new file mode 100644
index 00000000..de9c4058
--- /dev/null
+++ b/moon_dashboard/README.rst
@@ -0,0 +1,39 @@
+=============================================
+Moon plugin for Horizon (OpenStack Dashboard)
+=============================================
+
+Install Horizon
+===============
+
+https://docs.openstack.org/horizon/latest/install/index.html
+
+or for developper quick start:
+
+https://docs.openstack.org/horizon/latest/contributor/quickstart.html
+
+
+Moon plugin
+===========
+
+Clone the plugin:
+
+"git clone https://gitlab.forge.orange-labs.fr/moon/dashboard.git"
+
+* ``plugin`` is the location of moon plugin
+* ``horizon`` is the location of horizon
+
+Make symbolic link to enabled file:
+
+"ln -s ``plugin`Ì€`/moon/enabled/_32000_moon.py ``horizon``/openstack_dashboard/local/enabled/_32000_moon.py"
+
+Make symbolic link to dashboard folder:
+
+"ln -s ``plugin`Ì€`/moon/ ``horizon``/openstack_dashboard/dashboards/moon"
+
+Finish by restarting the Horizon server.
+
+
+Set Moon API endpoint
+===========
+
+Set the endpoint in ``plugin``/moon/moon/static/moon/js/moon.module.js file \ No newline at end of file
diff --git a/moon_dashboard/babel-django.cfg b/moon_dashboard/babel-django.cfg
new file mode 100644
index 00000000..fa906ad8
--- /dev/null
+++ b/moon_dashboard/babel-django.cfg
@@ -0,0 +1,5 @@
+[extractors]
+django = django_babel.extract:extract_django
+
+[python: **.py]
+[django: **/templates/**.html] \ No newline at end of file
diff --git a/moon_dashboard/babel-djangojs.cfg b/moon_dashboard/babel-djangojs.cfg
new file mode 100644
index 00000000..1c07ba6a
--- /dev/null
+++ b/moon_dashboard/babel-djangojs.cfg
@@ -0,0 +1,14 @@
+[extractors]
+# We use a custom extractor to find translatable strings in AngularJS
+# templates. The extractor is included in horizon.utils for now.
+# See http://babel.pocoo.org/docs/messages/#referencing-extraction-methods for
+# details on how this works.
+angular = horizon.utils.babel_extract_angular:extract_angular
+
+[javascript: **.js]
+
+# We need to look into all static folders for HTML files.
+# The **/static ensures that we also search within
+# /openstack_dashboard/dashboards/XYZ/static which will ensure
+# that plugins are also translated.
+[angular: **/static/**.html] \ No newline at end of file
diff --git a/moon_dashboard/moon/__init__.py b/moon_dashboard/moon/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/moon_dashboard/moon/__init__.py
diff --git a/moon_dashboard/moon/dashboard.py b/moon_dashboard/moon/dashboard.py
new file mode 100644
index 00000000..0e3e491e
--- /dev/null
+++ b/moon_dashboard/moon/dashboard.py
@@ -0,0 +1,13 @@
+from django.utils.translation import ugettext_lazy as _
+
+import horizon
+
+
+class Moon(horizon.Dashboard):
+ name = _("Moon")
+ slug = "moon"
+ panels = ('model','policy','pdp',) # Add your panels here.
+ default_panel = 'model' # Specify the slug of the default panel.
+
+
+horizon.register(Moon)
diff --git a/moon_dashboard/moon/enabled/_32000_moon.py b/moon_dashboard/moon/enabled/_32000_moon.py
new file mode 100644
index 00000000..73198de6
--- /dev/null
+++ b/moon_dashboard/moon/enabled/_32000_moon.py
@@ -0,0 +1,19 @@
+# The name of the dashboard to be added to HORIZON['dashboards']. Required.
+DASHBOARD = 'moon'
+
+# If set to True, this dashboard will not be added to the settings.
+DISABLED = False
+
+# A list of AngularJS modules to be loaded when Angular bootstraps.
+ADD_ANGULAR_MODULES = ['moon']
+
+# Automatically discover static resources in installed apps
+AUTO_DISCOVER_STATIC_FILES = True
+
+# A list of applications to be added to INSTALLED_APPS.
+ADD_INSTALLED_APPS = [
+ 'openstack_dashboard.dashboards.moon',
+]
+
+# A list of scss files to be included in the compressed set of files
+ADD_SCSS_FILES = ['moon/scss/moon.scss']
diff --git a/moon_dashboard/moon/model/__init__.py b/moon_dashboard/moon/model/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/moon_dashboard/moon/model/__init__.py
diff --git a/moon_dashboard/moon/model/panel.py b/moon_dashboard/moon/model/panel.py
new file mode 100644
index 00000000..9cb65ef0
--- /dev/null
+++ b/moon_dashboard/moon/model/panel.py
@@ -0,0 +1,23 @@
+# 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.
+
+from django.utils.translation import ugettext_lazy as _
+
+import horizon
+from openstack_dashboard.dashboards.moon import dashboard
+
+class Model(horizon.Panel):
+ name = _("Models")
+ slug = "model"
+
+
+dashboard.Moon.register(Model)
diff --git a/moon_dashboard/moon/model/templates/model/index.html b/moon_dashboard/moon/model/templates/model/index.html
new file mode 100644
index 00000000..db372a02
--- /dev/null
+++ b/moon_dashboard/moon/model/templates/model/index.html
@@ -0,0 +1,16 @@
+{% extends 'base.html' %}
+{% load i18n %}
+{% block title %}{% trans "Models" %}{% endblock %}
+
+{% block page_header %}
+ {% include "horizon/common/_page_header.html" with title=_("Models") %}
+{% endblock page_header %}
+
+
+
+{% block main %}
+ <ng-include
+ src="'{{ STATIC_URL }}moon/model/model.html'">
+ </ng-include>
+{% endblock %}
+
diff --git a/moon_dashboard/moon/model/tests.py b/moon_dashboard/moon/model/tests.py
new file mode 100644
index 00000000..ec988636
--- /dev/null
+++ b/moon_dashboard/moon/model/tests.py
@@ -0,0 +1,19 @@
+# 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.
+
+from horizon.test import helpers as test
+
+
+class MypanelTests(test.TestCase):
+ # Unit tests for mypanel.
+ def test_me(self):
+ self.assertTrue(1 + 1 == 2)
diff --git a/moon_dashboard/moon/model/urls.py b/moon_dashboard/moon/model/urls.py
new file mode 100644
index 00000000..ca9507fb
--- /dev/null
+++ b/moon_dashboard/moon/model/urls.py
@@ -0,0 +1,20 @@
+# 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.
+
+from django.conf.urls import url
+
+from openstack_dashboard.dashboards.moon.model import views
+
+
+urlpatterns = [
+ url(r'^$', views.IndexView.as_view(), name='index'),
+]
diff --git a/moon_dashboard/moon/model/views.py b/moon_dashboard/moon/model/views.py
new file mode 100644
index 00000000..73509537
--- /dev/null
+++ b/moon_dashboard/moon/model/views.py
@@ -0,0 +1,22 @@
+# 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.
+
+from horizon import views
+
+
+class IndexView(views.APIView):
+ # A very simple class-based view...
+ template_name = 'moon/model/index.html'
+
+ def get_data(self, request, context, *args, **kwargs):
+ # Add data to the context here...
+ return context
diff --git a/moon_dashboard/moon/pdp/__init__.py b/moon_dashboard/moon/pdp/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/moon_dashboard/moon/pdp/__init__.py
diff --git a/moon_dashboard/moon/pdp/panel.py b/moon_dashboard/moon/pdp/panel.py
new file mode 100644
index 00000000..9c4b3fa3
--- /dev/null
+++ b/moon_dashboard/moon/pdp/panel.py
@@ -0,0 +1,23 @@
+# 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.
+
+from django.utils.translation import ugettext_lazy as _
+
+import horizon
+from openstack_dashboard.dashboards.moon import dashboard
+
+class Pdp(horizon.Panel):
+ name = _("PDP")
+ slug = "pdp"
+
+
+dashboard.Moon.register(Pdp)
diff --git a/moon_dashboard/moon/pdp/templates/pdp/index.html b/moon_dashboard/moon/pdp/templates/pdp/index.html
new file mode 100644
index 00000000..30ac5f93
--- /dev/null
+++ b/moon_dashboard/moon/pdp/templates/pdp/index.html
@@ -0,0 +1,16 @@
+{% extends 'base.html' %}
+{% load i18n %}
+{% block title %}{% trans "PDP" %}{% endblock %}
+
+{% block page_header %}
+ {% include "horizon/common/_page_header.html" with title=_("PDP") %}
+{% endblock page_header %}
+
+
+
+{% block main %}
+ <ng-include
+ src="'{{ STATIC_URL }}moon/pdp/pdp.html'">
+ </ng-include>
+{% endblock %}
+
diff --git a/moon_dashboard/moon/pdp/tests.py b/moon_dashboard/moon/pdp/tests.py
new file mode 100644
index 00000000..ec988636
--- /dev/null
+++ b/moon_dashboard/moon/pdp/tests.py
@@ -0,0 +1,19 @@
+# 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.
+
+from horizon.test import helpers as test
+
+
+class MypanelTests(test.TestCase):
+ # Unit tests for mypanel.
+ def test_me(self):
+ self.assertTrue(1 + 1 == 2)
diff --git a/moon_dashboard/moon/pdp/urls.py b/moon_dashboard/moon/pdp/urls.py
new file mode 100644
index 00000000..a66c8e0c
--- /dev/null
+++ b/moon_dashboard/moon/pdp/urls.py
@@ -0,0 +1,20 @@
+# 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.
+
+from django.conf.urls import url
+
+from openstack_dashboard.dashboards.moon.pdp import views
+
+
+urlpatterns = [
+ url(r'^$', views.IndexView.as_view(), name='index'),
+]
diff --git a/moon_dashboard/moon/pdp/views.py b/moon_dashboard/moon/pdp/views.py
new file mode 100644
index 00000000..8355a5d5
--- /dev/null
+++ b/moon_dashboard/moon/pdp/views.py
@@ -0,0 +1,22 @@
+# 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.
+
+from horizon import views
+
+
+class IndexView(views.APIView):
+ # A very simple class-based view...
+ template_name = 'moon/pdp/index.html'
+
+ def get_data(self, request, context, *args, **kwargs):
+ # Add data to the context here...
+ return context
diff --git a/moon_dashboard/moon/policy/__init__.py b/moon_dashboard/moon/policy/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/moon_dashboard/moon/policy/__init__.py
diff --git a/moon_dashboard/moon/policy/panel.py b/moon_dashboard/moon/policy/panel.py
new file mode 100644
index 00000000..875a2d76
--- /dev/null
+++ b/moon_dashboard/moon/policy/panel.py
@@ -0,0 +1,23 @@
+# 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.
+
+from django.utils.translation import ugettext_lazy as _
+
+import horizon
+from openstack_dashboard.dashboards.moon import dashboard
+
+class Policy(horizon.Panel):
+ name = _("Policies")
+ slug = "policy"
+
+
+dashboard.Moon.register(Policy)
diff --git a/moon_dashboard/moon/policy/templates/policy/index.html b/moon_dashboard/moon/policy/templates/policy/index.html
new file mode 100644
index 00000000..67cd9c3d
--- /dev/null
+++ b/moon_dashboard/moon/policy/templates/policy/index.html
@@ -0,0 +1,16 @@
+{% extends 'base.html' %}
+{% load i18n %}
+{% block title %}{% trans "Policies" %}{% endblock %}
+
+{% block page_header %}
+ {% include "horizon/common/_page_header.html" with title=_("Policies") %}
+{% endblock page_header %}
+
+
+
+{% block main %}
+ <ng-include
+ src="'{{ STATIC_URL }}moon/policy/policy.html'">
+ </ng-include>
+{% endblock %}
+
diff --git a/moon_dashboard/moon/policy/tests.py b/moon_dashboard/moon/policy/tests.py
new file mode 100644
index 00000000..ec988636
--- /dev/null
+++ b/moon_dashboard/moon/policy/tests.py
@@ -0,0 +1,19 @@
+# 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.
+
+from horizon.test import helpers as test
+
+
+class MypanelTests(test.TestCase):
+ # Unit tests for mypanel.
+ def test_me(self):
+ self.assertTrue(1 + 1 == 2)
diff --git a/moon_dashboard/moon/policy/urls.py b/moon_dashboard/moon/policy/urls.py
new file mode 100644
index 00000000..81bde0ca
--- /dev/null
+++ b/moon_dashboard/moon/policy/urls.py
@@ -0,0 +1,20 @@
+# 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.
+
+from django.conf.urls import url
+
+from openstack_dashboard.dashboards.moon.policy import views
+
+
+urlpatterns = [
+ url(r'^$', views.IndexView.as_view(), name='index'),
+]
diff --git a/moon_dashboard/moon/policy/views.py b/moon_dashboard/moon/policy/views.py
new file mode 100644
index 00000000..826c833b
--- /dev/null
+++ b/moon_dashboard/moon/policy/views.py
@@ -0,0 +1,22 @@
+# 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.
+
+from horizon import views
+
+
+class IndexView(views.APIView):
+ # A very simple class-based view...
+ template_name = 'moon/policy/index.html'
+
+ def get_data(self, request, context, *args, **kwargs):
+ # Add data to the context here...
+ return context
diff --git a/moon_dashboard/moon/static/moon/js/angular-resource.js b/moon_dashboard/moon/static/moon/js/angular-resource.js
new file mode 100644
index 00000000..e8bb3014
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/js/angular-resource.js
@@ -0,0 +1,863 @@
+/**
+ * @license AngularJS v1.5.8
+ * (c) 2010-2016 Google, Inc. http://angularjs.org
+ * License: MIT
+ */
+(function(window, angular) {'use strict';
+
+var $resourceMinErr = angular.$$minErr('$resource');
+
+// Helper functions and regex to lookup a dotted path on an object
+// stopping at undefined/null. The path must be composed of ASCII
+// identifiers (just like $parse)
+var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/;
+
+function isValidDottedPath(path) {
+ return (path != null && path !== '' && path !== 'hasOwnProperty' &&
+ MEMBER_NAME_REGEX.test('.' + path));
+}
+
+function lookupDottedPath(obj, path) {
+ if (!isValidDottedPath(path)) {
+ throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path);
+ }
+ var keys = path.split('.');
+ for (var i = 0, ii = keys.length; i < ii && angular.isDefined(obj); i++) {
+ var key = keys[i];
+ obj = (obj !== null) ? obj[key] : undefined;
+ }
+ return obj;
+}
+
+/**
+ * Create a shallow copy of an object and clear other fields from the destination
+ */
+function shallowClearAndCopy(src, dst) {
+ dst = dst || {};
+
+ angular.forEach(dst, function(value, key) {
+ delete dst[key];
+ });
+
+ for (var key in src) {
+ if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
+ dst[key] = src[key];
+ }
+ }
+
+ return dst;
+}
+
+/**
+ * @ngdoc module
+ * @name ngResource
+ * @description
+ *
+ * # ngResource
+ *
+ * The `ngResource` module provides interaction support with RESTful services
+ * via the $resource service.
+ *
+ *
+ * <div doc-module-components="ngResource"></div>
+ *
+ * See {@link ngResource.$resourceProvider} and {@link ngResource.$resource} for usage.
+ */
+
+/**
+ * @ngdoc provider
+ * @name $resourceProvider
+ *
+ * @description
+ *
+ * Use `$resourceProvider` to change the default behavior of the {@link ngResource.$resource}
+ * service.
+ *
+ * ## Dependencies
+ * Requires the {@link ngResource } module to be installed.
+ *
+ */
+
+/**
+ * @ngdoc service
+ * @name $resource
+ * @requires $http
+ * @requires ng.$log
+ * @requires $q
+ * @requires ng.$timeout
+ *
+ * @description
+ * A factory which creates a resource object that lets you interact with
+ * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
+ *
+ * The returned resource object has action methods which provide high-level behaviors without
+ * the need to interact with the low level {@link ng.$http $http} service.
+ *
+ * Requires the {@link ngResource `ngResource`} module to be installed.
+ *
+ * By default, trailing slashes will be stripped from the calculated URLs,
+ * which can pose problems with server backends that do not expect that
+ * behavior. This can be disabled by configuring the `$resourceProvider` like
+ * this:
+ *
+ * ```js
+ app.config(['$resourceProvider', function($resourceProvider) {
+ // Don't strip trailing slashes from calculated URLs
+ $resourceProvider.defaults.stripTrailingSlashes = false;
+ }]);
+ * ```
+ *
+ * @param {string} url A parameterized URL template with parameters prefixed by `:` as in
+ * `/user/:username`. If you are using a URL with a port number (e.g.
+ * `http://example.com:8080/api`), it will be respected.
+ *
+ * If you are using a url with a suffix, just add the suffix, like this:
+ * `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')`
+ * or even `$resource('http://example.com/resource/:resource_id.:format')`
+ * If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be
+ * collapsed down to a single `.`. If you need this sequence to appear and not collapse then you
+ * can escape it with `/\.`.
+ *
+ * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
+ * `actions` methods. If a parameter value is a function, it will be called every time
+ * a param value needs to be obtained for a request (unless the param was overridden). The function
+ * will be passed the current data value as an argument.
+ *
+ * Each key value in the parameter object is first bound to url template if present and then any
+ * excess keys are appended to the url search query after the `?`.
+ *
+ * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
+ * URL `/path/greet?salutation=Hello`.
+ *
+ * If the parameter value is prefixed with `@`, then the value for that parameter will be
+ * extracted from the corresponding property on the `data` object (provided when calling a
+ * "non-GET" action method).
+ * For example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of
+ * `someParam` will be `data.someProp`.
+ * Note that the parameter will be ignored, when calling a "GET" action method (i.e. an action
+ * method that does not accept a request body)
+ *
+ * @param {Object.<Object>=} actions Hash with declaration of custom actions that should extend
+ * the default set of resource actions. The declaration should be created in the format of {@link
+ * ng.$http#usage $http.config}:
+ *
+ * {action1: {method:?, params:?, isArray:?, headers:?, ...},
+ * action2: {method:?, params:?, isArray:?, headers:?, ...},
+ * ...}
+ *
+ * Where:
+ *
+ * - **`action`** – {string} – The name of action. This name becomes the name of the method on
+ * your resource object.
+ * - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`,
+ * `DELETE`, `JSONP`, etc).
+ * - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of
+ * the parameter value is a function, it will be called every time when a param value needs to
+ * be obtained for a request (unless the param was overridden). The function will be passed the
+ * current data value as an argument.
+ * - **`url`** – {string} – action specific `url` override. The url templating is supported just
+ * like for the resource-level urls.
+ * - **`isArray`** – {boolean=} – If true then the returned object for this action is an array,
+ * see `returns` section.
+ * - **`transformRequest`** –
+ * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
+ * transform function or an array of such functions. The transform function takes the http
+ * request body and headers and returns its transformed (typically serialized) version.
+ * By default, transformRequest will contain one function that checks if the request data is
+ * an object and serializes to using `angular.toJson`. To prevent this behavior, set
+ * `transformRequest` to an empty array: `transformRequest: []`
+ * - **`transformResponse`** –
+ * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
+ * transform function or an array of such functions. The transform function takes the http
+ * response body and headers and returns its transformed (typically deserialized) version.
+ * By default, transformResponse will contain one function that checks if the response looks
+ * like a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior,
+ * set `transformResponse` to an empty array: `transformResponse: []`
+ * - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
+ * GET request, otherwise if a cache instance built with
+ * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
+ * caching.
+ * - **`timeout`** – `{number}` – timeout in milliseconds.<br />
+ * **Note:** In contrast to {@link ng.$http#usage $http.config}, {@link ng.$q promises} are
+ * **not** supported in $resource, because the same value would be used for multiple requests.
+ * If you are looking for a way to cancel requests, you should use the `cancellable` option.
+ * - **`cancellable`** – `{boolean}` – if set to true, the request made by a "non-instance" call
+ * will be cancelled (if not already completed) by calling `$cancelRequest()` on the call's
+ * return value. Calling `$cancelRequest()` for a non-cancellable or an already
+ * completed/cancelled request will have no effect.<br />
+ * - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the
+ * XHR object. See
+ * [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5)
+ * for more information.
+ * - **`responseType`** - `{string}` - see
+ * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
+ * - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods -
+ * `response` and `responseError`. Both `response` and `responseError` interceptors get called
+ * with `http response` object. See {@link ng.$http $http interceptors}.
+ *
+ * @param {Object} options Hash with custom settings that should extend the
+ * default `$resourceProvider` behavior. The supported options are:
+ *
+ * - **`stripTrailingSlashes`** – {boolean} – If true then the trailing
+ * slashes from any calculated URL will be stripped. (Defaults to true.)
+ * - **`cancellable`** – {boolean} – If true, the request made by a "non-instance" call will be
+ * cancelled (if not already completed) by calling `$cancelRequest()` on the call's return value.
+ * This can be overwritten per action. (Defaults to false.)
+ *
+ * @returns {Object} A resource "class" object with methods for the default set of resource actions
+ * optionally extended with custom `actions`. The default set contains these actions:
+ * ```js
+ * { 'get': {method:'GET'},
+ * 'save': {method:'POST'},
+ * 'query': {method:'GET', isArray:true},
+ * 'remove': {method:'DELETE'},
+ * 'delete': {method:'DELETE'} };
+ * ```
+ *
+ * Calling these methods invoke an {@link ng.$http} with the specified http method,
+ * destination and parameters. When the data is returned from the server then the object is an
+ * instance of the resource class. The actions `save`, `remove` and `delete` are available on it
+ * as methods with the `$` prefix. This allows you to easily perform CRUD operations (create,
+ * read, update, delete) on server-side data like this:
+ * ```js
+ * var User = $resource('/user/:userId', {userId:'@id'});
+ * var user = User.get({userId:123}, function() {
+ * user.abc = true;
+ * user.$save();
+ * });
+ * ```
+ *
+ * It is important to realize that invoking a $resource object method immediately returns an
+ * empty reference (object or array depending on `isArray`). Once the data is returned from the
+ * server the existing reference is populated with the actual data. This is a useful trick since
+ * usually the resource is assigned to a model which is then rendered by the view. Having an empty
+ * object results in no rendering, once the data arrives from the server then the object is
+ * populated with the data and the view automatically re-renders itself showing the new data. This
+ * means that in most cases one never has to write a callback function for the action methods.
+ *
+ * The action methods on the class object or instance object can be invoked with the following
+ * parameters:
+ *
+ * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])`
+ * - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])`
+ * - non-GET instance actions: `instance.$action([parameters], [success], [error])`
+ *
+ *
+ * Success callback is called with (value, responseHeaders) arguments, where the value is
+ * the populated resource instance or collection object. The error callback is called
+ * with (httpResponse) argument.
+ *
+ * Class actions return empty instance (with additional properties below).
+ * Instance actions return promise of the action.
+ *
+ * The Resource instances and collections have these additional properties:
+ *
+ * - `$promise`: the {@link ng.$q promise} of the original server interaction that created this
+ * instance or collection.
+ *
+ * On success, the promise is resolved with the same resource instance or collection object,
+ * updated with data from server. This makes it easy to use in
+ * {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view
+ * rendering until the resource(s) are loaded.
+ *
+ * On failure, the promise is rejected with the {@link ng.$http http response} object, without
+ * the `resource` property.
+ *
+ * If an interceptor object was provided, the promise will instead be resolved with the value
+ * returned by the interceptor.
+ *
+ * - `$resolved`: `true` after first server interaction is completed (either with success or
+ * rejection), `false` before that. Knowing if the Resource has been resolved is useful in
+ * data-binding.
+ *
+ * The Resource instances and collections have these additional methods:
+ *
+ * - `$cancelRequest`: If there is a cancellable, pending request related to the instance or
+ * collection, calling this method will abort the request.
+ *
+ * The Resource instances have these additional methods:
+ *
+ * - `toJSON`: It returns a simple object without any of the extra properties added as part of
+ * the Resource API. This object can be serialized through {@link angular.toJson} safely
+ * without attaching Angular-specific fields. Notice that `JSON.stringify` (and
+ * `angular.toJson`) automatically use this method when serializing a Resource instance
+ * (see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior)).
+ *
+ * @example
+ *
+ * # Credit card resource
+ *
+ * ```js
+ // Define CreditCard class
+ var CreditCard = $resource('/user/:userId/card/:cardId',
+ {userId:123, cardId:'@id'}, {
+ charge: {method:'POST', params:{charge:true}}
+ });
+
+ // We can retrieve a collection from the server
+ var cards = CreditCard.query(function() {
+ // GET: /user/123/card
+ // server returns: [ {id:456, number:'1234', name:'Smith'} ];
+
+ var card = cards[0];
+ // each item is an instance of CreditCard
+ expect(card instanceof CreditCard).toEqual(true);
+ card.name = "J. Smith";
+ // non GET methods are mapped onto the instances
+ card.$save();
+ // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
+ // server returns: {id:456, number:'1234', name: 'J. Smith'};
+
+ // our custom method is mapped as well.
+ card.$charge({amount:9.99});
+ // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
+ });
+
+ // we can create an instance as well
+ var newCard = new CreditCard({number:'0123'});
+ newCard.name = "Mike Smith";
+ newCard.$save();
+ // POST: /user/123/card {number:'0123', name:'Mike Smith'}
+ // server returns: {id:789, number:'0123', name: 'Mike Smith'};
+ expect(newCard.id).toEqual(789);
+ * ```
+ *
+ * The object returned from this function execution is a resource "class" which has "static" method
+ * for each action in the definition.
+ *
+ * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and
+ * `headers`.
+ *
+ * @example
+ *
+ * # User resource
+ *
+ * When the data is returned from the server then the object is an instance of the resource type and
+ * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
+ * operations (create, read, update, delete) on server-side data.
+
+ ```js
+ var User = $resource('/user/:userId', {userId:'@id'});
+ User.get({userId:123}, function(user) {
+ user.abc = true;
+ user.$save();
+ });
+ ```
+ *
+ * It's worth noting that the success callback for `get`, `query` and other methods gets passed
+ * in the response that came from the server as well as $http header getter function, so one
+ * could rewrite the above example and get access to http headers as:
+ *
+ ```js
+ var User = $resource('/user/:userId', {userId:'@id'});
+ User.get({userId:123}, function(user, getResponseHeaders){
+ user.abc = true;
+ user.$save(function(user, putResponseHeaders) {
+ //user => saved user object
+ //putResponseHeaders => $http header getter
+ });
+ });
+ ```
+ *
+ * You can also access the raw `$http` promise via the `$promise` property on the object returned
+ *
+ ```
+ var User = $resource('/user/:userId', {userId:'@id'});
+ User.get({userId:123})
+ .$promise.then(function(user) {
+ $scope.user = user;
+ });
+ ```
+ *
+ * @example
+ *
+ * # Creating a custom 'PUT' request
+ *
+ * In this example we create a custom method on our resource to make a PUT request
+ * ```js
+ * var app = angular.module('app', ['ngResource', 'ngRoute']);
+ *
+ * // Some APIs expect a PUT request in the format URL/object/ID
+ * // Here we are creating an 'update' method
+ * app.factory('Notes', ['$resource', function($resource) {
+ * return $resource('/notes/:id', null,
+ * {
+ * 'update': { method:'PUT' }
+ * });
+ * }]);
+ *
+ * // In our controller we get the ID from the URL using ngRoute and $routeParams
+ * // We pass in $routeParams and our Notes factory along with $scope
+ * app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
+ function($scope, $routeParams, Notes) {
+ * // First get a note object from the factory
+ * var note = Notes.get({ id:$routeParams.id });
+ * $id = note.id;
+ *
+ * // Now call update passing in the ID first then the object you are updating
+ * Notes.update({ id:$id }, note);
+ *
+ * // This will PUT /notes/ID with the note object in the request payload
+ * }]);
+ * ```
+ *
+ * @example
+ *
+ * # Cancelling requests
+ *
+ * If an action's configuration specifies that it is cancellable, you can cancel the request related
+ * to an instance or collection (as long as it is a result of a "non-instance" call):
+ *
+ ```js
+ // ...defining the `Hotel` resource...
+ var Hotel = $resource('/api/hotel/:id', {id: '@id'}, {
+ // Let's make the `query()` method cancellable
+ query: {method: 'get', isArray: true, cancellable: true}
+ });
+
+ // ...somewhere in the PlanVacationController...
+ ...
+ this.onDestinationChanged = function onDestinationChanged(destination) {
+ // We don't care about any pending request for hotels
+ // in a different destination any more
+ this.availableHotels.$cancelRequest();
+
+ // Let's query for hotels in '<destination>'
+ // (calls: /api/hotel?location=<destination>)
+ this.availableHotels = Hotel.query({location: destination});
+ };
+ ```
+ *
+ */
+angular.module('ngResource', ['ng']).
+ provider('$resource', function() {
+ var PROTOCOL_AND_DOMAIN_REGEX = /^https?:\/\/[^\/]*/;
+ var provider = this;
+
+ /**
+ * @ngdoc property
+ * @name $resourceProvider#defaults
+ * @description
+ * Object containing default options used when creating `$resource` instances.
+ *
+ * The default values satisfy a wide range of usecases, but you may choose to overwrite any of
+ * them to further customize your instances. The available properties are:
+ *
+ * - **stripTrailingSlashes** – `{boolean}` – If true, then the trailing slashes from any
+ * calculated URL will be stripped.<br />
+ * (Defaults to true.)
+ * - **cancellable** – `{boolean}` – If true, the request made by a "non-instance" call will be
+ * cancelled (if not already completed) by calling `$cancelRequest()` on the call's return
+ * value. For more details, see {@link ngResource.$resource}. This can be overwritten per
+ * resource class or action.<br />
+ * (Defaults to false.)
+ * - **actions** - `{Object.<Object>}` - A hash with default actions declarations. Actions are
+ * high-level methods corresponding to RESTful actions/methods on resources. An action may
+ * specify what HTTP method to use, what URL to hit, if the return value will be a single
+ * object or a collection (array) of objects etc. For more details, see
+ * {@link ngResource.$resource}. The actions can also be enhanced or overwritten per resource
+ * class.<br />
+ * The default actions are:
+ * ```js
+ * {
+ * get: {method: 'GET'},
+ * save: {method: 'POST'},
+ * query: {method: 'GET', isArray: true},
+ * remove: {method: 'DELETE'},
+ * delete: {method: 'DELETE'}
+ * }
+ * ```
+ *
+ * #### Example
+ *
+ * For example, you can specify a new `update` action that uses the `PUT` HTTP verb:
+ *
+ * ```js
+ * angular.
+ * module('myApp').
+ * config(['resourceProvider', function ($resourceProvider) {
+ * $resourceProvider.defaults.actions.update = {
+ * method: 'PUT'
+ * };
+ * });
+ * ```
+ *
+ * Or you can even overwrite the whole `actions` list and specify your own:
+ *
+ * ```js
+ * angular.
+ * module('myApp').
+ * config(['resourceProvider', function ($resourceProvider) {
+ * $resourceProvider.defaults.actions = {
+ * create: {method: 'POST'}
+ * get: {method: 'GET'},
+ * getAll: {method: 'GET', isArray:true},
+ * update: {method: 'PUT'},
+ * delete: {method: 'DELETE'}
+ * };
+ * });
+ * ```
+ *
+ */
+ this.defaults = {
+ // Strip slashes by default
+ stripTrailingSlashes: true,
+
+ // Make non-instance requests cancellable (via `$cancelRequest()`)
+ cancellable: false,
+
+ // Default actions configuration
+ actions: {
+ 'get': {method: 'GET'},
+ 'save': {method: 'POST'},
+ 'query': {method: 'GET', isArray: true},
+ 'remove': {method: 'DELETE'},
+ 'delete': {method: 'DELETE'}
+ }
+ };
+
+ this.$get = ['$http', '$log', '$q', '$timeout', function($http, $log, $q, $timeout) {
+
+ var noop = angular.noop,
+ forEach = angular.forEach,
+ extend = angular.extend,
+ copy = angular.copy,
+ isFunction = angular.isFunction;
+
+ /**
+ * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
+ * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set
+ * (pchar) allowed in path segments:
+ * segment = *pchar
+ * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
+ * pct-encoded = "%" HEXDIG HEXDIG
+ * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
+ * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
+ * / "*" / "+" / "," / ";" / "="
+ */
+ function encodeUriSegment(val) {
+ return encodeUriQuery(val, true).
+ replace(/%26/gi, '&').
+ replace(/%3D/gi, '=').
+ replace(/%2B/gi, '+');
+ }
+
+
+ /**
+ * This method is intended for encoding *key* or *value* parts of query component. We need a
+ * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't
+ * have to be encoded per http://tools.ietf.org/html/rfc3986:
+ * query = *( pchar / "/" / "?" )
+ * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
+ * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
+ * pct-encoded = "%" HEXDIG HEXDIG
+ * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
+ * / "*" / "+" / "," / ";" / "="
+ */
+ function encodeUriQuery(val, pctEncodeSpaces) {
+ return encodeURIComponent(val).
+ replace(/%40/gi, '@').
+ replace(/%3A/gi, ':').
+ replace(/%24/g, '$').
+ replace(/%2C/gi, ',').
+ replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
+ }
+
+ function Route(template, defaults) {
+ this.template = template;
+ this.defaults = extend({}, provider.defaults, defaults);
+ this.urlParams = {};
+ }
+
+ Route.prototype = {
+ setUrlParams: function(config, params, actionUrl) {
+ var self = this,
+ url = actionUrl || self.template,
+ val,
+ encodedVal,
+ protocolAndDomain = '';
+
+ var urlParams = self.urlParams = {};
+ forEach(url.split(/\W/), function(param) {
+ if (param === 'hasOwnProperty') {
+ throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name.");
+ }
+ if (!(new RegExp("^\\d+$").test(param)) && param &&
+ (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) {
+ urlParams[param] = {
+ isQueryParamValue: (new RegExp("\\?.*=:" + param + "(?:\\W|$)")).test(url)
+ };
+ }
+ });
+ url = url.replace(/\\:/g, ':');
+ url = url.replace(PROTOCOL_AND_DOMAIN_REGEX, function(match) {
+ protocolAndDomain = match;
+ return '';
+ });
+
+ params = params || {};
+ forEach(self.urlParams, function(paramInfo, urlParam) {
+ val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
+ if (angular.isDefined(val) && val !== null) {
+ if (paramInfo.isQueryParamValue) {
+ encodedVal = encodeUriQuery(val, true);
+ } else {
+ encodedVal = encodeUriSegment(val);
+ }
+ url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) {
+ return encodedVal + p1;
+ });
+ } else {
+ url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match,
+ leadingSlashes, tail) {
+ if (tail.charAt(0) == '/') {
+ return tail;
+ } else {
+ return leadingSlashes + tail;
+ }
+ });
+ }
+ });
+
+ // strip trailing slashes and set the url (unless this behavior is specifically disabled)
+ if (self.defaults.stripTrailingSlashes) {
+ url = url.replace(/\/+$/, '') || '/';
+ }
+
+ // then replace collapse `/.` if found in the last URL path segment before the query
+ // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x`
+ url = url.replace(/\/\.(?=\w+($|\?))/, '.');
+ // replace escaped `/\.` with `/.`
+ config.url = protocolAndDomain + url.replace(/\/\\\./, '/.');
+
+
+ // set params - delegate param encoding to $http
+ forEach(params, function(value, key) {
+ if (!self.urlParams[key]) {
+ config.params = config.params || {};
+ config.params[key] = value;
+ }
+ });
+ }
+ };
+
+
+ function resourceFactory(url, paramDefaults, actions, options) {
+ var route = new Route(url, options);
+
+ actions = extend({}, provider.defaults.actions, actions);
+
+ function extractParams(data, actionParams) {
+ var ids = {};
+ actionParams = extend({}, paramDefaults, actionParams);
+ forEach(actionParams, function(value, key) {
+ if (isFunction(value)) { value = value(data); }
+ ids[key] = value && value.charAt && value.charAt(0) == '@' ?
+ lookupDottedPath(data, value.substr(1)) : value;
+ });
+ return ids;
+ }
+
+ function defaultResponseInterceptor(response) {
+ return response.resource;
+ }
+
+ function Resource(value) {
+ shallowClearAndCopy(value || {}, this);
+ }
+
+ Resource.prototype.toJSON = function() {
+ var data = extend({}, this);
+ delete data.$promise;
+ delete data.$resolved;
+ return data;
+ };
+
+ forEach(actions, function(action, name) {
+ var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);
+ var numericTimeout = action.timeout;
+ var cancellable = angular.isDefined(action.cancellable) ? action.cancellable :
+ (options && angular.isDefined(options.cancellable)) ? options.cancellable :
+ provider.defaults.cancellable;
+
+ if (numericTimeout && !angular.isNumber(numericTimeout)) {
+ $log.debug('ngResource:\n' +
+ ' Only numeric values are allowed as `timeout`.\n' +
+ ' Promises are not supported in $resource, because the same value would ' +
+ 'be used for multiple requests. If you are looking for a way to cancel ' +
+ 'requests, you should use the `cancellable` option.');
+ delete action.timeout;
+ numericTimeout = null;
+ }
+
+ Resource[name] = function(a1, a2, a3, a4) {
+ var params = {}, data, success, error;
+
+ /* jshint -W086 */ /* (purposefully fall through case statements) */
+ switch (arguments.length) {
+ case 4:
+ error = a4;
+ success = a3;
+ //fallthrough
+ case 3:
+ case 2:
+ if (isFunction(a2)) {
+ if (isFunction(a1)) {
+ success = a1;
+ error = a2;
+ break;
+ }
+
+ success = a2;
+ error = a3;
+ //fallthrough
+ } else {
+ params = a1;
+ data = a2;
+ success = a3;
+ break;
+ }
+ case 1:
+ if (isFunction(a1)) success = a1;
+ else if (hasBody) data = a1;
+ else params = a1;
+ break;
+ case 0: break;
+ default:
+ throw $resourceMinErr('badargs',
+ "Expected up to 4 arguments [params, data, success, error], got {0} arguments",
+ arguments.length);
+ }
+ /* jshint +W086 */ /* (purposefully fall through case statements) */
+
+ var isInstanceCall = this instanceof Resource;
+ var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data));
+ var httpConfig = {};
+ var responseInterceptor = action.interceptor && action.interceptor.response ||
+ defaultResponseInterceptor;
+ var responseErrorInterceptor = action.interceptor && action.interceptor.responseError ||
+ undefined;
+ var timeoutDeferred;
+ var numericTimeoutPromise;
+
+ forEach(action, function(value, key) {
+ switch (key) {
+ default:
+ httpConfig[key] = copy(value);
+ break;
+ case 'params':
+ case 'isArray':
+ case 'interceptor':
+ case 'cancellable':
+ break;
+ }
+ });
+
+ if (!isInstanceCall && cancellable) {
+ timeoutDeferred = $q.defer();
+ httpConfig.timeout = timeoutDeferred.promise;
+
+ if (numericTimeout) {
+ numericTimeoutPromise = $timeout(timeoutDeferred.resolve, numericTimeout);
+ }
+ }
+
+ if (hasBody) httpConfig.data = data;
+ route.setUrlParams(httpConfig,
+ extend({}, extractParams(data, action.params || {}), params),
+ action.url);
+
+ var promise = $http(httpConfig).then(function(response) {
+ var data = response.data;
+
+ if (data) {
+ // Need to convert action.isArray to boolean in case it is undefined
+ // jshint -W018
+ if (angular.isArray(data) !== (!!action.isArray)) {
+ throw $resourceMinErr('badcfg',
+ 'Error in resource configuration for action `{0}`. Expected response to ' +
+ 'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object',
+ angular.isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url);
+ }
+ // jshint +W018
+ if (action.isArray) {
+ value.length = 0;
+ forEach(data, function(item) {
+ if (typeof item === "object") {
+ value.push(new Resource(item));
+ } else {
+ // Valid JSON values may be string literals, and these should not be converted
+ // into objects. These items will not have access to the Resource prototype
+ // methods, but unfortunately there
+ value.push(item);
+ }
+ });
+ } else {
+ var promise = value.$promise; // Save the promise
+ shallowClearAndCopy(data, value);
+ value.$promise = promise; // Restore the promise
+ }
+ }
+ response.resource = value;
+
+ return response;
+ }, function(response) {
+ (error || noop)(response);
+ return $q.reject(response);
+ });
+
+ promise['finally'](function() {
+ value.$resolved = true;
+ if (!isInstanceCall && cancellable) {
+ value.$cancelRequest = angular.noop;
+ $timeout.cancel(numericTimeoutPromise);
+ timeoutDeferred = numericTimeoutPromise = httpConfig.timeout = null;
+ }
+ });
+
+ promise = promise.then(
+ function(response) {
+ var value = responseInterceptor(response);
+ (success || noop)(value, response.headers);
+ return value;
+ },
+ responseErrorInterceptor);
+
+ if (!isInstanceCall) {
+ // we are creating instance / collection
+ // - set the initial promise
+ // - return the instance / collection
+ value.$promise = promise;
+ value.$resolved = false;
+ if (cancellable) value.$cancelRequest = timeoutDeferred.resolve;
+
+ return value;
+ }
+
+ // instance call
+ return promise;
+ };
+
+
+ Resource.prototype['$' + name] = function(params, success, error) {
+ if (isFunction(params)) {
+ error = success; success = params; params = {};
+ }
+ var result = Resource[name].call(this, params, this, success, error);
+ return result.$promise || result;
+ };
+ });
+
+ Resource.bind = function(additionalParamDefaults) {
+ return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);
+ };
+
+ return Resource;
+ }
+
+ return resourceFactory;
+ }];
+ });
+
+
+})(window, window.angular);
diff --git a/moon_dashboard/moon/static/moon/js/import.service.js b/moon_dashboard/moon/static/moon/js/import.service.js
new file mode 100755
index 00000000..d55c8a19
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/js/import.service.js
@@ -0,0 +1,27 @@
+(function () {
+
+ 'use strict';
+
+ angular
+ .module('moon')
+ .factory('moon.import.service', importService);
+
+ importService.$inject = ['moon.util.service', '$resource', 'moon.URI'];
+
+ function importService(util, $resource, URI) {
+ var host = URI.API;
+ var importResource = $resource(host + '/import/', {}, {
+ create: { method: 'POST' },
+ });
+
+ return {
+ importData: function importData(data) {
+ return importResource.create(null, data).$promise.then(success, util.displayErrorFunction('Unable to import data'));
+
+ function success(data) {
+ util.displaySuccess('Data imported');
+ }
+ }
+ }
+ }
+})(); \ No newline at end of file
diff --git a/moon_dashboard/moon/static/moon/js/moon.module.js b/moon_dashboard/moon/static/moon/js/moon.module.js
new file mode 100755
index 00000000..ed56ec2a
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/js/moon.module.js
@@ -0,0 +1,29 @@
+/**
+# Copyright 2015 Orange
+#
+# 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.
+ */
+
+(function () {
+
+ 'use strict';
+
+ var moon = angular
+
+ .module('moon', [
+ 'ngResource',
+ ]).constant('moon.URI', {
+ API: 'http://{{MANAGER_HOST}}:{{MANAGER_PORT}}',
+ })
+
+})();
diff --git a/moon_dashboard/moon/static/moon/js/util.service.js b/moon_dashboard/moon/static/moon/js/util.service.js
new file mode 100755
index 00000000..18ae901d
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/js/util.service.js
@@ -0,0 +1,136 @@
+(function () {
+
+ 'use strict';
+
+ angular
+ .module('moon')
+ .factory('moon.util.service', utilService);
+
+ utilService.$inject = ['horizon.framework.widgets.toast.service'];
+
+ function utilService(toast) {
+
+
+ return {
+ mapToArray: function mapToArray(map, action) {
+ var result = []
+ for (var key in map) {
+ if (map.hasOwnProperty(key)) {
+ var item = map[key];
+ item.id = key;
+ if (action != null) {
+ action(item);
+ }
+ result.push(item);
+ }
+ }
+ return result;
+ },
+
+ mapIdToItem: function mapIdToItem(array, map) {
+ if (array) {
+ for (var index = 0; index < array.length; index++) {
+ var id = array[index];
+ array[index] = map[id];
+ }
+ }
+ },
+
+ mapItemToId: function mapItemToId(array) {
+ if (array) {
+ for (var index = 0; index < array.length; index++) {
+ var item = array[index];
+ array[index] = item.id;
+ }
+ }
+ },
+
+ addToMap: function addToMap(array, map) {
+ if (array) {
+ for (var index = 0; index < array.length; index++) {
+ var item = array[index];
+ map[item.id] = item;
+ }
+ }
+ },
+
+ updateObject: function updateObject(object, newObject) {
+ for (var key in newObject) {
+ if (newObject.hasOwnProperty(key)) {
+ object[key] = newObject[key];
+ }
+ }
+ },
+
+ cleanObject: function cleanObject(object) {
+ for (var key in object) {
+ if (object.hasOwnProperty(key)) {
+ delete object[key];
+ }
+ }
+ },
+
+ pushAll: function pushAll(array, arrayToPush) {
+ Array.prototype.push.apply(array, arrayToPush);
+ },
+
+ indexOf: function indexOf(array, property, value) {
+ for (var i = 0; i < array.length; i += 1) {
+ if (array[i][property] === value) {
+ return i;
+ }
+ }
+ return -1;
+ },
+
+ createInternal: function createInternal(data, array, map, action) {
+ var added = this.mapToArray(data, action)
+ this.addToMap(added, map);
+ this.pushAll(array, added);
+ return added;
+ },
+
+ updateInternal: function updateInternal(data, map, action) {
+ var updated = this.mapToArray(data, action)
+ var result = []
+ for (var index = 0; index < updated.length; index++) {
+ var item = updated[index];
+ this.updateObject(map[item.id], item)
+ result.push(map[item.id])
+ }
+ return result;
+ },
+
+ removeInternal: function removeInternal(id, array, map) {
+ var old = map[id];
+ delete map[old.id];
+ array.splice(array.indexOf(old), 1);
+ return old;
+ },
+
+ arrayToTitleMap: function arrayToTitleMap(array) {
+ return array.map(function (item) {
+ return { value: item.id, name: item.name }
+ }).sort(function (itemA, itemB) {
+ return itemA.name.localeCompare(itemB.name);
+ })
+ },
+
+ displayErrorFunction: function displayErrorFunction(message) {
+ return function() {
+ toast.add('error', gettext(message));
+ }
+ },
+
+ displaySuccess: function displaySuccess(message) {
+ toast.add('success', gettext(message));
+ },
+
+ displayError: function displayError(message) {
+ toast.add('error', gettext(message));
+ },
+
+ }
+
+ }
+})(); \ No newline at end of file
diff --git a/moon_dashboard/moon/static/moon/js/util.service.spec.js b/moon_dashboard/moon/static/moon/js/util.service.spec.js
new file mode 100755
index 00000000..d8e3ed31
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/js/util.service.spec.js
@@ -0,0 +1,86 @@
+(function () {
+ 'use strict';
+
+ describe('moon.util.service', function () {
+ var service;
+
+ beforeEach(module('horizon.app.core'));
+ beforeEach(module('horizon.framework'));
+ beforeEach(module('moon'));
+
+ beforeEach(inject(function ($injector) {
+ service = $injector.get('moon.util.service');
+ }));
+
+ it('should push all', function () {
+ var a1 = [0, 1, 2];
+ var a2 = [3, 4];
+ service.pushAll(a1, a2)
+
+ expect(a1.length).toBe(5);
+ expect(a1).toEqual([0, 1, 2, 3, 4]);
+ });
+
+ it('should index of', function () {
+ var a = [{ name: 'n0' }, { name: 'n1' }, { name: 'n2' }];
+ var result = service.indexOf(a, 'name', 'n1');
+
+ expect(result).toBe(1);
+ });
+
+ it('should map to array', function () {
+ var map = { "a": { name: "a" }, "b": { name: "b" } };
+ var result = service.mapToArray(map);
+
+ expect(result.length).toBe(2);
+ });
+
+ it('should map ID to item', function () {
+ var map = { "a": { name: "a" }, "b": { name: "b" } };
+ var array = ["a", "b"];
+ service.mapIdToItem(array, map);
+
+ expect(array.length).toBe(2);
+ expect(array[0].name).toBe("a");
+ expect(array[1].name).toBe("b");
+ });
+
+ it('should map item to ID', function () {
+ var array = [{ id: "a" }, { id: "b" }];
+ service.mapItemToId(array);
+
+ expect(array.length).toBe(2);
+ expect(array[0]).toBe("a");
+ expect(array[1]).toBe("b");
+ });
+
+ it('should add to map', function () {
+ var map = { "a": { name: "a" }, "b": { name: "b" } };
+ var array = [{ id: "c" }];
+ service.addToMap(array, map);
+
+ expect(map.c).toEqual({ id: "c" });
+ });
+
+ it('should update object', function () {
+ var object = { a: 1, b: "test" };
+ var update = { a: 2, c: "test2" };
+ service.updateObject(object, update);
+
+ expect(object.a).toBe(2);
+ expect(object.b).toBe("test");
+ expect(object.c).toBe("test2");
+ });
+
+ it('should clean object', function () {
+ var object = { a: 1, b: "test" };
+ service.cleanObject(object);
+
+ expect(object.a).not.toBeDefined();
+ expect(object.b).not.toBeDefined();
+ expect(object).toEqual({});
+ });
+ });
+
+
+})(); \ No newline at end of file
diff --git a/moon_dashboard/moon/static/moon/model/model.controller.js b/moon_dashboard/moon/static/moon/model/model.controller.js
new file mode 100644
index 00000000..d6a7503b
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/model/model.controller.js
@@ -0,0 +1,244 @@
+(function () {
+ 'use strict';
+
+ angular
+ .module('moon')
+ .directive('onReadFile', directive)
+ .controller('moon.model.controller', controller);
+
+ controller.$inject = ['moon.util.service', 'moon.model.service', 'moon.import.service', 'horizon.framework.widgets.form.ModalFormService'];
+
+ directive.$inject = ['$parse'];
+
+ function directive($parse) {
+ return {
+ restrict: 'A',
+ scope: false,
+ link: function (scope, element, attrs) {
+ element.bind('change', function (e) {
+
+ var onFileReadFn = $parse(attrs.onReadFile);
+ var reader = new FileReader();
+
+ reader.onload = function () {
+ var fileContents = reader.result;
+ scope.$apply(function () {
+ onFileReadFn(scope, {
+ 'contents': fileContents
+ });
+ });
+ };
+ reader.readAsText(element[0].files[0]);
+ });
+ }
+ };
+ }
+
+ var categoryMap = {
+ 'subject': {
+ addTitle: 'Add Subject Category',
+ removeTitleFromMetaRule: 'Are you sure to remove from meta rule this Subject Category?',
+ removeTitle: 'Are you sure to remove this Subject Category?',
+ listName: 'subject_categories',
+ serviceListName: 'subjectCategories'
+ },
+ 'object': {
+ addTitle: 'Add Object Category',
+ removeTitleFromMetaRule: 'Are you sure to remove from meta rule this Object Category?',
+ removeTitle: 'Are you sure to remove this Object Category?',
+ listName: 'object_categories',
+ serviceListName: 'objectCategories'
+ },
+ 'action': {
+ addTitle: 'Add Action Category',
+ removeTitleFromMetaRule: 'Are you sure to remove from meta rule this Action Category?',
+ removeTitle: 'Are you sure to remove this Action Category?',
+ listName: 'action_categories',
+ serviceListName: 'actionCategories'
+ },
+ }
+
+ function controller(util, modelService, importService, ModalFormService) {
+ var self = this;
+ self.model = modelService;
+ self.showOrphan = false;
+ modelService.initialize();
+
+ self.importData = function importData(text) {
+ importService.importData(JSON.parse(text)).then(function () {
+ modelService.initialize();
+ })
+ }
+
+ self.createModel = function createModel() {
+ var schema = {
+ type: "object",
+ properties: {
+ name: { type: "string", minLength: 2, title: gettext("Name") },
+ description: { type: "string", minLength: 2, title: gettext("Description") }
+ }
+ };
+ var model = { name: '', description: '' };
+ var config = {
+ title: gettext('Create Model'),
+ schema: schema,
+ form: ['name', { key: 'description', type: 'textarea' }],
+ model: model
+ };
+ ModalFormService.open(config).then(submit);
+
+ function submit(form) {
+ modelService.createModel(form.model);
+ }
+ }
+
+ self.updateModel = function updateModel(model) {
+ var schema = {
+ type: "object",
+ properties: {
+ name: { type: "string", minLength: 2, title: gettext("Name") },
+ description: { type: "string", minLength: 2, title: gettext("Description") }
+ }
+ };
+ var config = {
+ title: gettext('Update Model'),
+ schema: schema,
+ form: ['name', { key: 'description', type: 'textarea' }],
+ model: angular.copy(model)
+ };
+ ModalFormService.open(config).then(submit);
+
+ function submit(form) {
+ modelService.updateModel(form.model);
+ }
+ }
+
+ self.removeModel = function removeModel(model) {
+ if (confirm(gettext('Are you sure to delete this Model?')))
+ modelService.removeModel(model);
+ }
+
+ self.addMetaRule = function addMetaRule(model) {
+ var schema = {
+ type: "object",
+ properties: {
+ name: { type: "string", minLength: 2, title: gettext("Name") },
+ description: { type: "string", minLength: 2, title: gettext("Description") },
+ id: { type: "string", title: gettext("Select a Meta Rule:") }
+ }
+ };
+ var metaRule = { name: '', description: '' };
+ var titleMap = util.arrayToTitleMap(modelService.metaRules)
+ var config = {
+ title: gettext('Add Meta Rule'),
+ schema: schema,
+ form: [{ key: 'id', type: 'select', titleMap: titleMap }, { type: 'help', helpvalue: gettext("Or create a new one:") }, 'name', { key: 'description', type: 'textarea' }],
+ model: metaRule
+ };
+ ModalFormService.open(config).then(submit);
+
+ function submit(form) {
+ function addMetaRuleToModel(metaRule) {
+ var modelCopy = angular.copy(model);
+ modelCopy.meta_rules.push(metaRule);
+ modelService.updateModel(modelCopy);
+ }
+
+ if (form.model.name) {
+ modelService.createMetaRule(form.model).then(addMetaRuleToModel)
+ } else if (form.model.id) {
+ addMetaRuleToModel(modelService.getMetaRule(form.model.id));
+ }
+ }
+ }
+
+ self.updateMetaRule = function updateMetaRule(metaRule) {
+ var schema = {
+ type: "object",
+ properties: {
+ name: { type: "string", minLength: 2, title: gettext("Name") },
+ description: { type: "string", minLength: 2, title: gettext("Description") }
+ }
+ };
+ var metaRuleCopy = angular.copy(metaRule);
+ var config = {
+ title: gettext('Update Meta Rule'),
+ schema: schema,
+ form: ['name', { key: 'description', type: 'textarea' }],
+ model: metaRuleCopy
+ };
+ ModalFormService.open(config).then(submit);
+
+ function submit(form) {
+ modelService.updateMetaRule(form.model);
+ }
+ }
+
+ self.removeMetaRuleFromModel = function removeMetaRuleFromModel(model, metaRule) {
+ if (confirm(gettext('Are you sure to remove this Meta Rule from model?'))) {
+ var modelCopy = angular.copy(model);
+ modelCopy.meta_rules.splice(model.meta_rules.indexOf(metaRule), 1);
+ modelService.updateModel(modelCopy);
+ }
+ }
+
+ self.removeMetaRule = function removeMetaRule(metaRule) {
+ if (confirm(gettext('Are you sure to remove this Meta Rule?'))) {
+ modelService.removeMetaRule(metaRule);
+ }
+ }
+
+ self.addCategory = function addCategory(type, metaRule) {
+ var typeValue = categoryMap[type];
+ var schema = {
+ type: "object",
+ properties: {
+ name: { type: "string", minLength: 2, title: gettext("Name") },
+ description: { type: "string", minLength: 2, title: gettext("Description") },
+ id: { type: "string", title: gettext("Select a Category:") }
+ }
+ };
+ var category = { name: '', description: '' };
+ var titleMap = util.arrayToTitleMap(modelService[typeValue.serviceListName])
+ var config = {
+ title: gettext(typeValue.addTitle),
+ schema: schema,
+ form: [{ key: 'id', type: 'select', titleMap: titleMap }, { type: 'help', helpvalue: gettext("Or create a new one:") }, 'name', { key: 'description', type: 'textarea' }],
+ model: category
+ };
+ ModalFormService.open(config).then(submit);
+
+ function submit(form) {
+ function addCategoryToMetaRule(category) {
+ var metaRuleCopy = angular.copy(metaRule);
+ metaRuleCopy[typeValue.listName].push(category);
+ modelService.updateMetaRule(metaRuleCopy)
+ }
+
+ if (form.model.name) {
+ modelService.createCategory(type, form.model).then(addCategoryToMetaRule)
+ } else if (form.model.id) {
+ addCategoryToMetaRule(modelService.getCategory(type, form.model.id));
+ }
+ }
+ }
+
+ self.removeCategoryFromMetaRule = function removeCategoryFromMetaRule(type, metaRule, category) {
+ var typeValue = categoryMap[type];
+ if (confirm(gettext(typeValue.removeTitleFromMetaRule))) {
+ var metaRuleCopy = angular.copy(metaRule);
+ metaRuleCopy[typeValue.listName].splice(metaRule[typeValue.listName].indexOf(category), 1);
+ modelService.updateMetaRule(metaRuleCopy);
+ }
+ }
+
+ self.removeCategory = function removeCategory(type, category) {
+ var typeValue = categoryMap[type];
+ if (confirm(gettext(typeValue.removeTitle))) {
+ modelService.removeCategory(type, category);
+ }
+ }
+
+
+ }
+})(); \ No newline at end of file
diff --git a/moon_dashboard/moon/static/moon/model/model.html b/moon_dashboard/moon/static/moon/model/model.html
new file mode 100644
index 00000000..98d64c75
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/model/model.html
@@ -0,0 +1,143 @@
+<div ng-controller="moon.model.controller as ctrl">
+ <div ng-if="ctrl.model.orphanMetaRules.length
+ || ctrl.model.orphanSubjectCategories.length
+ || ctrl.model.orphanActionCategories.length
+ || ctrl.model.orphanObjectCategories.length" class="alert alert-dismissable alert-warning">
+ <button type="button" class="close" data-dismiss="alert" ng-click="ctrl.showOrphan=false">×</button>
+ <h4 translate>Warning!</h4>
+ <p translate>
+ Some metarules or categories are orphan, please check them and delete them if necessary.
+ <a href="" ng-click="ctrl.showOrphan=true" ng-show="!ctrl.showOrphan" translate>Show orphans</a>
+ <a href="" ng-click="ctrl.showOrphan=false" ng-show="ctrl.showOrphan" translate>Hide orphans</a>
+ </p>
+ </div>
+
+ <div class="row" ng-show="ctrl.showOrphan">
+ <div class="list-group col-lg-3" ng-if="ctrl.model.orphanMetaRules.length">
+ <h3 class="list-group-item active" translate>Orphan Meta rules</h3>
+ <div ng-repeat="metaRule in ctrl.model.orphanMetaRules | orderBy:'name'" class="list-group-item">
+ <h4 class="list-group-item-heading inline">{$ metaRule.name $}</h4>
+ <button type="button" class="fa fa-trash pull-right" ng-click="ctrl.removeMetaRule(metaRule)" title="{$ 'Remove Meta rule' | translate $}"></button>
+ <p class="list-group-item-text">{$ metaRule.description $}</p>
+ </div>
+ </div>
+
+ <div class="list-group col-lg-3" ng-if="ctrl.model.orphanSubjectCategories.length">
+ <h3 class="list-group-item active" translate>Orphan Subject categories</h3>
+ <div ng-repeat="subject in ctrl.model.orphanSubjectCategories | orderBy:'name'" class="list-group-item">
+ <h4 class="list-group-item-heading inline">{$ subject.name $}</h4>
+ <button type="button" class="fa fa-trash pull-right" ng-click="ctrl.removeCategory('subject', subject)" title="{$ 'Remove Subject category' | translate $}"></button>
+ <p class="list-group-item-text">{$ subject.description $}</p>
+ </div>
+ </div>
+
+ <div class="list-group col-lg-3" ng-if="ctrl.model.orphanObjectCategories.length">
+ <h3 class="list-group-item active" translate>Orphan Object categories</h3>
+ <div ng-repeat="object in ctrl.model.orphanObjectCategories | orderBy:'name'" class="list-group-item">
+ <h4 class="list-group-item-heading inline">{$ object.name $}</h4>
+ <button type="button" class="fa fa-trash pull-right" ng-click="ctrl.removeCategory('object', object)" title="{$ 'Remove Object category' | translate $}"></button>
+ <p class="list-group-item-text">{$ object.description $}</p>
+ </div>
+ </div>
+
+ <div class="list-group col-lg-3" ng-if="ctrl.model.orphanActionCategories.length">
+ <h3 class="list-group-item active" translate>Orphan Action categories</h3>
+ <div ng-repeat="action in ctrl.model.orphanActionCategories | orderBy:'name'" class="list-group-item">
+ <h4 class="list-group-item-heading inline">{$ action.name $}</h4>
+ <button type="button" class="fa fa-trash pull-right" ng-click="ctrl.removeCategory('action', action)" title="{$ 'Remove Action category' | translate $}"></button>
+ <p class="list-group-item-text">{$ action.description $}</p>
+ </div>
+ </div>
+ </div>
+
+ <div class="clearfix list-group">
+ <div class="pull-right">
+ <input type="search" class="form-control filter" placeholder="Filter" ng-model="filterText">
+ <button type="button" class="btn btn-default" ng-click="ctrl.createModel()">
+ <span class="fa fa-plus"></span>
+ <translate>Create Model</translate>
+ </button>
+ <label for="file" class="label-file btn btn-primary">
+ <span class="fa fa-upload"></span>
+ <translate>Import</translate>
+ </label>
+ <input id="file" class="input-file" type="file" on-read-file="ctrl.importData(contents)" accept="application/json,.json"/>
+ <!--button type="button" class="btn btn-primary" ng-click="ctrl.createModel()">
+ <span class="fa fa-upload"></span>
+ <translate>Import</translate>
+ </button-->
+ </div>
+ </div>
+
+
+ <div class="list-group">
+ <div ng-repeat="model in ctrl.model.models | orderBy:'name' | filter:filterText " class="list-group-item">
+ <h3 class="list-group-item-heading inline">{$ model.name $}</h3>
+ <div class="pull-right">
+ <button type="button" class="fa fa-trash" ng-click="ctrl.removeModel(model)" title="{$ 'Remove Model' | translate $}"></button>
+ <button type="button" class="fa fa-edit" ng-click="ctrl.updateModel(model)" title="{$ 'Edit Model' | translate $}"></button>
+ </div>
+ <p class="list-group-item-text">{$ model.description $}</p>
+ <details class="list-group-item-text">
+ <summary>
+ <h4 class="inline">{$ model.meta_rules.length $}
+ <translate>meta rule(s)</translate>
+ </h4>
+ <button type="button" class="fa fa-plus " ng-click="ctrl.addMetaRule(model)" title="{$ 'Add Meta Rule' | translate $}"></button>
+ </summary>
+ <div class="list-group">
+ <div ng-repeat="metaRule in model.meta_rules | orderBy:'name'" class="list-group-item">
+ <h3 class="list-group-item-heading inline">{$ metaRule.name $}</h3>
+ <div class="pull-right">
+ <button type="button" class="fa fa-trash" ng-click="ctrl.removeMetaRuleFromModel(model, metaRule)" title="{$ 'Remove Meta Rule' | translate $}"></button>
+ <button type="button" class="fa fa-edit" ng-click="ctrl.updateMetaRule(metaRule)" title="{$ 'Edit Meta Rule' | translate $}"></button>
+ </div>
+ <p class="list-group-item-text">{$ metaRule.description $}</p>
+ <p class="list-group-item-text">
+ <table class="table categories">
+ <thead>
+ <tr>
+ <th>
+ <span translate>Subjects</span>
+ <button type="button" class="fa fa-plus pull-right" ng-click="ctrl.addCategory('subject', metaRule)" title="{$ 'Add Subject' | translate $}"></button>
+ </th>
+ <th>
+ <span translate>Objects</span>
+ <button type="button" class="fa fa-plus pull-right" ng-click="ctrl.addCategory('object', metaRule)" title="{$ 'Add Object' | translate $}"></button>
+ </th>
+ <th>
+ <span translate>Actions</span>
+ <button type="button" class="fa fa-plus pull-right" ng-click="ctrl.addCategory('action', metaRule)" title="{$ 'Add Action' | translate $}"></button>
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>
+ <p ng-repeat="category in metaRule.subject_categories">
+ <span>{$ category.name $}</span>
+ <button type="button" class="fa fa-trash pull-right" ng-click="ctrl.removeCategoryFromMetaRule('subject', metaRule, category)" title="{$ 'Remove Subject' | translate $}"></button>
+ </p>
+ </td>
+ <td>
+ <p ng-repeat="category in metaRule.object_categories">
+ <span>{$ category.name $}</span>
+ <button type="button" class="fa fa-trash pull-right" ng-click="ctrl.removeCategoryFromMetaRule('object', metaRule, category)" title="{$ 'Remove Object' | translate $}"></button>
+ </p>
+ </td>
+ <td>
+ <p ng-repeat="category in metaRule.action_categories">
+ <span>{$ category.name $}</span>
+ <button type="button" class="fa fa-trash pull-right" ng-click="ctrl.removeCategoryFromMetaRule('action', metaRule, category)" title="{$ 'Remove Action' | translate $}"></button>
+ </p>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </p>
+ </div>
+ </div>
+ </details>
+ </div>
+ </div>
+</div> \ No newline at end of file
diff --git a/moon_dashboard/moon/static/moon/model/model.service.js b/moon_dashboard/moon/static/moon/model/model.service.js
new file mode 100755
index 00000000..76c3da01
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/model/model.service.js
@@ -0,0 +1,286 @@
+(function () {
+
+ 'use strict';
+
+ angular
+ .module('moon')
+ .factory('moon.model.service', modelService);
+
+ modelService.$inject = ['moon.util.service', '$resource', 'moon.URI', '$q'];
+
+ function modelService(util, $resource, URI, $q) {
+ var host = URI.API;
+ var modelResource = $resource(host + '/models/' + ':id', {}, {
+ get: { method: 'GET' },
+ query: { method: 'GET' },
+ create: { method: 'POST' },
+ remove: { method: 'DELETE' },
+ update: { method: 'PATCH' }
+ });
+
+ var metaRuleResource = $resource(host + '/meta_rules/' + ':id', {}, {
+ query: { method: 'GET' },
+ get: { method: 'GET' },
+ update: { method: 'PATCH' },
+ create: { method: 'POST' },
+ remove: { method: 'DELETE' }
+ });
+
+ var subjectCategoryResource = $resource(host + '/subject_categories/' + ':id', {}, {
+ query: { method: 'GET' },
+ get: { method: 'GET' },
+ create: { method: 'POST' },
+ remove: { method: 'DELETE' }
+ });
+
+ var objectCategoryResource = $resource(host + '/object_categories/' + ':id', {}, {
+ query: { method: 'GET' },
+ get: { method: 'GET' },
+ create: { method: 'POST' },
+ remove: { method: 'DELETE' }
+ });
+
+ var actionCategoryResource = $resource(host + '/action_categories/' + ':id', {}, {
+ query: { method: 'GET' },
+ get: { method: 'GET' },
+ create: { method: 'POST' },
+ remove: { method: 'DELETE' }
+ });
+
+ var modelsMap = {};
+ var metaRulesMap = {};
+ var subjectCategoriesMap = {};
+ var objectCategoriesMap = {};
+ var actionCategoriesMap = {};
+ var models = [];
+ var metaRules = [];
+ var orphanMetaRules = [];
+ var subjectCategories = [];
+ var objectCategories = [];
+ var actionCategories = [];
+ var orphanSubjectCategories = [];
+ var orphanObjectCategories = [];
+ var orphanActionCategories = [];
+
+ var categoryMap = {
+ 'subject': {
+ resource: subjectCategoryResource,
+ map: subjectCategoriesMap,
+ list: subjectCategories,
+ listName: 'subject_categories'
+ },
+ 'object': {
+ resource: objectCategoryResource,
+ map: objectCategoriesMap,
+ list: objectCategories,
+ listName: 'object_categories'
+ },
+ 'action': {
+ resource: actionCategoryResource,
+ map: actionCategoriesMap,
+ list: actionCategories,
+ listName: 'action_categories'
+ }
+ }
+
+ function loadModels() {
+ var queries = {
+ subjectCategories: subjectCategoryResource.query().$promise,
+ objectCategories: objectCategoryResource.query().$promise,
+ actionCategories: actionCategoryResource.query().$promise,
+ metaRules: metaRuleResource.query().$promise,
+ models: modelResource.query().$promise,
+ }
+
+ var result = $q.all(queries).then(function (result) {
+ createModels(result.models, result.metaRules, result.subjectCategories, result.objectCategories, result.actionCategories)
+ console.log('moon', 'models initialized')
+ })
+
+ return result;
+ }
+
+ function createModels(modelsData, metarulesData, subjectCategoriesData, objectCategoriesData, actionCategoriesData) {
+ util.cleanObject(modelsMap);
+ util.cleanObject(metaRulesMap);
+ util.cleanObject(subjectCategoriesMap);
+ util.cleanObject(objectCategoriesMap);
+ util.cleanObject(actionCategoriesMap);
+ models.splice(0, models.length);
+ metaRules.splice(0, metaRules.length);
+ subjectCategories.splice(0, subjectCategories.length);
+ objectCategories.splice(0, objectCategories.length);
+ actionCategories.splice(0, actionCategories.length);
+ if (subjectCategoriesData.subject_categories) createCategoryInternal('subject', subjectCategoriesData.subject_categories);
+ if (objectCategoriesData.object_categories) createCategoryInternal('object', objectCategoriesData.object_categories);
+ if (actionCategoriesData.action_categories) createCategoryInternal('action', actionCategoriesData.action_categories);
+ if (metarulesData.meta_rules) createMetaRuleInternal(metarulesData.meta_rules);
+ if (modelsData.models) createModelInternal(modelsData.models);
+ updateOrphan();
+ }
+
+ function mapModel(model) {
+ util.mapIdToItem(model.meta_rules, metaRulesMap);
+ }
+
+ function createModelInternal(data) {
+ return util.createInternal(data, models, modelsMap, mapModel);
+ }
+
+ function updateModelInternal(data) {
+ return util.updateInternal(data, modelsMap, mapModel);
+ }
+
+ function removeModelInternal(id) {
+ return util.removeInternal(id, models, modelsMap);
+ }
+
+ function mapMetaRule(metaRule) {
+ util.mapIdToItem(metaRule.subject_categories, subjectCategoriesMap);
+ util.mapIdToItem(metaRule.object_categories, objectCategoriesMap);
+ util.mapIdToItem(metaRule.action_categories, actionCategoriesMap);
+ }
+
+ function createMetaRuleInternal(data) {
+ return util.createInternal(data, metaRules, metaRulesMap, mapMetaRule);
+ }
+
+ function updateMetaRuleInternal(data) {
+ return util.updateInternal(data, metaRulesMap, mapMetaRule);
+ }
+
+ function removeMetaRuleInternal(id) {
+ return util.removeInternal(id, metaRules, metaRulesMap);
+ }
+
+ function createCategoryInternal(type, data) {
+ var categoryValue = categoryMap[type];
+ return util.createInternal(data, categoryValue.list, categoryValue.map)
+ }
+
+ function removeCategoryInternal(type, id) {
+ var categoryValue = categoryMap[type];
+ return util.removeInternal(id, categoryValue.list, categoryValue.map);
+ }
+
+ function updateOrphan() {
+ updateOrphanInternal(metaRules, orphanMetaRules, models, "meta_rules");
+ updateOrphanInternal(subjectCategories, orphanSubjectCategories, metaRules, "subject_categories");
+ updateOrphanInternal(objectCategories, orphanObjectCategories, metaRules, "object_categories");
+ updateOrphanInternal(actionCategories, orphanActionCategories, metaRules, "action_categories");
+ }
+
+ function updateOrphanInternal(list, orphanList, parentList, childListName) {
+ orphanList.splice(0, orphanList.length);
+ util.pushAll(orphanList, list);
+ for (var i = 0; i < parentList.length; i++) {
+ var parent = parentList[i];
+ var children = parent[childListName];
+ if (children) {
+ for (var j = 0; j < children.length; j++) {
+ var child = children[j];
+ var notOrphanIndex = util.indexOf(orphanList, "id", child.id);
+ if (notOrphanIndex >= 0) {
+ orphanList.splice(notOrphanIndex, 1);
+ }
+ }
+ }
+ }
+ }
+
+
+ return {
+ initialize: loadModels,
+ createModels: createModels,
+ models: models,
+ metaRules: metaRules,
+ orphanMetaRules: orphanMetaRules,
+ orphanSubjectCategories: orphanSubjectCategories,
+ orphanObjectCategories: orphanObjectCategories,
+ orphanActionCategories: orphanActionCategories,
+ subjectCategories: subjectCategories,
+ objectCategories: objectCategories,
+ actionCategories: actionCategories,
+ getModel: function getModel(id) {
+ return modelsMap[id];
+ },
+ createModel: function createModel(model) {
+ modelResource.create(null, model, success, util.displayErrorFunction('Unable to create model'));
+
+ function success(data) {
+ createModelInternal(data.models);
+ util.displaySuccess('Model created');
+ }
+ },
+ removeModel: function removeModel(model) {
+ modelResource.remove({ id: model.id }, null, success, util.displayErrorFunction('Unable to remove model'));
+
+ function success(data) {
+ removeModelInternal(model.id);
+ updateOrphan();
+ util.displaySuccess('Model removed');
+ }
+ },
+ updateModel: function updateModel(model) {
+ util.mapItemToId(model.meta_rules)
+ modelResource.update({ id: model.id }, model, success, util.displayErrorFunction('Unable to update model'));
+
+ function success(data) {
+ updateModelInternal(data.models)
+ updateOrphan();
+ util.displaySuccess('Model updated');
+ }
+ },
+ getMetaRule: function getMetaRule(id) {
+ return metaRulesMap[id];
+ },
+ createMetaRule: function createMetaRule(metaRule) {
+ return metaRuleResource.create(null, metaRule).$promise.then(function (data) {
+ util.displaySuccess('Meta Rule created');
+ return createMetaRuleInternal(data.meta_rules)[0];
+ }, util.displayErrorFunction('Unable to create meta rule'))
+ },
+ updateMetaRule: function updateMetaRule(metaRule) {
+ util.mapItemToId(metaRule.subject_categories);
+ util.mapItemToId(metaRule.object_categories);
+ util.mapItemToId(metaRule.action_categories);
+ metaRuleResource.update({ id: metaRule.id }, metaRule, success, util.displayErrorFunction('Unable to update meta rule'));
+
+ function success(data) {
+ updateMetaRuleInternal(data.meta_rules);
+ updateOrphan();
+ util.displaySuccess('Meta Rule updated');
+ }
+ },
+ removeMetaRule: function removeMetaRule(metaRule) {
+ metaRuleResource.remove({ id: metaRule.id }, null, success, util.displayErrorFunction('Unable to remove meta rule'));
+
+ function success(data) {
+ removeMetaRuleInternal(metaRule.id);
+ updateOrphan();
+ util.displaySuccess('Meta Rule removed');
+ }
+ },
+ getCategory: function getCategory(type, id) {
+ return categoryMap[type].map[id];
+ },
+ createCategory: function createCategory(type, category) {
+ var categoryValue = categoryMap[type];
+ return categoryValue.resource.create({}, category).$promise.then(function (data) {
+ util.displaySuccess('Category created');
+ return createCategoryInternal(type, data[categoryValue.listName])[0];
+ }, util.displayErrorFunction('Unable to create category'))
+ },
+ removeCategory: function removeCategory(type, category) {
+ var categoryValue = categoryMap[type];
+ categoryValue.resource.remove({ id: category.id }, null, success, util.displayErrorFunction('Unable to remove category'));
+
+ function success(data) {
+ removeCategoryInternal(type, category.id);
+ updateOrphan();
+ util.displaySuccess('Category removed');
+ }
+ },
+ }
+ }
+})(); \ No newline at end of file
diff --git a/moon_dashboard/moon/static/moon/model/model.service.spec.js b/moon_dashboard/moon/static/moon/model/model.service.spec.js
new file mode 100755
index 00000000..04d47793
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/model/model.service.spec.js
@@ -0,0 +1,288 @@
+(function () {
+ 'use strict';
+
+ describe('moon.model.service', function () {
+ var service, $httpBackend, URI;
+ var modelsData, metaRulesData, subjectCategoriesData, objectCategoriesData, actionCategoriesData;
+
+ function initData() {
+ modelsData = {
+ models:
+ { 'modelId1': { name: 'model1', description: 'mDescription1', meta_rules: ['metaRuleId1'] } }
+ };
+
+ subjectCategoriesData = {
+ subject_categories:
+ {
+ 'subjectCategoryId1': { name: 'subjectCategory1', description: 'scDescription1' },
+ 'subjectCategoryId2': { name: 'subjectCategory2', description: 'scDescription2' }
+ },
+ };
+ objectCategoriesData = {
+ object_categories:
+ {
+ 'objectCategoryId1': { name: 'objectCategory1', description: 'ocDescription1' },
+ 'objectCategoryId2': { name: 'objectCategory2', description: 'ocDescription2' }
+ }
+ };
+ actionCategoriesData = {
+ action_categories:
+ {
+ 'actionCategoryId1': { name: 'actionCategory1', description: 'acDescription1' },
+ 'actionCategoryId2': { name: 'actionCategory2', description: 'acDescription2' }
+ }
+ };
+ metaRulesData = {
+ meta_rules:
+ {
+ 'metaRuleId1': { name: 'metaRule1', description: 'mrDescription1', subject_categories: ['subjectCategoryId1'], object_categories: ['objectCategoryId1'], action_categories: ['actionCategoryId1'] },
+ 'metaRuleId2': { name: 'metaRule2', description: 'mrDescription2', subject_categories: [], object_categories: [], action_categories: [] }
+ }
+ };
+ }
+
+ beforeEach(module('horizon.app.core'));
+ beforeEach(module('horizon.framework'));
+ beforeEach(module('moon'));
+
+ beforeEach(inject(function ($injector) {
+ service = $injector.get('moon.model.service');
+ $httpBackend = $injector.get('$httpBackend');
+ URI = $injector.get('moon.URI');
+ }));
+
+ afterEach(function () {
+ $httpBackend.verifyNoOutstandingExpectation();
+ $httpBackend.verifyNoOutstandingRequest();
+ });
+
+ it('should initialize', function () {
+ initData();
+ $httpBackend.expectGET(URI.API + '/subject_categories').respond(200, subjectCategoriesData);
+ $httpBackend.expectGET(URI.API + '/object_categories').respond(200, objectCategoriesData);
+ $httpBackend.expectGET(URI.API + '/action_categories').respond(200, actionCategoriesData);
+ $httpBackend.expectGET(URI.API + '/meta_rules').respond(200, metaRulesData);
+ $httpBackend.expectGET(URI.API + '/models').respond(200, modelsData);
+
+ service.initialize();
+ $httpBackend.flush();
+
+ expect(service.models.length).toBe(1);
+ var model = service.models[0];
+ expect(model.id).toBe('modelId1');
+ expect(model.name).toBe('model1');
+ expect(model.description).toBe('mDescription1');
+
+ expect(service.metaRules.length).toBe(2);
+ expect(model.meta_rules.length).toBe(1);
+ var metaRule = model.meta_rules[0];
+ expect(metaRule.id).toBe('metaRuleId1');
+ expect(metaRule.name).toBe('metaRule1');
+ expect(metaRule.description).toBe('mrDescription1');
+
+ expect(service.subjectCategories.length).toBe(2);
+ expect(metaRule.subject_categories.length).toBe(1);
+ var subjectCategory = metaRule.subject_categories[0];
+ expect(subjectCategory.id).toBe('subjectCategoryId1');
+ expect(subjectCategory.name).toBe('subjectCategory1');
+ expect(subjectCategory.description).toBe('scDescription1');
+
+ expect(service.objectCategories.length).toBe(2);
+ expect(metaRule.object_categories.length).toBe(1);
+ var objectCategory = metaRule.object_categories[0];
+ expect(objectCategory.id).toBe('objectCategoryId1');
+ expect(objectCategory.name).toBe('objectCategory1');
+ expect(objectCategory.description).toBe('ocDescription1');
+
+ expect(service.actionCategories.length).toBe(2);
+ expect(metaRule.action_categories.length).toBe(1);
+ var actionCategory = metaRule.action_categories[0];
+ expect(actionCategory.id).toBe('actionCategoryId1');
+ expect(actionCategory.name).toBe('actionCategory1');
+ expect(actionCategory.description).toBe('acDescription1');
+
+ expect(service.orphanMetaRules.length).toBe(1);
+ metaRule = service.orphanMetaRules[0];
+ expect(metaRule.id).toBe('metaRuleId2');
+ expect(metaRule.name).toBe('metaRule2');
+ expect(metaRule.description).toBe('mrDescription2');
+
+ expect(service.orphanSubjectCategories.length).toBe(1);
+ subjectCategory = service.orphanSubjectCategories[0];
+ expect(subjectCategory.id).toBe('subjectCategoryId2');
+ expect(subjectCategory.name).toBe('subjectCategory2');
+ expect(subjectCategory.description).toBe('scDescription2');
+
+ expect(service.orphanObjectCategories.length).toBe(1);
+ objectCategory = service.orphanObjectCategories[0];
+ expect(objectCategory.id).toBe('objectCategoryId2');
+ expect(objectCategory.name).toBe('objectCategory2');
+ expect(objectCategory.description).toBe('ocDescription2');
+
+ expect(service.orphanActionCategories.length).toBe(1);
+ actionCategory = service.orphanActionCategories[0];
+ expect(actionCategory.id).toBe('actionCategoryId2');
+ expect(actionCategory.name).toBe('actionCategory2');
+ expect(actionCategory.description).toBe('acDescription2');
+
+ });
+
+
+
+ it('should create model', function () {
+ var modelCreatedData = {
+ models:
+ { 'modelId1': { name: 'model1', description: 'mDescription1', meta_rules: [] } }
+ };
+
+ $httpBackend.expectPOST(URI.API + '/models').respond(200, modelCreatedData);
+
+ service.createModel({ name: 'model1', description: 'mDescription1' });
+ $httpBackend.flush();
+
+ expect(service.models.length).toBe(1);
+ var model = service.models[0];
+ expect(model.id).toBe('modelId1');
+ expect(model.name).toBe('model1');
+ expect(model.description).toBe('mDescription1');
+ });
+
+ it('should remove model', function () {
+ initData();
+ service.createModels(modelsData, metaRulesData, subjectCategoriesData, objectCategoriesData, actionCategoriesData);
+
+ $httpBackend.expectDELETE(URI.API + '/models/modelId1').respond(200);
+
+ service.removeModel({ id: 'modelId1' });
+ $httpBackend.flush();
+
+ expect(service.models.length).toBe(0);
+
+ expect(service.orphanMetaRules.length).toBe(2);
+ });
+
+ it('should update model', function () {
+ initData();
+ var modelUpdatedData = {
+ models:
+ { 'modelId1': { name: 'model2', description: 'mDescription2', meta_rules: ['metaRuleId2'] } }
+ };
+ service.createModels(modelsData, metaRulesData, subjectCategoriesData, objectCategoriesData, actionCategoriesData);
+
+ $httpBackend.expectPATCH(URI.API + '/models/modelId1').respond(200, modelUpdatedData);
+
+ service.updateModel({ id: 'modelId1', name: 'model2', description: 'mDescription2', meta_rules: service.getMetaRule('metaRuleId2') });
+ $httpBackend.flush();
+
+ expect(service.models.length).toBe(1);
+ var model = service.models[0];
+ expect(model.id).toBe('modelId1');
+ expect(model.name).toBe('model2');
+ expect(model.description).toBe('mDescription2');
+
+ expect(model.meta_rules.length).toBe(1);
+ var metaRule = model.meta_rules[0];
+ expect(metaRule.id).toBe('metaRuleId2');
+
+ expect(service.orphanMetaRules.length).toBe(1);
+ metaRule = service.orphanMetaRules[0];
+ expect(metaRule.id).toBe('metaRuleId1');
+ });
+
+ it('should create meta rule', function () {
+ var metaRuleCreatedData = {
+ meta_rules:
+ { 'metaRuleId1': { name: 'metaRule1', description: 'mrDescription1' } }
+ };
+
+ $httpBackend.expectPOST(URI.API + '/meta_rules').respond(200, metaRuleCreatedData);
+
+ service.createMetaRule({ name: 'metaRule1', description: 'mrDescription1' });
+ $httpBackend.flush();
+
+ expect(service.metaRules.length).toBe(1);
+ var metaRule = service.metaRules[0];
+ expect(metaRule.id).toBe('metaRuleId1');
+ expect(metaRule.name).toBe('metaRule1');
+ expect(metaRule.description).toBe('mrDescription1');
+ });
+
+ it('should update meta rule', function () {
+ initData();
+ var metaRuleUpdatedData = {
+ meta_rules:
+ { 'metaRuleId1': { name: 'metaRule2', description: 'mrDescription2', subject_categories: ['subjectCategoryId2'], object_categories: ['objectCategoryId2'], action_categories: ['actionCategoryId2'] } }
+ };
+ service.createModels(modelsData, metaRulesData, subjectCategoriesData, objectCategoriesData, actionCategoriesData);
+
+ $httpBackend.expectPATCH(URI.API + '/meta_rules/metaRuleId1').respond(200, metaRuleUpdatedData);
+
+ service.updateMetaRule({ id: 'metaRuleId1', name: 'metaRule2', description: 'mrDescription2', subject_categories: [service.getCategory('subject', 'subjectCategoryId2')], object_categories: [service.getCategory('object', 'objectCategoryId2')], action_categories: [service.getCategory('action','actionCategoryId2')] });
+ $httpBackend.flush();
+
+ var metaRule = service.getMetaRule('metaRuleId1');
+ expect(metaRule.id).toBe('metaRuleId1');
+ expect(metaRule.name).toBe('metaRule2');
+ expect(metaRule.description).toBe('mrDescription2');
+
+ expect(service.orphanSubjectCategories.length).toBe(1);
+ var subjectCategory = service.orphanSubjectCategories[0];
+ expect(subjectCategory.id).toBe('subjectCategoryId1');
+
+ expect(service.orphanObjectCategories.length).toBe(1);
+ var objectCategory = service.orphanObjectCategories[0];
+ expect(objectCategory.id).toBe('objectCategoryId1');
+
+ expect(service.orphanActionCategories.length).toBe(1);
+ var actionCategory = service.orphanActionCategories[0];
+ expect(actionCategory.id).toBe('actionCategoryId1');
+ });
+
+ it('should remove meta rule', function () {
+ initData();
+ service.createModels(modelsData, metaRulesData, subjectCategoriesData, objectCategoriesData, actionCategoriesData);
+
+ $httpBackend.expectDELETE(URI.API + '/meta_rules/metaRuleId2').respond(200);
+
+ service.removeMetaRule(service.getMetaRule('metaRuleId2'));
+ $httpBackend.flush();
+
+ expect(service.metaRules.length).toBe(1);
+ expect(service.orphanMetaRules.length).toBe(0);
+ });
+
+ it('should create category', function () {
+ var categoryCreatedData = {
+ subject_categories:
+ { 'subjectCategoryId1': { name: 'subjectCategory1', description: 'scDescription1' } }
+ };
+
+ $httpBackend.expectPOST(URI.API + '/subject_categories').respond(200, categoryCreatedData);
+
+ service.createCategory('subject', { name: 'subjectCategory1', description: 'scDescription1' });
+ $httpBackend.flush();
+
+ expect(service.subjectCategories.length).toBe(1);
+ var subjectCategory = service.subjectCategories[0];
+ expect(subjectCategory.id).toBe('subjectCategoryId1');
+ expect(subjectCategory.name).toBe('subjectCategory1');
+ expect(subjectCategory.description).toBe('scDescription1');
+ });
+
+ it('should remove category', function () {
+ initData();
+ service.createModels(modelsData, metaRulesData, subjectCategoriesData, objectCategoriesData, actionCategoriesData);
+
+ $httpBackend.expectDELETE(URI.API + '/subject_categories/subjectCategoryId2').respond(200);
+
+ service.removeCategory('subject', service.getCategory('subject', 'subjectCategoryId2'));
+ $httpBackend.flush();
+
+ expect(service.subjectCategories.length).toBe(1);
+ expect(service.orphanSubjectCategories.length).toBe(0);
+ });
+
+ });
+
+
+})(); \ No newline at end of file
diff --git a/moon_dashboard/moon/static/moon/pdp/pdp.controller.js b/moon_dashboard/moon/static/moon/pdp/pdp.controller.js
new file mode 100644
index 00000000..c57f3b28
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/pdp/pdp.controller.js
@@ -0,0 +1,121 @@
+(function () {
+ 'use strict';
+
+ angular
+ .module('moon')
+ .controller('moon.pdp.controller',
+ controller);
+
+ controller.$inject = ['moon.util.service', 'moon.pdp.service', 'horizon.framework.widgets.form.ModalFormService'];
+
+ function controller(util, pdpService, ModalFormService) {
+ var self = this;
+ self.model = pdpService;
+ pdpService.initialize();
+
+ self.createPdp = function createPdp() {
+ var schema = {
+ type: "object",
+ properties: {
+ name: { type: "string", minLength: 2, title: gettext("Name") },
+ description: { type: "string", minLength: 2, title: gettext("Description") }
+ }
+ };
+ var pdp = { name: '', description: '' };
+ var config = {
+ title: gettext('Create PDP'),
+ schema: schema,
+ form: ['name', { key: 'description', type: 'textarea' }],
+ model: pdp
+ };
+ ModalFormService.open(config).then(submit);
+
+ function submit(form) {
+ pdpService.createPdp(form.model);
+ }
+ }
+
+ self.updatePdp = function updatePdp(pdp) {
+ var schema = {
+ type: "object",
+ properties: {
+ name: { type: "string", minLength: 2, title: gettext("Name") },
+ description: { type: "string", minLength: 2, title: gettext("Description") }
+ }
+ };
+ var config = {
+ title: gettext('Update PDP'),
+ schema: schema,
+ form: ['name', { key: 'description', type: 'textarea' }],
+ model: angular.copy(pdp)
+ };
+ ModalFormService.open(config).then(submit);
+
+ function submit(form) {
+ pdpService.updatePdp(form.model);
+ }
+ }
+
+ self.removePdp = function removePdp(pdp) {
+ if (confirm(gettext('Are you sure to delete this PDP?')))
+ pdpService.removePdp(pdp);
+ }
+
+ self.addPolicy = function addPolicy(pdp) {
+ var schema = {
+ type: "object",
+ properties: {
+ id: { type: "string", title: gettext("Select a Policy:") }
+ }
+ };
+ var titleMap = util.arrayToTitleMap(pdpService.policies)
+ var config = {
+ title: gettext('Add Policy'),
+ schema: schema,
+ form: [{ key: 'id', type: 'select', titleMap: titleMap }],
+ model: {}
+ };
+ ModalFormService.open(config).then(submit);
+
+ function submit(form) {
+ var pdpCopy = angular.copy(pdp);
+ pdpCopy.security_pipeline.push(pdpService.getPolicy(form.model.id));
+ pdpService.updatePdp(pdpCopy);
+ }
+ }
+
+ self.removePolicyFromPdp = function removePolicyFromPdp(pdp, policy) {
+ if (confirm(gettext('Are you sure to remove this Policy from PDP?'))) {
+ var pdpCopy = angular.copy(pdp);
+ pdpCopy.security_pipeline.splice(pdp.security_pipeline.indexOf(policy), 1);
+ pdpService.updatePdp(pdpCopy);
+ }
+ }
+
+ self.changeProject = function changeProject(pdp) {
+ var schema = {
+ type: "object",
+ properties: {
+ id: { type: "string", title: gettext("Select a Project:") }
+ }
+ };
+ var model = {id : pdp.keystone_project_id};
+
+ var titleMap = util.arrayToTitleMap(pdpService.projects)
+ var config = {
+ title: gettext('Change Project'),
+ schema: schema,
+ form: [{ key: 'id', type: 'select', titleMap: titleMap }],
+ model: model
+ };
+ ModalFormService.open(config).then(submit);
+
+ function submit(form) {
+ var pdpCopy = angular.copy(pdp);
+ pdpCopy.project = pdpService.getProject(form.model.id);
+ pdpService.updatePdp(pdpCopy);
+ }
+ }
+
+ }
+})(); \ No newline at end of file
diff --git a/moon_dashboard/moon/static/moon/pdp/pdp.html b/moon_dashboard/moon/static/moon/pdp/pdp.html
new file mode 100644
index 00000000..2456a261
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/pdp/pdp.html
@@ -0,0 +1,41 @@
+<div ng-controller="moon.pdp.controller as ctrl">
+ <div class="clearfix list-group">
+ <div class="pull-right">
+ <input type="search" class="form-control filter" placeholder="Filter" ng-model="filterText">
+ <button type="button" class="btn btn-default" ng-click="ctrl.createPdp()">
+ <span class="fa fa-plus"></span>
+ <translate>Create PDP</translate>
+ </button>
+ </div>
+ </div>
+ <div class="list-group">
+ <div ng-repeat="pdp in ctrl.model.pdps | orderBy:'name' | filter:filterText " class="list-group-item">
+ <h3 class="list-group-item-heading inline">{$ pdp.name $}</h3>
+ <div class="pull-right">
+ <button type="button" class="fa fa-trash" ng-click="ctrl.removePdp(pdp)" title="{$ 'Remove PDP' | translate $}"></button>
+ <button type="button" class="fa fa-edit" ng-click="ctrl.updatePdp(pdp)" title="{$ 'Edit PDP' | translate $}"></button>
+ </div>
+ <p class="list-group-item-text">{$ pdp.description $}</p>
+ <h4 class="list-group-item-text">
+ <translate>Project: {$ pdp.project ? pdp.project.name : 'none' $}</translate>
+ <button type="button" class="fa fa-edit" ng-click="ctrl.changeProject(pdp)" title="{$ 'Change project' | translate $}"></button>
+ </h4>
+
+ <details class="list-group-item-text">
+ <summary>
+ <h4 class="inline">{$ pdp.security_pipeline.length $}
+ <translate>policy(ies)</translate>
+ </h4>
+ <button type="button" class="fa fa-plus " ng-click="ctrl.addPolicy(pdp)" title="{$ 'Add Policy' | translate $}"></button>
+ </summary>
+ <div class="list-group">
+ <div ng-repeat="policy in pdp.security_pipeline | orderBy:'name'" class="list-group-item">
+ <h3 class="list-group-item-heading inline">{$ policy.name $}</h3>
+ <button type="button" class="fa fa-trash pull-right" ng-click="ctrl.removePolicyFromPdp(pdp, policy)" title="{$ 'Remove Policy' | translate $}"></button>
+ <p class="list-group-item-text">{$ policy.description $}</p>
+ </div>
+ </div>
+ </details>
+ </div>
+ </div>
+</div> \ No newline at end of file
diff --git a/moon_dashboard/moon/static/moon/pdp/pdp.service.js b/moon_dashboard/moon/static/moon/pdp/pdp.service.js
new file mode 100755
index 00000000..e18971be
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/pdp/pdp.service.js
@@ -0,0 +1,123 @@
+(function () {
+
+ 'use strict';
+
+ angular
+ .module('moon')
+ .factory('moon.pdp.service', pdpService);
+
+ pdpService.$inject = ['moon.util.service', '$resource', 'moon.URI', '$q', 'horizon.app.core.openstack-service-api.keystone'];
+
+ function pdpService(util, $resource, URI, $q, keystone) {
+ var host = URI.API;
+
+ var pdpResource = $resource(host + '/pdp/' + ':id', {}, {
+ get: { method: 'GET' },
+ query: { method: 'GET' },
+ create: { method: 'POST' },
+ remove: { method: 'DELETE' },
+ update: { method: 'PATCH' }
+ });
+
+ var policyResource = $resource(host + '/policies/' + ':id', {}, {
+ query: { method: 'GET' },
+ });
+
+ var pdpsMap = {};
+ var pdps = [];
+ var policiesMap = {};
+ var policies = [];
+ var projectsMap = {};
+ var projects = [];
+
+ function loadPdps() {
+ var queries = {
+ pdps: pdpResource.query().$promise,
+ policies: policyResource.query().$promise,
+ projects: keystone.getProjects()
+ }
+
+ $q.all(queries).then(function (result) {
+ createPdps(result.pdps, result.policies, result.projects.data)
+ console.log('moon', 'pdps initialized', pdps)
+ })
+ }
+
+ function createPdps(pdpsData, policiesData, projectsData) {
+ pdps.splice(0, pdps.length);
+ policies.splice(0, policies.length);
+ projects.splice(0, projects.length);
+ util.cleanObject(pdpsMap);
+ util.cleanObject(policiesMap);
+ util.cleanObject(projectsMap)
+
+ util.createInternal(policiesData.policies, policies, policiesMap);
+ util.pushAll(projects, projectsData.items);
+ util.addToMap(projects, projectsMap);
+ createPdpInternal(pdpsData.pdps);
+ }
+
+ function mapPdp(pdp) {
+ util.mapIdToItem(pdp.security_pipeline, policiesMap);
+ pdp.project = null;
+ if (pdp.keystone_project_id) {
+ pdp.project = projectsMap[pdp.keystone_project_id];
+ }
+ }
+
+ function createPdpInternal(data) {
+ return util.createInternal(data, pdps, pdpsMap, mapPdp);
+ }
+
+ function updatePdpInternal(data) {
+ return util.updateInternal(data, pdpsMap, mapPdp);
+ }
+
+ function removePdpInternal(id) {
+ return util.removeInternal(id, pdps, pdpsMap);
+ }
+
+ return {
+ initialize: loadPdps,
+ createPdps: createPdps,
+ pdps: pdps,
+ policies: policies,
+ projects: projects,
+ createPdp: function createPdp(pdp) {
+ pdp.keystone_project_id = null;
+ pdp.security_pipeline = [];
+ pdpResource.create(null, pdp, success, util.displayErrorFunction('Unable to create PDP'));
+
+ function success(data) {
+ createPdpInternal(data.pdps);
+ util.displaySuccess('PDP created');
+ }
+ },
+ removePdp: function removePdp(pdp) {
+ pdpResource.remove({ id: pdp.id }, null, success, util.displayErrorFunction('Unable to remove PDP'));
+
+ function success(data) {
+ removePdpInternal(pdp.id);
+ util.displaySuccess('PDP removed');
+ }
+ },
+ updatePdp: function updatePdp(pdp) {
+ util.mapItemToId(pdp.security_pipeline);
+ pdp.keystone_project_id = pdp.project ? pdp.project.id : null;
+ pdpResource.update({ id: pdp.id }, pdp, success, util.displayErrorFunction('Unable to update PDP'));
+
+ function success(data) {
+ updatePdpInternal(data.pdps)
+ util.displaySuccess('PDP updated');
+ }
+ },
+ getPolicy: function getPolicy(id) {
+ return policiesMap[id];
+ },
+ getProject: function getProject(id) {
+ return projectsMap[id];
+ },
+ }
+
+ }
+})(); \ No newline at end of file
diff --git a/moon_dashboard/moon/static/moon/pdp/pdp.service.spec.js b/moon_dashboard/moon/static/moon/pdp/pdp.service.spec.js
new file mode 100755
index 00000000..4208467f
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/pdp/pdp.service.spec.js
@@ -0,0 +1,143 @@
+(function () {
+ 'use strict';
+
+ describe('moon.pdp.service', function () {
+ var service, $httpBackend, URI;
+ var pdpsData, policiesData, projectsData;
+
+
+ function initData() {
+ pdpsData = {
+ pdps:
+ { 'pdpId1': { name: 'pdp1', description: 'pdpDescription1', security_pipeline: ['policyId1'], keystone_project_id: 'projectId1' } }
+ };
+
+ policiesData = {
+ policies:
+ {
+ 'policyId1': { name: 'policy1', description: 'pDescription1' },
+ 'policyId2': { name: 'policy2', description: 'pDescription2' }
+ }
+ };
+
+ projectsData = {
+ items: [
+ { name: "project1", id: "projectId1" },
+ { name: "project2", id: "projectId2" }
+ ]
+ };
+
+ }
+
+ beforeEach(module('horizon.app.core'));
+ beforeEach(module('horizon.framework'));
+ beforeEach(module('moon'));
+
+ beforeEach(inject(function ($injector) {
+ service = $injector.get('moon.pdp.service');
+ $httpBackend = $injector.get('$httpBackend');
+ URI = $injector.get('moon.URI');
+ }));
+
+ afterEach(function () {
+ $httpBackend.verifyNoOutstandingExpectation();
+ $httpBackend.verifyNoOutstandingRequest();
+ });
+
+ it('should initialize', function () {
+ initData();
+ $httpBackend.expectGET(URI.API + '/pdp').respond(200, pdpsData);
+ $httpBackend.expectGET(URI.API + '/policies').respond(200, policiesData);
+ $httpBackend.expectGET('/api/keystone/projects/').respond(200, projectsData);
+
+
+ service.initialize();
+ $httpBackend.flush();
+
+ expect(service.pdps.length).toBe(1);
+ var pdp = service.pdps[0];
+ expect(pdp.id).toBe('pdpId1');
+ expect(pdp.name).toBe('pdp1');
+ expect(pdp.description).toBe('pdpDescription1');
+ expect(pdp.security_pipeline.length).toBe(1);
+ expect(pdp.security_pipeline[0].id).toBe('policyId1');
+ expect(pdp.keystone_project_id).toBe('projectId1');
+ expect(pdp.project.id).toBe('projectId1');
+
+ expect(service.policies.length).toBe(2);
+ var policy = service.policies[0];
+ expect(policy.id).toBe('policyId1');
+ expect(policy.name).toBe('policy1');
+ expect(policy.description).toBe('pDescription1');
+
+
+ expect(service.projects.length).toBe(2);
+ var project = service.projects[0];
+ expect(project.id).toBe('projectId1');
+ expect(project.name).toBe('project1');
+
+ });
+
+
+
+ it('should create pdp', function () {
+ var pdpCreatedData = {
+ pdps:
+ { 'pdpId1': { name: 'pdp1', description: 'pdpDescription1', security_pipeline: [], keystone_project_id: null } }
+ };
+
+ $httpBackend.expectPOST(URI.API + '/pdp').respond(200, pdpCreatedData);
+
+ service.createPdp({ name: 'pdp1', description: 'pdpDescription1' });
+ $httpBackend.flush();
+
+ expect(service.pdps.length).toBe(1);
+ var pdp = service.pdps[0];
+ expect(pdp.id).toBe('pdpId1');
+ expect(pdp.name).toBe('pdp1');
+ expect(pdp.description).toBe('pdpDescription1');
+ expect(pdp.project).toBe(null);
+ expect(pdp.security_pipeline.length).toBe(0);
+ });
+
+ it('should remove pdp', function () {
+ initData();
+ service.createPdps(pdpsData, policiesData, projectsData);
+
+ $httpBackend.expectDELETE(URI.API + '/pdp/pdpId1').respond(200);
+
+ service.removePdp({ id: 'pdpId1' });
+ $httpBackend.flush();
+
+ expect(service.pdps.length).toBe(0);
+ });
+
+ it('should update pdp', function () {
+ initData();
+ var pdpUpdatedData = {
+ pdps:
+ { 'pdpId1': { name: 'pdp2', description: 'pdpDescription2', security_pipeline: ['policyId2'], keystone_project_id: 'projectId2' } }
+ };
+ service.createPdps(pdpsData, policiesData, projectsData);
+
+ $httpBackend.expectPATCH(URI.API + '/pdp/pdpId1').respond(200, pdpUpdatedData);
+
+ service.updatePdp({ id: 'pdpId1', name: 'pdp2', description: 'pdpDescription2', security_pipeline: [service.getPolicy('policyId2')], project: service.getProject('projectId2') });
+ $httpBackend.flush();
+
+ expect(service.pdps.length).toBe(1);
+ var pdp = service.pdps[0];
+ expect(pdp.id).toBe('pdpId1');
+ expect(pdp.name).toBe('pdp2');
+ expect(pdp.description).toBe('pdpDescription2');
+ expect(pdp.project.id).toBe('projectId2');
+ expect(pdp.security_pipeline.length).toBe(1);
+ expect(pdp.security_pipeline[0].id).toBe('policyId2');
+
+ });
+
+
+ });
+
+
+})(); \ No newline at end of file
diff --git a/moon_dashboard/moon/static/moon/policy/policy.controller.js b/moon_dashboard/moon/static/moon/policy/policy.controller.js
new file mode 100644
index 00000000..6c6631cf
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/policy/policy.controller.js
@@ -0,0 +1,295 @@
+(function () {
+ 'use strict';
+
+ angular
+ .module('moon')
+ .controller('moon.policy.controller',
+ controller);
+
+ controller.$inject = ['moon.util.service', 'moon.policy.service', 'moon.model.service', 'horizon.framework.widgets.form.ModalFormService'];
+
+ function controller(util, policyService, modelService, ModalFormService) {
+ var self = this;
+ var genres = [{ value: 'admin', name: gettext('admin') }, { value: 'authz', name: gettext('authz') }];
+ self.model = policyService;
+ self.selectedRule = null;
+ self.currentData = null;
+ policyService.initialize();
+
+ var dataTitleMaps = {};
+
+ var categoryMap = {
+ subject: {
+ perimeterId: 'subject_id'
+ },
+ object: {
+ perimeterId: 'object_id'
+ },
+ action: {
+ perimeterId: 'action_id'
+ },
+ }
+
+ function createAddDataButton(type, index, category, config, policy) {
+ config.form.push({
+ "key": type + index + "Button",
+ "type": "button",
+ "title": "Add",
+ onClick: createDataFunction(type, category, policy)
+ })
+ }
+
+ function createDataFunction(type, category, policy) {
+ return function () {
+ var schema = {
+ type: "object",
+ properties: {
+ name: { type: "string", minLength: 2, title: gettext("Name") },
+ description: { type: "string", minLength: 2, title: gettext("Description") },
+ }
+ };
+ var data = { name: '', description: '' };
+ var config = {
+ title: gettext('Create Data of ' + category.name + ' category'),
+ schema: schema,
+ form: ['name', { key: 'description', type: 'textarea' }],
+ model: data
+ };
+ ModalFormService.open(config).then(submit);
+
+ function submit(form) {
+ policyService.createData(type, policy, category, form.model).then(
+ function (data) {
+ util.pushAll(dataTitleMaps[category.id], util.arrayToTitleMap(data));
+ }
+ );
+ }
+ }
+ }
+
+ function getOrCreateDataTitleMap(category, data, policy) {
+ var result = dataTitleMaps[category.id];
+ if (!result) {
+ result = util.arrayToTitleMap(data);
+ dataTitleMaps[category.id] = result;
+ }
+ return result;
+ }
+
+ function createDataSelect(type, categories, data, config, policy) {
+ for (var i = 0; i < categories.length; i++) {
+ var category = categories[i];
+ var titleMap = getOrCreateDataTitleMap(category, data, policy);
+ config.schema.properties[type + i] = { type: "string", title: gettext('Select ' + type + ' data of ' + category.name + ' category') };
+ config.form.push({ key: type + i, type: 'select', titleMap: titleMap });
+ createAddDataButton(type, i, category, config, policy);
+ }
+ }
+
+ function pushData(type, model, array) {
+ var i = 0;
+ while ((type + i) in model) {
+ array.push(model[type + i]);
+ i++;
+ }
+ }
+
+ self.createPolicy = function createPolicy() {
+ var schema = {
+ type: "object",
+ properties: {
+ name: { type: "string", minLength: 2, title: gettext("Name") },
+ description: { type: "string", minLength: 2, title: gettext("Description") },
+ genre: { type: "string", title: gettext("genre") },
+ model_id: { type: "string", title: gettext("Select a Model:") }
+ }
+ };
+ var policy = { name: '', description: '', model_id: null, genre: '' };
+ var titleMap = util.arrayToTitleMap(modelService.models)
+ var config = {
+ title: gettext('Create Policy'),
+ schema: schema,
+ form: ['name', { key: 'description', type: 'textarea' }, { key: 'genre', type: 'select', titleMap: genres }, { key: 'model_id', type: 'select', titleMap: titleMap }],
+ model: policy
+ };
+ ModalFormService.open(config).then(submit);
+
+ function submit(form) {
+ policyService.createPolicy(form.model);
+ }
+ }
+
+ self.updatePolicy = function updatePolicy(policy) {
+ var schema = {
+ type: "object",
+ properties: {
+ name: { type: "string", minLength: 2, title: gettext("Name") },
+ description: { type: "string", minLength: 2, title: gettext("Description") },
+ genre: { type: "string", title: gettext("Genre") },
+ }
+ };
+ var config = {
+ title: gettext('Update Policy'),
+ schema: schema,
+ form: ['name', { key: 'description', type: 'textarea' }, { key: 'genre', type: 'select', titleMap: genres }],
+ model: { name: policy.name, description: policy.description, model_id: policy.model_id, id: policy.id, genre: policy.genre }
+ };
+ ModalFormService.open(config).then(submit);
+
+ function submit(form) {
+ policyService.updatePolicy(form.model);
+ }
+ }
+
+ self.addRuleWithMetaRule = function addRuleWithMetaRule(policy, metaRule) {
+ var schema = {
+ type: "object",
+ properties: {
+ instructions: { type: "string", title: gettext("Instructions") }
+ }
+ };
+
+ var config = {
+ title: gettext('Add Rule'),
+ schema: schema,
+ form: [],
+ model: {
+ instructions: '[{"decision": "grant"}]'
+ }
+ };
+ dataTitleMaps = {};
+ createDataSelect('subject', metaRule.subject_categories, policy.subjectData, config, policy);
+ createDataSelect('object', metaRule.object_categories, policy.objectData, config, policy);
+ createDataSelect('action', metaRule.action_categories, policy.actionData, config, policy);
+ config.form.push({ key: 'instructions', type: 'textarea' })
+
+ ModalFormService.open(config).then(submit);
+
+ function submit(form) {
+ var rule = { enabled: true };
+ rule.instructions = JSON.parse(form.model.instructions);
+ rule.meta_rule_id = metaRule.id;
+ rule.policy_id = policy.id;
+ rule.rule = [];
+ pushData('subject', form.model, rule.rule);
+ pushData('object', form.model, rule.rule);
+ pushData('action', form.model, rule.rule);
+ policyService.addRuleToPolicy(policy, rule);
+ }
+ }
+
+ self.addRule = function addRule(policy) {
+ var schema = {
+ type: "object",
+ properties: {
+ metaRuleId: { type: "string", title: gettext("Select a Metarule:") }
+ }
+ };
+ var rule = { metaRuleId: null };
+ var titleMap = util.arrayToTitleMap(policy.model.meta_rules);
+ var config = {
+ title: gettext('Add Rule'),
+ schema: schema,
+ form: [{ key: 'metaRuleId', type: 'select', titleMap: titleMap }],
+ model: rule
+ };
+ ModalFormService.open(config).then(submit);
+
+ function submit(form) {
+ self.addRuleWithMetaRule(policy, modelService.getMetaRule(form.model.metaRuleId));
+ }
+ }
+
+ self.removePolicy = function removePolicy(policy) {
+ if (confirm(gettext('Are you sure to delete this Policy?')))
+ policyService.removePolicy(policy);
+ }
+
+ self.populatePolicy = function populatePolicy(policy) {
+ policyService.populatePolicy(policy);
+ }
+
+ self.removeRuleFromPolicy = function removeRuleFromPolicy(policy, rule) {
+ if (confirm(gettext('Are you sure to delete this Rule?')))
+ policyService.removeRuleFromPolicy(policy, rule);
+ }
+
+ self.showRule = function showRule(rule) {
+ self.selectedRule = rule;
+ }
+
+ self.hideRule = function hideRule() {
+ self.selectedRule = null;
+ self.currentData = null;
+ }
+
+ self.assignData = function assignData(type, policy, data) {
+ self.currentData = {
+ data: data,
+ type: type,
+ loading: true,
+ perimeters: [],
+ assignments: []
+ }
+
+ policyService.loadPerimetersAndAssignments(type, policy).then(function (values) {
+ var category = categoryMap[type];
+ self.currentData.loading = false;
+ self.currentData.perimeters = values.perimeters;
+ for (var index = 0; index < values.assignments.length; index++) {
+ var assignment = values.assignments[index];
+ if (assignment.assignments.indexOf(data.id) >= 0) {
+ var perimeter = values.perimetersMap[assignment[category.perimeterId]];
+ self.currentData.assignments.push(perimeter);
+ self.currentData.perimeters.splice(self.currentData.perimeters.indexOf(perimeter), 1);
+ }
+ }
+ })
+ }
+
+ self.createPerimeter = function createPerimeter(type, policy) {
+ var schema = {
+ type: "object",
+ properties: {
+ name: { type: "string", minLength: 2, title: gettext("Name") },
+ description: { type: "string", minLength: 2, title: gettext("Description") },
+ }
+ };
+ if (type == 'subject') {
+ schema.properties.email = { type: "email", "type": "string", "pattern": "^\\S+@\\S+$", title: gettext("Email") }
+ }
+ var perimeter = { name: '', description: '' };
+ var config = {
+ title: gettext('Create Perimeter'),
+ schema: schema,
+ form: ['name', { key: 'description', type: 'textarea' }],
+ model: perimeter
+ };
+ if (type == 'subject') {
+ config.form.push('email');
+ }
+
+ ModalFormService.open(config).then(submit);
+
+ function submit(form) {
+ policyService.createPerimeter(type, policy, form.model).then(function (perimeters) {
+ util.pushAll(self.currentData.perimeters, perimeters);
+ })
+ }
+ }
+
+ self.assign = function assign(type, policy, perimeter, data) {
+ policyService.createAssignment(type, policy, perimeter, data).then(function () {
+ self.currentData.assignments.push(perimeter);
+ self.currentData.perimeters.splice(self.currentData.perimeters.indexOf(perimeter), 1);
+ })
+ }
+
+ self.unassign = function unassign(type, policy, perimeter, data) {
+ policyService.removeAssignment(type, policy, perimeter, data).then(function () {
+ self.currentData.perimeters.push(perimeter);
+ self.currentData.assignments.splice(self.currentData.assignments.indexOf(perimeter), 1);
+ })
+ }
+ }
+})(); \ No newline at end of file
diff --git a/moon_dashboard/moon/static/moon/policy/policy.html b/moon_dashboard/moon/static/moon/policy/policy.html
new file mode 100644
index 00000000..70789fbb
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/policy/policy.html
@@ -0,0 +1,158 @@
+<div ng-controller="moon.policy.controller as ctrl">
+ <div class="clearfix list-group">
+ <div class="pull-right">
+ <input type="search" class="form-control filter" placeholder="Filter" ng-model="filterText">
+ <button type="button" class="btn btn-default" ng-click="ctrl.createPolicy()">
+ <span class="fa fa-plus"></span>
+ <translate>Create Policy</translate>
+ </button>
+ </div>
+ </div>
+
+ <div class="list-group">
+ <div ng-repeat="policy in ctrl.model.policies | orderBy:'name' | filter:filterText" class="list-group-item">
+ <h3 class="list-group-item-heading inline">{$ policy.name $}</h3>
+ <div class="pull-right">
+ <button type="button" class="fa fa-trash" title="{$ 'Remove Policy' | translate $}" ng-click="ctrl.removePolicy(policy)"></button>
+ <button type="button" class="fa fa-edit" title="{$ 'Edit Policy' | translate $}" ng-click="ctrl.updatePolicy(policy)"></button>
+ </div>
+ <p class="list-group-item-text">{$ policy.description $}</p>
+ <h4 class="list-group-item-text">
+ <translate>Model: {$ policy.model ? policy.model.name : 'none' $}</translate>
+ </h4>
+ <h4 class="list-group-item-text">
+ <translate>Genre:</translate>
+ <translate>{$ policy.genre ? policy.genre : 'none' $}</translate>
+ </h4>
+ <details class="list-group-item-text">
+ <summary ng-click="ctrl.populatePolicy(policy)">
+ <h4 class="inline" translate>Rules</h4>
+ <button type="button" class="fa fa-plus " ng-click="ctrl.addRule(policy)" title="{$ 'Add Rule' | translate $}"></button>
+ </summary>
+ <div class="list-group">
+ <p ng-if="!policy.rules" class="list-group-item-text" translate>Loading rules...</p>
+ <div ng-if="policy.rules" ng-repeat="rule in policy.rules | orderBy:'name'" class="list-group-item">
+ <div class="list-group-item-heading" ng-if="ctrl.selectedRule != rule">
+ <div class="inline-block width-200">
+ <b>
+ <translate>Metarule: </translate>
+ </b> {$ rule.metaRule.name $}
+ </div>
+ <b>
+ <translate>Rule: </translate>
+ </b>
+ <span ng-repeat="data in rule.subjectData">
+ <span>{$ data.name $}{$ $last ? '' : ', ' $}</span>
+ </span> |
+ <span ng-repeat="data in rule.actionData">
+ <span>{$ data.name $}{$ $last ? '' : ', ' $}</span>
+ </span> |
+ <span ng-repeat="data in rule.objectData">
+ <span>{$ data.name $}{$ $last ? '' : ', ' $}</span>
+ </span>
+ <div class="pull-right">
+ <button type="button" class="fa fa-trash pull-right" ng-click="ctrl.removeRuleFromPolicy(policy, rule)" title="{$ 'Remove Rule' | translate $}"></button>
+ <button type="button" class="fa fa-eye pull-right" ng-click="ctrl.showRule(rule)" title="{$ 'Show Rule' | translate $}"></button>
+ </div>
+ </div>
+
+ <div ng-if="ctrl.selectedRule == rule">
+ <h3 class="list-group-item-heading inline">
+ <translate>Metarule: </translate> {$ rule.metaRule.name $}</h3>
+ <div class="pull-right">
+ <button type="button" class="fa fa-trash pull-right" ng-click="ctrl.removeRuleFromPolicy(policy, rule)" title="{$ 'Remove Rule' | translate $}"></button>
+ <button type="button" class="fa fa-eye-slash pull-right" ng-click="ctrl.hideRule()" title="{$ 'Hide Rule' | translate $}"></button>
+ </div>
+ <p class="list-group-item-text">
+ <table class="table">
+ <thead>
+ <tr>
+ <th>
+ <span translate>Subjects</span>
+ </th>
+ <th>
+ <span translate>Objects</span>
+ </th>
+ <th>
+ <span translate>Actions</span>
+ </th>
+ <th>
+ <span translate>Instructions</span>
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>
+ <p ng-repeat="data in rule.subjectData">
+ <span ng-class="{'text-primary': ctrl.currentData.data == data}">{$ data.name $}</span>
+ <button ng-if="ctrl.currentData.data != data" type="button" class="fa fa-exchange pull-right" ng-click="ctrl.assignData('subject', policy, data)"
+ title="{$ 'Assign to perimeters' | translate $}"></button>
+ <button ng-if="ctrl.currentData.data == data" type="button" class="fa fa-times pull-right" ng-click="ctrl.currentData = null"
+ title="{$ 'Close' | translate $}"></button>
+ </p>
+ </td>
+ <td>
+ <p ng-repeat="data in rule.objectData">
+ <span ng-class="{'text-primary': ctrl.currentData.data == data}">{$ data.name $}</span>
+ <button ng-if="ctrl.currentData.data != data" type="button" class="fa fa-exchange pull-right" ng-click="ctrl.assignData('object', policy, data)"
+ title="{$ 'Assign to perimeters' | translate $}"></button>
+ <button ng-if="ctrl.currentData.data == data" type="button" class="fa fa-times pull-right" ng-click="ctrl.currentData = null"
+ title="{$ 'Close' | translate $}"></button>
+ </p>
+ </td>
+ <td>
+ <p ng-repeat="data in rule.actionData">
+ <span ng-class="{'text-primary': ctrl.currentData.data == data}">{$ data.name $}</span>
+ <button ng-if="ctrl.currentData.data != data" type="button" class="fa fa-exchange pull-right" ng-click="ctrl.assignData('action', policy, data)"
+ title="{$ 'Assign to perimeters' | translate $}"></button>
+ <button ng-if="ctrl.currentData.data == data" type="button" class="fa fa-times pull-right" ng-click="ctrl.currentData = null"
+ title="{$ 'Close' | translate $}"></button>
+ </p>
+ </td>
+ <td>
+ <pre ng-bind="rule.instructions | json "></pre>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ <div ng-if="ctrl.currentData && ctrl.currentData.loading" class="row padding-10">
+ <h4 translate>Loading...</h4>
+ </div>
+ <div ng-if="ctrl.currentData && !ctrl.currentData.loading" class="row">
+ <div class="padding-10">
+ <h3>
+ <translate>Assign perimeters to</translate> {$ ctrl.currentData.data.name $}</h3>
+ <input type="search" class="form-control filter" placeholder="Filter" ng-model="filterPerimeter">
+ <button type="button" class="btn btn-default" ng-click="ctrl.createPerimeter(ctrl.currentData.type, policy)">
+ <span class="fa fa-plus"></span>
+ <translate>Create Perimeter</translate>
+ </button>
+ </div>
+ <div>
+ <div class="col-lg-4">
+ <h4 translate>Available perimeters</h4>
+ <div class="w-100 height-200 scroll list-group border">
+ <button class="list-group-item" ng-repeat="perimeter in ctrl.currentData.perimeters | orderBy:'name' | filter:filterPerimeter" title="{$ perimeter.description $}"
+ ng-click="ctrl.assign(ctrl.currentData.type, policy, perimeter, ctrl.currentData.data)">{$ perimeter.name $}</button>
+ </div>
+ <p translate class="mt-5">Click to assign</p>
+ </div>
+ <div class="col-lg-4">
+ <h4 translate>Assigned perimeters</h4>
+ <div class="w-100 list-group border height-200 scroll">
+ <button class="list-group-item" ng-repeat="perimeter in ctrl.currentData.assignments | orderBy:'name' | filter:filterPerimeter" title="{$ perimeter.description $}"
+ ng-click="ctrl.unassign(ctrl.currentData.type, policy, perimeter, ctrl.currentData.data)">{$ perimeter.name $}</button>
+ </div>
+ <p translate class="mt-5">Click to unassign</p>
+ </div>
+ </div>
+ </div>
+ </p>
+ </div>
+ </div>
+ </div>
+ </details>
+ </div>
+ </div>
+</div> \ No newline at end of file
diff --git a/moon_dashboard/moon/static/moon/policy/policy.service.js b/moon_dashboard/moon/static/moon/policy/policy.service.js
new file mode 100755
index 00000000..87250b2e
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/policy/policy.service.js
@@ -0,0 +1,330 @@
+(function () {
+
+ 'use strict';
+
+ angular
+ .module('moon')
+ .factory('moon.policy.service', policyService);
+
+ policyService.$inject = ['moon.util.service', 'moon.model.service', '$resource', 'moon.URI', '$q', 'horizon.framework.widgets.toast.service'];
+
+ function policyService(util, modelService, $resource, URI, $q, toast) {
+ var host = URI.API;
+
+ var policyResource = $resource(host + '/policies/' + ':id', {}, {
+ get: { method: 'GET' },
+ query: { method: 'GET' },
+ create: { method: 'POST' },
+ remove: { method: 'DELETE' },
+ update: { method: 'PATCH' }
+ });
+
+ var policyRulesResource = $resource(host + '/policies/' + ':policy_id' + '/rules/' + ':rule_id', {}, {
+ get: { method: 'GET' },
+ query: { method: 'GET' },
+ create: { method: 'POST' },
+ remove: { method: 'DELETE' }
+ });
+
+ var policySubjectDataResource = $resource(host + '/policies/' + ':policy_id' + '/subject_data/' + ':category_id', {}, {
+ query: {method: 'GET'},
+ create: { method: 'POST' },
+ })
+
+ var policyObjectDataResource = $resource(host + '/policies/' + ':policy_id' + '/object_data/' + ':category_id', {}, {
+ query: {method: 'GET'},
+ create: { method: 'POST' },
+ })
+
+ var policyActionDataResource = $resource(host + '/policies/' + ':policy_id' + '/action_data/' + ':category_id', {}, {
+ query: {method: 'GET'},
+ create: { method: 'POST' },
+ })
+
+ var policySubjectPerimetersResource = $resource(host + '/policies/' + ':policy_id' + '/subjects', {}, {
+ query: {method: 'GET'},
+ create: { method: 'POST' },
+ })
+
+ var policyObjectPerimetersResource = $resource(host + '/policies/' + ':policy_id' + '/objects', {}, {
+ query: {method: 'GET'},
+ create: { method: 'POST' },
+ })
+
+ var policyActionPerimetersResource = $resource(host + '/policies/' + ':policy_id' + '/actions', {}, {
+ query: {method: 'GET'},
+ create: { method: 'POST' },
+ })
+
+ var policySubjectAssignmentsResource = $resource(host + '/policies/' + ':policy_id' + '/subject_assignments/' + ':perimeter_id' + '/' + ':category_id' + '/' + ':data_id', {}, {
+ query: {method: 'GET'},
+ create: { method: 'POST' },
+ remove: { method: 'DELETE' }
+ })
+
+ var policyObjectAssignmentsResource = $resource(host + '/policies/' + ':policy_id' + '/object_assignments/' + ':perimeter_id' + '/' + ':category_id' + '/' + ':data_id', {}, {
+ query: {method: 'GET'},
+ create: { method: 'POST' },
+ remove: { method: 'DELETE' }
+ })
+
+ var policyActionAssignmentsResource = $resource(host + '/policies/' + ':policy_id' + '/action_assignments/' + ':perimeter_id' + '/' + ':category_id' + '/' + ':data_id', {}, {
+ query: {method: 'GET'},
+ create: { method: 'POST' },
+ remove: { method: 'DELETE' }
+ })
+
+
+ var categoryMap = {
+ 'subject': {
+ resource: policySubjectDataResource,
+ arrayName: "subjectData",
+ mapName: "subjectDataMap",
+ responseName: "subject_data",
+ perimeterResource: policySubjectPerimetersResource,
+ assignmentResource: policySubjectAssignmentsResource,
+ perimeterResponseName: "subjects",
+ assignmentResponseName: "subject_assignments",
+ },
+ 'object': {
+ resource: policyObjectDataResource,
+ arrayName: "objectData",
+ mapName: "objectDataMap",
+ responseName: "object_data",
+ perimeterResource: policyObjectPerimetersResource,
+ assignmentResource: policyObjectAssignmentsResource,
+ perimeterResponseName: "objects",
+ assignmentResponseName: "object_assignments",
+ },
+ 'action': {
+ resource: policyActionDataResource,
+ arrayName: "actionData",
+ mapName: "actionDataMap",
+ responseName: "action_data",
+ perimeterResource: policyActionPerimetersResource,
+ assignmentResource: policyActionAssignmentsResource,
+ perimeterResponseName: "actions",
+ assignmentResponseName: "action_assignments",
+ }
+ }
+
+ var policiesMap = {};
+ var policies = [];
+
+ function loadPolicies() {
+ var queries = {
+ policies: policyResource.query().$promise,
+ models: modelService.initialize(),
+ }
+
+ $q.all(queries).then(function (result) {
+ createPolicies(result.policies);
+ console.log('moon', 'policies initialized')
+ })
+ }
+
+ function createPolicies(policiesData) {
+ policies.splice(0, policies.length);
+ util.cleanObject(policiesMap);
+ createPolicyInternal(policiesData.policies);
+ }
+
+ function mapPolicy(policy) {
+ if (policy.model_id) {
+ policy.model = modelService.getModel(policy.model_id);
+ }
+ }
+
+ function createPolicyInternal(data) {
+ return util.createInternal(data, policies, policiesMap, mapPolicy);
+ }
+
+ function removePolicyInternal(id) {
+ return util.removeInternal(id, policies, policiesMap);
+ }
+
+ function updatePolicyInternal(data) {
+ return util.updateInternal(data, policiesMap, mapPolicy);
+ }
+
+ function removeRuleInternal(policy, rule) {
+ policy.rules.splice(policy.rules.indexOf(rule), 1);
+ }
+
+ function loadPolicyRule(policy) {
+ if (!policy.rules) {
+ var queries = {
+ rules: policyRulesResource.query({ policy_id: policy.id }).$promise,
+ subjectData: policySubjectDataResource.query({ policy_id: policy.id }).$promise,
+ objectData: policyObjectDataResource.query({ policy_id: policy.id }).$promise,
+ actionData: policyActionDataResource.query({ policy_id: policy.id }).$promise,
+ }
+
+ $q.all(queries).then(function (result) {
+ createRules(policy, result.rules, result.subjectData, result.objectData, result.actionData)
+ }, util.displayErrorFunction('Unable to load rules'))
+ }
+ }
+
+ function createRules(policy, rulesData, subjectsData, objectsData, actionsData) {
+ policy.rules = rulesData ? rulesData.rules.rules : [];
+ policy.subjectDataMap = subjectsData.subject_data.length > 0 ? subjectsData.subject_data[0].data : [];
+ policy.subjectData = util.mapToArray(policy.subjectDataMap);
+ policy.objectDataMap = objectsData.object_data.length > 0 ? objectsData.object_data[0].data : [];
+ policy.objectData = util.mapToArray(policy.objectDataMap);
+ policy.actionDataMap = actionsData.action_data.length > 0 ? actionsData.action_data[0].data : [];
+ policy.actionData = util.mapToArray(policy.actionDataMap);
+ for (var i = 0; i < policy.rules.length; i++) {
+ var rule = policy.rules[i];
+ populateRule(policy, rule);
+ }
+ }
+
+ function populateRule(policy, rule) {
+ if (rule.meta_rule_id) {
+ rule.metaRule = modelService.getMetaRule(rule.meta_rule_id);
+ }
+ if (rule.metaRule) {
+ var j = 0;
+ var k, id;
+ rule.subjectData = [];
+ rule.objectData = [];
+ rule.actionData = [];
+ for (k = 0; k < rule.metaRule.subject_categories.length; k++) {
+ id = rule.rule[j + k];
+ rule.subjectData.push(policy.subjectDataMap[id]);
+ }
+ j += k;
+ for (k = 0; k < rule.metaRule.object_categories.length; k++) {
+ id = rule.rule[j + k];
+ rule.objectData.push(policy.objectDataMap[id]);
+ }
+ j += k;
+ for (k = 0; k < rule.metaRule.action_categories.length; k++) {
+ id = rule.rule[j + k];
+ rule.actionData.push(policy.actionDataMap[id]);
+ }
+ }
+ return rule;
+ }
+
+ return {
+ initialize: loadPolicies,
+ createPolicies: createPolicies,
+ policies: policies,
+ getPolicy: function getPolicy(id) {
+ return policiesMap[id];
+ },
+ createPolicy: function createPolicy(policy) {
+ policyResource.create(null, policy, success, util.displayErrorFunction('Unable to create Policy'));
+
+ function success(data) {
+ createPolicyInternal(data.policies);
+ util.displaySuccess('Policy created');
+ }
+ },
+ removePolicy: function removePolicy(policy) {
+ policyResource.remove({ id: policy.id }, null, success, util.displayErrorFunction('Unable to remove Policy'));
+
+ function success(data) {
+ removePolicyInternal(policy.id);
+ util.displaySuccess('Policy removed');
+ }
+ },
+ updatePolicy: function updatePolicy(policy) {
+ policyResource.update({ id: policy.id }, policy, success, util.displayErrorFunction('Unable to update Policy'));
+
+ function success(data) {
+ updatePolicyInternal(data.policies)
+ util.displaySuccess('Policy updated');
+ }
+ },
+ populatePolicy: loadPolicyRule,
+ createRules: createRules,
+ addRuleToPolicy: function addRuleToPolicy(policy, rule) {
+ policyRulesResource.create({ policy_id: policy.id }, rule, success, util.displayErrorFunction('Unable to create Rule'));
+
+ function success(data) {
+ var rules = util.mapToArray(data.rules);
+ for (var i = 0; i < rules.length; i++) {
+ var rule = rules[i];
+ policy.rules.push(populateRule(policy, rule))
+ }
+ util.displaySuccess('Rule created');
+ }
+ },
+ removeRuleFromPolicy: function removeRuleFromPolicy(policy, rule) {
+ policyRulesResource.remove({ policy_id: policy.id, rule_id: rule.id }, null, success, util.displayErrorFunction('Unable to remove Rule'));
+
+ function success(data) {
+ removeRuleInternal(policy, rule);
+ util.displaySuccess('Rule removed');
+ }
+ },
+ createData: function createData(type, policy, category, dataCategory) {
+ var categoryValue = categoryMap[type];
+ return categoryValue.resource.create({ policy_id: policy.id, category_id: category.id }, dataCategory).$promise.then(
+ function (data) {
+ var result = util.createInternal(data[categoryValue.responseName].data, policy[categoryValue.arrayName], policy[categoryValue.mapName]);
+ util.displaySuccess('Data created');
+ return result;
+ },
+ util.displayErrorFunction('Unable to create Data')
+ );
+ },
+ createPerimeter: function createPerimeter(type, policy, perimeter) {
+ var categoryValue = categoryMap[type];
+ return categoryValue.perimeterResource.create({ policy_id: policy.id }, perimeter).$promise.then(
+ function (data) {
+ util.displaySuccess('Perimeter created');
+ return util.mapToArray(data[categoryValue.perimeterResponseName]);
+ },
+ util.displayErrorFunction('Unable to create Perimeter')
+ );
+ },
+ loadPerimetersAndAssignments: function loadPerimetersAndAssignments(type, policy) {
+ var categoryValue = categoryMap[type];
+ var queries = {
+ perimeters: categoryValue.perimeterResource.query({ policy_id: policy.id }).$promise,
+ assignments: categoryValue.assignmentResource.query({ policy_id: policy.id }).$promise,
+ }
+
+ return $q.all(queries).then(function (data) {
+ var result = {};
+ result.assignments = util.mapToArray(data.assignments[categoryValue.assignmentResponseName]);
+ result.perimetersMap = data.perimeters[categoryValue.perimeterResponseName];
+ result.perimeters = util.mapToArray(result.perimetersMap);
+ return result;
+ }, util.displayErrorFunction('Unable to load Perimeters'))
+
+ },
+ createAssignment: function createAssignment(type, policy, perimeter, data) {
+ var categoryValue = categoryMap[type];
+ var assignment = {
+ "id": perimeter.id,
+ "category_id": data.category_id,
+ "data_id": data.id,
+ "policy_id": policy.id
+ }
+ return categoryValue.assignmentResource.create({ policy_id: policy.id }, assignment).$promise.then(
+ function (data) {
+ util.displaySuccess('Assignment created');
+ return util.mapToArray(data[categoryValue.assignmentResponseName]);
+ },
+ util.displayErrorFunction('Unable to create Assignment')
+ )
+ },
+ removeAssignment: function removeAssignment(type, policy, perimeter, data) {
+ var categoryValue = categoryMap[type];
+
+ return categoryValue.assignmentResource.remove({ policy_id: policy.id, perimeter_id: perimeter.id, category_id: data.category_id, data_id: data.id }, null).$promise.then(
+ function (data) {
+ util.displaySuccess('Assignment removed');
+ },
+ util.displayErrorFunction('Unable to remove Assignment')
+ )
+ },
+ }
+
+ }
+})(); \ No newline at end of file
diff --git a/moon_dashboard/moon/static/moon/policy/policy.service.spec.js b/moon_dashboard/moon/static/moon/policy/policy.service.spec.js
new file mode 100755
index 00000000..045bf9b3
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/policy/policy.service.spec.js
@@ -0,0 +1,336 @@
+(function () {
+ 'use strict';
+
+ describe('moon.policy.service', function () {
+ var service, modelService, $httpBackend, URI;
+ var policiesData;
+ var modelsData, metaRulesData, subjectCategoriesData, objectCategoriesData, actionCategoriesData;
+ var rulesData, subjectsData, objectsData, actionsData;
+
+
+ function initData() {
+ policiesData = {
+ policies:
+ {
+ 'policyId1': { name: 'policy1', description: 'pDescription1', genre: 'genre1', model_id: 'modelId1' },
+ }
+ };
+
+ modelsData = {
+ models:
+ { 'modelId1': { name: 'model1', description: 'mDescription1', meta_rules: ['metaRuleId1'] } }
+ };
+
+ subjectCategoriesData = {
+ subject_categories:
+ {
+ 'subjectCategoryId1': { name: 'subjectCategory1', description: 'scDescription1' },
+ 'subjectCategoryId2': { name: 'subjectCategory2', description: 'scDescription2' }
+ },
+ };
+ objectCategoriesData = {
+ object_categories:
+ {
+ 'objectCategoryId1': { name: 'objectCategory1', description: 'ocDescription1' },
+ 'objectCategoryId2': { name: 'objectCategory2', description: 'ocDescription2' }
+ }
+ };
+ actionCategoriesData = {
+ action_categories:
+ {
+ 'actionCategoryId1': { name: 'actionCategory1', description: 'acDescription1' },
+ 'actionCategoryId2': { name: 'actionCategory2', description: 'acDescription2' }
+ }
+ };
+ metaRulesData = {
+ meta_rules:
+ {
+ 'metaRuleId1': { name: 'metaRule1', description: 'mrDescription1', subject_categories: ['subjectCategoryId1'], object_categories: ['objectCategoryId1'], action_categories: ['actionCategoryId1'] },
+ 'metaRuleId2': { name: 'metaRule2', description: 'mrDescription2', subject_categories: [], object_categories: [], action_categories: [] }
+ }
+ };
+ }
+
+ function initRuleData() {
+ rulesData = {
+ rules: {
+ rules: [
+ { meta_rule_id: 'metaRuleId1', rule: ['subjectId1', 'objectId1', 'actionId1'], id: 'ruleId1', instructions: { test: 'test' } }
+ ]
+ }
+ };
+
+ subjectsData = {
+ subject_data:
+ [
+ {
+ data: {
+ 'subjectId1': { name: 'subject1', description: 'sDescription1' },
+ }
+ }
+ ]
+ };
+ objectsData = {
+ object_data:
+ [
+ {
+ data: {
+ 'objectId1': { name: 'object1', description: 'oDescription1' },
+ }
+ }
+ ]
+ };
+ actionsData = {
+ action_data:
+ [
+ {
+ data: {
+ 'actionId1': { name: 'action1', description: 'aDescription1' },
+ }
+ }
+ ]
+ };
+ }
+
+ beforeEach(module('horizon.app.core'));
+ beforeEach(module('horizon.framework'));
+ beforeEach(module('moon'));
+
+ beforeEach(inject(function ($injector) {
+ service = $injector.get('moon.policy.service');
+ modelService = $injector.get('moon.model.service');
+ $httpBackend = $injector.get('$httpBackend');
+ URI = $injector.get('moon.URI');
+ }));
+
+ afterEach(function () {
+ $httpBackend.verifyNoOutstandingExpectation();
+ $httpBackend.verifyNoOutstandingRequest();
+ });
+
+ it('should initialize', function () {
+ initData();
+ $httpBackend.expectGET(URI.API + '/policies').respond(200, policiesData);
+ $httpBackend.expectGET(URI.API + '/subject_categories').respond(200, subjectCategoriesData);
+ $httpBackend.expectGET(URI.API + '/object_categories').respond(200, objectCategoriesData);
+ $httpBackend.expectGET(URI.API + '/action_categories').respond(200, actionCategoriesData);
+ $httpBackend.expectGET(URI.API + '/meta_rules').respond(200, metaRulesData);
+ $httpBackend.expectGET(URI.API + '/models').respond(200, modelsData);
+
+
+ service.initialize();
+ $httpBackend.flush();
+
+ expect(service.policies.length).toBe(1);
+ var policy = service.policies[0];
+ expect(policy.id).toBe('policyId1');
+ expect(policy.name).toBe('policy1');
+ expect(policy.description).toBe('pDescription1');
+ expect(policy.genre).toBe('genre1');
+ expect(policy.model.id).toBe('modelId1');
+
+ });
+
+
+
+ it('should create policy', function () {
+ initData();
+ modelService.createModels(modelsData, metaRulesData, subjectCategoriesData, objectCategoriesData, actionCategoriesData);
+
+ var policyCreatedData = {
+ policies:
+ { 'policyId1': { name: 'policy1', description: 'pDescription1', genre: 'genre1', model_id: 'modelId1' } }
+ };
+
+ $httpBackend.expectPOST(URI.API + '/policies').respond(200, policyCreatedData);
+
+ service.createPolicy({ name: 'policy1', description: 'pDescription1', genre: 'genre1', model: modelService.getModel('modelId1') });
+ $httpBackend.flush();
+
+ expect(service.policies.length).toBe(1);
+ var policy = service.policies[0];
+ expect(policy.id).toBe('policyId1');
+ expect(policy.name).toBe('policy1');
+ expect(policy.description).toBe('pDescription1');
+ expect(policy.genre).toBe('genre1');
+ expect(policy.model.id).toBe('modelId1');
+ });
+
+ it('should remove policy', function () {
+ initData();
+ modelService.createModels(modelsData, metaRulesData, subjectCategoriesData, objectCategoriesData, actionCategoriesData);
+ service.createPolicies(policiesData);
+
+ $httpBackend.expectDELETE(URI.API + '/policies/policyId1').respond(200);
+
+ service.removePolicy({ id: 'policyId1' });
+ $httpBackend.flush();
+
+ expect(service.policies.length).toBe(0);
+ });
+
+ it('should update policy', function () {
+ initData();
+ var policyUpdatedData = {
+ policies:
+ { 'policyId1': { name: 'policy2', description: 'pDescription2', genre: 'genre2', model_id: 'modelId1' } }
+ };
+ modelService.createModels(modelsData, metaRulesData, subjectCategoriesData, objectCategoriesData, actionCategoriesData);
+ service.createPolicies(policiesData);
+
+ $httpBackend.expectPATCH(URI.API + '/policies/policyId1').respond(200, policyUpdatedData);
+
+ service.updatePolicy({ id: 'policyId1', name: 'policy2', description: 'pDescription2', genre: 'genre2', model: modelService.getModel('modelId1') });
+ $httpBackend.flush();
+
+ expect(service.policies.length).toBe(1);
+ var policy = service.policies[0];
+ expect(policy.id).toBe('policyId1');
+ expect(policy.name).toBe('policy2');
+ expect(policy.description).toBe('pDescription2');
+ expect(policy.genre).toBe('genre2');
+ expect(policy.model.id).toBe('modelId1');
+
+ });
+
+
+ it('should populate policy', function () {
+ initData();
+ initRuleData();
+ modelService.createModels(modelsData, metaRulesData, subjectCategoriesData, objectCategoriesData, actionCategoriesData);
+ service.createPolicies(policiesData);
+
+ var policy = service.getPolicy('policyId1')
+
+ $httpBackend.expectGET(URI.API + '/policies/policyId1/rules').respond(200, rulesData);
+ $httpBackend.expectGET(URI.API + '/policies/policyId1/subject_data').respond(200, subjectsData);
+ $httpBackend.expectGET(URI.API + '/policies/policyId1/object_data').respond(200, objectsData);
+ $httpBackend.expectGET(URI.API + '/policies/policyId1/action_data').respond(200, actionsData);
+
+ service.populatePolicy(policy);
+ $httpBackend.flush();
+
+ expect(policy.rules.length).toBe(1);
+ var rule = policy.rules[0];
+ expect(rule.id).toBe('ruleId1');
+ expect(rule.metaRule.id).toBe('metaRuleId1');
+ expect(rule.instructions.test).toBe('test');
+ expect(rule.subjectData.length).toBe(1);
+ expect(rule.subjectData[0].id).toBe('subjectId1');
+ expect(rule.objectData.length).toBe(1);
+ expect(rule.objectData[0].id).toBe('objectId1');
+ expect(rule.actionData.length).toBe(1);
+ expect(rule.actionData[0].id).toBe('actionId1');
+
+ expect(policy.subjectData.length).toBe(1);
+ var subjectData = policy.subjectData[0];
+ expect(subjectData.id).toBe('subjectId1');
+ expect(subjectData.name).toBe('subject1');
+ expect(subjectData.description).toBe('sDescription1');
+
+ expect(policy.objectData.length).toBe(1);
+ var objectData = policy.objectData[0];
+ expect(objectData.id).toBe('objectId1');
+ expect(objectData.name).toBe('object1');
+ expect(objectData.description).toBe('oDescription1');
+
+ expect(policy.actionData.length).toBe(1);
+ var actionData = policy.actionData[0];
+ expect(actionData.id).toBe('actionId1');
+ expect(actionData.name).toBe('action1');
+ expect(actionData.description).toBe('aDescription1');
+
+ });
+
+
+ it('should add rule to policy', function () {
+ initData();
+ initRuleData();
+ modelService.createModels(modelsData, metaRulesData, subjectCategoriesData, objectCategoriesData, actionCategoriesData);
+ service.createPolicies(policiesData);
+
+
+ var ruleCreatedData = {
+ rules: {
+ 'ruleId1': { meta_rule_id: 'metaRuleId1', rule: ['subjectId1', 'objectId1', 'actionId1'], instructions: { test: 'test' } }
+ }
+ };
+
+ var policy = service.getPolicy('policyId1');
+
+ service.createRules(policy, null, subjectsData, objectsData, actionsData);
+
+ $httpBackend.expectPOST(URI.API + '/policies/policyId1/rules').respond(200, ruleCreatedData);
+
+ service.addRuleToPolicy(policy, { meta_rule_id: 'metaRuleId1', rule: ['subjectId1', 'objectId1', 'actionId1'], instructions: { test: 'test' } });
+ $httpBackend.flush();
+
+ expect(policy.rules.length).toBe(1);
+ var rule = policy.rules[0];
+ expect(rule.id).toBe('ruleId1');
+ expect(rule.metaRule.id).toBe('metaRuleId1');
+ expect(rule.subjectData.length).toBe(1);
+ expect(rule.subjectData[0].id).toBe('subjectId1');
+ expect(rule.objectData.length).toBe(1);
+ expect(rule.objectData[0].id).toBe('objectId1');
+ expect(rule.actionData.length).toBe(1);
+ expect(rule.actionData[0].id).toBe('actionId1');
+
+ });
+
+ it('should remove rule from policy', function () {
+ initData();
+ initRuleData();
+ modelService.createModels(modelsData, metaRulesData, subjectCategoriesData, objectCategoriesData, actionCategoriesData);
+ service.createPolicies(policiesData);
+
+ var policy = service.getPolicy('policyId1');
+
+ service.createRules(policy, rulesData, subjectsData, objectsData, actionsData);
+
+ $httpBackend.expectDELETE(URI.API + '/policies/policyId1/rules/ruleId1').respond(200);
+
+ service.removeRuleFromPolicy(policy, { id: 'ruleId1' });
+ $httpBackend.flush();
+
+ expect(policy.rules.length).toBe(0);
+ });
+
+
+ it('should create data', function () {
+ initData();
+ initRuleData();
+ modelService.createModels(modelsData, metaRulesData, subjectCategoriesData, objectCategoriesData, actionCategoriesData);
+ service.createPolicies(policiesData);
+
+
+ var dataCreatedData = {
+ subject_data: {
+ data: {
+ 'subjectId1': { name: 'subject1', description: 'sDescription1' },
+ }
+ }
+ };
+
+ var policy = service.getPolicy('policyId1');
+ policy.subjectData = [];
+ policy.subjectDataMap = {};
+
+ $httpBackend.expectPOST(URI.API + '/policies/policyId1/subject_data/subjectCategoryId1').respond(200, dataCreatedData);
+
+ service.createData('subject', policy, modelService.getCategory('subject', 'subjectCategoryId1'), { name: 'subject1', description: 'sDescription1' });
+ $httpBackend.flush();
+
+ expect(policy.subjectData.length).toBe(1);
+ var subjectData = policy.subjectData[0];
+ expect(subjectData.id).toBe('subjectId1');
+ expect(subjectData.name).toBe('subject1');
+ expect(subjectData.description).toBe('sDescription1');
+
+ });
+
+
+ });
+
+
+})(); \ No newline at end of file
diff --git a/moon_dashboard/moon/static/moon/scss/moon.scss b/moon_dashboard/moon/static/moon/scss/moon.scss
new file mode 100644
index 00000000..20bf6c41
--- /dev/null
+++ b/moon_dashboard/moon/static/moon/scss/moon.scss
@@ -0,0 +1,54 @@
+.inline {
+ display: inline;
+}
+
+.inline-block {
+ display: inline-block;
+}
+
+summary{
+ outline:none;
+ margin-bottom: 10px;
+}
+
+details {
+ cursor: default;
+}
+
+.filter {
+ display: inline-block;
+ width: auto;
+ vertical-align: middle;
+}
+
+.categories td {
+ width: 33%;
+}
+
+.width-200 {
+ width: 200px;
+}
+
+.height-200 {
+ height: 200px;
+}
+
+.border {
+ border: 1px #DDD solid;
+}
+
+.padding-10 {
+ padding: 10px;
+}
+
+.scroll {
+ overflow-y: auto;
+}
+
+.mt-5 {
+ margin-top: 5px;
+}
+
+.input-file {
+ display: none !important;
+} \ No newline at end of file
diff --git a/moon_dashboard/moon/templates/moon/base.html b/moon_dashboard/moon/templates/moon/base.html
new file mode 100644
index 00000000..f07a01ba
--- /dev/null
+++ b/moon_dashboard/moon/templates/moon/base.html
@@ -0,0 +1,11 @@
+{% load horizon %}{% jstemplate %}[% extends 'base.html' %]
+
+[% block sidebar %]
+ [% include 'horizon/common/_sidebar.html' %]
+[% endblock %]
+
+[% block main %]
+ [% include "horizon/_messages.html" %]
+ [% block {{ dash_name }}_main %][% endblock %]
+[% endblock %]
+{% endjstemplate %}
diff --git a/moon_dashboard/run.sh b/moon_dashboard/run.sh
new file mode 100644
index 00000000..bf18faa2
--- /dev/null
+++ b/moon_dashboard/run.sh
@@ -0,0 +1,26 @@
+#!/bin/sh
+# sudo docker run -ti --rm -p 8000:8000 -e MANAGER_HOST=localhost -e MANAGER_PORT=30001 -e KEYSTONE_HOST=localhost -e KEYSTONE_PORT=30005 moonplatform/dashboard:dev
+
+CONSTANT_FILE=/root/horizon/openstack_dashboard/dashboards/moon/static/moon/js/moon.module.js
+
+sed "s/{{MANAGER_HOST}}/$MANAGER_HOST/g" -i $CONSTANT_FILE
+sed "s/{{MANAGER_PORT}}/$MANAGER_PORT/g" -i $CONSTANT_FILE
+sed "s/{{KEYSTONE_HOST}}/$KEYSTONE_HOST/g" -i $CONSTANT_FILE
+sed "s/{{KEYSTONE_PORT}}/$KEYSTONE_PORT/g" -i $CONSTANT_FILE
+
+cd /root/horizon
+
+LOCAL_SETTINGS=/root/horizon/openstack_dashboard/local/local_settings.py
+sed "s/OPENSTACK_HOST = \"127.0.0.1\"/OPENSTACK_HOST = \"${OPENSTACK_HOST}\"/" -i $LOCAL_SETTINGS
+sed "s#OPENSTACK_KEYSTONE_URL = \"http:\/\/%s:5000\/v2.0\" % OPENSTACK_HOST#OPENSTACK_KEYSTONE_URL = \"${OPENSTACK_KEYSTONE_URL}\"#" -i $LOCAL_SETTINGS
+
+echo -----------------
+grep OPENSTACK_HOST $LOCAL_SETTINGS
+grep OPENSTACK_KEYSTONE_URL LOCAL_SETTINGS
+echo -----------------
+
+echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $CONSTANT_FILE"
+cat $CONSTANT_FILE
+echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
+
+tox -e runserver -- 0.0.0.0:8000 \ No newline at end of file
diff --git a/moon_dashboard/setup.cfg b/moon_dashboard/setup.cfg
new file mode 100644
index 00000000..f68765dd
--- /dev/null
+++ b/moon_dashboard/setup.cfg
@@ -0,0 +1,24 @@
+[metadata]
+name = moon
+version=1.2.0
+summary = A dashboard plugin for Moon
+description-file =
+ README.rst
+author = Jonathan Gourdin
+author_email = jonathan.gourdin@orange.com
+home-page = https://docs.openstack.org/horizon/latest/
+classifiers = [
+ Environment :: OpenStack
+ Framework :: Django
+ Intended Audience :: Developers
+ Intended Audience :: System Administrators
+ License :: OSI Approved :: Apache Software License
+ Operating System :: POSIX :: Linux
+ Programming Language :: Python
+ Programming Language :: Python :: 2
+ Programming Language :: Python :: 2.7
+ Programming Language :: Python :: 3.5
+
+[files]
+packages =
+ moon \ No newline at end of file
diff --git a/moon_dashboard/setup.py b/moon_dashboard/setup.py
new file mode 100644
index 00000000..4794e334
--- /dev/null
+++ b/moon_dashboard/setup.py
@@ -0,0 +1,14 @@
+# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT
+import setuptools
+
+# In python < 2.7.4, a lazy loading of package `pbr` will break
+# setuptools if some other modules registered functions in `atexit`.
+# solution from: http://bugs.python.org/issue15881#msg170215
+try:
+ import multiprocessing # noqa
+except ImportError:
+ pass
+
+setuptools.setup(
+ setup_requires=['pbr>=1.8'],
+ pbr=True) \ No newline at end of file
diff --git a/moon_forming/Changelog b/moon_forming/Changelog
new file mode 100644
index 00000000..a107efd9
--- /dev/null
+++ b/moon_forming/Changelog
@@ -0,0 +1,11 @@
+CHANGES
+=======
+
+1.4.0
+-----
+- Update the python_moondb version to 1.2.10
+
+1.4.1
+-----
+- Update the python_moondb version to 1.2.16
+
diff --git a/moon_forming/Dockerfile b/moon_forming/Dockerfile
index ffae02c5..3a39880b 100644
--- a/moon_forming/Dockerfile
+++ b/moon_forming/Dockerfile
@@ -1,5 +1,13 @@
FROM python:3
+
+LABEL Name=Forming
+LABEL Description="Configuration job for the Moon platform"
+LABEL Maintainer="Thomas Duval"
+LABEL Url="https://wiki.opnfv.org/display/moon/Moon+Project+Proposal"
+
+USER root
+
WORKDIR /usr/src/app
RUN pip install --no-cache-dir --upgrade requests pytest pyyaml python_moonutilities python_moondb python_moonclient
diff --git a/moon_forming/conf2consul.py b/moon_forming/conf2consul.py
index 148bf923..df7a6b18 100644
--- a/moon_forming/conf2consul.py
+++ b/moon_forming/conf2consul.py
@@ -6,6 +6,8 @@ import logging
import json
import base64
+__version__ = "1.4.1"
+
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("moon.conf2consul")
requests_log = logging.getLogger("requests.packages.urllib3")
diff --git a/moon_interface/Changelog b/moon_interface/Changelog
index f58682a9..cea475f2 100644
--- a/moon_interface/Changelog
+++ b/moon_interface/Changelog
@@ -26,3 +26,7 @@ CHANGES
4.3.3
-----
- use the threading capability of Flask app
+
+4.3.3-1
+-----
+- Fix a bug in authz_requests
diff --git a/moon_interface/Dockerfile b/moon_interface/Dockerfile
index 069346c3..00880496 100644
--- a/moon_interface/Dockerfile
+++ b/moon_interface/Dockerfile
@@ -1,10 +1,15 @@
FROM python:3
+LABEL Name=Interface
+LABEL Description="Interface component for the Moon platform"
+LABEL Maintainer="Thomas Duval"
+LABEL Url="https://wiki.opnfv.org/display/moon/Moon+Project+Proposal"
+
+USER root
+
ADD . /root
WORKDIR /root/
-RUN pip3 install -r requirements.txt
-RUN if [ -d /root/dist ]; then for FILE in $(ls /root/dist/*.tar.gz); do pip install $FILE --upgrade; done; fi
-RUN if [ -d /root/dist ]; then for FILE in $(ls /root/dist/*.whl); do pip install $FILE --upgrade; done; fi
-RUN pip3 install .
+RUN pip3 install --no-cache-dir -r requirements.txt
+RUN pip3 install --no-cache-dir .
CMD ["python3", "-m", "moon_interface"] \ No newline at end of file
diff --git a/moon_interface/moon_interface/__init__.py b/moon_interface/moon_interface/__init__.py
index 0fb32055..a8cd9455 100644
--- a/moon_interface/moon_interface/__init__.py
+++ b/moon_interface/moon_interface/__init__.py
@@ -3,4 +3,4 @@
# license which can be found in the file 'LICENSE' in this package distribution
# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
-__version__ = "4.3.3"
+__version__ = "4.3.3-1"
diff --git a/moon_interface/moon_interface/authz_requests.py b/moon_interface/moon_interface/authz_requests.py
index 2ef0e0a1..c809053b 100644
--- a/moon_interface/moon_interface/authz_requests.py
+++ b/moon_interface/moon_interface/authz_requests.py
@@ -65,6 +65,7 @@ class AuthzRequest:
"(with address - {})".format(req.status_code)
)
success = True
+ break
except requests.exceptions.ConnectionError:
logger.error("Cannot connect to {}".format(
"http://{}:{}/authz".format(
diff --git a/moon_interface/tests/unit_python/api/test_authz.py b/moon_interface/tests/unit_python/api/test_authz.py
index 052bc9c9..a227a303 100644
--- a/moon_interface/tests/unit_python/api/test_authz.py
+++ b/moon_interface/tests/unit_python/api/test_authz.py
@@ -23,7 +23,8 @@ def test_authz_true(context):
assert "result" in data
assert data['result'] is True
-def test_authz_False(context):
+
+def test_authz_false(context):
import moon_interface.server
server = moon_interface.server.create_server()
client = server.app.test_client()
@@ -48,7 +49,7 @@ def test_authz_effect_unset(context, set_consul_and_db):
set_consul_and_db.register_uri(
'POST', 'http://127.0.0.1:8081/authz',
- content = conftest.get_pickled_context_invalid()
+ content=conftest.get_pickled_context_invalid()
)
req = client.get("/authz/{p_id}/{s_id}/{o_id}/{a_id}".format(
@@ -63,6 +64,7 @@ def test_authz_effect_unset(context, set_consul_and_db):
assert "result" in data
assert data['result'] is False
+
def test_authz_invalid_ip(context, set_consul_and_db):
import moon_interface.server
server = moon_interface.server.create_server()
diff --git a/moon_manager/Changelog b/moon_manager/Changelog
index 2bd01595..56521a0e 100644
--- a/moon_manager/Changelog
+++ b/moon_manager/Changelog
@@ -28,3 +28,15 @@ CHANGES
- use the threading capability of Flask app
- set the number of manager to 1
- update to the latest version of the python-moondb library
+
+4.5.2-1
+-----
+integrating validtion to send mandatory key names
+
+4.5.3
+-----
+- Removing try catch from all requets to allow raised exception to be passed to http server, to send actual error to client side
+- fixing test cases to assert on the expected exception after removing try-catch
+- allow 404 to be catched from our side instead of flask itself
+- revert the params in the get/post/patch/delete to be by default = None, so that we could catch the param if it was None
+instead of having not found url if the param is mandatory \ No newline at end of file
diff --git a/moon_manager/Dockerfile b/moon_manager/Dockerfile
index 630c275b..d264a113 100644
--- a/moon_manager/Dockerfile
+++ b/moon_manager/Dockerfile
@@ -1,10 +1,15 @@
FROM python:3
+LABEL Name=Manager
+LABEL Description="Manager component for the Moon platform"
+LABEL Maintainer="Thomas Duval"
+LABEL Url="https://wiki.opnfv.org/display/moon/Moon+Project+Proposal"
+
+USER root
+
ADD . /root
WORKDIR /root/
-RUN pip3 install -r requirements.txt
-RUN if [ -d /root/dist ]; then for FILE in $(ls /root/dist/*.tar.gz); do pip install $FILE --upgrade; done; fi
-RUN if [ -d /root/dist ]; then for FILE in $(ls /root/dist/*.whl); do pip install $FILE --upgrade; done; fi
-RUN pip3 install .
+RUN pip3 install --no-cache-dir -r requirements.txt
+RUN pip3 install --no-cache-dir .
CMD ["python3", "-m", "moon_manager"] \ No newline at end of file
diff --git a/moon_manager/moon_manager/__init__.py b/moon_manager/moon_manager/__init__.py
index 20a70977..205f6d8c 100644
--- a/moon_manager/moon_manager/__init__.py
+++ b/moon_manager/moon_manager/__init__.py
@@ -3,4 +3,4 @@
# license which can be found in the file 'LICENSE' in this package distribution
# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
-__version__ = "4.5.2"
+__version__ = "4.5.3"
diff --git a/moon_manager/moon_manager/api/assignments.py b/moon_manager/moon_manager/api/assignments.py
index a1d10ccb..426789e6 100644
--- a/moon_manager/moon_manager/api/assignments.py
+++ b/moon_manager/moon_manager/api/assignments.py
@@ -53,17 +53,14 @@ class SubjectAssignments(Resource):
}
:internal_api: get_subject_assignments
"""
- try:
- data = PolicyManager.get_subject_assignments(
- user_id=user_id, policy_id=uuid,
- subject_id=perimeter_id, category_id=category_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.get_subject_assignments(
+ user_id=user_id, policy_id=uuid,
+ subject_id=perimeter_id, category_id=category_id)
+
return {"subject_assignments": data}
- @validate_input("post", kwargs_state=[True, False, False, False, False], body_state=[True, True, True])
+ @validate_input("post", kwargs_state=[True, False, False, False, False], body_state={"id":True, "category_id":True, "data_id":True})
@check_auth
def post(self, uuid, perimeter_id=None, category_id=None,
data_id=None, user_id=None):
@@ -89,18 +86,13 @@ class SubjectAssignments(Resource):
}
:internal_api: update_subject_assignment
"""
- try:
- data_id = request.json.get("data_id")
- category_id = request.json.get("category_id")
- perimeter_id = request.json.get("id")
- data = PolicyManager.add_subject_assignment(
- user_id=user_id, policy_id=uuid,
- subject_id=perimeter_id, category_id=category_id,
- data_id=data_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data_id = request.json.get("data_id")
+ category_id = request.json.get("category_id")
+ perimeter_id = request.json.get("id")
+ data = PolicyManager.add_subject_assignment(
+ user_id=user_id, policy_id=uuid,
+ subject_id=perimeter_id, category_id=category_id,
+ data_id=data_id)
return {"subject_assignments": data}
@validate_input("delete", kwargs_state=[True, True, True, True, False])
@@ -120,15 +112,12 @@ class SubjectAssignments(Resource):
}
:internal_api: delete_subject_assignment
"""
- try:
- data = PolicyManager.delete_subject_assignment(
- user_id=user_id, policy_id=uuid,
- subject_id=perimeter_id, category_id=category_id,
- data_id=data_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.delete_subject_assignment(
+ user_id=user_id, policy_id=uuid,
+ subject_id=perimeter_id, category_id=category_id,
+ data_id=data_id)
+
return {"result": True}
@@ -166,17 +155,14 @@ class ObjectAssignments(Resource):
}
:internal_api: get_object_assignments
"""
- try:
- data = PolicyManager.get_object_assignments(
- user_id=user_id, policy_id=uuid,
- object_id=perimeter_id, category_id=category_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.get_object_assignments(
+ user_id=user_id, policy_id=uuid,
+ object_id=perimeter_id, category_id=category_id)
+
return {"object_assignments": data}
- @validate_input("post", kwargs_state=[True, False, False, False, False], body_state=[True, True, True])
+ @validate_input("post", kwargs_state=[True, False, False, False, False], body_state={"id":True, "category_id":True, "data_id":True})
@check_auth
def post(self, uuid, perimeter_id=None, category_id=None,
data_id=None, user_id=None):
@@ -202,18 +188,15 @@ class ObjectAssignments(Resource):
}
:internal_api: update_object_assignment
"""
- try:
- data_id = request.json.get("data_id")
- category_id = request.json.get("category_id")
- perimeter_id = request.json.get("id")
- data = PolicyManager.add_object_assignment(
- user_id=user_id, policy_id=uuid,
- object_id=perimeter_id, category_id=category_id,
- data_id=data_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data_id = request.json.get("data_id")
+ category_id = request.json.get("category_id")
+ perimeter_id = request.json.get("id")
+ data = PolicyManager.add_object_assignment(
+ user_id=user_id, policy_id=uuid,
+ object_id=perimeter_id, category_id=category_id,
+ data_id=data_id)
+
return {"object_assignments": data}
@validate_input("delete", kwargs_state=[True, True, True, True, False])
@@ -233,15 +216,11 @@ class ObjectAssignments(Resource):
}
:internal_api: delete_object_assignment
"""
- try:
- data = PolicyManager.delete_object_assignment(
- user_id=user_id, policy_id=uuid,
- object_id=perimeter_id, category_id=category_id,
- data_id=data_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = PolicyManager.delete_object_assignment(
+ user_id=user_id, policy_id=uuid,
+ object_id=perimeter_id, category_id=category_id,
+ data_id=data_id)
+
return {"result": True}
@@ -279,17 +258,13 @@ class ActionAssignments(Resource):
}
:internal_api: get_action_assignments
"""
- try:
- data = PolicyManager.get_action_assignments(
- user_id=user_id, policy_id=uuid,
- action_id=perimeter_id, category_id=category_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = PolicyManager.get_action_assignments(
+ user_id=user_id, policy_id=uuid,
+ action_id=perimeter_id, category_id=category_id)
+
return {"action_assignments": data}
- @validate_input("post", kwargs_state=[True, False, False, False, False], body_state=[True, True, True])
+ @validate_input("post", kwargs_state=[True, False, False, False, False], body_state={"id":True, "category_id":True, "data_id":True})
@check_auth
def post(self, uuid, perimeter_id=None, category_id=None,
data_id=None, user_id=None):
@@ -315,18 +290,15 @@ class ActionAssignments(Resource):
}
:internal_api: update_action_assignment
"""
- try:
- data_id = request.json.get("data_id")
- category_id = request.json.get("category_id")
- perimeter_id = request.json.get("id")
- data = PolicyManager.add_action_assignment(
- user_id=user_id, policy_id=uuid,
- action_id=perimeter_id, category_id=category_id,
- data_id=data_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data_id = request.json.get("data_id")
+ category_id = request.json.get("category_id")
+ perimeter_id = request.json.get("id")
+ data = PolicyManager.add_action_assignment(
+ user_id=user_id, policy_id=uuid,
+ action_id=perimeter_id, category_id=category_id,
+ data_id=data_id)
+
return {"action_assignments": data}
@validate_input("delete", kwargs_state=[True, True, True, True, False])
@@ -346,13 +318,10 @@ class ActionAssignments(Resource):
}
:internal_api: delete_action_assignment
"""
- try:
- data = PolicyManager.delete_action_assignment(
- user_id=user_id, policy_id=uuid,
- action_id=perimeter_id, category_id=category_id,
- data_id=data_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.delete_action_assignment(
+ user_id=user_id, policy_id=uuid,
+ action_id=perimeter_id, category_id=category_id,
+ data_id=data_id)
+
return {"result": True}
diff --git a/moon_manager/moon_manager/api/data.py b/moon_manager/moon_manager/api/data.py
index 4b22f9dc..d887ac2b 100644
--- a/moon_manager/moon_manager/api/data.py
+++ b/moon_manager/moon_manager/api/data.py
@@ -54,18 +54,16 @@ class SubjectData(Resource):
}]
:internal_api: get_subject_data
"""
- try:
- data = PolicyManager.get_subject_data(user_id=user_id,
- policy_id=uuid,
- category_id=category_id,
- data_id=data_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ logger.info("api.get {} {} {}".format(uuid, category_id, data_id))
+ data = PolicyManager.get_subject_data(user_id=user_id,
+ policy_id=uuid,
+ category_id=category_id,
+ data_id=data_id)
+ logger.info("api.get data = {}".format(data))
+
return {"subject_data": data}
- @validate_input("post", kwargs_state=[True, True, False, False], body_state=[True, False])
+ @validate_input("post", kwargs_state=[True, True, False, False], body_state={"name":True})
@check_auth
def post(self, uuid, category_id=None, data_id=None, user_id=None):
"""Create or update a subject.
@@ -90,15 +88,11 @@ class SubjectData(Resource):
}
:internal_api: add_subject_data
"""
- try:
- data = PolicyManager.set_subject_data(user_id=user_id,
- policy_id=uuid,
+ data = PolicyManager.set_subject_data(user_id=user_id,
+ policy_id=uuid,
category_id=category_id,
value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
return {"subject_data": data}
@validate_input("delete", kwargs_state=[True, False, False, False])
@@ -116,14 +110,11 @@ class SubjectData(Resource):
}]
:internal_api: delete_subject_data
"""
- try:
- data = PolicyManager.delete_subject_data(user_id=user_id,
- policy_id=uuid,
- data_id=data_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ logger.info("api.delete {} {}".format(uuid, data_id))
+ data = PolicyManager.delete_subject_data(user_id=user_id,
+ policy_id=uuid,
+ data_id=data_id)
+
return {"result": True}
@@ -162,18 +153,14 @@ class ObjectData(Resource):
}]
:internal_api: get_object_data
"""
- try:
- data = PolicyManager.get_object_data(user_id=user_id,
- policy_id=uuid,
- category_id=category_id,
- data_id=data_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = PolicyManager.get_object_data(user_id=user_id,
+ policy_id=uuid,
+ category_id=category_id,
+ data_id=data_id)
+
return {"object_data": data}
- @validate_input("post", kwargs_state=[True, True, False, False], body_state=[True, False])
+ @validate_input("post", kwargs_state=[True, True, False, False], body_state={"name":True})
@check_auth
def post(self, uuid, category_id=None, data_id=None, user_id=None):
"""Create or update a object.
@@ -198,15 +185,11 @@ class ObjectData(Resource):
}
:internal_api: add_object_data
"""
- try:
- data = PolicyManager.add_object_data(user_id=user_id,
- policy_id=uuid,
- category_id=category_id,
- value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = PolicyManager.add_object_data(user_id=user_id,
+ policy_id=uuid,
+ category_id=category_id,
+ value=request.json)
+
return {"object_data": data}
@validate_input("delete", kwargs_state=[True, False, False, False])
@@ -224,14 +207,10 @@ class ObjectData(Resource):
}
:internal_api: delete_object_data
"""
- try:
- data = PolicyManager.delete_object_data(user_id=user_id,
- policy_id=uuid,
- data_id=data_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = PolicyManager.delete_object_data(user_id=user_id,
+ policy_id=uuid,
+ data_id=data_id)
+
return {"result": True}
@@ -270,18 +249,14 @@ class ActionData(Resource):
}]
:internal_api: get_action_data
"""
- try:
- data = PolicyManager.get_action_data(user_id=user_id,
- policy_id=uuid,
- category_id=category_id,
- data_id=data_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = PolicyManager.get_action_data(user_id=user_id,
+ policy_id=uuid,
+ category_id=category_id,
+ data_id=data_id)
+
return {"action_data": data}
- @validate_input("post", kwargs_state=[True, True, False, False], body_state=[True, False])
+ @validate_input("post", kwargs_state=[True, True, False, False], body_state={"name":True})
@check_auth
def post(self, uuid, category_id=None, data_id=None, user_id=None):
"""Create or update a action.
@@ -306,15 +281,10 @@ class ActionData(Resource):
}
:internal_api: add_action_data
"""
- try:
- data = PolicyManager.add_action_data(user_id=user_id,
- policy_id=uuid,
- category_id=category_id,
- value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = PolicyManager.add_action_data(user_id=user_id,
+ policy_id=uuid,
+ category_id=category_id,
+ value=request.json)
return {"action_data": data}
@validate_input("delete", kwargs_state=[True, False, False, False])
@@ -332,14 +302,10 @@ class ActionData(Resource):
}
:internal_api: delete_action_data
"""
- try:
- data = PolicyManager.delete_action_data(user_id=user_id,
- policy_id=uuid,
- data_id=data_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = PolicyManager.delete_action_data(user_id=user_id,
+ policy_id=uuid,
+ data_id=data_id)
+
return {"result": True}
diff --git a/moon_manager/moon_manager/api/json_import.py b/moon_manager/moon_manager/api/json_import.py
index ae9a21d0..e57a27c1 100644
--- a/moon_manager/moon_manager/api/json_import.py
+++ b/moon_manager/moon_manager/api/json_import.py
@@ -81,17 +81,15 @@ class JsonImport(Resource):
def _reorder_rules_ids(self, rule, ordered_perimeter_categories_ids, json_data_ids, policy_id, get_function):
ordered_json_ids = [None]*len(ordered_perimeter_categories_ids)
- logger.info("ordered_json_ids {}".format(ordered_json_ids))
- logger.info("json_data_ids {}".format(json_data_ids))
for json_id in json_data_ids:
- logger.info("json_id {}".format(json_id))
data = get_function(self._user_id, policy_id, data_id=json_id)
data = data[0]
- logger.info("data {}".format(data))
if data["category_id"] not in ordered_perimeter_categories_ids:
- raise InvalidJson("The category id {} of the rule {} does not match the meta rule".format(data["category_id"], rule))
+ raise InvalidJson("The category id {} of the rule {} does not match the meta rule".format(
+ data["category_id"], rule))
if ordered_json_ids[ordered_perimeter_categories_ids.index(data["category_id"])] is not None:
- raise InvalidJson("The category id {} of the rule {} shall not be used twice in the same rule".format(data["category_id"], rule))
+ raise InvalidJson("The category id {} of the rule {} shall not be used twice in the same rule".format(
+ data["category_id"], rule))
ordered_json_ids[ordered_perimeter_categories_ids.index(data["category_id"])] = json_id
logger.info(ordered_json_ids)
return ordered_json_ids
@@ -106,7 +104,8 @@ class JsonImport(Resource):
JsonUtils.copy_field_if_exists(json_rule, json_to_use, "enabled", bool, default_value=True)
json_ids = dict()
- JsonUtils.convert_name_to_id(json_rule, json_ids, "policy", "policy_id", "policy", PolicyManager, self._user_id)
+ JsonUtils.convert_name_to_id(json_rule, json_ids, "policy", "policy_id", "policy",
+ PolicyManager, self._user_id)
JsonUtils.convert_name_to_id(json_rule, json_to_use, "meta_rule", "meta_rule_id", "meta_rule", ModelManager, self._user_id)
json_subject_ids = dict()
json_object_ids = dict()
@@ -124,7 +123,7 @@ class JsonImport(Resource):
json_to_use_rule = json_to_use_rule + self._reorder_rules_ids(json_rule, meta_rule["action_categories"], json_action_ids["action"], json_ids["policy_id"], PolicyManager.get_action_data)
json_to_use["rule"] = json_to_use_rule
try:
- logger.info("Adding / updating a rule from json {}".format(json_to_use))
+ logger.debug("Adding / updating a rule from json {}".format(json_to_use))
PolicyManager.add_rule(self._user_id, json_ids["policy_id"], json_to_use["meta_rule_id"], json_to_use)
except exceptions.RuleExisting:
pass
@@ -135,15 +134,14 @@ class JsonImport(Resource):
logger.info("Input meta rules : {}".format(json_meta_rules))
for json_meta_rule in json_meta_rules:
json_to_use = dict()
- logger.info("Input meta rule : {}".format(json_meta_rule))
JsonUtils.copy_field_if_exists(json_meta_rule, json_to_use, "name", str)
JsonUtils.copy_field_if_exists(json_meta_rule, json_to_use, "description", str)
JsonUtils.convert_names_to_ids(json_meta_rule, json_to_use, "subject_categories", "subject_categories", "subject_category", ModelManager, self._user_id)
JsonUtils.convert_names_to_ids(json_meta_rule, json_to_use, "object_categories", "object_categories", "object_category", ModelManager, self._user_id)
JsonUtils.convert_names_to_ids(json_meta_rule, json_to_use, "action_categories", "action_categories", "action_category", ModelManager, self._user_id)
- logger.info("Adding / updating a metarule from json {}".format(json_meta_rule))
+ logger.debug("Adding / updating a metarule from json {}".format(json_meta_rule))
meta_rule = ModelManager.add_meta_rule(self._user_id, meta_rule_id=None, value=json_to_use)
- logger.info("Added / updated meta rule : {}".format(meta_rule))
+ logger.debug("Added / updated meta rule : {}".format(meta_rule))
def _import_subject_object_action_assignments(self, json_item_assignments, type_element):
import_method = getattr(PolicyManager, 'add_' + type_element + '_assignment')
@@ -178,14 +176,18 @@ class JsonImport(Resource):
# find the policy related to the current data
data = get_method(self._user_id, policy_id, data_id, json_assignment["category_id"])
if data is not None and len(data) == 1:
- logger.info("Adding / updating a {} assignment from json {}".format(type_element, json_assignment))
- import_method(self._user_id, policy_id, json_assignment["id"], json_assignment["category_id"], data_id)
+ logger.debug("Adding / updating a {} assignment from json {}".format(type_element,
+ json_assignment))
+ import_method(self._user_id, policy_id, json_assignment["id"], json_assignment["category_id"],
+ data_id)
else:
raise UnknownData("Unknown data with id {}".format(data_id))
# case the data has not been found in any policies
if has_found_data is False:
- raise InvalidJson("The json contains unknown {} data or category : {}".format(type_element,json_item_assignment))
+ raise InvalidJson("The json contains unknown {} data or category : {}".format(
+ type_element,
+ json_item_assignment))
def _import_subject_object_action_datas(self, json_items_data, mandatory_policy_ids, type_element):
if type_element == "subject":
@@ -201,7 +203,6 @@ class JsonImport(Resource):
item_override = JsonUtils.get_override(json_items_data)
if item_override is True:
raise ForbiddenOverride("{} datas do not support override flag !".format(type_element))
- logger.info("json_item_data {}".format(json_item_data))
json_to_use = dict()
JsonUtils.copy_field_if_exists(json_item_data, json_to_use, "name", str)
JsonUtils.copy_field_if_exists(json_item_data, json_to_use, "description", str)
@@ -209,11 +210,9 @@ class JsonImport(Resource):
# field_mandatory : not mandatory if there is some mandatory policies
JsonUtils.convert_names_to_ids(json_item_data, json_policy, "policies", "policy_id", "policy",
PolicyManager, self._user_id, field_mandatory=len(mandatory_policy_ids) == 0)
- logger.info("json_policy {}".format(json_policy))
json_category = dict()
JsonUtils.convert_name_to_id(json_item_data, json_category, "category", "category_id", type_element+"_category",
ModelManager, self._user_id)
- logger.info("json_category {}".format(json_category))
policy_ids = []
if "policy_id" in json_policy:
policy_ids = json_policy["policy_id"]
@@ -232,15 +231,12 @@ class JsonImport(Resource):
for policy_id in mandatory_policy_ids:
try:
- # existing_datas = get_method(self._user_id, policy_id,category_id=category_id)
- # logger.info(existing_datas)
- logger.info("Adding / updating a {} data with policy id {} and category id {} from json {}".format(type_element, policy_id, category_id, json_to_use))
data = import_method(self._user_id, policy_id, category_id=category_id, value=json_to_use)
- logger.info("Added / updated {} data : {}".format(type_element, data))
except exceptions.PolicyUnknown:
raise UnknownPolicy("Unknown policy with id {}".format(policy_id))
except Exception as e:
- raise BaseException(str(e))
+ logger.exception(str(e))
+ raise e
def _import_subject_object_action_categories(self, json_item_categories, type_element):
import_method = getattr(ModelManager, 'add_' + type_element + '_category')
@@ -267,14 +263,13 @@ class JsonImport(Resource):
raise ForbiddenOverride("{} categories do not support override flag !".format(type_element))
try:
- logger.info("Adding a {} category from json {}".format(type_element, json_to_use))
category = import_method(self._user_id, existing_id, json_to_use)
- logger.info("Added category {}".format(category))
except (exceptions.SubjectCategoryExisting, exceptions.ObjectCategoryExisting, exceptions.ActionCategoryExisting):
# it already exists: do nothing
- logger.info("Ignored {} category with name {} is already in the database".format(type_element, json_to_use["name"]))
+ logger.warning("Ignored {} category with name {} is already in the database".format(type_element, json_to_use["name"]))
except Exception as e:
- logger.info("Error while importing the category : {}".format(str(e)))
+ logger.warning("Error while importing the category : {}".format(str(e)))
+ logger.exception(str(e))
raise e
def _import_subject_object_action(self, json_items, mandatory_policy_ids, type_element):
@@ -302,7 +297,7 @@ class JsonImport(Resource):
raise ForbiddenOverride("{} does not support override flag !".format(type_element))
if len(policy_ids) == 0:
- raise MissingPolicy("a {} needs at least one policy to be created or updated : {}".format(type_element, json.dumps(json_item)))
+ raise MissingPolicy("a {} needs at least one policy to be created or updated : {}".format(type_element, json.dumps(json_item)))
for policy_id in policy_ids:
try:
@@ -312,16 +307,13 @@ class JsonImport(Resource):
if items_in_db[key_in_db]["name"] == json_without_policy_name["name"]:
key = key_in_db
break
- if key is None:
- logger.info("Adding a {} from json {} to the policy with id {}".format(type_element, json_without_policy_name, policy_id))
- else:
- logger.info("Updating a {} from json {} to the policy with id {}".format(type_element, json_without_policy_name, policy_id))
element = import_method(self._user_id, policy_id, perimeter_id=key, value=json_without_policy_name)
- logger.info("Added / updated {} : {}".format(type_element, element))
+ logger.debug("Added / updated {} : {}".format(type_element, element))
except exceptions.PolicyUnknown:
raise UnknownPolicy("Unknown policy when adding a {}!".format(type_element))
except Exception as e:
+ logger.exception(str(e))
raise BaseException(str(e))
def _import_policies(self, json_policies):
@@ -335,7 +327,7 @@ class JsonImport(Resource):
# policy_in_db = PolicyManager.get_policies_by_name(json_without_model_name["name"])
policies = PolicyManager.get_policies(self._user_id)
policy_in_db = None
- logger.info(policies)
+ policy_id = None
for policy_key in policies:
if policies[policy_key]["name"] == json_policy["name"]:
policy_in_db = policies[policy_key]
@@ -350,9 +342,10 @@ class JsonImport(Resource):
policy_mandatory = JsonUtils.get_mandatory(json_policy)
if policy_override is False and policy_does_exist:
- policy_mandatory_ids.append(policy_id)
- logger.warning("Existing policy not updated because of the override option is not set !")
- continue
+ if policy_id:
+ policy_mandatory_ids.append(policy_id)
+ logger.warning("Existing policy not updated because of the override option is not set !")
+ continue
json_without_model_name = dict()
JsonUtils.copy_field_if_exists(json_policy, json_without_model_name, "name", str)
@@ -361,16 +354,14 @@ class JsonImport(Resource):
JsonUtils.convert_name_to_id(json_policy, json_without_model_name, "model", "model_id", "model", ModelManager, self._user_id, field_mandatory=False)
if not policy_does_exist:
- logger.info("Creating policy {} ".format(json_without_model_name))
+ logger.debug("Creating policy {} ".format(json_without_model_name))
added_policy = PolicyManager.add_policy(self._user_id, None, json_without_model_name)
- logger.info("Added policy {}".format(added_policy))
if policy_mandatory is True:
keys = list(added_policy.keys())
policy_mandatory_ids.append(keys[0])
elif policy_override is True:
- logger.info("Updating policy {} ".format(json_without_model_name))
+ logger.debug("Updating policy {} ".format(json_without_model_name))
updated_policy = PolicyManager.update_policy(self._user_id, policy_id, json_without_model_name)
- logger.info("Updated policy {}".format(updated_policy))
if policy_mandatory is True:
policy_mandatory_ids.append(policy_id)
return policy_mandatory_ids
@@ -380,7 +371,7 @@ class JsonImport(Resource):
raise InvalidJson("models shall be a list!")
for json_model in json_models:
- logger.info("json_model {}".format(json_model))
+ logger.debug("json_model {}".format(json_model))
models = ModelManager.get_models(self._user_id)
model_in_db = None
model_id = None
@@ -389,19 +380,16 @@ class JsonImport(Resource):
model_in_db = models[model_key]
model_id = model_key
- logger.info("model in db".format(model_in_db))
# this should not occur as the model has been put in db previously in _import_models_without_new_meta_rules
if model_in_db is None:
- raise UnknownModel("Unknwon model ")
+ raise UnknownModel("Unknown model ")
json_key = dict()
JsonUtils.convert_names_to_ids(json_model, json_key, "meta_rules", "meta_rule_id", "meta_rule", ModelManager, self._user_id)
- logger.info("json_key {}".format(json_key))
for meta_rule_id in json_key["meta_rule_id"]:
if meta_rule_id not in model_in_db["meta_rules"]:
model_in_db["meta_rules"].append(meta_rule_id)
- logger.info("Updating model with id {} : {} ".format(model_id, model_in_db))
ModelManager.update_model(self._user_id, model_id, model_in_db)
def _import_models_without_new_meta_rules(self, json_models):
@@ -426,16 +414,14 @@ class JsonImport(Resource):
if model_in_db is None:
model_does_exist = False
else:
- logger.info("model_in_db {}".format(model_in_db))
- # JsonUtils.convert_names_to_ids(model_in_db, json_without_new_metarules, "meta_rules", "meta_rule_id", "meta_rule", ModelManager, self._user_id)
json_without_new_metarules["meta_rule_id"] = model_in_db["meta_rules"]
model_does_exist = True
model_override = JsonUtils.get_override(json_model)
if not model_does_exist:
- logger.info("Creating model {} ".format(json_without_new_metarules))
+ logger.debug("Creating model {} ".format(json_without_new_metarules))
ModelManager.add_model(self._user_id, None, json_without_new_metarules)
elif model_override is True:
- logger.info("Updating model with id {} : {} ".format(model_id, json_without_new_metarules))
+ logger.debug("Updating model with id {} : {} ".format(model_id, json_without_new_metarules))
ModelManager.update_model(self._user_id, model_id, json_without_new_metarules)
def _import_pdps(self, json_pdps):
@@ -462,11 +448,11 @@ class JsonImport(Resource):
self._user_id = user_id
if 'file' in request.files:
file = request.files['file']
- logger.info("Importing {} file...".format(file))
+ logger.debug("Importing {} file...".format(file))
json_content = json.load(file)
else:
json_content = request.json
- logger.info("Importing content: {} ...".format(json_content))
+ logger.debug("Importing content: {} ...".format(json_content))
# first import the models without the meta rules as they are not yet defined
if "models" in json_content:
diff --git a/moon_manager/moon_manager/api/meta_data.py b/moon_manager/moon_manager/api/meta_data.py
index f3b22d29..62ca050f 100644
--- a/moon_manager/moon_manager/api/meta_data.py
+++ b/moon_manager/moon_manager/api/meta_data.py
@@ -45,16 +45,12 @@ class SubjectCategories(Resource):
}
:internal_api: get_subject_categories
"""
- try:
- data = ModelManager.get_subject_categories(
- user_id=user_id, category_id=category_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = ModelManager.get_subject_categories(
+ user_id=user_id, category_id=category_id)
+
return {"subject_categories": data}
- @validate_input("post",body_state=[True,False])
+ @validate_input("post",body_state={"name":True})
@check_auth
def post(self, category_id=None, user_id=None):
"""Create or update a subject category.
@@ -73,13 +69,9 @@ class SubjectCategories(Resource):
}
:internal_api: add_subject_category
"""
- try:
- data = ModelManager.add_subject_category(
- user_id=user_id, value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = ModelManager.add_subject_category(
+ user_id=user_id, value=request.json)
+
return {"subject_categories": data}
@validate_input("delete",kwargs_state=[True,False])
@@ -95,13 +87,10 @@ class SubjectCategories(Resource):
}
:internal_api: delete_subject_category
"""
- try:
- data = ModelManager.delete_subject_category(
- user_id=user_id, category_id=category_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = ModelManager.delete_subject_category(
+ user_id=user_id, category_id=category_id)
+
return {"result": True}
@@ -131,16 +120,12 @@ class ObjectCategories(Resource):
}
:internal_api: get_object_categories
"""
- try:
- data = ModelManager.get_object_categories(
- user_id=user_id, category_id=category_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = ModelManager.get_object_categories(
+ user_id=user_id, category_id=category_id)
+
return {"object_categories": data}
- @validate_input("post", body_state=[True, False])
+ @validate_input("post", body_state={"name":True})
@check_auth
def post(self, category_id=None, user_id=None):
"""Create or update a object category.
@@ -159,13 +144,10 @@ class ObjectCategories(Resource):
}
:internal_api: add_object_category
"""
- try:
- data = ModelManager.add_object_category(
- user_id=user_id, value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = ModelManager.add_object_category(
+ user_id=user_id, value=request.json)
+
return {"object_categories": data}
@validate_input("delete", kwargs_state=[True, False])
@@ -181,13 +163,10 @@ class ObjectCategories(Resource):
}
:internal_api: delete_object_category
"""
- try:
- data = ModelManager.delete_object_category(
- user_id=user_id, category_id=category_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = ModelManager.delete_object_category(
+ user_id=user_id, category_id=category_id)
+
return {"result": True}
@@ -217,16 +196,13 @@ class ActionCategories(Resource):
}
:internal_api: get_action_categories
"""
- try:
- data = ModelManager.get_action_categories(
- user_id=user_id, category_id=category_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = ModelManager.get_action_categories(
+ user_id=user_id, category_id=category_id)
+
return {"action_categories": data}
- @validate_input("post", body_state=[True, False])
+ @validate_input("post", body_state={"name":True})
@check_auth
def post(self, category_id=None, user_id=None):
"""Create or update an action category.
@@ -245,13 +221,10 @@ class ActionCategories(Resource):
}
:internal_api: add_action_category
"""
- try:
- data = ModelManager.add_action_category(
- user_id=user_id, value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = ModelManager.add_action_category(
+ user_id=user_id, value=request.json)
+
return {"action_categories": data}
@validate_input("delete", kwargs_state=[True, False])
@@ -267,11 +240,7 @@ class ActionCategories(Resource):
}
:internal_api: delete_action_category
"""
- try:
- data = ModelManager.delete_action_category(
- user_id=user_id, category_id=category_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = ModelManager.delete_action_category(
+ user_id=user_id, category_id=category_id)
+
return {"result": True}
diff --git a/moon_manager/moon_manager/api/meta_rules.py b/moon_manager/moon_manager/api/meta_rules.py
index afc11eba..3dc9996b 100644
--- a/moon_manager/moon_manager/api/meta_rules.py
+++ b/moon_manager/moon_manager/api/meta_rules.py
@@ -51,16 +51,13 @@ class MetaRules(Resource):
}
:internal_api: get_meta_rules
"""
- try:
- data = ModelManager.get_meta_rules(
- user_id=user_id, meta_rule_id=meta_rule_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = ModelManager.get_meta_rules(
+ user_id=user_id, meta_rule_id=meta_rule_id)
+
return {"meta_rules": data}
- @validate_input("post", body_state=[True, True, True, True])
+ @validate_input("post", body_state={"name":True, "subject_categories":True, "object_categories":True, "action_categories":True})
@check_auth
def post(self, meta_rule_id=None, user_id=None):
"""Add a meta rule
@@ -87,18 +84,15 @@ class MetaRules(Resource):
}
:internal_api: add_meta_rules
"""
- try:
- data = ModelManager.add_meta_rule(
- user_id=user_id, meta_rule_id=None, value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = ModelManager.add_meta_rule(
+ user_id=user_id, meta_rule_id=None, value=request.json)
+
return {"meta_rules": data}
- @validate_input("patch", kwargs_state=[True, False], body_state=[True, True, True, True])
+ @validate_input("patch", kwargs_state=[True, False], body_state={"name":True, "subject_categories":True, "object_categories":True, "action_categories":True})
@check_auth
- def patch(self, meta_rule_id, user_id=None):
+ def patch(self, meta_rule_id=None, user_id=None):
"""Update a meta rule
:param meta_rule_id: Meta rule ID
@@ -123,18 +117,14 @@ class MetaRules(Resource):
}
:internal_api: set_meta_rules
"""
- try:
- data = ModelManager.set_meta_rule(
- user_id=user_id, meta_rule_id=meta_rule_id, value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = ModelManager.set_meta_rule(
+ user_id=user_id, meta_rule_id=meta_rule_id, value=request.json)
+
return {"meta_rules": data}
@validate_input("delete", kwargs_state=[True, False])
@check_auth
- def delete(self, meta_rule_id, user_id=None):
+ def delete(self, meta_rule_id=None, user_id=None):
"""Delete a meta rule
:param meta_rule_id: Meta rule ID
@@ -152,12 +142,9 @@ class MetaRules(Resource):
}
:internal_api: delete_meta_rules
"""
- try:
- data = ModelManager.delete_meta_rule(
- user_id=user_id, meta_rule_id=meta_rule_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = ModelManager.delete_meta_rule(
+ user_id=user_id, meta_rule_id=meta_rule_id)
+
return {"result": True}
diff --git a/moon_manager/moon_manager/api/models.py b/moon_manager/moon_manager/api/models.py
index 440a4d2b..c3068367 100644
--- a/moon_manager/moon_manager/api/models.py
+++ b/moon_manager/moon_manager/api/models.py
@@ -46,15 +46,11 @@ class Models(Resource):
}
:internal_api: get_models
"""
- try:
- data = ModelManager.get_models(user_id=user_id, model_id=uuid)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = ModelManager.get_models(user_id=user_id, model_id=uuid)
+
return {"models": data}
- @validate_input("post", body_state=[True, False, True])
+ @validate_input("post", body_state={"name":True, "meta_rules":True})
@check_auth
def post(self, uuid=None, user_id=None):
"""Create model.
@@ -75,18 +71,14 @@ class Models(Resource):
}
:internal_api: add_model
"""
- try:
- data = ModelManager.add_model(
- user_id=user_id, model_id=uuid, value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = ModelManager.add_model(
+ user_id=user_id, model_id=uuid, value=request.json)
+
return {"models": data}
@validate_input("delete", kwargs_state=[True, False])
@check_auth
- def delete(self, uuid, user_id=None):
+ def delete(self, uuid=None, user_id=None):
"""Delete a model
:param uuid: uuid of the model to delete
@@ -97,17 +89,14 @@ class Models(Resource):
}
:internal_api: delete_model
"""
- try:
- data = ModelManager.delete_model(user_id=user_id, model_id=uuid)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = ModelManager.delete_model(user_id=user_id, model_id=uuid)
+
return {"result": True}
- @validate_input("patch", kwargs_state=[True, False], body_state=[True, False, True])
+ @validate_input("patch", kwargs_state=[True, False], body_state={"name":True, "meta_rules":True})
@check_auth
- def patch(self, uuid, user_id=None):
+ def patch(self, uuid=None, user_id=None):
"""Update a model
:param uuid: uuid of the model to update
@@ -121,12 +110,8 @@ class Models(Resource):
}
:internal_api: update_model
"""
- try:
- data = ModelManager.update_model(
- user_id=user_id, model_id=uuid, value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = ModelManager.update_model(
+ user_id=user_id, model_id=uuid, value=request.json)
+
return {"models": data}
diff --git a/moon_manager/moon_manager/api/pdp.py b/moon_manager/moon_manager/api/pdp.py
index fd20c85f..a5d7c007 100644
--- a/moon_manager/moon_manager/api/pdp.py
+++ b/moon_manager/moon_manager/api/pdp.py
@@ -114,15 +114,12 @@ class PDP(Resource):
}
:internal_api: get_pdp
"""
- try:
- data = PDPManager.get_pdp(user_id=user_id, pdp_id=uuid)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PDPManager.get_pdp(user_id=user_id, pdp_id=uuid)
+
return {"pdps": data}
- @validate_input("post", body_state=[True, True, True, False])
+ @validate_input("post", body_state={"name": True, "security_pipeline": True, "keystone_project_id": True})
@check_auth
def post(self, uuid=None, user_id=None):
"""Create pdp.
@@ -145,23 +142,20 @@ class PDP(Resource):
}
:internal_api: add_pdp
"""
- try:
- data = dict(request.json)
- if not data.get("keystone_project_id"):
- data["keystone_project_id"] = None
- else:
- if check_keystone_pid(data.get("keystone_project_id")):
- raise exceptions.PdpKeystoneMappingConflict
- data = PDPManager.add_pdp(
- user_id=user_id, pdp_id=None, value=request.json)
- uuid = list(data.keys())[0]
- logger.debug("data={}".format(data))
- logger.debug("uuid={}".format(uuid))
- add_pod(uuid=uuid, data=data[uuid])
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = dict(request.json)
+ if not data.get("keystone_project_id"):
+ data["keystone_project_id"] = None
+ else:
+ if check_keystone_pid(data.get("keystone_project_id")):
+ raise exceptions.PdpKeystoneMappingConflict
+ data = PDPManager.add_pdp(
+ user_id=user_id, pdp_id=None, value=request.json)
+ uuid = list(data.keys())[0]
+ logger.debug("data={}".format(data))
+ logger.debug("uuid={}".format(uuid))
+ add_pod(uuid=uuid, data=data[uuid])
+
return {"pdps": data}
@validate_input("delete", kwargs_state=[True, False])
@@ -177,16 +171,12 @@ class PDP(Resource):
}
:internal_api: delete_pdp
"""
- try:
- data = PDPManager.delete_pdp(user_id=user_id, pdp_id=uuid)
- delete_pod(uuid)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+ data = PDPManager.delete_pdp(user_id=user_id, pdp_id=uuid)
+ delete_pod(uuid)
+
return {"result": True}
- @validate_input("patch", kwargs_state=[True, False], body_state=[True, True, True, False])
+ @validate_input("patch", kwargs_state=[True, False], body_state={"name": True, "security_pipeline": True, "keystone_project_id": True})
@check_auth
def patch(self, uuid, user_id=None):
"""Update a pdp
@@ -203,21 +193,18 @@ class PDP(Resource):
}
:internal_api: update_pdp
"""
- try:
- _data = dict(request.json)
- if not _data.get("keystone_project_id"):
- _data["keystone_project_id"] = None
- else:
- if check_keystone_pid(_data.get("keystone_project_id")):
- raise exceptions.PdpKeystoneMappingConflict
- data = PDPManager.update_pdp(
- user_id=user_id, pdp_id=uuid, value=_data)
- logger.debug("data={}".format(data))
- logger.debug("uuid={}".format(uuid))
- add_pod(uuid=uuid, data=data[uuid])
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ _data = dict(request.json)
+ if not _data.get("keystone_project_id"):
+ _data["keystone_project_id"] = None
+ else:
+ if check_keystone_pid(_data.get("keystone_project_id")):
+ raise exceptions.PdpKeystoneMappingConflict
+ data = PDPManager.update_pdp(
+ user_id=user_id, pdp_id=uuid, value=_data)
+ logger.debug("data={}".format(data))
+ logger.debug("uuid={}".format(uuid))
+ add_pod(uuid=uuid, data=data[uuid])
+
return {"pdps": data}
diff --git a/moon_manager/moon_manager/api/perimeter.py b/moon_manager/moon_manager/api/perimeter.py
index 014aa4b9..6c39c43d 100644
--- a/moon_manager/moon_manager/api/perimeter.py
+++ b/moon_manager/moon_manager/api/perimeter.py
@@ -55,21 +55,18 @@ class Subjects(Resource):
}
:internal_api: get_subjects
"""
- try:
- data = PolicyManager.get_subjects(
- user_id=user_id,
- policy_id=uuid,
- perimeter_id=perimeter_id
- )
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.get_subjects(
+ user_id=user_id,
+ policy_id=uuid,
+ perimeter_id=perimeter_id
+ )
+
return {"subjects": data}
- @validate_input("post", body_state=[True, False, False, False])
+ @validate_input("post", body_state={"name":True})
@check_auth
- def post(self, uuid=None, perimeter_id=None, user_id=None):
+ def post(self, uuid, perimeter_id=None, user_id=None):
"""Create or update a subject.
:param uuid: uuid of the policy
@@ -92,25 +89,22 @@ class Subjects(Resource):
}
:internal_api: set_subject
"""
- try:
- if not perimeter_id:
- data = PolicyManager.get_subjects(user_id=user_id,
- policy_id=None)
- if 'name' in request.json:
- for data_id, data_value in data.items():
- if data_value['name'] == request.json['name']:
- perimeter_id = data_id
- break
- data = PolicyManager.add_subject(
- user_id=user_id, policy_id=uuid,
- perimeter_id=perimeter_id, value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ if not perimeter_id:
+ data = PolicyManager.get_subjects(user_id=user_id,
+ policy_id=uuid)
+ if 'name' in request.json:
+ for data_id, data_value in data.items():
+ if data_value['name'] == request.json['name']:
+ perimeter_id = data_id
+ break
+ data = PolicyManager.add_subject(
+ user_id=user_id, policy_id=uuid,
+ perimeter_id=perimeter_id, value=request.json)
+
return {"subjects": data}
- @validate_input("patch", kwargs_state=[False, True, False], body_state=[True, False, False, False])
+ @validate_input("patch", kwargs_state=[False, True, False], body_state={"name":True})
@check_auth
def patch(self, uuid, perimeter_id=None, user_id=None):
"""Create or update a subject.
@@ -135,22 +129,19 @@ class Subjects(Resource):
}
:internal_api: set_subject
"""
- try:
- if not perimeter_id:
- data = PolicyManager.get_subjects(user_id=user_id,
- policy_id=None)
- if 'name' in request.json:
- for data_id, data_value in data.items():
- if data_value['name'] == request.json['name']:
- perimeter_id = data_id
- break
- data = PolicyManager.add_subject(
- user_id=user_id, policy_id=uuid,
- perimeter_id=perimeter_id, value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ if not perimeter_id:
+ data = PolicyManager.get_subjects(user_id=user_id,
+ policy_id=None)
+ if 'name' in request.json:
+ for data_id, data_value in data.items():
+ if data_value['name'] == request.json['name']:
+ perimeter_id = data_id
+ break
+ data = PolicyManager.add_subject(
+ user_id=user_id, policy_id=uuid,
+ perimeter_id=perimeter_id, value=request.json)
+
return {"subjects": data}
@validate_input("delete", kwargs_state=[False, True, False])
@@ -172,13 +163,10 @@ class Subjects(Resource):
}
:internal_api: delete_subject
"""
- try:
- data = PolicyManager.delete_subject(
- user_id=user_id, policy_id=uuid, perimeter_id=perimeter_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.delete_subject(
+ user_id=user_id, policy_id=uuid, perimeter_id=perimeter_id)
+
return {"result": True}
@@ -213,21 +201,18 @@ class Objects(Resource):
}
:internal_api: get_objects
"""
- try:
- data = PolicyManager.get_objects(
- user_id=user_id,
- policy_id=uuid,
- perimeter_id=perimeter_id
- )
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.get_objects(
+ user_id=user_id,
+ policy_id=uuid,
+ perimeter_id=perimeter_id
+ )
+
return {"objects": data}
- @validate_input("post", body_state=[True, False, False, False])
+ @validate_input("post", body_state={"name":True})
@check_auth
- def post(self, uuid=None, perimeter_id=None, user_id=None):
+ def post(self, uuid, perimeter_id=None, user_id=None):
"""Create or update a object.
:param uuid: uuid of the policy
@@ -245,23 +230,20 @@ class Objects(Resource):
}
:internal_api: set_object
"""
- try:
- data = PolicyManager.get_objects(user_id=user_id, policy_id=None)
- if 'name' in request.json:
- for data_id, data_value in data.items():
- if data_value['name'] == request.json['name']:
- perimeter_id = data_id
- break
- data = PolicyManager.add_object(
- user_id=user_id, policy_id=uuid,
- perimeter_id=perimeter_id, value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.get_objects(user_id=user_id, policy_id=uuid)
+ if 'name' in request.json:
+ for data_id, data_value in data.items():
+ if data_value['name'] == request.json['name']:
+ perimeter_id = data_id
+ break
+ data = PolicyManager.add_object(
+ user_id=user_id, policy_id=uuid,
+ perimeter_id=perimeter_id, value=request.json)
+
return {"objects": data}
- @validate_input("patch", kwargs_state=[False, True, False], body_state=[True, False, False, False])
+ @validate_input("patch", kwargs_state=[False, True, False], body_state={"name":True})
@check_auth
def patch(self, uuid, perimeter_id=None, user_id=None):
"""Create or update a object.
@@ -281,20 +263,17 @@ class Objects(Resource):
}
:internal_api: set_object
"""
- try:
- data = PolicyManager.get_objects(user_id=user_id, policy_id=None)
- if 'name' in request.json:
- for data_id, data_value in data.items():
- if data_value['name'] == request.json['name']:
- perimeter_id = data_id
- break
- data = PolicyManager.add_object(
- user_id=user_id, policy_id=uuid,
- perimeter_id=perimeter_id, value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.get_objects(user_id=user_id, policy_id=uuid)
+ if 'name' in request.json:
+ for data_id, data_value in data.items():
+ if data_value['name'] == request.json['name']:
+ perimeter_id = data_id
+ break
+ data = PolicyManager.add_object(
+ user_id=user_id, policy_id=uuid,
+ perimeter_id=perimeter_id, value=request.json)
+
return {"objects": data}
@validate_input("delete", kwargs_state=[False, True, False])
@@ -313,13 +292,10 @@ class Objects(Resource):
}
:internal_api: delete_object
"""
- try:
- data = PolicyManager.delete_object(
- user_id=user_id, policy_id=uuid, perimeter_id=perimeter_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.delete_object(
+ user_id=user_id, policy_id=uuid, perimeter_id=perimeter_id)
+
return {"result": True}
@@ -354,18 +330,15 @@ class Actions(Resource):
}
:internal_api: get_actions
"""
- try:
- data = PolicyManager.get_actions(
- user_id=user_id, policy_id=uuid, perimeter_id=perimeter_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.get_actions(
+ user_id=user_id, policy_id=uuid, perimeter_id=perimeter_id)
+
return {"actions": data}
- @validate_input("post", body_state=[True, False, False, False])
+ @validate_input("post", body_state={"name":True})
@check_auth
- def post(self, uuid=None, perimeter_id=None, user_id=None):
+ def post(self, uuid, perimeter_id=None, user_id=None):
"""Create or update a action.
:param uuid: uuid of the policy
@@ -383,23 +356,20 @@ class Actions(Resource):
}
:internal_api: set_action
"""
- try:
- data = PolicyManager.get_actions(user_id=user_id, policy_id=None)
- if 'name' in request.json:
- for data_id, data_value in data.items():
- if data_value['name'] == request.json['name']:
- perimeter_id = data_id
- break
- data = PolicyManager.add_action(
- user_id=user_id, policy_id=uuid,
- perimeter_id=perimeter_id, value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.get_actions(user_id=user_id, policy_id=uuid)
+ if 'name' in request.json:
+ for data_id, data_value in data.items():
+ if data_value['name'] == request.json['name']:
+ perimeter_id = data_id
+ break
+ data = PolicyManager.add_action(
+ user_id=user_id, policy_id=uuid,
+ perimeter_id=perimeter_id, value=request.json)
+
return {"actions": data}
- @validate_input("patch", kwargs_state=[False, True, False], body_state=[True, False, False, False])
+ @validate_input("patch", kwargs_state=[False, True, False], body_state={"name":True})
@check_auth
def patch(self, uuid, perimeter_id=None, user_id=None):
"""Create or update a action.
@@ -419,20 +389,17 @@ class Actions(Resource):
}
:internal_api: set_action
"""
- try:
- data = PolicyManager.get_actions(user_id=user_id, policy_id=None)
- if 'name' in request.json:
- for data_id, data_value in data.items():
- if data_value['name'] == request.json['name']:
- perimeter_id = data_id
- break
- data = PolicyManager.add_action(
- user_id=user_id, policy_id=uuid,
- perimeter_id=perimeter_id, value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.get_actions(user_id=user_id, policy_id=uuid)
+ if 'name' in request.json:
+ for data_id, data_value in data.items():
+ if data_value['name'] == request.json['name']:
+ perimeter_id = data_id
+ break
+ data = PolicyManager.add_action(
+ user_id=user_id, policy_id=uuid,
+ perimeter_id=perimeter_id, value=request.json)
+
return {"actions": data}
@validate_input("delete", kwargs_state=[False, True, False])
@@ -451,11 +418,8 @@ class Actions(Resource):
}
:internal_api: delete_action
"""
- try:
- data = PolicyManager.delete_action(
- user_id=user_id, policy_id=uuid, perimeter_id=perimeter_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.delete_action(
+ user_id=user_id, policy_id=uuid, perimeter_id=perimeter_id)
+
return {"result": True}
diff --git a/moon_manager/moon_manager/api/policies.py b/moon_manager/moon_manager/api/policies.py
index 1a9e0bae..9fe237b2 100644
--- a/moon_manager/moon_manager/api/policies.py
+++ b/moon_manager/moon_manager/api/policies.py
@@ -12,6 +12,8 @@ from flask_restful import Resource
import logging
from python_moonutilities.security_functions import check_auth
from python_moondb.core import PolicyManager
+from python_moonutilities.security_functions import validate_input
+
__version__ = "4.3.2"
@@ -30,6 +32,7 @@ class Policies(Resource):
"/policies/<string:uuid>/",
)
+ @validate_input("get", kwargs_state=[False, False])
@check_auth
def get(self, uuid=None, user_id=None):
"""Retrieve all policies
@@ -46,14 +49,12 @@ class Policies(Resource):
}
:internal_api: get_policies
"""
- try:
- data = PolicyManager.get_policies(user_id=user_id, policy_id=uuid)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.get_policies(user_id=user_id, policy_id=uuid)
+
return {"policies": data}
+ @validate_input("post", body_state={"name": True, "model_id":True})
@check_auth
def post(self, uuid=None, user_id=None):
"""Create policy.
@@ -76,17 +77,15 @@ class Policies(Resource):
}
:internal_api: add_policy
"""
- try:
- data = PolicyManager.add_policy(
- user_id=user_id, policy_id=uuid, value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.add_policy(
+ user_id=user_id, policy_id=uuid, value=request.json)
+
return {"policies": data}
+ @validate_input("delete", kwargs_state=[ True, False])
@check_auth
- def delete(self, uuid, user_id=None):
+ def delete(self, uuid=None, user_id=None):
"""Delete a policy
:param uuid: uuid of the policy to delete
@@ -97,16 +96,14 @@ class Policies(Resource):
}
:internal_api: delete_policy
"""
- try:
- data = PolicyManager.delete_policy(user_id=user_id, policy_id=uuid)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.delete_policy(user_id=user_id, policy_id=uuid)
+
return {"result": True}
+ @validate_input("patch", kwargs_state=[True, False], body_state={"name": True, "model_id":True})
@check_auth
- def patch(self, uuid, user_id=None):
+ def patch(self, uuid=None, user_id=None):
"""Update a policy
:param uuid: uuid of the policy to update
@@ -121,12 +118,9 @@ class Policies(Resource):
}
:internal_api: update_policy
"""
- try:
- data = PolicyManager.update_policy(
- user_id=user_id, policy_id=uuid, value=request.json)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.update_policy(
+ user_id=user_id, policy_id=uuid, value=request.json)
+
return {"policies": data}
diff --git a/moon_manager/moon_manager/api/rules.py b/moon_manager/moon_manager/api/rules.py
index ecb066d9..a0248097 100644
--- a/moon_manager/moon_manager/api/rules.py
+++ b/moon_manager/moon_manager/api/rules.py
@@ -49,17 +49,14 @@ class Rules(Resource):
}
:internal_api: get_rules
"""
- try:
- data = PolicyManager.get_rules(user_id=user_id,
+
+ data = PolicyManager.get_rules(user_id=user_id,
policy_id=uuid,
rule_id=rule_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
return {"rules": data}
- @validate_input("post", kwargs_state=[True, False, False], body_state=[True, False, False, False])
+ @validate_input("post", kwargs_state=[True, False, False], body_state={"meta_rule_id": True, "rule": True, "instructions": True})
@check_auth
def post(self, uuid=None, rule_id=None, user_id=None):
"""Add a rule to a meta rule
@@ -111,15 +108,12 @@ class Rules(Resource):
:internal_api: add_rule
"""
args = request.json
- try:
- data = PolicyManager.add_rule(user_id=user_id,
- policy_id=uuid,
- meta_rule_id=args['meta_rule_id'],
- value=args)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.add_rule(user_id=user_id,
+ policy_id=uuid,
+ meta_rule_id=args['meta_rule_id'],
+ value=args)
+
return {"rules": data}
@validate_input("delete", kwargs_state=[True, True, False])
@@ -133,12 +127,9 @@ class Rules(Resource):
:return: { "result": true }
:internal_api: delete_rule
"""
- try:
- data = PolicyManager.delete_rule(
- user_id=user_id, policy_id=uuid, rule_id=rule_id)
- except Exception as e:
- logger.error(e, exc_info=True)
- return {"result": False,
- "error": str(e)}, 500
+
+ data = PolicyManager.delete_rule(
+ user_id=user_id, policy_id=uuid, rule_id=rule_id)
+
return {"result": True}
diff --git a/moon_manager/moon_manager/api/slaves.py b/moon_manager/moon_manager/api/slaves.py
index f5b3fa14..769b681f 100644
--- a/moon_manager/moon_manager/api/slaves.py
+++ b/moon_manager/moon_manager/api/slaves.py
@@ -11,12 +11,11 @@ from flask import request
from flask_restful import Resource
import logging
import requests
-import time
from python_moonutilities.security_functions import check_auth
-from python_moondb.core import PDPManager
-from python_moondb.core import PolicyManager
-from python_moondb.core import ModelManager
-from python_moonutilities import configuration, exceptions
+
+from python_moonutilities import configuration
+from python_moonutilities.security_functions import validate_input
+
__version__ = "4.3.0"
@@ -42,6 +41,7 @@ class Slaves(Resource):
self.orchestrator_port = conf["components/orchestrator"].get("port",
80)
+ @validate_input("get", kwargs_state=[False, False])
@check_auth
def get(self, uuid=None, user_id=None):
"""Retrieve all slaves
@@ -66,6 +66,8 @@ class Slaves(Resource):
))
return {"slaves": req.json().get("slaves", dict())}
+ @validate_input("patch", kwargs_state=[False, False],
+ body_state={"op": True, "variable": True, "value": True})
@check_auth
def patch(self, uuid=None, user_id=None):
"""Update a slave
diff --git a/moon_manager/moon_manager/http_server.py b/moon_manager/moon_manager/http_server.py
index a7258a75..204e7e04 100644
--- a/moon_manager/moon_manager/http_server.py
+++ b/moon_manager/moon_manager/http_server.py
@@ -112,11 +112,12 @@ class CustomApi(Api):
@staticmethod
def handle_error(e):
try:
- error_message = dumps({'message': str(e), "code": getattr(e, "code", 500)})
+ error_message = dumps({"result": False, 'message': str(e), "code": getattr(e, "code", 500)})
+ logger.error(e, exc_info=True)
logger.error(error_message)
return make_response(error_message, getattr(e, "code", 500))
except Exception as e2: # unhandled exception in the api...
- logger.error(str(e2))
+ logger.exception(str(e2))
return make_response(error_message, 500)
@@ -132,7 +133,7 @@ class HTTPServer(Server):
self.manager_port = conf["components/manager"].get("port", 80)
# TODO : specify only few urls instead of *
CORS(self.app)
- self.api = CustomApi(self.app)
+ self.api = CustomApi(self.app, catch_all_404s=True)
self.__set_route()
def __set_route(self):
diff --git a/moon_manager/tests/unit_python/api/import_export_utilities.py b/moon_manager/tests/unit_python/api/import_export_utilities.py
index b1c8a541..12cb208e 100644
--- a/moon_manager/tests/unit_python/api/import_export_utilities.py
+++ b/moon_manager/tests/unit_python/api/import_export_utilities.py
@@ -3,13 +3,12 @@
# license which can be found in the file 'LICENSE' in this package distribution
# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
-import api.utilities as utilities
import api.test_unit_models as test_models
import api.test_policies as test_policies
import api.test_perimeter as test_perimeter
-import api.meta_data_test as test_categories
+import api.test_meta_data as test_categories
import api.test_data as test_data
-import api.meta_rules_test as test_meta_rules
+import api.test_meta_rules as test_meta_rules
import api.test_assignemnt as test_assignments
import api.test_rules as test_rules
import logging
@@ -21,7 +20,6 @@ def clean_models(client):
req, models = test_models.get_models(client)
for key in models["models"]:
client.delete("/models/{}".format(key))
- print("deleted model with id {}".format(key))
def clean_policies(client):
@@ -29,7 +27,6 @@ def clean_policies(client):
for key in policies["policies"]:
req = client.delete("/policies/{}".format(key))
assert req.status_code == 200
- print("deleted policy with id {}".format(key))
def clean_subjects(client):
@@ -40,9 +37,8 @@ def clean_subjects(client):
policy_keys = subject["policy_list"]
logger.info("subjects policy_keys {}".format(policy_keys))
for policy_key in policy_keys:
- client.delete("/policies/{}/subjects/{}".format(policy_key,key))
+ client.delete("/policies/{}/subjects/{}".format(policy_key, key))
client.delete("/subjects/{}".format(key))
- print("deleted subject with id {}".format(key))
def clean_objects(client):
@@ -53,15 +49,13 @@ def clean_objects(client):
policy_keys = object_["policy_list"]
logger.info("objects policy_keys {}".format(policy_keys))
for policy_key in policy_keys:
- print("/policies/{}/objects/{}".format(policy_key, key))
- req = client.delete("/policies/{}/objects/{}".format(policy_key, key))
+ client.delete("/policies/{}/objects/{}".format(policy_key, key))
client.delete("/objects/{}".format(key))
- print("deleted object with id {}".format(key))
def clean_actions(client):
actions = test_perimeter.get_actions(client)
- logger.info("objects {}".format(actions))
+ logger.info("actions {}".format(actions))
for key in actions[1]["actions"]:
action = actions[1]["actions"][key]
policy_keys = action["policy_list"]
@@ -69,7 +63,6 @@ def clean_actions(client):
for policy_key in policy_keys:
client.delete("/policies/{}/actions/{}".format(policy_key, key))
client.delete("/actions/{}".format(key))
- print("deleted action with id {}".format(key))
def clean_subject_categories(client):
@@ -95,10 +88,12 @@ def clean_action_categories(client):
def clean_subject_data(client):
req, policies = test_policies.get_policies(client)
+ logger.info("clean_subject_data on {}".format(policies))
for policy_key in policies["policies"]:
req, data = test_data.get_subject_data(client, policy_id=policy_key)
- print(data)
+ logger.info("============= data {}".format(data))
for key in data["subject_data"]:
+ logger.info("============= Deleting {}/{}".format(policy_key, key))
client.delete("/policies/{}/subject_data/{}".format(policy_key, key))
@@ -106,7 +101,6 @@ def clean_object_data(client):
req, policies = test_policies.get_policies(client)
for policy_key in policies["policies"]:
req, data = test_data.get_object_data(client, policy_id=policy_key)
- print(data)
for key in data["object_data"]:
client.delete("/policies/{}/object_data/{}".format(policy_key, key))
@@ -123,7 +117,8 @@ def clean_meta_rule(client):
req, meta_rules = test_meta_rules.get_meta_rules(client)
meta_rules = meta_rules["meta_rules"]
for meta_rule_key in meta_rules:
- print(meta_rule_key)
+ logger.info("clean_meta_rule.meta_rule_key={}".format(meta_rule_key))
+ logger.info("clean_meta_rule.meta_rule={}".format(meta_rules[meta_rule_key]))
client.delete("/meta_rules/{}".format(meta_rule_key))
@@ -136,7 +131,8 @@ def clean_subject_assignments(client):
cat_key = assignments["subject_assignments"][key]["category_id"]
data_keys = assignments["subject_assignments"][key]["assignments"]
for data_key in data_keys:
- req = client.delete("/policies/{}/subject_assignments/{}/{}/{}".format(policy_key, subject_key, cat_key, data_key))
+ client.delete("/policies/{}/subject_assignments/{}/{}/{}".format(policy_key, subject_key,
+ cat_key, data_key))
def clean_object_assignments(client):
@@ -148,7 +144,8 @@ def clean_object_assignments(client):
cat_key = assignments["object_assignments"][key]["category_id"]
data_keys = assignments["object_assignments"][key]["assignments"]
for data_key in data_keys:
- req = client.delete("/policies/{}/object_assignments/{}/{}/{}".format(policy_key, object_key, cat_key, data_key))
+ client.delete("/policies/{}/object_assignments/{}/{}/{}".format(policy_key, object_key,
+ cat_key, data_key))
def clean_action_assignments(client):
@@ -160,14 +157,14 @@ def clean_action_assignments(client):
cat_key = assignments["action_assignments"][key]["category_id"]
data_keys = assignments["action_assignments"][key]["assignments"]
for data_key in data_keys:
- req = client.delete("/policies/{}/action_assignments/{}/{}/{}".format(policy_key, action_key, cat_key, data_key))
+ client.delete("/policies/{}/action_assignments/{}/{}/{}".format(policy_key, action_key,
+ cat_key, data_key))
def clean_rules(client):
req, policies = test_policies.get_policies(client)
for policy_key in policies["policies"]:
req, rules = test_rules.get_rules(client, policy_key)
- print(rules)
rules = rules["rules"]
rules = rules["rules"]
for rule_key in rules:
@@ -183,10 +180,6 @@ def clean_all(client):
clean_meta_rule(client)
- clean_subject_categories(client)
- clean_object_categories(client)
- clean_action_categories(client)
-
clean_subject_data(client)
clean_object_data(client)
clean_action_data(client)
@@ -195,5 +188,9 @@ def clean_all(client):
clean_objects(client)
clean_subjects(client)
+ clean_subject_categories(client)
+ clean_object_categories(client)
+ clean_action_categories(client)
+
clean_policies(client)
- clean_models(client) \ No newline at end of file
+ clean_models(client)
diff --git a/moon_manager/tests/unit_python/api/test_assignemnt.py b/moon_manager/tests/unit_python/api/test_assignemnt.py
index 4e2acddc..22c727af 100644
--- a/moon_manager/tests/unit_python/api/test_assignemnt.py
+++ b/moon_manager/tests/unit_python/api/test_assignemnt.py
@@ -1,5 +1,7 @@
import api.utilities as utilities
import json
+from helpers import data_builder as builder
+from uuid import uuid4
# subject_categories_test
@@ -11,11 +13,19 @@ def get_subject_assignment(client, policy_id):
return req, subject_assignment
-def add_subject_assignment(client, policy_id, category_id):
+def add_subject_assignment(client):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex)
+ subject_id = builder.create_subject(policy_id)
+ data_id = builder.create_subject_data(policy_id=policy_id, category_id=subject_category_id)
+
data = {
- "id": "id1",
- "category_id": category_id,
- "data_id": "data_id1"
+ "id": subject_id,
+ "category_id": subject_category_id,
+ "data_id": data_id
}
req = client.post("/policies/{}/subject_assignments".format(policy_id), data=json.dumps(data),
headers={'Content-Type': 'application/json'})
@@ -23,36 +33,42 @@ def add_subject_assignment(client, policy_id, category_id):
return req, subject_assignment
+def add_subject_assignment_without_cat_id(client):
+
+ data = {
+ "id": "subject_id",
+ "category_id": "",
+ "data_id": "data_id"
+ }
+ req = client.post("/policies/{}/subject_assignments".format("1111"), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ subject_assignment = utilities.get_json(req.data)
+ return req, subject_assignment
+
+
def delete_subject_assignment(client, policy_id, sub_id, cat_id,data_id):
req = client.delete("/policies/{}/subject_assignments/{}/{}/{}".format(policy_id, sub_id, cat_id,data_id))
return req
def test_add_subject_assignment():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, subject_assignment = add_subject_assignment(client, policy_id, "111")
+ req, subject_assignment = add_subject_assignment(client)
assert req.status_code == 200
assert isinstance(subject_assignment, dict)
- value = subject_assignment["subject_assignments"]
assert "subject_assignments" in subject_assignment
- id = list(value.keys())[0]
- assert value[id]['policy_id'] == policy_id
- assert value[id]['category_id'] == "111"
- assert value[id]['subject_id'] == "id1"
def test_add_subject_assignment_without_cat_id():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, subject_assignment = add_subject_assignment(client, policy_id, "")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == 'Empty String'
+ req, subject_assignment = add_subject_assignment_without_cat_id(client)
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'category_id', [Empty String]"
def test_get_subject_assignment():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
+ policy_id = builder.get_policy_id_with_subject_assignment()
req, subject_assignment = get_subject_assignment(client, policy_id)
assert req.status_code == 200
assert isinstance(subject_assignment, dict)
@@ -61,7 +77,7 @@ def test_get_subject_assignment():
def test_delete_subject_assignment():
client = utilities.register_client()
- policy_id = utilities.get_policy_id()
+ policy_id = builder.get_policy_id_with_subject_assignment()
req, subject_assignment = get_subject_assignment(client, policy_id)
value = subject_assignment["subject_assignments"]
id = list(value.keys())[0]
@@ -72,7 +88,7 @@ def test_delete_subject_assignment():
def test_delete_subject_assignment_without_policy_id():
client = utilities.register_client()
success_req = delete_subject_assignment(client, "", "id1", "111" ,"data_id1")
- assert success_req.status_code == 500
+ assert success_req.status_code == 404
# ---------------------------------------------------------------------------
@@ -86,13 +102,35 @@ def get_object_assignment(client, policy_id):
return req, object_assignment
-def add_object_assignment(client, policy_id, category_id):
+def add_object_assignment(client):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex)
+ object_id = builder.create_object(policy_id)
+ data_id = builder.create_object_data(policy_id=policy_id, category_id=object_category_id)
+
+ data = {
+ "id": object_id,
+ "category_id": object_category_id,
+ "data_id": data_id
+ }
+
+ req = client.post("/policies/{}/object_assignments".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ object_assignment = utilities.get_json(req.data)
+ return req, object_assignment
+
+
+def add_object_assignment_without_cat_id(client):
+
data = {
- "id": "id1",
- "category_id": category_id,
- "data_id": "data_id1"
+ "id": "object_id",
+ "category_id": "",
+ "data_id": "data_id"
}
- req = client.post("/policies/{}/object_assignments/{}".format(policy_id, category_id), data=json.dumps(data),
+ req = client.post("/policies/{}/object_assignments".format("1111"), data=json.dumps(data),
headers={'Content-Type': 'application/json'})
object_assignment = utilities.get_json(req.data)
return req, object_assignment
@@ -104,7 +142,7 @@ def delete_object_assignment(client, policy_id, obj_id, cat_id, data_id):
def test_get_object_assignment():
- policy_id = utilities.get_policy_id()
+ policy_id = builder.get_policy_id_with_object_assignment()
client = utilities.register_client()
req, object_assignment = get_object_assignment(client, policy_id)
assert req.status_code == 200
@@ -113,30 +151,22 @@ def test_get_object_assignment():
def test_add_object_assignment():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, object_assignment = add_object_assignment(client, policy_id, "111")
+ req, object_assignment = add_object_assignment(client)
assert req.status_code == 200
- assert isinstance(object_assignment, dict)
- value = object_assignment["object_assignments"]
assert "object_assignments" in object_assignment
- id = list(value.keys())[0]
- assert value[id]['policy_id'] == policy_id
- assert value[id]['category_id'] == "111"
- assert value[id]['object_id'] == "id1"
def test_add_object_assignment_without_cat_id():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, object_assignment = add_object_assignment(client, policy_id, "")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == 'Empty String'
+ req, object_assignment = add_object_assignment_without_cat_id(client)
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'category_id', [Empty String]"
def test_delete_object_assignment():
client = utilities.register_client()
- policy_id = utilities.get_policy_id()
+ policy_id = builder.get_policy_id_with_object_assignment()
req, object_assignment = get_object_assignment(client, policy_id)
value = object_assignment["object_assignments"]
id = list(value.keys())[0]
@@ -146,8 +176,8 @@ def test_delete_object_assignment():
def test_delete_object_assignment_without_policy_id():
client = utilities.register_client()
- success_req = delete_object_assignment(client, "", "id1", "111" ,"data_id1")
- assert success_req.status_code == 500
+ success_req = delete_object_assignment(client, "", "id1", "111","data_id1")
+ assert success_req.status_code == 404
# ---------------------------------------------------------------------------
@@ -161,13 +191,34 @@ def get_action_assignment(client, policy_id):
return req, action_assignment
-def add_action_assignment(client, policy_id, category_id):
+def add_action_assignment(client):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex)
+ action_id = builder.create_action(policy_id)
+ data_id = builder.create_action_data(policy_id=policy_id, category_id=action_category_id)
+
+ data = {
+ "id": action_id,
+ "category_id": action_category_id,
+ "data_id": data_id
+ }
+ req = client.post("/policies/{}/action_assignments".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ action_assignment = utilities.get_json(req.data)
+ return req, action_assignment
+
+
+def add_action_assignment_without_cat_id(client):
+
data = {
- "id": "id1",
- "category_id": category_id,
- "data_id": "data_id1"
+ "id": "action_id",
+ "category_id": "",
+ "data_id": "data_id"
}
- req = client.post("/policies/{}/action_assignments/{}".format(policy_id, category_id), data=json.dumps(data),
+ req = client.post("/policies/{}/action_assignments".format("1111"), data=json.dumps(data),
headers={'Content-Type': 'application/json'})
action_assignment = utilities.get_json(req.data)
return req, action_assignment
@@ -179,7 +230,7 @@ def delete_action_assignment(client, policy_id, action_id, cat_id, data_id):
def test_get_action_assignment():
- policy_id = utilities.get_policy_id()
+ policy_id = builder.get_policy_id_with_action_assignment()
client = utilities.register_client()
req, action_assignment = get_action_assignment(client, policy_id)
assert req.status_code == 200
@@ -188,30 +239,22 @@ def test_get_action_assignment():
def test_add_action_assignment():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, action_assignment = add_action_assignment(client, policy_id, "111")
+ req, action_assignment = add_action_assignment(client)
assert req.status_code == 200
- assert isinstance(action_assignment, dict)
- value = action_assignment["action_assignments"]
assert "action_assignments" in action_assignment
- id = list(value.keys())[0]
- assert value[id]['policy_id'] == policy_id
- assert value[id]['category_id'] == "111"
- assert value[id]['action_id'] == "id1"
def test_add_action_assignment_without_cat_id():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, action_assignment = add_action_assignment(client, policy_id, "")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == 'Empty String'
+ req, action_assignment = add_action_assignment_without_cat_id(client)
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'category_id', [Empty String]"
def test_delete_action_assignment():
client = utilities.register_client()
- policy_id = utilities.get_policy_id()
+ policy_id = builder.get_policy_id_with_action_assignment()
req, action_assignment = get_action_assignment(client, policy_id)
value = action_assignment["action_assignments"]
id = list(value.keys())[0]
@@ -222,6 +265,6 @@ def test_delete_action_assignment():
def test_delete_action_assignment_without_policy_id():
client = utilities.register_client()
success_req = delete_action_assignment(client, "", "id1", "111" ,"data_id1")
- assert success_req.status_code == 500
+ assert success_req.status_code == 404
# ---------------------------------------------------------------------------
diff --git a/moon_manager/tests/unit_python/api/test_data.py b/moon_manager/tests/unit_python/api/test_data.py
index f806ea2a..ff0856af 100644
--- a/moon_manager/tests/unit_python/api/test_data.py
+++ b/moon_manager/tests/unit_python/api/test_data.py
@@ -5,7 +5,8 @@
import api.utilities as utilities
import json
-
+from helpers import data_builder as builder
+from uuid import uuid4
# subject_categories_test
@@ -19,12 +20,17 @@ def get_subject_data(client, policy_id, category_id=None):
return req, subject_data
-def add_subject_data(client, name, policy_id, category_id):
+def add_subject_data(client, name):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex)
data = {
"name": name,
"description": "description of {}".format(name)
}
- req = client.post("/policies/{}/subject_data/{}".format(policy_id, category_id), data=json.dumps(data),
+ req = client.post("/policies/{}/subject_data/{}".format(policy_id, subject_category_id), data=json.dumps(data),
headers={'Content-Type': 'application/json'})
subject_data = utilities.get_json(req.data)
return req, subject_data
@@ -45,9 +51,8 @@ def test_get_subject_data():
def test_add_subject_data():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, subject_data = add_subject_data(client, "testuser", policy_id, "111")
+ req, subject_data = add_subject_data(client, "testuser")
assert req.status_code == 200
assert isinstance(subject_data, dict)
value = subject_data["subject_data"]['data']
@@ -59,31 +64,29 @@ def test_add_subject_data():
def test_delete_subject_data():
client = utilities.register_client()
- policy_id = utilities.get_policy_id()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id,policy_id = builder.create_new_policy()
success_req = delete_subject_data(client, policy_id)
assert success_req.status_code == 200
def test_add_subject_data_with_empty_user():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, subject_data = add_subject_data(client, "", policy_id, "111")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "Empty String"
+ req, subject_data = add_subject_data(client, "")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
def test_add_subject_data_with_user_contain_space():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, subject_data = add_subject_data(client, "test user", policy_id, "111")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "String contains space"
+ req, subject_data = add_subject_data(client, "test user")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
def test_delete_subject_data_without_policy_id():
client = utilities.register_client()
success_req = delete_subject_data(client, "")
- assert success_req.status_code == 500
+ assert success_req.status_code == 404
# ---------------------------------------------------------------------------
@@ -99,12 +102,17 @@ def get_object_data(client, policy_id, category_id=None):
return req, object_data
-def add_object_data(client, name, policy_id, category_id):
+def add_object_data(client, name):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex)
data = {
"name": name,
"description": "description of {}".format(name)
}
- req = client.post("/policies/{}/object_data/{}".format(policy_id, category_id), data=json.dumps(data),
+ req = client.post("/policies/{}/object_data/{}".format(policy_id, object_category_id), data=json.dumps(data),
headers={'Content-Type': 'application/json'})
object_data = utilities.get_json(req.data)
return req, object_data
@@ -125,9 +133,8 @@ def test_get_object_data():
def test_add_object_data():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, object_data = add_object_data(client, "testuser", policy_id, "111")
+ req, object_data = add_object_data(client, "testuser")
assert req.status_code == 200
assert isinstance(object_data, dict)
value = object_data["object_data"]['data']
@@ -149,25 +156,23 @@ def test_delete_object_data():
def test_add_object_data_with_empty_user():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, subject_data = add_subject_data(client, "", policy_id, "111")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "Empty String"
+ req, subject_data = add_object_data(client, "")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
def test_add_object_data_with_user_contain_space():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, object_data = add_object_data(client, "test user", policy_id, "111")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "String contains space"
+ req, object_data = add_object_data(client, "test user")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
def test_delete_object_data_without_policy_id():
client = utilities.register_client()
success_req = delete_object_data(client, "")
- assert success_req.status_code == 500
+ assert success_req.status_code == 404
# ---------------------------------------------------------------------------
# action_categories_test
@@ -182,12 +187,17 @@ def get_action_data(client, policy_id, category_id=None):
return req, action_data
-def add_action_data(client, name, policy_id, category_id):
+def add_action_data(client, name):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex)
data = {
"name": name,
"description": "description of {}".format(name)
}
- req = client.post("/policies/{}/action_data/{}".format(policy_id, category_id), data=json.dumps(data),
+ req = client.post("/policies/{}/action_data/{}".format(policy_id, action_category_id), data=json.dumps(data),
headers={'Content-Type': 'application/json'})
action_data = utilities.get_json(req.data)
return req, action_data
@@ -208,9 +218,8 @@ def test_get_action_data():
def test_add_action_data():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, action_data = add_action_data(client, "testuser", policy_id, "111")
+ req, action_data = add_action_data(client, "testuser")
assert req.status_code == 200
assert isinstance(action_data, dict)
value = action_data["action_data"]['data']
@@ -228,23 +237,21 @@ def test_delete_action_data():
def test_add_action_data_with_empty_user():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, action_data = add_action_data(client, "", policy_id, "111")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "Empty String"
+ req, action_data = add_action_data(client, "")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
def test_add_action_data_with_user_contain_space():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, action_data = add_action_data(client, "test user", policy_id, "111")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "String contains space"
+ req, action_data = add_action_data(client, "test user")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
def test_delete_action_data_without_policy_id():
client = utilities.register_client()
success_req = delete_action_data(client, "")
- assert success_req.status_code == 500
+ assert success_req.status_code == 404
# ---------------------------------------------------------------------------
diff --git a/moon_manager/tests/unit_python/api/test_export.py b/moon_manager/tests/unit_python/api/test_export.py
index 122ab927..ac8e8d17 100644
--- a/moon_manager/tests/unit_python/api/test_export.py
+++ b/moon_manager/tests/unit_python/api/test_export.py
@@ -51,11 +51,11 @@ ASSIGNMENTS = {"models": [{"name": "test model", "description": "", "meta_rules"
"action_data": [{"name": "test action data", "description": "action data description", "policies": [{"name": "test policy"}], "category": {"name": "test action categories"}}],
"meta_rules": [{"name": "meta rule", "description": "valid meta rule", "subject_categories": [{"name": "test subject categories"}], "object_categories": [{"name": "test object categories"}], "action_categories": [{"name": "test action categories"}]}],
"subjects": [{"name": "testuser", "description": "description of the subject", "extra": {"field_extra_subject": "value extra subject"}, "policies": [{"name": "test policy"}]}],
- "objects": [{"name": "test object", "description": "description of the object", "extra": {"field_extra_object": "value extra object"}, "policies": [{"name": "test policy"}]}],
- "actions": [{"name": "test action", "description": "description of the action", "extra": {"field_extra_action": "value extra action"}, "policies": [{"name": "test policy"}]}],
+ "objects": [{"name": "test object e0", "description": "description of the object", "extra": {"field_extra_object": "value extra object"}, "policies": [{"name": "test policy"}]}],
+ "actions": [{"name": "test action e0", "description": "description of the action", "extra": {"field_extra_action": "value extra action"}, "policies": [{"name": "test policy"}]}],
"subject_assignments": [{"subject": {"name": "testuser"}, "category": {"name": "test subject categories"}, "assignments": [{"name": "test subject data"}]}],
- "object_assignments": [{"object": {"name": "test object"}, "category": {"name": "test object categories"}, "assignments": [{"name": "test object data"}]}],
- "action_assignments": [{"action": {"name": "test action"}, "category": {"name": "test action categories"}, "assignments": [{"name": "test action data"}]}]}
+ "object_assignments": [{"object": {"name": "test object e0"}, "category": {"name": "test object categories"}, "assignments": [{"name": "test object data"}]}],
+ "action_assignments": [{"action": {"name": "test action e0"}, "category": {"name": "test action categories"}, "assignments": [{"name": "test action data"}]}]}
RULES = {"models": [{"name": "test model", "description": "", "meta_rules": [{"name": "meta rule"}]}],
"policies": [{"name": "test policy", "genre": "authz", "description": "policy description", "model": {"name" : "test model"}}],
@@ -67,12 +67,12 @@ RULES = {"models": [{"name": "test model", "description": "", "meta_rules": [{"n
"action_data": [{"name": "test action data", "description": "action data description", "policies": [{"name": "test policy"}], "category": {"name": "test action categories"}}],
"meta_rules": [{"name": "meta rule", "description": "valid meta rule", "subject_categories": [{"name": "test subject categories"}], "object_categories": [{"name": "test object categories"}], "action_categories": [{"name": "test action categories"}]}],
"subjects": [{"name": "testuser", "description": "description of the subject", "extra": {"field_extra_subject": "value extra subject"}, "policies": [{"name": "test policy"}]}],
- "objects": [{"name": "test object", "description": "description of the object", "extra": {"field_extra_object": "value extra object"}, "policies": [{"name": "test policy"}]}],
- "actions": [{"name": "test action", "description": "description of the action", "extra": {"field_extra_action": "value extra action"}, "policies": [{"name": "test policy"}]}],
+ "objects": [{"name": "test object e1", "description": "description of the object", "extra": {"field_extra_object": "value extra object"}, "policies": [{"name": "test policy"}]}],
+ "actions": [{"name": "test action e1", "description": "description of the action", "extra": {"field_extra_action": "value extra action"}, "policies": [{"name": "test policy"}]}],
"subject_assignments": [{"subject": {"name": "testuser"}, "category": {"name": "test subject categories"}, "assignments": [{"name": "test subject data"}]}],
- "object_assignments": [{"object": {"name": "test object"}, "category": {"name": "test object categories"}, "assignments": [{"name": "test object data"}]}],
- "action_assignments": [{"action": {"name": "test action"}, "category": {"name": "test action categories"}, "assignments": [{"name": "test action data"}]}],
- "rules": [{"meta_rule": {"name" : "meta rule"}, "rule": {"subject_data" : [{"name":"test subject data"}], "object_data": [{"name": "test object data"}], "action_data": [{"name": "test action data"}]}, "policy": {"name" :"test policy"}, "instructions" : {"decision" : "grant"}, "enabled": True}]
+ "object_assignments": [{"object": {"name": "test object e1"}, "category": {"name": "test object categories"}, "assignments": [{"name": "test object data"}]}],
+ "action_assignments": [{"action": {"name": "test action e1"}, "category": {"name": "test action categories"}, "assignments": [{"name": "test action data"}]}],
+ "rules": [{"meta_rule": {"name": "meta rule"}, "rule": {"subject_data": [{"name": "test subject data"}], "object_data": [{"name": "test object data"}], "action_data": [{"name": "test action data"}]}, "policy": {"name":"test policy"}, "instructions": {"decision": "grant"}, "enabled": True}]
}
@@ -87,7 +87,6 @@ def test_export_models():
assert req.status_code == 200
data = utilities.get_json(req.data)
- print(data)
assert "content" in data
assert "models" in data["content"]
assert isinstance(data["content"]["models"], list)
@@ -110,7 +109,6 @@ def test_export_policies():
assert req.status_code == 200
data = utilities.get_json(req.data)
- print(data)
assert "content" in data
assert "policies" in data["content"]
assert isinstance(data["content"]["policies"], list)
@@ -136,7 +134,6 @@ def test_export_subject_object_action():
assert req.status_code == 200
data = utilities.get_json(req.data)
- print(data)
assert "content" in data
type_elements = ["subject", "object", "action"]
for type_element in type_elements:
@@ -158,10 +155,8 @@ def test_export_subject_object_action():
assert isinstance(element["extra"], dict)
key_dict = "field_extra_" + type_element
value_dict = "value extra " + type_element
- #TODO change this after bug fix on extra
- if False:
- assert key_dict in element["extra"]
- assert element["extra"][key_dict] == value_dict
+ assert key_dict in element["extra"]
+ assert element["extra"][key_dict] == value_dict
def test_export_subject_object_action_categories():
@@ -196,7 +191,6 @@ def test_export_subject_object_action_data():
req = client.get("/export")
assert req.status_code == 200
data = utilities.get_json(req.data)
- print(data)
assert "content" in data
type_elements = ["subject", "object", "action"]
for type_element in type_elements:
@@ -207,9 +201,9 @@ def test_export_subject_object_action_data():
data_elt = data["content"][key][0]
assert data_elt["name"] == "test " + type_element + " data"
assert data_elt["description"] == type_element + " data description"
- assert isinstance(data_elt["policy"],dict)
+ assert isinstance(data_elt["policy"], dict)
assert data_elt["policy"]["name"] == "test policy"
- assert isinstance(data_elt["category"],dict)
+ assert isinstance(data_elt["category"], dict)
assert data_elt["category"]["name"] == "test " + type_element + " categories"
@@ -223,7 +217,6 @@ def test_export_assignments():
req = client.get("/export")
assert req.status_code == 200
data = utilities.get_json(req.data)
- print(data)
assert "content" in data
type_elements = ["subject", "object", "action"]
for type_element in type_elements:
@@ -237,7 +230,7 @@ def test_export_assignments():
if type_element == "subject":
assert assignment_elt[type_element]["name"] == "testuser"
else:
- assert assignment_elt[type_element]["name"] == "test " + type_element
+ assert assignment_elt[type_element]["name"] == "test " + type_element + " e0"
assert "category" in assignment_elt
assert isinstance(assignment_elt["category"], dict)
assert assignment_elt["category"]["name"] == "test " + type_element + " categories"
@@ -246,6 +239,8 @@ def test_export_assignments():
assert len(assignment_elt["assignments"]) == 1
assert assignment_elt["assignments"][0]["name"] == "test " + type_element + " data"
+ import_export_utilities.clean_all(client)
+
def test_export_rules():
client = utilities.register_client()
@@ -257,7 +252,6 @@ def test_export_rules():
req = client.get("/export")
assert req.status_code == 200
data = utilities.get_json(req.data)
- print(data)
assert "content" in data
assert "rules" in data["content"]
assert isinstance(data["content"]["rules"], list)
@@ -267,7 +261,7 @@ def test_export_rules():
assert "decision" in rule["instructions"]
assert rule["instructions"]["decision"] == "grant"
assert "enabled" in rule
- assert rule["enabled"] == True
+ assert rule["enabled"]
assert "meta_rule" in rule
assert rule["meta_rule"]["name"] == "meta rule"
assert "policy" in rule
diff --git a/moon_manager/tests/unit_python/api/test_import.py b/moon_manager/tests/unit_python/api/test_import.py
index 12a1cc6b..f1ab8251 100644
--- a/moon_manager/tests/unit_python/api/test_import.py
+++ b/moon_manager/tests/unit_python/api/test_import.py
@@ -6,10 +6,9 @@
import api.utilities as utilities
import api.test_unit_models as test_models
import api.test_policies as test_policies
-import api.test_perimeter as test_perimeter
-import api.meta_data_test as test_categories
+import api.test_meta_data as test_categories
import api.test_data as test_data
-import api.meta_rules_test as test_meta_rules
+import api.test_meta_rules as test_meta_rules
import api.test_assignemnt as test_assignments
import api.test_rules as test_rules
import api.import_export_utilities as import_export_utilities
@@ -37,11 +36,17 @@ SUBJECTS = [{"subjects": [{"name": "testuser", "description": "description of th
{"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}], "subjects": [{"name": "testuser", "description": "description of the subject", "extra": {}, "policies": [{"name": "test policy"}]}]}]
-OBJECTS = [{"objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": []}]},
- {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}], "objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": []}]},
- {"policies": [{"name": "test other policy", "genre": "authz", "description": "description", "model": {}, "mandatory": True}], "objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": []}]},
- {"objects": [{"name": "test object", "description": "new description of the object", "extra": {"test": "test extra"}, "policies": [{"name": "test other policy"}]}]},
- {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}], "objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": [{"name": "test policy"}]}]}]
+OBJECTS = [
+ {"objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": []}]},
+ {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}],
+ "objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": []}]},
+ {"policies": [{"name": "test other policy", "genre": "authz", "description": "description", "model": {}, "mandatory": True}],
+ "objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": []}]},
+ {"objects": [{"name": "test object", "description": "new description of the object", "extra": {"test": "test extra"},
+ "policies": [{"name": "test other policy"}]}]},
+ {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}],
+ "objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": [{"name": "test policy"}]}]},
+]
ACTIONS = [{"actions": [{"name": "test action", "description": "description of the action", "extra": {}, "policies": []}]},
@@ -100,7 +105,8 @@ META_RULES = [{"meta_rules" :[{"name": "bad meta rule", "description": "not vali
{"meta_rules": [{"name": "bad meta rule", "description": "not valid meta rule", "subject_categories": [{"name": "test subject categories"}], "object_categories": [{"name": "test object categories"}], "action_categories": [{"name": "not valid category"}]}]},
{"meta_rules": [{"name": "good meta rule", "description": "valid meta rule", "subject_categories": [{"name": "test subject categories"}], "object_categories": [{"name": "test object categories"}], "action_categories": [{"name": "test action categories"}]}]}]
-PRE_ASSIGNMENTS = {"models": [{"name": "test model", "description": "", "meta_rules": [{"name" : "good meta rule"}]}],
+
+PRE_ASSIGNMENTS = {"models": [{"name": "test model", "description": "", "meta_rules": [{"name": "good meta rule"}]}],
"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {"name" : "test model"}, "mandatory": True}],
"subject_categories": [{"name": "test subject categories", "description": "subject category description"}],
"object_categories": [{"name": "test object categories", "description": "object category description"}],
@@ -168,8 +174,8 @@ def test_import_policies():
try:
data = utilities.get_json(req.data)
assert data == "Import ok !"
- except Exception as e:
- assert counter == 2 # this is an expected failure
+ except Exception:
+ assert counter == 2 # this is an expected failure
continue
req, policies = test_policies.get_policies(client)
@@ -189,7 +195,7 @@ def test_import_policies():
def test_import_subject_object_action():
client = utilities.register_client()
- type_elements =["object", "action"]
+ type_elements = ["object", "action"]
for type_element in type_elements:
import_export_utilities.clean_all(client)
@@ -197,21 +203,18 @@ def test_import_subject_object_action():
# set the getters and the comparison values
if type_element == "subject":
elements = SUBJECTS
- get_method = test_perimeter.get_subjects
- clean_method= import_export_utilities.clean_subjects
+ clean_method = import_export_utilities.clean_subjects
name = "testuser"
key_extra = "email"
value_extra = "new-email@test.com"
elif type_element == "object":
elements = OBJECTS
- get_method = test_perimeter.get_objects
clean_method = import_export_utilities.clean_objects
name = "test object"
key_extra = "test"
value_extra = "test extra"
else:
elements = ACTIONS
- get_method = test_perimeter.get_actions
clean_method = import_export_utilities.clean_actions
name = "test action"
key_extra = "test"
@@ -219,7 +222,6 @@ def test_import_subject_object_action():
for element in elements:
counter = counter + 1
- print("counter {}".format(counter))
if counter == 2 or counter == 4:
clean_method(client)
@@ -231,28 +233,23 @@ def test_import_subject_object_action():
try:
data = utilities.get_json(req.data)
except Exception as e:
- print(str(e))
assert False
#assert counter < 2 #  this is an expected failure
#continue
assert data == "Import ok !"
- get_elements = get_method(client)
- get_elements = get_elements[1][type_element + "s"]
+ get_elements = utilities.get_json(client.get("/"+type_element + "s").data)
+ get_elements = get_elements[type_element + "s"]
assert len(list(get_elements.keys())) == 1
values = list(get_elements.values())
assert values[0]["name"] == name
- print(values[0])
if counter == 2 or counter == 4:
assert values[0]["description"] == "description of the " + type_element
- print(values[0])
#assert not values[0]["extra"]
if counter == 3:
- #TODO uncomment this if update shall be done through import !
- #assert values[0]["description"] == "new description of the " + type_element
- #assert values[0]["extra"][key_extra] == value_extra
- assert True
+ assert values[0]["description"] == "new description of the " + type_element
+ assert values[0]["extra"][key_extra] == value_extra
# assert len(values[0]["policy_list"]) == 1
import_export_utilities.clean_all(client)
@@ -309,10 +306,9 @@ def test_import_meta_rules():
assert data == "Import ok !"
assert req.status_code == 200
- req ,meta_rules= test_meta_rules.get_meta_rules(client)
+ req, meta_rules = test_meta_rules.get_meta_rules(client)
meta_rules = meta_rules["meta_rules"]
key = list(meta_rules.keys())[0]
- print(meta_rules)
assert isinstance(meta_rules,dict)
assert meta_rules[key]["name"] == "good meta rule"
assert meta_rules[key]["description"] == "valid meta rule"
@@ -367,8 +363,6 @@ def test_import_subject_object_action_assignments():
assert req.status_code == 500
continue
else:
- print(data)
- print(req)
assert data == "Import ok !"
assert req.status_code == 200
req, policies = test_policies.get_policies(client)
@@ -398,16 +392,13 @@ def test_import_rules():
req, rules = test_rules.test_get_rules()
rules = rules["rules"]
- policy_key = rules["policy_id"]
rules = rules["rules"]
- print(rules)
assert len(rules) == 1
rules = rules[0]
- assert rules["enabled"] == True
+ assert rules["enabled"]
assert rules["instructions"]["decision"] == "grant"
req, meta_rules = test_meta_rules.get_meta_rules(client)
- print(meta_rules)
assert meta_rules["meta_rules"][list(meta_rules["meta_rules"].keys())[0]]["name"] == "good meta rule"
@@ -439,7 +430,6 @@ def test_import_subject_object_action_data():
if counter == 0 or counter == 1:
assert req.status_code == 500
continue
- print(counter)
assert req.status_code == 200
data = utilities.get_json(req.data)
assert data == "Import ok !"
@@ -448,30 +438,20 @@ def test_import_subject_object_action_data():
policies = policies["policies"]
req, categories = get_categories(client)
categories = categories[type_element + "_categories"]
- print("categories {}".format(categories))
- print("policies {}".format(policies))
- print("data in import {}".format(element))
case_tested = False
for policy_key in policies.keys():
- print("policy in test {}".format(policy_key))
policy = policies[policy_key]
- print("policy {}".format(policy))
for category_key in categories:
- print("category in test {}".format(category_key))
- print("looking for {} data with policy {} and category {}".format(type_element, policy_key,category_key))
req, get_elements = get_method(client, policy_id=policy_key, category_id=category_key)
if len(get_elements[type_element+"_data"]) == 0:
continue
- # do this because the backend gives an element with empty data if the policy_key, category_key couple does not have any data...
+ # do this because the backend gives an element with empty data if the policy_key,
+ # category_key couple does not have any data...
get_elements = get_elements[type_element+"_data"]
- print("test")
if len(get_elements[0]["data"]) == 0:
- print("test2")
continue
- print("get_elements {}".format(get_elements))
-
if policy["name"] == "test policy":
assert len(get_elements) == 1
el = get_elements[0]
@@ -481,7 +461,6 @@ def test_import_subject_object_action_data():
el = el["data"][list(el["data"].keys())[0]]
if "value" in el:
el = el["value"]
- print(el)
assert el["name"] == "one valid " + type_element + " data"
if counter == 3:
assert len(el["data"].keys()) == 2
@@ -503,7 +482,6 @@ def test_import_subject_object_action_data():
assert isinstance(el["data"], dict)
assert len(el["data"].keys()) == 1
el = el["data"][list(el["data"].keys())[0]]
- print(el)
if "value" in el:
el = el["value"]
assert el["name"] == "valid " + type_element + " data"
@@ -517,4 +495,4 @@ def test_clean():
client = utilities.register_client()
import_export_utilities.clean_all(client)
#restore the database as previously
- utilities.get_policy_id() \ No newline at end of file
+ utilities.get_policy_id()
diff --git a/moon_manager/tests/unit_python/api/test_meta_data.py b/moon_manager/tests/unit_python/api/test_meta_data.py
new file mode 100644
index 00000000..4cb86913
--- /dev/null
+++ b/moon_manager/tests/unit_python/api/test_meta_data.py
@@ -0,0 +1,235 @@
+import json
+import api.utilities as utilities
+
+#subject_categories_test
+
+
+def get_subject_categories(client):
+ req = client.get("/subject_categories")
+ subject_categories = utilities.get_json(req.data)
+ return req, subject_categories
+
+
+def add_subject_categories(client, name):
+ data = {
+ "name": name,
+ "description": "description of {}".format(name)
+ }
+ req = client.post("/subject_categories", data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ subject_categories = utilities.get_json(req.data)
+ return req, subject_categories
+
+
+def delete_subject_categories(client, name):
+ request, subject_categories = get_subject_categories(client)
+ for key, value in subject_categories['subject_categories'].items():
+ if value['name'] == name:
+ return client.delete("/subject_categories/{}".format(key))
+
+
+def delete_subject_categories_without_id(client):
+ req = client.delete("/subject_categories/{}".format(""))
+ return req
+
+
+def test_get_subject_categories():
+ client = utilities.register_client()
+ req, subject_categories = get_subject_categories(client)
+ assert req.status_code == 200
+ assert isinstance(subject_categories, dict)
+ assert "subject_categories" in subject_categories
+
+
+def test_add_subject_categories():
+ client = utilities.register_client()
+ req, subject_categories = add_subject_categories(client, "testuser")
+ assert req.status_code == 200
+ assert isinstance(subject_categories, dict)
+ value = list(subject_categories["subject_categories"].values())[0]
+ assert "subject_categories" in subject_categories
+ assert value['name'] == "testuser"
+ assert value['description'] == "description of {}".format("testuser")
+
+
+def test_add_subject_categories_with_empty_user():
+ client = utilities.register_client()
+ req, subject_categories = add_subject_categories(client, "")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
+
+
+def test_add_subject_categories_with_user_contain_space():
+ client = utilities.register_client()
+ req, subject_categories = add_subject_categories(client, "test user")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
+
+
+def test_delete_subject_categories():
+ client = utilities.register_client()
+ req = delete_subject_categories(client, "testuser")
+ assert req.status_code == 200
+
+
+def test_delete_subject_categories_without_id():
+ client = utilities.register_client()
+ req = delete_subject_categories_without_id(client)
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "400: Subject Category Unknown"
+
+
+#---------------------------------------------------------------------------
+#object_categories_test
+
+def get_object_categories(client):
+ req = client.get("/object_categories")
+ object_categories = utilities.get_json(req.data)
+ return req, object_categories
+
+
+def add_object_categories(client, name):
+ data = {
+ "name": name,
+ "description": "description of {}".format(name)
+ }
+ req = client.post("/object_categories", data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ object_categories = utilities.get_json(req.data)
+ return req, object_categories
+
+
+def delete_object_categories(client, name):
+ request, object_categories = get_object_categories(client)
+ for key, value in object_categories['object_categories'].items():
+ if value['name'] == name:
+ return client.delete("/object_categories/{}".format(key))
+
+
+def delete_object_categories_without_id(client):
+ req = client.delete("/object_categories/{}".format(""))
+ return req
+
+
+def test_get_object_categories():
+ client = utilities.register_client()
+ req, object_categories = get_object_categories(client)
+ assert req.status_code == 200
+ assert isinstance(object_categories, dict)
+ assert "object_categories" in object_categories
+
+
+def test_add_object_categories():
+ client = utilities.register_client()
+ req, object_categories = add_object_categories(client, "testuser")
+ assert req.status_code == 200
+ assert isinstance(object_categories, dict)
+ value = list(object_categories["object_categories"].values())[0]
+ assert "object_categories" in object_categories
+ assert value['name'] == "testuser"
+ assert value['description'] == "description of {}".format("testuser")
+
+
+def test_add_object_categories_with_empty_user():
+ client = utilities.register_client()
+ req, object_categories = add_object_categories(client, "")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
+
+
+def test_add_object_categories_with_user_contain_space():
+ client = utilities.register_client()
+ req, object_categories = add_object_categories(client, "test user")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
+
+
+def test_delete_object_categories():
+ client = utilities.register_client()
+ req = delete_object_categories(client, "testuser")
+ assert req.status_code == 200
+
+
+def test_delete_object_categories_without_id():
+ client = utilities.register_client()
+ req = delete_object_categories_without_id(client)
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "400: Object Category Unknown"
+
+
+#---------------------------------------------------------------------------
+#action_categories_test
+
+def get_action_categories(client):
+ req = client.get("/action_categories")
+ action_categories = utilities.get_json(req.data)
+ return req, action_categories
+
+
+def add_action_categories(client, name):
+ data = {
+ "name": name,
+ "description": "description of {}".format(name)
+ }
+ req = client.post("/action_categories", data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ action_categories = utilities.get_json(req.data)
+ return req, action_categories
+
+
+def delete_action_categories(client, name):
+ request, action_categories = get_action_categories(client)
+ for key, value in action_categories['action_categories'].items():
+ if value['name'] == name:
+ return client.delete("/action_categories/{}".format(key))
+
+
+def delete_action_categories_without_id(client):
+ req = client.delete("/action_categories/{}".format(""))
+ return req
+
+
+def test_get_action_categories():
+ client = utilities.register_client()
+ req, action_categories = get_action_categories(client)
+ assert req.status_code == 200
+ assert isinstance(action_categories, dict)
+ assert "action_categories" in action_categories
+
+
+def test_add_action_categories():
+ client = utilities.register_client()
+ req, action_categories = add_action_categories(client, "testuser")
+ assert req.status_code == 200
+ assert isinstance(action_categories, dict)
+ value = list(action_categories["action_categories"].values())[0]
+ assert "action_categories" in action_categories
+ assert value['name'] == "testuser"
+ assert value['description'] == "description of {}".format("testuser")
+
+
+def test_add_action_categories_with_empty_user():
+ client = utilities.register_client()
+ req, action_categories = add_action_categories(client, "")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
+
+
+def test_add_action_categories_with_user_contain_space():
+ client = utilities.register_client()
+ req, action_categories = add_action_categories(client, "test user")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
+
+
+def test_delete_action_categories():
+ client = utilities.register_client()
+ req = delete_action_categories(client, "testuser")
+ assert req.status_code == 200
+
+
+def test_delete_action_categories_without_id():
+ client = utilities.register_client()
+ req = delete_action_categories_without_id(client)
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "400: Action Category Unknown"
diff --git a/moon_manager/tests/unit_python/api/test_meta_rules.py b/moon_manager/tests/unit_python/api/test_meta_rules.py
new file mode 100644
index 00000000..80d648b4
--- /dev/null
+++ b/moon_manager/tests/unit_python/api/test_meta_rules.py
@@ -0,0 +1,175 @@
+import json
+import api.utilities as utilities
+from helpers import category_helper
+from uuid import uuid4
+
+
+def get_meta_rules(client):
+ req = client.get("/meta_rules")
+ meta_rules = utilities.get_json(req.data)
+ return req, meta_rules
+
+
+def add_meta_rules(client, name):
+ subject_category = category_helper.add_subject_category(value={"name": "subject category name"+uuid4().hex, "description": "description 1"})
+ subject_category_id = list(subject_category.keys())[0]
+ object_category = category_helper.add_object_category(value={"name": "object category name"+ uuid4().hex, "description": "description 1"})
+ object_category_id = list(object_category.keys())[0]
+ action_category = category_helper.add_action_category(value={"name": "action category name"+uuid4().hex, "description": "description 1"})
+ action_category_id = list(action_category.keys())[0]
+
+ data = {
+ "name": name,
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
+ }
+ req = client.post("/meta_rules", data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ meta_rules = utilities.get_json(req.data)
+ return req, meta_rules
+
+
+def add_meta_rules_without_subject_category_ids(client, name):
+ data = {
+ "name": name,
+ "subject_categories": [],
+ "object_categories": ["object_category_id1"],
+ "action_categories": ["action_category_id1"]
+ }
+ req = client.post("/meta_rules", data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ meta_rules = utilities.get_json(req.data)
+ return req, meta_rules
+
+
+def update_meta_rules(client, name, metaRuleId):
+ subject_category = category_helper.add_subject_category(
+ value={"name": "subject category name update" + uuid4().hex, "description": "description 1"})
+ subject_category_id = list(subject_category.keys())[0]
+ object_category = category_helper.add_object_category(
+ value={"name": "object category name update" + uuid4().hex, "description": "description 1"})
+ object_category_id = list(object_category.keys())[0]
+ action_category = category_helper.add_action_category(
+ value={"name": "action category name update" + uuid4().hex, "description": "description 1"})
+ action_category_id = list(action_category.keys())[0]
+ data = {
+ "name": name,
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
+ }
+ req = client.patch("/meta_rules/{}".format(metaRuleId), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ meta_rules = utilities.get_json(req.data)
+ return req, meta_rules
+
+
+def update_meta_rules_without_subject_category_ids(client, name):
+ data = {
+ "name": name,
+ "subject_categories": [],
+ "object_categories": ["object_category_id1"],
+ "action_categories": ["action_category_id1"]
+ }
+ req = client.post("/meta_rules", data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ meta_rules = utilities.get_json(req.data)
+ return req, meta_rules
+
+
+def delete_meta_rules(client, name):
+ request, meta_rules = get_meta_rules(client)
+ for key, value in meta_rules['meta_rules'].items():
+ if value['name'] == name:
+ req = client.delete("/meta_rules/{}".format(key))
+ break
+ return req
+
+
+def delete_meta_rules_without_id(client):
+ req = client.delete("/meta_rules/{}".format(""))
+ return req
+
+
+def test_get_meta_rules():
+ client = utilities.register_client()
+ req, meta_rules = get_meta_rules(client)
+ assert req.status_code == 200
+ assert isinstance(meta_rules, dict)
+ assert "meta_rules" in meta_rules
+
+
+def test_add_meta_rules():
+ client = utilities.register_client()
+ req, meta_rules = add_meta_rules(client, "testuser")
+ assert req.status_code == 200
+ assert isinstance(meta_rules, dict)
+ value = list(meta_rules["meta_rules"].values())[0]
+ assert "meta_rules" in meta_rules
+ assert value['name'] == "testuser"
+
+
+def test_add_meta_rules_with_empty_user():
+ client = utilities.register_client()
+ req, meta_rules = add_meta_rules(client, "")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
+
+
+def test_add_meta_rules_with_user_contain_space():
+ client = utilities.register_client()
+ req, meta_rules = add_meta_rules(client, "test user")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
+
+
+def test_add_meta_rules_without_subject_categories():
+ client = utilities.register_client()
+ req, meta_rules = add_meta_rules_without_subject_category_ids(client, "testuser")
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'subject_categories', [Empty Container]"
+
+
+def test_delete_meta_rules():
+ client = utilities.register_client()
+ req = delete_meta_rules(client, "testuser")
+ assert req.status_code == 200
+
+
+def test_delete_meta_rules_without_id():
+ client = utilities.register_client()
+ req = delete_meta_rules_without_id(client)
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "400: Meta Rule Unknown"
+
+
+def test_update_meta_rules():
+ client = utilities.register_client()
+ req = add_meta_rules(client, "testuser")
+ meta_rule_id = list(req[1]['meta_rules'])[0]
+ req_update = update_meta_rules(client, "testuser", meta_rule_id)
+ assert req_update[0].status_code == 200
+ delete_meta_rules(client, "testuser")
+ get_meta_rules(client)
+
+
+def test_update_meta_rules_without_id():
+ client = utilities.register_client()
+ req_update = update_meta_rules(client, "testuser", "")
+ assert req_update[0].status_code == 400
+ assert json.loads(req_update[0].data)["message"] == "400: Meta Rule Unknown"
+
+
+def test_update_meta_rules_without_user():
+ client = utilities.register_client()
+ req_update = update_meta_rules(client, "", "")
+ assert req_update[0].status_code == 400
+ assert json.loads(req_update[0].data)["message"] == "Key: 'name', [Empty String]"
+
+
+def test_update_meta_rules_without_subject_categories():
+ client = utilities.register_client()
+ req_update = update_meta_rules_without_subject_category_ids(client, "testuser")
+ assert req_update[0].status_code == 400
+ assert json.loads(req_update[0].data)["message"] == "Key: 'subject_categories', [Empty Container]"
diff --git a/moon_manager/tests/unit_python/api/test_pdp.py b/moon_manager/tests/unit_python/api/test_pdp.py
index fbaa6c7b..1ac9b84f 100644
--- a/moon_manager/tests/unit_python/api/test_pdp.py
+++ b/moon_manager/tests/unit_python/api/test_pdp.py
@@ -1,6 +1,7 @@
import json
import api.utilities as utilities
-import pytest
+from helpers import data_builder as builder
+from uuid import uuid4
def get_pdp(client):
@@ -42,9 +43,15 @@ def test_get_pdp():
def test_add_pdp():
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex,
+ model_name="model1" + uuid4().hex)
data = {
"name": "testuser",
- "security_pipeline": ["policy_id_1", "policy_id_2"],
+ "security_pipeline": [policy_id],
"keystone_project_id": "keystone_project_id",
"description": "description of testuser"
}
@@ -78,8 +85,8 @@ def test_add_pdp_with_empty_user():
}
client = utilities.register_client()
req, models = add_pdp(client, data)
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "Empty String"
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
def test_add_pdp_with_user_contain_space():
@@ -91,8 +98,8 @@ def test_add_pdp_with_user_contain_space():
}
client = utilities.register_client()
req, models = add_pdp(client, data)
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "String contains space"
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
def test_add_pdp_without_security_pipeline():
@@ -104,8 +111,8 @@ def test_add_pdp_without_security_pipeline():
}
client = utilities.register_client()
req, meta_rules = add_pdp(client, data)
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == 'Empty Container'
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'security_pipeline', [Empty Container]"
def test_add_pdp_without_keystone():
@@ -117,20 +124,33 @@ def test_add_pdp_without_keystone():
}
client = utilities.register_client()
req, meta_rules = add_pdp(client, data)
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == 'Empty String'
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'keystone_project_id', [Empty String]"
def test_update_pdp():
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy(
+ subject_category_name="subject_category1"+uuid4().hex,
+ object_category_name="object_category1"+uuid4().hex,
+ action_category_name="action_category1"+uuid4().hex,
+ meta_rule_name="meta_rule_1"+uuid4().hex,
+ model_name="model1"+uuid4().hex)
data_add = {
"name": "testuser",
- "security_pipeline": ["policy_id_1", "policy_id_2"],
+ "security_pipeline": [policy_id],
"keystone_project_id": "keystone_project_id",
"description": "description of testuser"
}
+
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id_update = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex,
+ model_name="model1" + uuid4().hex)
data_update = {
"name": "testuser",
- "security_pipeline": ["policy_id_1_update", "policy_id_2_update"],
+ "security_pipeline": [policy_id_update],
"keystone_project_id": "keystone_project_id_update",
"description": "description of testuser"
}
@@ -151,7 +171,8 @@ def test_update_pdp():
def test_update_pdp_without_id():
client = utilities.register_client()
req_update = update_pdp(client, "testuser", "")
- assert req_update[0].status_code == 500
+ assert req_update[0].status_code == 400
+ assert json.loads(req_update[0].data)["message"] == 'Invalid Key :name not found'
def test_update_pdp_without_user():
@@ -163,8 +184,8 @@ def test_update_pdp_without_user():
}
client = utilities.register_client()
req_update = update_pdp(client, data, "")
- assert req_update[0].status_code == 500
- assert json.loads(req_update[0].data)["message"] == "Empty String"
+ assert req_update[0].status_code == 400
+ assert json.loads(req_update[0].data)["message"] == "Key: 'name', [Empty String]"
def test_update_pdp_without_security_pipeline():
@@ -176,5 +197,5 @@ def test_update_pdp_without_security_pipeline():
}
client = utilities.register_client()
req_update = update_pdp(client, data, "")
- assert req_update[0].status_code == 500
- assert json.loads(req_update[0].data)["message"] == "Empty Container" \ No newline at end of file
+ assert req_update[0].status_code == 400
+ assert json.loads(req_update[0].data)["message"] == "Key: 'security_pipeline', [Empty Container]" \ No newline at end of file
diff --git a/moon_manager/tests/unit_python/api/test_perimeter.py b/moon_manager/tests/unit_python/api/test_perimeter.py
index b13bb2ed..322d90c6 100644
--- a/moon_manager/tests/unit_python/api/test_perimeter.py
+++ b/moon_manager/tests/unit_python/api/test_perimeter.py
@@ -2,6 +2,8 @@
# import moon_manager.api
import json
import api.utilities as utilities
+from helpers import data_builder as builder
+from uuid import uuid4
def get_subjects(client):
@@ -11,13 +13,19 @@ def get_subjects(client):
def add_subjects(client, name):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex,
+ model_name="model1" + uuid4().hex)
data = {
- "name": name,
+ "name": name + uuid4().hex,
"description": "description of {}".format(name),
"password": "password for {}".format(name),
"email": "{}@moon".format(name)
}
- req = client.post("/subjects", data=json.dumps(data),
+ req = client.post("/policies/{}/subjects".format(policy_id), data=json.dumps(data),
headers={'Content-Type': 'application/json'})
subjects = utilities.get_json(req.data)
return req, subjects
@@ -25,11 +33,10 @@ def add_subjects(client, name):
def delete_subject(client):
subjects = get_subjects(client)
- for key, value in subjects[1]['subjects'].items():
- if value['name'] == "testuser":
- req = client.delete("/subjects/{}".format(key))
- break
- return req
+ value = subjects[1]['subjects']
+ id = list(value.keys())[0]
+ policy_id = builder.get_policy_id_with_subject_assignment()
+ return client.delete("/policies/{}/subjects/{}".format(policy_id, id))
def delete_subjects_without_perimeter_id(client):
@@ -48,25 +55,39 @@ def test_perimeter_get_subject():
def test_perimeter_add_subject():
client = utilities.register_client()
req, subjects = add_subjects(client, "testuser")
- assert req.status_code == 200
value = list(subjects["subjects"].values())[0]
+ assert req.status_code == 200
assert "subjects" in subjects
- assert value['name'] == "testuser"
- assert value["email"] == "{}@moon".format("testuser")
+ assert value["name"] is not None
+ assert value["email"] is not None
def test_perimeter_add_subject_without_name():
client = utilities.register_client()
- req, subjects = add_subjects(client, "")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "Empty String"
+ data = {
+ "name": "",
+ "description": "description of {}".format(""),
+ "password": "password for {}".format(""),
+ "email": "{}@moon".format("")
+ }
+ req = client.post("/policies/{}/subjects".format("111"), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
def test_perimeter_add_subject_with_name_contain_spaces():
client = utilities.register_client()
- req, subjects = add_subjects(client, "test user")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "String contains space"
+ data = {
+ "name": "test user",
+ "description": "description of {}".format("test user"),
+ "password": "password for {}".format("test user"),
+ "email": "{}@moon".format("test user")
+ }
+ req = client.post("/policies/{}/subjects".format("111"), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
def test_perimeter_delete_subject():
@@ -78,7 +99,8 @@ def test_perimeter_delete_subject():
def test_perimeter_delete_subjects_without_perimeter_id():
client = utilities.register_client()
req = delete_subjects_without_perimeter_id(client)
- assert req.status_code == 500
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "400: Subject Unknown"
def get_objects(client):
@@ -88,11 +110,17 @@ def get_objects(client):
def add_objects(client, name):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policyId = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex,
+ model_name="model1" + uuid4().hex)
data = {
- "name": name,
+ "name": name + uuid4().hex,
"description": "description of {}".format(name),
}
- req = client.post("/objects", data=json.dumps(data),
+ req = client.post("/policies/{}/objects/".format(policyId), data=json.dumps(data),
headers={'Content-Type': 'application/json'})
objects = utilities.get_json(req.data)
return req, objects
@@ -100,11 +128,10 @@ def add_objects(client, name):
def delete_object(client):
objects = get_objects(client)
- for key, value in objects[1]['objects'].items():
- if value['name'] == "testuser":
- req = client.delete("/objects/{}".format(key))
- break
- return req
+ value = objects[1]['objects']
+ id = list(value.keys())[0]
+ policy_id = builder.get_policy_id_with_object_assignment()
+ return client.delete("/policies/{}/objects/{}".format(policy_id, id))
def delete_objects_without_perimeter_id(client):
@@ -123,24 +150,34 @@ def test_perimeter_get_object():
def test_perimeter_add_object():
client = utilities.register_client()
req, objects = add_objects(client, "testuser")
- assert req.status_code == 200
value = list(objects["objects"].values())[0]
+ assert req.status_code == 200
assert "objects" in objects
- assert value['name'] == "testuser"
+ assert value['name'] is not None
def test_perimeter_add_object_without_name():
client = utilities.register_client()
- req, objects = add_objects(client, "")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "Empty String"
+ data = {
+ "name": "",
+ "description": "description of {}".format(""),
+ }
+ req = client.post("/policies/{}/objects/".format("111"), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
def test_perimeter_add_object_with_name_contain_spaces():
client = utilities.register_client()
- req, objects = add_objects(client, "test user")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "String contains space"
+ data = {
+ "name": "test user",
+ "description": "description of {}".format("test user"),
+ }
+ req = client.post("/policies/{}/objects/".format("111"), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
def test_perimeter_delete_object():
@@ -152,7 +189,8 @@ def test_perimeter_delete_object():
def test_perimeter_delete_objects_without_perimeter_id():
client = utilities.register_client()
req = delete_objects_without_perimeter_id(client)
- assert req.status_code == 500
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "400: Object Unknown"
def get_actions(client):
@@ -162,11 +200,17 @@ def get_actions(client):
def add_actions(client, name):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policyId = builder.create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex,
+ model_name="model1" + uuid4().hex)
data = {
- "name": name,
+ "name": name + uuid4().hex,
"description": "description of {}".format(name),
}
- req = client.post("/actions", data=json.dumps(data),
+ req = client.post("/policies/{}/actions".format(policyId), data=json.dumps(data),
headers={'Content-Type': 'application/json'})
actions = utilities.get_json(req.data)
return req, actions
@@ -174,11 +218,10 @@ def add_actions(client, name):
def delete_actions(client):
actions = get_actions(client)
- for key, value in actions[1]['actions'].items():
- if value['name'] == "testuser":
- req = client.delete("/actions/{}".format(key))
- break
- return req
+ value = actions[1]['actions']
+ id = list(value.keys())[0]
+ policy_id = builder.get_policy_id_with_action_assignment()
+ return client.delete("/policies/{}/actions/{}".format(policy_id, id))
def delete_actions_without_perimeter_id(client):
@@ -197,24 +240,34 @@ def test_perimeter_get_actions():
def test_perimeter_add_actions():
client = utilities.register_client()
req, actions = add_actions(client, "testuser")
- assert req.status_code == 200
value = list(actions["actions"].values())[0]
+ assert req.status_code == 200
assert "actions" in actions
- assert value['name'] == "testuser"
+ assert value['name'] is not None
def test_perimeter_add_actions_without_name():
client = utilities.register_client()
- req, actions = add_actions(client, "")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "Empty String"
+ data = {
+ "name": "",
+ "description": "description of {}".format(""),
+ }
+ req = client.post("/policies/{}/actions".format("111"), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
def test_perimeter_add_actions_with_name_contain_spaces():
client = utilities.register_client()
- req, actions = add_actions(client, "test user")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "String contains space"
+ data = {
+ "name": "test user",
+ "description": "description of {}".format("test user"),
+ }
+ req = client.post("/policies/{}/actions".format("111"), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
def test_perimeter_delete_actions():
@@ -226,5 +279,5 @@ def test_perimeter_delete_actions():
def test_perimeter_delete_actions_without_perimeter_id():
client = utilities.register_client()
req = delete_actions_without_perimeter_id(client)
- assert req.status_code == 500
-
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "400: Action Unknown"
diff --git a/moon_manager/tests/unit_python/api/test_policies.py b/moon_manager/tests/unit_python/api/test_policies.py
index 40be35e6..cd50f4c7 100644
--- a/moon_manager/tests/unit_python/api/test_policies.py
+++ b/moon_manager/tests/unit_python/api/test_policies.py
@@ -4,8 +4,9 @@
# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
import json
-import api.utilities as utilities
from uuid import uuid4
+import api.utilities as utilities
+from helpers import model_helper
def get_policies(client):
@@ -15,10 +16,12 @@ def get_policies(client):
def add_policies(client, name):
+ req = model_helper.add_model(model_id="mls_model_id"+uuid4().hex)
+ model_id = list(req.keys())[0]
data = {
"name": name,
"description": "description of {}".format(name),
- "model_id": "modelId",
+ "model_id": model_id,
"genre": "genre"
}
req = client.post("/policies", data=json.dumps(data),
@@ -30,9 +33,8 @@ def add_policies(client, name):
def delete_policies(client, name):
request, policies = get_policies(client)
for key, value in policies['policies'].items():
- if value['name'] == name:
- req = client.delete("/policies/{}".format(key))
- break
+ req = client.delete("/policies/{}".format(key))
+ break
return req
@@ -50,8 +52,8 @@ def test_get_policies():
def test_add_policies():
- client = utilities.register_client()
policy_name = "testuser" + uuid4().hex
+ client = utilities.register_client()
req, policies = add_policies(client, policy_name)
assert req.status_code == 200
assert isinstance(policies, dict)
@@ -59,8 +61,6 @@ def test_add_policies():
assert "policies" in policies
assert value['name'] == policy_name
assert value["description"] == "description of {}".format(policy_name)
- assert value["model_id"] == "modelId"
- assert value["genre"] == "genre"
def test_delete_policies():
@@ -72,5 +72,6 @@ def test_delete_policies():
def test_delete_policies_without_id():
client = utilities.register_client()
req = delete_policies_without_id(client)
- assert req.status_code == 500
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == '400: Policy Unknown'
diff --git a/moon_manager/tests/unit_python/api/test_rules.py b/moon_manager/tests/unit_python/api/test_rules.py
index d12b7186..af1501e4 100644
--- a/moon_manager/tests/unit_python/api/test_rules.py
+++ b/moon_manager/tests/unit_python/api/test_rules.py
@@ -1,5 +1,8 @@
import api.utilities as utilities
import json
+from helpers import data_builder as builder
+from uuid import uuid4
+from helpers import policy_helper
def get_rules(client, policy_id):
@@ -8,10 +11,16 @@ def get_rules(client, policy_id):
return req, rules
-def add_rules(client, policy_id):
+def add_rules(client):
+ sub_id, obj_id, act_id, meta_rule_id, policy_id = builder.create_new_policy("sub_cat" + uuid4().hex,
+ "obj_cat" + uuid4().hex,
+ "act_cat" + uuid4().hex)
+ sub_data_id = builder.create_subject_data(policy_id, sub_id)
+ obj_data_id = builder.create_object_data(policy_id, obj_id)
+ act_data_id = builder.create_action_data(policy_id, act_id)
data = {
- "meta_rule_id": "meta_rule_id1",
- "rule": ["subject_data_id2", "object_data_id2", "action_data_id2"],
+ "meta_rule_id": meta_rule_id,
+ "rule": [sub_data_id, obj_data_id, act_data_id],
"instructions": (
{"decision": "grant"},
),
@@ -23,6 +32,21 @@ def add_rules(client, policy_id):
return req, rules
+def add_rules_without_policy_id(client):
+ data = {
+ "meta_rule_id": "meta_rule_id",
+ "rule": ["sub_data_id", "obj_data_id", "act_data_id"],
+ "instructions": (
+ {"decision": "grant"},
+ ),
+ "enabled": True
+ }
+ req = client.post("/policies/{}/rules".format(None), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ rules = utilities.get_json(req.data)
+ return req, rules
+
+
def add_rules_without_meta_rule_id(client, policy_id):
data = {
"meta_rule_id": "",
@@ -68,48 +92,57 @@ def test_get_rules():
def test_add_rules():
- policy_id = utilities.get_policy_id()
client = utilities.register_client()
- req, rules = add_rules(client, policy_id)
+ req, rules = add_rules(client, )
assert req.status_code == 200
- assert isinstance(rules, dict)
- value = rules["rules"]
- assert "rules" in rules
- id = list(value.keys())[0]
- assert value[id]["meta_rule_id"] == "meta_rule_id1"
def test_add_rules_without_policy_id():
client = utilities.register_client()
- req, rules = add_rules(client, None)
- assert req.status_code == 500
+ req, rules = add_rules_without_policy_id(client)
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "400: Policy Unknown"
def test_add_rules_without_meta_rule_id():
policy_id = utilities.get_policy_id()
client = utilities.register_client()
req, rules = add_rules_without_meta_rule_id(client, policy_id)
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == 'Empty String'
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'meta_rule_id', [Empty String]"
def test_add_rules_without_rule():
policy_id = utilities.get_policy_id()
client = utilities.register_client()
req, rules = add_rules_without_rule(client, policy_id)
- assert req.status_code == 500
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == 'Invalid Key :rule not found'
-def test_delete_rules():
+def test_delete_rules_with_invalid_parameters():
client = utilities.register_client()
rules = delete_rules(client, "", "")
- assert rules.status_code == 500
+ assert rules.status_code == 404
def test_delete_rules_without_policy_id():
client = utilities.register_client()
- policy_id = utilities.get_policy_id()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy()
+ sub_data_id = builder.create_subject_data(policy_id, subject_category_id)
+ obj_data_id = builder.create_object_data(policy_id, object_category_id)
+ act_data_id = builder.create_action_data(policy_id, action_category_id)
+ data = {
+ "meta_rule_id": meta_rule_id,
+ "rule": [sub_data_id, obj_data_id, act_data_id],
+ "instructions": (
+ {"decision": "grant"},
+ ),
+ "enabled": True
+ }
+ client.post("/policies/{}/rules".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
req, added_rules = get_rules(client, policy_id)
- id = added_rules["rules"]['rules'][0]['id']
+ id = list(added_rules["rules"]["rules"])[0]["id"]
rules = delete_rules(client, None, id)
assert rules.status_code == 200
diff --git a/moon_manager/tests/unit_python/api/test_unit_models.py b/moon_manager/tests/unit_python/api/test_unit_models.py
index 52cb2871..d754b976 100644
--- a/moon_manager/tests/unit_python/api/test_unit_models.py
+++ b/moon_manager/tests/unit_python/api/test_unit_models.py
@@ -5,6 +5,8 @@
import json
import api.utilities as utilities
+from helpers import data_builder as builder
+from uuid import uuid4
def get_models(client):
@@ -14,10 +16,14 @@ def get_models(client):
def add_models(client, name):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule(
+ subject_category_name="subject_category"+uuid4().hex,
+ object_category_name="object_category"+uuid4().hex, action_category_name="action_category"+uuid4().hex,
+ meta_rule_name="meta_rule" + uuid4().hex)
data = {
"name": name,
"description": "description of {}".format(name),
- "meta_rules": ["meta_rule_id1", "meta_rule_id2"]
+ "meta_rules": [meta_rule_id]
}
req = client.post("/models", data=json.dumps(data),
headers={'Content-Type': 'application/json'})
@@ -26,13 +32,18 @@ def add_models(client, name):
def update_model(client, name, model_id):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule(
+ subject_category_name="subject_category" + uuid4().hex,
+ object_category_name="object_category" + uuid4().hex, action_category_name="action_category" + uuid4().hex,
+ meta_rule_name="meta_rule" + uuid4().hex)
+
data = {
"name": name,
"description": "description of {}".format(name),
- "meta_rules": ["meta_rule_id1_update", "meta_rule_id2_update"]
+ "meta_rules": [meta_rule_id]
}
req = client.patch("/models/{}".format(model_id), data=json.dumps(data),
- headers={'Content-Type': 'application/json'})
+ headers={'Content-Type': 'application/json'})
models = utilities.get_json(req.data)
return req, models
@@ -56,7 +67,7 @@ def update_model_without_meta_rules_ids(client, name):
"meta_rules": []
}
req = client.patch("/models", data=json.dumps(data),
- headers={'Content-Type': 'application/json'})
+ headers={'Content-Type': 'application/json'})
models = utilities.get_json(req.data)
return req, models
@@ -77,7 +88,7 @@ def delete_models_without_id(client):
def clean_models():
client = utilities.register_client()
- req, models= get_models(client)
+ req, models = get_models(client)
for key, value in models['models'].items():
print(key)
print(value)
@@ -86,7 +97,7 @@ def clean_models():
def test_get_models():
client = utilities.register_client()
- req, models= get_models(client)
+ req, models = get_models(client)
assert req.status_code == 200
assert isinstance(models, dict)
assert "models" in models
@@ -98,11 +109,10 @@ def test_add_models():
req, models = add_models(client, "testuser")
assert req.status_code == 200
assert isinstance(models, dict)
- value = list(models["models"].values())[0]
+ model_id = list(models["models"])[0]
assert "models" in models
- assert value['name'] == "testuser"
- assert value["description"] == "description of {}".format("testuser")
- assert value["meta_rules"][0] == "meta_rule_id1"
+ assert models['models'][model_id]['name'] == "testuser"
+ assert models['models'][model_id]["description"] == "description of {}".format("testuser")
def test_delete_models():
@@ -114,31 +124,32 @@ def test_delete_models():
def test_delete_models_without_id():
client = utilities.register_client()
req = delete_models_without_id(client)
- assert req.status_code == 500
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "400: Model Unknown"
def test_add_model_with_empty_user():
clean_models()
client = utilities.register_client()
req, models = add_models(client, "")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "Empty String"
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [Empty String]"
def test_add_model_with_user_contain_space():
clean_models()
client = utilities.register_client()
req, models = add_models(client, "test user")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == "String contains space"
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'name', [String contains space]"
def test_add_model_without_meta_rules():
clean_models()
client = utilities.register_client()
req, meta_rules = add_model_without_meta_rules_ids(client, "testuser")
- assert req.status_code == 500
- assert json.loads(req.data)["message"] == 'Empty Container'
+ assert req.status_code == 400
+ assert json.loads(req.data)["message"] == "Key: 'meta_rules', [Empty Container]"
def test_update_model():
@@ -148,8 +159,8 @@ def test_update_model():
model_id = list(req[1]['models'])[0]
req_update = update_model(client, "testuser", model_id)
assert req_update[0].status_code == 200
- value = list(req_update[1]["models"].values())[0]
- assert value["meta_rules"][0] == "meta_rule_id1_update"
+ model_id = list(req_update[1]["models"])[0]
+ assert req_update[1]["models"][model_id]["meta_rules"][0] is not None
delete_models(client, "testuser")
@@ -157,19 +168,19 @@ def test_update_meta_rules_without_id():
clean_models()
client = utilities.register_client()
req_update = update_model(client, "testuser", "")
- assert req_update[0].status_code == 500
+ assert req_update[0].status_code == 400
+ assert json.loads(req_update[0].data)["message"] == "400: Model Unknown"
def test_update_meta_rules_without_user():
client = utilities.register_client()
req_update = update_model(client, "", "")
- assert req_update[0].status_code == 500
- assert json.loads(req_update[0].data)["message"] == "Empty String"
+ assert req_update[0].status_code == 400
+ assert json.loads(req_update[0].data)["message"] == "Key: 'name', [Empty String]"
def test_update_meta_rules_without_meta_rules():
client = utilities.register_client()
req_update = update_model_without_meta_rules_ids(client, "testuser")
- assert req_update[0].status_code == 500
- assert json.loads(req_update[0].data)["message"] == "Empty Container"
-
+ assert req_update[0].status_code == 400
+ assert json.loads(req_update[0].data)["message"] == "Key: 'meta_rules', [Empty Container]"
diff --git a/moon_manager/tests/unit_python/api/utilities.py b/moon_manager/tests/unit_python/api/utilities.py
index ce897619..2e51fec8 100644
--- a/moon_manager/tests/unit_python/api/utilities.py
+++ b/moon_manager/tests/unit_python/api/utilities.py
@@ -1,5 +1,5 @@
import json
-
+from uuid import uuid4
def get_json(data):
return json.loads(data.decode("utf-8"))
@@ -13,16 +13,14 @@ def register_client():
def get_policy_id():
- import api.test_policies as policies
- client = register_client()
- policy_id = ''
- req, policy = policies.get_policies(client)
- for id in policy['policies']:
- if id:
- policy_id = id
- break
- print("policy id {}".format(policy_id))
- if not policy_id:
- policies.add_policies(client, "testuser")
- policy_id = get_policy_id()
+ from helpers import policy_helper
+ value = {
+ "name": "test_policy"+uuid4().hex,
+ "model_id": "",
+ "genre": "authz",
+ "description": "test",
+ }
+ policy_helper.add_policies(value=value)
+ req = policy_helper.get_policies()
+ policy_id = list(req.keys())[0]
return policy_id
diff --git a/moon_manager/tests/unit_python/conftest.py b/moon_manager/tests/unit_python/conftest.py
index 902a41a2..d9899231 100644
--- a/moon_manager/tests/unit_python/conftest.py
+++ b/moon_manager/tests/unit_python/conftest.py
@@ -187,12 +187,14 @@ def no_requests(monkeypatch):
'DELETE', 'http://keystone:5000/v3/auth/tokens',
headers={'X-Subject-Token': "111111111"}
)
+
+ def match_request_text(request):
+ # request.url may be None, or '' prevents a TypeError.
+ return 'http://keystone:5000/v3/users?name=testuser' in request.url
+
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',
+ requests_mock.ANY, '/v3/users',
+ additional_matcher=match_request_text,
json={"users": {}}
)
m.register_uri(
diff --git a/moon_manager/tests/unit_python/helpers/__init__.py b/moon_manager/tests/unit_python/helpers/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/moon_manager/tests/unit_python/helpers/__init__.py
diff --git a/moon_manager/tests/unit_python/helpers/assignment_helper.py b/moon_manager/tests/unit_python/helpers/assignment_helper.py
new file mode 100644
index 00000000..22a56e38
--- /dev/null
+++ b/moon_manager/tests/unit_python/helpers/assignment_helper.py
@@ -0,0 +1,49 @@
+# 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'.
+
+def get_action_assignments(policy_id, action_id=None, category_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_action_assignments("", policy_id, action_id, category_id)
+
+
+def add_action_assignment(policy_id, action_id, category_id, data_id):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_action_assignment("", policy_id, action_id, category_id, data_id)
+
+
+def delete_action_assignment(policy_id, action_id, category_id, data_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_action_assignment("", policy_id, action_id, category_id, data_id)
+
+
+def get_object_assignments(policy_id, object_id=None, category_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_object_assignments("", policy_id, object_id, category_id)
+
+
+def add_object_assignment(policy_id, object_id, category_id, data_id):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_object_assignment("", policy_id, object_id, category_id, data_id)
+
+
+def delete_object_assignment(policy_id, object_id, category_id, data_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_object_assignment("", policy_id, object_id, category_id, data_id)
+
+
+def get_subject_assignments(policy_id, subject_id=None, category_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_subject_assignments("", policy_id, subject_id, category_id)
+
+
+def add_subject_assignment(policy_id, subject_id, category_id, data_id):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_subject_assignment("", policy_id, subject_id, category_id, data_id)
+
+
+def delete_subject_assignment(policy_id, subject_id, category_id, data_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_subject_assignment("", policy_id, subject_id, category_id, data_id)
+
diff --git a/moon_manager/tests/unit_python/helpers/category_helper.py b/moon_manager/tests/unit_python/helpers/category_helper.py
new file mode 100644
index 00000000..6c419ca8
--- /dev/null
+++ b/moon_manager/tests/unit_python/helpers/category_helper.py
@@ -0,0 +1,40 @@
+# 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'.
+
+
+def add_subject_category(cat_id=None, value=None):
+ from python_moondb.core import ModelManager
+ category = ModelManager.add_subject_category(user_id=None, category_id=cat_id, value=value)
+ return category
+
+
+def get_subject_category(cat_id=None):
+ from python_moondb.core import ModelManager
+ category = ModelManager.get_subject_categories(user_id=None, category_id=cat_id)
+ return category
+
+
+def add_object_category(cat_id=None, value=None):
+ from python_moondb.core import ModelManager
+ category = ModelManager.add_object_category(user_id=None, category_id=cat_id, value=value)
+ return category
+
+
+def get_object_category(cat_id=None):
+ from python_moondb.core import ModelManager
+ category = ModelManager.get_object_categories(user_id=None, category_id=cat_id)
+ return category
+
+
+def add_action_category(cat_id=None, value=None):
+ from python_moondb.core import ModelManager
+ category = ModelManager.add_action_category(user_id=None, category_id=cat_id, value=value)
+ return category
+
+
+def get_action_category(cat_id=None):
+ from python_moondb.core import ModelManager
+ category = ModelManager.get_action_categories(user_id=None, category_id=cat_id)
+ return category
diff --git a/moon_manager/tests/unit_python/helpers/data_builder.py b/moon_manager/tests/unit_python/helpers/data_builder.py
new file mode 100644
index 00000000..2a7c5979
--- /dev/null
+++ b/moon_manager/tests/unit_python/helpers/data_builder.py
@@ -0,0 +1,209 @@
+# 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 .category_helper import *
+from .policy_helper import *
+from .data_helper import *
+from helpers import model_helper
+from .meta_rule_helper import *
+import api.utilities as utilities
+import json
+
+
+def create_subject_category(name):
+ subject_category = add_subject_category(
+ value={"name": name + uuid4().hex, "description": "description 1"})
+ return list(subject_category.keys())[0]
+
+
+def create_object_category(name):
+ object_category = add_object_category(
+ value={"name": name + uuid4().hex, "description": "description 1"})
+ return list(object_category.keys())[0]
+
+
+def create_action_category(name):
+ action_category = add_action_category(
+ value={"name": name + uuid4().hex, "description": "description 1"})
+ return list(action_category.keys())[0]
+
+
+def create_model(meta_rule_id, model_name="test_model"):
+ value = {
+ "name": model_name + uuid4().hex,
+ "description": "test",
+ "meta_rules": [meta_rule_id]
+
+ }
+ return value
+
+
+def create_policy(model_id, policy_name="policy_1"):
+ value = {
+ "name": policy_name,
+ "model_id": model_id,
+ "genre": "authz",
+ "description": "test",
+ }
+ return value
+
+
+def create_pdp(policies_ids):
+ value = {
+ "name": "test_pdp",
+ "security_pipeline": policies_ids,
+ "keystone_project_id": "keystone_project_id1",
+ "description": "...",
+ }
+ return value
+
+
+def create_new_policy(subject_category_name="subjectCategory", object_category_name="objectCategory",
+ action_category_name="actionCategory",
+ model_name="test_model" + uuid4().hex, policy_name="policy_1" + uuid4().hex,
+ meta_rule_name="meta_rule1" + uuid4().hex):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = create_new_meta_rule(
+ subject_category_name=subject_category_name + uuid4().hex,
+ object_category_name=object_category_name + uuid4().hex,
+ action_category_name=action_category_name + uuid4().hex, meta_rule_name=meta_rule_name + uuid4().hex)
+ model = model_helper.add_model(value=create_model(meta_rule_id, model_name))
+ model_id = list(model.keys())[0]
+ value = create_policy(model_id, policy_name)
+ policy = add_policies(value=value)
+ assert policy
+ policy_id = list(policy.keys())[0]
+ return subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id
+
+
+def create_new_meta_rule(subject_category_name="subjectCategory", object_category_name="objectCategory",
+ action_category_name="actionCategory",
+ meta_rule_name="meta_rule1" + uuid4().hex):
+ subject_category_id = create_subject_category(subject_category_name)
+ object_category_id = create_object_category(object_category_name)
+ action_category_id = create_action_category(action_category_name)
+ value = {"name": meta_rule_name,
+ "algorithm": "name of the meta rule algorithm",
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
+ }
+ meta_rule = add_meta_rule(value=value)
+ return subject_category_id, object_category_id, action_category_id, list(meta_rule.keys())[0]
+
+
+def create_subject(policy_id):
+ value = {
+ "name": "testuser" + uuid4().hex,
+ "description": "test",
+ }
+ subject = add_subject(policy_id=policy_id, value=value)
+ return list(subject.keys())[0]
+
+
+def create_object(policy_id):
+ value = {
+ "name": "testobject" + uuid4().hex,
+ "description": "test",
+ }
+ object = add_object(policy_id=policy_id, value=value)
+ return list(object.keys())[0]
+
+
+def create_action(policy_id):
+ value = {
+ "name": "testaction" + uuid4().hex,
+ "description": "test",
+ }
+ action = add_action(policy_id=policy_id, value=value)
+ return list(action.keys())[0]
+
+
+def create_subject_data(policy_id, category_id):
+ value = {
+ "name": "subject-security-level",
+ "description": {"low": "", "medium": "", "high": ""},
+ }
+ subject_data = add_subject_data(policy_id=policy_id, category_id=category_id, value=value).get('data')
+ assert subject_data
+ return list(subject_data.keys())[0]
+
+
+def create_object_data(policy_id, category_id):
+ value = {
+ "name": "object-security-level",
+ "description": {"low": "", "medium": "", "high": ""},
+ }
+ object_data = add_object_data(policy_id=policy_id, category_id=category_id, value=value).get('data')
+ return list(object_data.keys())[0]
+
+
+def create_action_data(policy_id, category_id):
+ value = {
+ "name": "action-type",
+ "description": {"vm-action": "", "storage-action": "", },
+ }
+ action_data = add_action_data(policy_id=policy_id, category_id=category_id, value=value).get('data')
+ return list(action_data.keys())[0]
+
+
+def get_policy_id_with_subject_assignment():
+ client = utilities.register_client()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex)
+ subject_id = create_subject(policy_id)
+ data_id = create_subject_data(policy_id=policy_id, category_id=subject_category_id)
+
+ data = {
+ "id": subject_id,
+ "category_id": subject_category_id,
+ "data_id": data_id
+ }
+ client.post("/policies/{}/subject_assignments".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ return policy_id
+
+
+def get_policy_id_with_object_assignment():
+ client = utilities.register_client()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex)
+ object_id = create_object(policy_id)
+ data_id = create_object_data(policy_id=policy_id, category_id=object_category_id)
+
+ data = {
+ "id": object_id,
+ "category_id": object_category_id,
+ "data_id": data_id
+ }
+
+ client.post("/policies/{}/object_assignments".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ return policy_id
+
+
+def get_policy_id_with_action_assignment():
+ client = utilities.register_client()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = create_new_policy(
+ subject_category_name="subject_category1" + uuid4().hex,
+ object_category_name="object_category1" + uuid4().hex,
+ action_category_name="action_category1" + uuid4().hex,
+ meta_rule_name="meta_rule_1" + uuid4().hex)
+ action_id = create_action(policy_id)
+ data_id = create_action_data(policy_id=policy_id, category_id=action_category_id)
+
+ data = {
+ "id": action_id,
+ "category_id": action_category_id,
+ "data_id": data_id
+ }
+ client.post("/policies/{}/action_assignments".format(policy_id), data=json.dumps(data),
+ headers={'Content-Type': 'application/json'})
+ return policy_id
diff --git a/moon_manager/tests/unit_python/helpers/data_helper.py b/moon_manager/tests/unit_python/helpers/data_helper.py
new file mode 100644
index 00000000..da6b9376
--- /dev/null
+++ b/moon_manager/tests/unit_python/helpers/data_helper.py
@@ -0,0 +1,99 @@
+# 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'.
+
+
+def get_action_data(policy_id, data_id=None, category_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_action_data("", policy_id, data_id, category_id)
+
+
+def add_action_data(policy_id, data_id=None, category_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_action_data("", policy_id, data_id, category_id, value)
+
+
+def delete_action_data(policy_id, data_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_action_data("", policy_id, data_id)
+
+
+def get_object_data(policy_id, data_id=None, category_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_object_data("", policy_id, data_id, category_id)
+
+
+def add_object_data(policy_id, data_id=None, category_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_object_data("", policy_id, data_id, category_id, value)
+
+
+def delete_object_data(policy_id, data_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_object_data("", policy_id, data_id)
+
+
+def get_subject_data(policy_id, data_id=None, category_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_subject_data("", policy_id, data_id, category_id)
+
+
+def add_subject_data(policy_id, data_id=None, category_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.set_subject_data("", policy_id, data_id, category_id, value)
+
+
+def delete_subject_data(policy_id, data_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_subject_data("", policy_id, data_id)
+
+
+def get_actions(policy_id, perimeter_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_actions("", policy_id, perimeter_id)
+
+
+def add_action(policy_id, perimeter_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_action("", policy_id, perimeter_id, value)
+
+
+def delete_action(policy_id, perimeter_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_action("", policy_id, perimeter_id)
+
+
+def get_objects(policy_id, perimeter_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_objects("", policy_id, perimeter_id)
+
+
+def add_object(policy_id, perimeter_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_object("", policy_id, perimeter_id, value)
+
+
+def delete_object(policy_id, perimeter_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_object("", policy_id, perimeter_id)
+
+
+def get_subjects(policy_id, perimeter_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_subjects("", policy_id, perimeter_id)
+
+
+def add_subject(policy_id, perimeter_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_subject("", policy_id, perimeter_id, value)
+
+
+def delete_subject(policy_id, perimeter_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_subject("", policy_id, perimeter_id)
+
+
+def get_available_metadata(policy_id):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_available_metadata("", policy_id)
diff --git a/moon_manager/tests/unit_python/helpers/meta_rule_helper.py b/moon_manager/tests/unit_python/helpers/meta_rule_helper.py
new file mode 100644
index 00000000..e882706b
--- /dev/null
+++ b/moon_manager/tests/unit_python/helpers/meta_rule_helper.py
@@ -0,0 +1,49 @@
+# 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 helpers import data_builder as builder
+from uuid import uuid4
+
+
+def set_meta_rule(meta_rule_id, value=None):
+ from python_moondb.core import ModelManager
+ if not value:
+ action_category_id = builder.create_action_category("action_category_id1"+uuid4().hex)
+ subject_category_id = builder.create_subject_category("subject_category_id1"+uuid4().hex)
+ object_category_id = builder.create_object_category("object_category_id1"+uuid4().hex)
+ value = {
+ "name": "MLS_meta_rule",
+ "description": "test",
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
+ }
+ return ModelManager.set_meta_rule(user_id=None, meta_rule_id=meta_rule_id, value=value)
+
+
+def add_meta_rule(meta_rule_id=None, value=None):
+ from python_moondb.core import ModelManager
+ if not value:
+ action_category_id = builder.create_action_category("action_category_id1"+uuid4().hex)
+ subject_category_id = builder.create_subject_category("subject_category_id1"+uuid4().hex)
+ object_category_id = builder.create_object_category("object_category_id1"+uuid4().hex)
+ value = {
+ "name": "MLS_meta_rule"+uuid4().hex,
+ "description": "test",
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
+ }
+ return ModelManager.add_meta_rule(user_id=None, meta_rule_id=meta_rule_id, value=value)
+
+
+def get_meta_rules(meta_rule_id=None):
+ from python_moondb.core import ModelManager
+ return ModelManager.get_meta_rules(user_id=None, meta_rule_id=meta_rule_id)
+
+
+def delete_meta_rules(meta_rule_id=None):
+ from python_moondb.core import ModelManager
+ ModelManager.delete_meta_rule(user_id=None, meta_rule_id=meta_rule_id)
diff --git a/moon_manager/tests/unit_python/helpers/model_helper.py b/moon_manager/tests/unit_python/helpers/model_helper.py
new file mode 100644
index 00000000..d2ffb85b
--- /dev/null
+++ b/moon_manager/tests/unit_python/helpers/model_helper.py
@@ -0,0 +1,51 @@
+# 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 helpers import data_builder as builder
+from uuid import uuid4
+
+
+def get_models(model_id=None):
+ from python_moondb.core import ModelManager
+ return ModelManager.get_models(user_id=None, model_id=model_id)
+
+
+def add_model(model_id=None, value=None):
+ from python_moondb.core import ModelManager
+ if not value:
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule(
+ subject_category_name="subject_category1"+uuid4().hex,
+ object_category_name="object_category1"+uuid4().hex,
+ action_category_name="action_category1"+uuid4().hex)
+ name = "MLS" if model_id is None else "MLS " + model_id
+ value = {
+ "name": name,
+ "description": "test",
+ "meta_rules": [meta_rule_id]
+ }
+ return ModelManager.add_model(user_id=None, model_id=model_id, value=value)
+
+
+def delete_models(uuid=None, name=None):
+ from python_moondb.core import ModelManager
+ if not uuid:
+ for model_id, model_value in get_models():
+ if name == model_value['name']:
+ uuid = model_id
+ break
+ ModelManager.delete_model(user_id=None, model_id=uuid)
+
+
+def delete_all_models():
+ from python_moondb.core import ModelManager
+ models_values = get_models()
+ print(models_values)
+ for model_id, model_value in models_values.items():
+ ModelManager.delete_model(user_id=None, model_id=model_id)
+
+
+def update_model(model_id=None, value=None):
+ from python_moondb.core import ModelManager
+ return ModelManager.update_model(user_id=None, model_id=model_id, value=value)
diff --git a/moon_manager/tests/unit_python/helpers/pdp_helper.py b/moon_manager/tests/unit_python/helpers/pdp_helper.py
new file mode 100644
index 00000000..3d169b06
--- /dev/null
+++ b/moon_manager/tests/unit_python/helpers/pdp_helper.py
@@ -0,0 +1,23 @@
+# 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'.
+
+def update_pdp(pdp_id, value):
+ from python_moondb.core import PDPManager
+ return PDPManager.update_pdp("", pdp_id, value)
+
+
+def delete_pdp(pdp_id):
+ from python_moondb.core import PDPManager
+ PDPManager.delete_pdp("", pdp_id)
+
+
+def add_pdp(pdp_id=None, value=None):
+ from python_moondb.core import PDPManager
+ return PDPManager.add_pdp("", pdp_id, value)
+
+
+def get_pdp(pdp_id=None):
+ from python_moondb.core import PDPManager
+ return PDPManager.get_pdp("", pdp_id)
diff --git a/moon_manager/tests/unit_python/helpers/policy_helper.py b/moon_manager/tests/unit_python/helpers/policy_helper.py
new file mode 100644
index 00000000..c932ee3a
--- /dev/null
+++ b/moon_manager/tests/unit_python/helpers/policy_helper.py
@@ -0,0 +1,61 @@
+# 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'.
+
+def get_policies():
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_policies("admin")
+
+
+def add_policies(policy_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ if not value:
+ value = {
+ "name": "test_policy",
+ "model_id": "",
+ "genre": "authz",
+ "description": "test",
+ }
+ return PolicyManager.add_policy("admin", policy_id=policy_id, value=value)
+
+
+def delete_policies(uuid=None, name=None):
+ from python_moondb.core import PolicyManager
+ if not uuid:
+ for policy_id, policy_value in get_policies():
+ if name == policy_value['name']:
+ uuid = policy_id
+ break
+ PolicyManager.delete_policy("admin", uuid)
+
+
+def update_policy(policy_id, value):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.update_policy("admin", policy_id, value)
+
+
+def get_policy_from_meta_rules(meta_rule_id):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_policy_from_meta_rules("admin", meta_rule_id)
+
+
+def get_rules(policy_id=None, meta_rule_id=None, rule_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_rules("", policy_id, meta_rule_id, rule_id)
+
+
+def add_rule(policy_id=None, meta_rule_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ if not value:
+ value = {
+ "rule": ("high", "medium", "vm-action"),
+ "instructions": ({"decision": "grant"}),
+ "enabled": "",
+ }
+ return PolicyManager.add_rule("", policy_id, meta_rule_id, value)
+
+
+def delete_rule(policy_id=None, rule_id=None):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_rule("", policy_id, rule_id)
diff --git a/moon_manager/tests/unit_python/requirements.txt b/moon_manager/tests/unit_python/requirements.txt
index 21975ce3..6c6e5bb8 100644
--- a/moon_manager/tests/unit_python/requirements.txt
+++ b/moon_manager/tests/unit_python/requirements.txt
@@ -2,4 +2,4 @@ flask
flask_cors
flask_restful
python_moondb
-python_moonutilities \ No newline at end of file
+python_moonutilities
diff --git a/moon_orchestrator/Dockerfile b/moon_orchestrator/Dockerfile
index 4d75d6d7..09d12fda 100644
--- a/moon_orchestrator/Dockerfile
+++ b/moon_orchestrator/Dockerfile
@@ -1,10 +1,15 @@
FROM python:3
+LABEL Name=Orchestrator
+LABEL Description="Orchestrator component for the Moon platform"
+LABEL Maintainer="Thomas Duval"
+LABEL Url="https://wiki.opnfv.org/display/moon/Moon+Project+Proposal"
+
+USER root
+
ADD . /root
WORKDIR /root/
-RUN pip3 install -r requirements.txt
-RUN if [ -d /root/dist ]; then for FILE in $(ls /root/dist/*.tar.gz); do pip install $FILE --upgrade; done; fi
-RUN if [ -d /root/dist ]; then for FILE in $(ls /root/dist/*.whl); do pip install $FILE --upgrade; done; fi
-RUN pip3 install .
+RUN pip3 install --no-cache-dir -r requirements.txt
+RUN pip3 install --no-cache-dir .
CMD ["python3", "-m", "moon_orchestrator"] \ No newline at end of file
diff --git a/moon_wrapper/Dockerfile b/moon_wrapper/Dockerfile
index 00aeb3f1..e3ad9020 100644
--- a/moon_wrapper/Dockerfile
+++ b/moon_wrapper/Dockerfile
@@ -1,10 +1,15 @@
FROM python:3
+LABEL Name=Wrapper
+LABEL Description="Wrapper component for the Moon platform"
+LABEL Maintainer="Thomas Duval"
+LABEL Url="https://wiki.opnfv.org/display/moon/Moon+Project+Proposal"
+
+USER root
+
ADD . /root
WORKDIR /root/
-RUN pip3 install -r requirements.txt
-RUN if [ -d /root/dist ]; then for FILE in $(ls /root/dist/*.tar.gz); do pip install $FILE --upgrade; done; fi
-RUN if [ -d /root/dist ]; then for FILE in $(ls /root/dist/*.whl); do pip install $FILE --upgrade; done; fi
-RUN pip3 install .
+RUN pip3 install --no-cache-dir -r requirements.txt
+RUN pip3 install --no-cache-dir .
CMD ["python3", "-m", "moon_wrapper"]
diff --git a/python_moonclient/Changelog b/python_moonclient/Changelog
index c58d83c4..9066e449 100644
--- a/python_moonclient/Changelog
+++ b/python_moonclient/Changelog
@@ -68,3 +68,7 @@ CHANGES
- moon object data list
- moon action data list
- moon metarule list
+
+1.4.1
+-----
+- Update exception during configuration
diff --git a/python_moonclient/python_moonclient/__init__.py b/python_moonclient/python_moonclient/__init__.py
index 8b353f9f..e3ad9307 100644
--- a/python_moonclient/python_moonclient/__init__.py
+++ b/python_moonclient/python_moonclient/__init__.py
@@ -3,4 +3,4 @@
# 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.0"
+__version__ = "1.4.1"
diff --git a/python_moonclient/python_moonclient/core/config.py b/python_moonclient/python_moonclient/core/config.py
index 300ebf1a..f8e3fe29 100644
--- a/python_moonclient/python_moonclient/core/config.py
+++ b/python_moonclient/python_moonclient/core/config.py
@@ -7,7 +7,9 @@ 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("xxx")
+ raise Exception("Exception when retrieving configuration from Consul: {} {}".format(
+ req.status_code, req.text
+ ))
data = req.json()
if len(data) == 1:
data = data[0]
diff --git a/python_moondb/Changelog b/python_moondb/Changelog
index acd72883..f4feef62 100644
--- a/python_moondb/Changelog
+++ b/python_moondb/Changelog
@@ -73,3 +73,36 @@ CHANGES
1.2.9
-----
- Add some verifications when deleting some elements in database
+
+1.2.10
+-----
+- Update the migration script because of a bug introduced in 1.2.8 in rule table
+- Fix bugs due to the previous version
+
+1.2.11
+------
+- adding test cases for perimeter
+- adding subject_object_action to model_test
+- update import of exception
+- add unit_test to test_model
+- add validation for not accepting blank perimeter name or category name
+
+1.2.12
+------
+- Fix the SubjectExisting exception problem
+
+1.2.13
+------
+- Add validations and refactor test cases
+
+1.2.14
+------
+- Fix some bugs for the manager and clean the code
+
+1.2.15
+------
+- Fix test cases after removing syntax error in exceptions
+
+1.2.16
+------
+- Fix the "key length error" in meta_rule table
diff --git a/python_moondb/python_moondb/__init__.py b/python_moondb/python_moondb/__init__.py
index 287558f7..e2e16287 100644
--- a/python_moondb/python_moondb/__init__.py
+++ b/python_moondb/python_moondb/__init__.py
@@ -3,5 +3,4 @@
# 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.2.9"
-
+__version__ = "1.2.16"
diff --git a/python_moondb/python_moondb/api/model.py b/python_moondb/python_moondb/api/model.py
index f5858662..c1603b83 100644
--- a/python_moondb/python_moondb/api/model.py
+++ b/python_moondb/python_moondb/api/model.py
@@ -22,6 +22,10 @@ class ModelManager(Managers):
def update_model(self, user_id, model_id, value):
if model_id not in self.driver.get_models(model_id=model_id):
raise exceptions.ModelUnknown
+ if value and 'meta_rules' in value:
+ for meta_rule_id in value['meta_rules']:
+ if not self.driver.get_meta_rules(meta_rule_id=meta_rule_id):
+ raise exceptions.MetaRuleUnknown
return self.driver.update_model(model_id=model_id, value=value)
@enforce(("read", "write"), "models")
@@ -41,6 +45,10 @@ class ModelManager(Managers):
raise exceptions.ModelExisting
if not model_id:
model_id = uuid4().hex
+ if value and 'meta_rules' in value:
+ for meta_rule_id in value['meta_rules']:
+ if not self.driver.get_meta_rules(meta_rule_id=meta_rule_id):
+ raise exceptions.MetaRuleUnknown
return self.driver.add_model(model_id=model_id, value=value)
@enforce("read", "models")
@@ -51,6 +59,19 @@ class ModelManager(Managers):
def set_meta_rule(self, user_id, meta_rule_id, value):
if meta_rule_id not in self.driver.get_meta_rules(meta_rule_id=meta_rule_id):
raise exceptions.MetaRuleUnknown
+ if value:
+ if 'subject_categories' in value:
+ for subject_category_id in value['subject_categories']:
+ if not self.driver.get_subject_categories(category_id=subject_category_id):
+ raise exceptions.SubjectCategoryUnknown
+ if 'object_categories' in value:
+ for object_category_id in value['object_categories']:
+ if not self.driver.get_object_categories(category_id=object_category_id):
+ raise exceptions.ObjectCategoryUnknown
+ if 'action_categories' in value:
+ for action_category_id in value['action_categories']:
+ if not self.driver.get_action_categories(category_id=action_category_id):
+ raise exceptions.ActionCategoryUnknown
return self.driver.set_meta_rule(meta_rule_id=meta_rule_id, value=value)
@enforce("read", "meta_rules")
@@ -61,6 +82,19 @@ class ModelManager(Managers):
def add_meta_rule(self, user_id, meta_rule_id=None, value=None):
if meta_rule_id in self.driver.get_meta_rules(meta_rule_id=meta_rule_id):
raise exceptions.MetaRuleExisting
+ if value:
+ if 'subject_categories' in value:
+ for subject_category_id in value['subject_categories']:
+ if not self.driver.get_subject_categories(category_id=subject_category_id):
+ raise exceptions.SubjectCategoryUnknown
+ if 'object_categories' in value:
+ for object_category_id in value['object_categories']:
+ if not self.driver.get_object_categories(category_id=object_category_id):
+ raise exceptions.ObjectCategoryUnknown
+ if 'action_categories' in value:
+ for action_category_id in value['action_categories']:
+ if not self.driver.get_action_categories(category_id=action_category_id):
+ raise exceptions.ActionCategoryUnknown
return self.driver.set_meta_rule(meta_rule_id=meta_rule_id, value=value)
@enforce(("read", "write"), "meta_rules")
@@ -93,8 +127,11 @@ class ModelManager(Managers):
meta_rules = self.get_meta_rules(user_id=user_id)
for meta_rule_id in meta_rules:
for subject_category_id in meta_rules[meta_rule_id]['subject_categories']:
+ logger.info("delete_subject_category {} {}".format(subject_category_id, meta_rule_id))
+ logger.info("delete_subject_category {}".format(meta_rules[meta_rule_id]))
if subject_category_id == category_id:
- raise exceptions.DeleteCategoryWithMetaRule
+ self.delete_meta_rule(user_id, meta_rule_id)
+ # raise exceptions.DeleteCategoryWithMetaRule
if self.driver.is_subject_data_exist(category_id=category_id):
raise exceptions.DeleteCategoryWithData
return self.driver.delete_subject_category(category_id=category_id)
@@ -119,7 +156,7 @@ class ModelManager(Managers):
for meta_rule_id in meta_rules:
for object_category_id in meta_rules[meta_rule_id]['object_categories']:
if object_category_id == category_id:
- raise exceptions.DeleteCategoryWithMetaRule
+ self.delete_meta_rule(user_id, meta_rule_id)
if self.driver.is_object_data_exist(category_id=category_id):
raise exceptions.DeleteCategoryWithData
return self.driver.delete_object_category(category_id=category_id)
@@ -144,7 +181,7 @@ class ModelManager(Managers):
for meta_rule_id in meta_rules:
for action_category_id in meta_rules[meta_rule_id]['action_categories']:
if action_category_id == category_id:
- raise exceptions.DeleteCategoryWithMetaRule
+ self.delete_meta_rule(user_id, meta_rule_id)
if self.driver.is_action_data_exist(category_id=category_id):
raise exceptions.DeleteCategoryWithData
return self.driver.delete_action_category(category_id=category_id)
diff --git a/python_moondb/python_moondb/api/pdp.py b/python_moondb/python_moondb/api/pdp.py
index 7e852ca8..d0a071c9 100644
--- a/python_moondb/python_moondb/api/pdp.py
+++ b/python_moondb/python_moondb/api/pdp.py
@@ -22,6 +22,10 @@ class PDPManager(Managers):
def update_pdp(self, user_id, pdp_id, value):
if pdp_id not in self.driver.get_pdp(pdp_id=pdp_id):
raise exceptions.PdpUnknown
+ if value and 'security_pipeline' in value:
+ for policy_id in value['security_pipeline']:
+ if not Managers.PolicyManager.get_policies(user_id=user_id, policy_id=policy_id):
+ raise exceptions.PolicyUnknown
return self.driver.update_pdp(pdp_id=pdp_id, value=value)
@enforce(("read", "write"), "pdp")
@@ -36,6 +40,10 @@ class PDPManager(Managers):
raise exceptions.PdpExisting
if not pdp_id:
pdp_id = uuid4().hex
+ if value and 'security_pipeline' in value:
+ for policy_id in value['security_pipeline']:
+ if not Managers.PolicyManager.get_policies(user_id=user_id, policy_id=policy_id):
+ raise exceptions.PolicyUnknown
return self.driver.add_pdp(pdp_id=pdp_id, value=value)
@enforce("read", "pdp")
diff --git a/python_moondb/python_moondb/api/policy.py b/python_moondb/python_moondb/api/policy.py
index 69392e6d..05c2b7d5 100644
--- a/python_moondb/python_moondb/api/policy.py
+++ b/python_moondb/python_moondb/api/policy.py
@@ -40,6 +40,9 @@ class PolicyManager(Managers):
def update_policy(self, user_id, policy_id, value):
if policy_id not in self.driver.get_policies(policy_id=policy_id):
raise exceptions.PolicyUnknown
+ if value and 'model_id' in value and value['model_id'] != "":
+ if not Managers.ModelManager.get_models(user_id, model_id=value['model_id']):
+ raise exceptions.ModelUnknown
return self.driver.update_policy(policy_id=policy_id, value=value)
@enforce(("read", "write"), "policies")
@@ -60,6 +63,9 @@ class PolicyManager(Managers):
raise exceptions.PolicyExisting
if not policy_id:
policy_id = uuid4().hex
+ if value and 'model_id' in value and value['model_id'] != "":
+ if not Managers.ModelManager.get_models(user_id, model_id=value['model_id']):
+ raise exceptions.ModelUnknown
return self.driver.add_policy(policy_id=policy_id, value=value)
@enforce("read", "policies")
@@ -68,10 +74,19 @@ class PolicyManager(Managers):
@enforce("read", "perimeter")
def get_subjects(self, user_id, policy_id, perimeter_id=None):
+ if not policy_id:
+ pass
+ elif not (policy_id and self.get_policies(user_id=user_id, policy_id=policy_id)):
+ raise exceptions.PolicyUnknown
return self.driver.get_subjects(policy_id=policy_id, perimeter_id=perimeter_id)
@enforce(("read", "write"), "perimeter")
def add_subject(self, user_id, policy_id, perimeter_id=None, value=None):
+ if not value or "name" not in value or not value["name"].strip():
+ raise exceptions.PerimeterNameInvalid
+ if value["name"] in map(lambda x: x['name'],
+ self.get_subjects(user_id, policy_id, perimeter_id).values()):
+ raise exceptions.SubjectExisting
k_user = Managers.KeystoneManager.get_user_by_name(value.get('name'))
if not k_user['users']:
k_user = Managers.KeystoneManager.create_user(value)
@@ -94,10 +109,16 @@ class PolicyManager(Managers):
@enforce(("read", "write"), "perimeter")
def delete_subject(self, user_id, policy_id, perimeter_id):
+ if policy_id and not self.get_policies(user_id=user_id, policy_id=policy_id):
+ raise exceptions.PolicyUnknown
return self.driver.delete_subject(policy_id=policy_id, perimeter_id=perimeter_id)
@enforce("read", "perimeter")
def get_objects(self, user_id, policy_id, perimeter_id=None):
+ if not policy_id:
+ pass
+ elif not (policy_id and self.get_policies(user_id=user_id, policy_id=policy_id)):
+ raise exceptions.PolicyUnknown
return self.driver.get_objects(policy_id=policy_id, perimeter_id=perimeter_id)
@enforce(("read", "write"), "perimeter")
@@ -110,21 +131,30 @@ class PolicyManager(Managers):
@enforce(("read", "write"), "perimeter")
def delete_object(self, user_id, policy_id, perimeter_id):
+ if policy_id and not self.get_policies(user_id=user_id, policy_id=policy_id):
+ raise exceptions.PolicyUnknown
return self.driver.delete_object(policy_id=policy_id, perimeter_id=perimeter_id)
@enforce("read", "perimeter")
def get_actions(self, user_id, policy_id, perimeter_id=None):
+ if not policy_id:
+ pass
+ elif not (policy_id and self.get_policies(user_id=user_id, policy_id=policy_id)):
+ raise exceptions.PolicyUnknown
return self.driver.get_actions(policy_id=policy_id, perimeter_id=perimeter_id)
@enforce(("read", "write"), "perimeter")
def add_action(self, user_id, policy_id, perimeter_id=None, value=None):
- logger.info("add_action {}".format(policy_id))
+ logger.debug("add_action {}".format(policy_id))
if not self.get_policies(user_id=user_id, policy_id=policy_id):
raise exceptions.PolicyUnknown
return self.driver.set_action(policy_id=policy_id, perimeter_id=perimeter_id, value=value)
@enforce(("read", "write"), "perimeter")
def delete_action(self, user_id, policy_id, perimeter_id):
+ logger.debug("delete_action {} {} {}".format(policy_id, perimeter_id, self.get_policies(user_id=user_id, policy_id=policy_id)))
+ if policy_id and not self.get_policies(user_id=user_id, policy_id=policy_id):
+ raise exceptions.PolicyUnknown
return self.driver.delete_action(policy_id=policy_id, perimeter_id=perimeter_id)
@enforce("read", "data")
@@ -144,6 +174,8 @@ class PolicyManager(Managers):
def set_subject_data(self, user_id, policy_id, data_id=None, category_id=None, value=None):
if not category_id:
raise Exception('Invalid category id')
+ if not Managers.ModelManager.get_subject_categories(user_id=user_id, category_id=category_id):
+ raise exceptions.MetaDataUnknown
if not self.get_policies(user_id=user_id, policy_id=policy_id):
raise exceptions.PolicyUnknown
if not data_id:
@@ -175,6 +207,8 @@ class PolicyManager(Managers):
def add_object_data(self, user_id, policy_id, data_id=None, category_id=None, value=None):
if not category_id:
raise Exception('Invalid category id')
+ if not Managers.ModelManager.get_object_categories(user_id=user_id, category_id=category_id):
+ raise exceptions.MetaDataUnknown
if not self.get_policies(user_id=user_id, policy_id=policy_id):
raise exceptions.PolicyUnknown
if not data_id:
@@ -206,6 +240,8 @@ class PolicyManager(Managers):
def add_action_data(self, user_id, policy_id, data_id=None, category_id=None, value=None):
if not category_id:
raise Exception('Invalid category id')
+ if not Managers.ModelManager.get_action_categories(user_id=user_id, category_id=category_id):
+ raise exceptions.MetaDataUnknown
if not self.get_policies(user_id=user_id, policy_id=policy_id):
raise exceptions.PolicyUnknown
if not data_id:
@@ -228,6 +264,12 @@ class PolicyManager(Managers):
def add_subject_assignment(self, user_id, policy_id, subject_id, category_id, data_id):
if not self.get_policies(user_id=user_id, policy_id=policy_id):
raise exceptions.PolicyUnknown
+ if not self.get_subjects(user_id=user_id, policy_id=policy_id, perimeter_id=subject_id):
+ raise exceptions.SubjectUnknown
+ if not Managers.ModelManager.get_subject_categories(user_id=user_id, category_id=category_id):
+ raise exceptions.MetaDataUnknown
+ if not self.get_subject_data(user_id=user_id, policy_id=policy_id, data_id=data_id):
+ raise exceptions.DataUnknown
return self.driver.add_subject_assignment(policy_id=policy_id, subject_id=subject_id,
category_id=category_id, data_id=data_id)
@@ -244,6 +286,12 @@ class PolicyManager(Managers):
def add_object_assignment(self, user_id, policy_id, object_id, category_id, data_id):
if not self.get_policies(user_id=user_id, policy_id=policy_id):
raise exceptions.PolicyUnknown
+ if not self.get_objects(user_id=user_id, policy_id=policy_id, perimeter_id=object_id):
+ raise exceptions.ObjectUnknown
+ if not Managers.ModelManager.get_object_categories(user_id=user_id, category_id=category_id):
+ raise exceptions.MetaDataUnknown
+ if not self.get_object_data(user_id=user_id, policy_id=policy_id, data_id=data_id):
+ raise exceptions.DataUnknown
return self.driver.add_object_assignment(policy_id=policy_id, object_id=object_id,
category_id=category_id, data_id=data_id)
@@ -260,6 +308,12 @@ class PolicyManager(Managers):
def add_action_assignment(self, user_id, policy_id, action_id, category_id, data_id):
if not self.get_policies(user_id=user_id, policy_id=policy_id):
raise exceptions.PolicyUnknown
+ if not self.get_actions(user_id=user_id, policy_id=policy_id, perimeter_id=action_id):
+ raise exceptions.ActionUnknown
+ if not Managers.ModelManager.get_action_categories(user_id=user_id, category_id=category_id):
+ raise exceptions.MetaDataUnknown
+ if not self.get_action_data(user_id=user_id, policy_id=policy_id, data_id=data_id):
+ raise exceptions.DataUnknown
return self.driver.add_action_assignment(policy_id=policy_id, action_id=action_id,
category_id=category_id, data_id=data_id)
@@ -271,11 +325,14 @@ class PolicyManager(Managers):
@enforce("read", "rules")
def get_rules(self, user_id, policy_id, meta_rule_id=None, rule_id=None):
return self.driver.get_rules(policy_id=policy_id, meta_rule_id=meta_rule_id, rule_id=rule_id)
+ logger.info("delete_subject_data: {} {}".format(policy_id, data_id))
@enforce(("read", "write"), "rules")
def add_rule(self, user_id, policy_id, meta_rule_id, value):
if not self.get_policies(user_id=user_id, policy_id=policy_id):
raise exceptions.PolicyUnknown
+ if not self.ModelManager.get_meta_rules(user_id=user_id, meta_rule_id=meta_rule_id):
+ raise exceptions.MetaRuleUnknown
return self.driver.add_rule(policy_id=policy_id, meta_rule_id=meta_rule_id, value=value)
@enforce(("read", "write"), "rules")
diff --git a/python_moondb/python_moondb/backends/sql.py b/python_moondb/python_moondb/backends/sql.py
index 366ed7de..7310e7f3 100644
--- a/python_moondb/python_moondb/backends/sql.py
+++ b/python_moondb/python_moondb/backends/sql.py
@@ -14,7 +14,7 @@ from sqlalchemy import create_engine
from contextlib import contextmanager
from sqlalchemy import types as sql_types
from python_moonutilities import configuration
-from python_moonutilities.exceptions import *
+from python_moonutilities import exceptions
from python_moondb.core import PDPDriver, PolicyDriver, ModelDriver
import sqlalchemy
@@ -134,6 +134,7 @@ class PerimeterBase(DictBase):
name = sql.Column(sql.String(256), nullable=False)
value = sql.Column(JsonBlob(), nullable=True)
__mapper_args__ = {'concrete': True}
+
def __repr__(self):
return "{} with name {} : {}".format(self.id, self.name, json.dumps(self.value))
@@ -155,6 +156,7 @@ class PerimeterBase(DictBase):
'value': dict_value
}
+
class Subject(Base, PerimeterBase):
__tablename__ = 'subjects'
@@ -352,7 +354,7 @@ class PDPConnector(BaseConnector, PDPDriver):
setattr(ref, "value", d)
return {ref.id: ref.to_dict()}
except sqlalchemy.exc.IntegrityError:
- raise PdpExisting
+ raise exceptions.PdpExisting
def delete_pdp(self, pdp_id):
with self.get_session_for_write() as session:
@@ -374,7 +376,7 @@ class PDPConnector(BaseConnector, PDPDriver):
session.add(new)
return {new.id: new.to_dict()}
except sqlalchemy.exc.IntegrityError:
- raise PdpExisting
+ raise exceptions.PdpExisting
def get_pdp(self, pdp_id=None):
with self.get_session_for_read() as session:
@@ -416,7 +418,7 @@ class PolicyConnector(BaseConnector, PolicyDriver):
new = Policy.from_dict({
"id": policy_id if policy_id else uuid4().hex,
"name": value["name"],
- "model_id": value["model_id"],
+ "model_id": value.get("model_id", ""),
"value": value_wo_other_info
})
session.add(new)
@@ -452,13 +454,20 @@ class PolicyConnector(BaseConnector, PolicyDriver):
return {_ref.id: _ref.to_return() for _ref in ref_list}
def __set_perimeter(self, ClassType, ClassTypeException, policy_id, perimeter_id=None, value=None):
- _perimeter = None
+ if not value or "name" not in value or not value["name"].strip():
+ raise exceptions.PerimeterNameInvalid
with self.get_session_for_write() as session:
+ _perimeter = None
if perimeter_id:
query = session.query(ClassType)
query = query.filter_by(id=perimeter_id)
_perimeter = query.first()
- logger.info("+++++++++++++ {}".format(_perimeter))
+ if not perimeter_id and not _perimeter:
+ query = session.query(ClassType)
+ query = query.filter_by(name=value['name'])
+ _perimeter = query.first()
+ if _perimeter:
+ raise ClassTypeException
if not _perimeter:
if "policy_list" not in value or type(value["policy_list"]) is not list:
value["policy_list"] = []
@@ -466,9 +475,9 @@ class PolicyConnector(BaseConnector, PolicyDriver):
value["policy_list"] = [policy_id, ]
value_wo_name = copy.deepcopy(value)
- value_wo_name.pop("name",None)
+ value_wo_name.pop("name", None)
new = ClassType.from_dict({
- "id": uuid4().hex,
+ "id": perimeter_id if perimeter_id else uuid4().hex,
"name": value["name"],
"value": value_wo_name
})
@@ -480,7 +489,7 @@ class PolicyConnector(BaseConnector, PolicyDriver):
_value["value"]["policy_list"] = []
if policy_id and policy_id not in _value["value"]["policy_list"]:
_value["value"]["policy_list"].append(policy_id)
- logger.info("-------------_value- {}".format(_value))
+ _value["value"].update(value)
name = _value["value"]["name"]
_value["value"].pop("name")
@@ -489,13 +498,11 @@ class PolicyConnector(BaseConnector, PolicyDriver):
"name": name,
"value": _value["value"]
})
- logger.info("-------------- new {}".format(new_perimeter))
- logger.info("-------------- old {}".format(_perimeter))
_perimeter.value = new_perimeter.value
_perimeter.name = new_perimeter.name
return {_perimeter.id: _perimeter.to_return()}
- def __delete_perimeter(self,ClassType, ClassUnknownException, policy_id, perimeter_id):
+ def __delete_perimeter(self, ClassType, ClassUnknownException, policy_id, perimeter_id):
with self.get_session_for_write() as session:
query = session.query(ClassType)
query = query.filter_by(id=perimeter_id)
@@ -503,7 +510,6 @@ class PolicyConnector(BaseConnector, PolicyDriver):
if not _perimeter:
raise ClassUnknownException
old_perimeter = copy.deepcopy(_perimeter.to_dict())
- # value = _subject.to_dict()
try:
old_perimeter["value"]["policy_list"].remove(policy_id)
new_perimeter = ClassType.from_dict(old_perimeter)
@@ -517,39 +523,41 @@ class PolicyConnector(BaseConnector, PolicyDriver):
def set_subject(self, policy_id, perimeter_id=None, value=None):
try:
- return self.__set_perimeter(Subject, SubjectExisting, policy_id, perimeter_id=perimeter_id, value=value)
+ return self.__set_perimeter(Subject, exceptions.SubjectExisting, policy_id, perimeter_id=perimeter_id, value=value)
except sqlalchemy.exc.IntegrityError:
- raise SubjectExisting
+ raise exceptions.SubjectExisting
def delete_subject(self, policy_id, perimeter_id):
- self.__delete_perimeter(Subject, SubjectUnknown, policy_id, perimeter_id)
+ self.__delete_perimeter(Subject, exceptions.SubjectUnknown, policy_id, perimeter_id)
def get_objects(self, policy_id, perimeter_id=None):
return self.__get_perimeters(Object, policy_id, perimeter_id)
def set_object(self, policy_id, perimeter_id=None, value=None):
try:
- return self.__set_perimeter(Object, ObjectExisting, policy_id, perimeter_id=perimeter_id, value=value)
- except sqlalchemy.exc.IntegrityError:
- raise ObjectExisting
+ return self.__set_perimeter(Object, exceptions.ObjectExisting, policy_id, perimeter_id=perimeter_id, value=value)
+ except sqlalchemy.exc.IntegrityError as e:
+ logger.exception("IntegrityError {}".format(e))
+ raise exceptions.ObjectExisting
def delete_object(self, policy_id, perimeter_id):
- self.__delete_perimeter(Object, ObjectUnknown, policy_id, perimeter_id)
+ self.__delete_perimeter(Object, exceptions.ObjectUnknown, policy_id, perimeter_id)
def get_actions(self, policy_id, perimeter_id=None):
return self.__get_perimeters(Action, policy_id, perimeter_id)
def set_action(self, policy_id, perimeter_id=None, value=None):
try:
- return self.__set_perimeter(Action, ActionExisting, policy_id, perimeter_id=perimeter_id, value=value)
+ return self.__set_perimeter(Action, exceptions.ActionExisting, policy_id, perimeter_id=perimeter_id, value=value)
except sqlalchemy.exc.IntegrityError:
- raise ActionExisting
+ raise exceptions.ActionExisting
def delete_action(self, policy_id, perimeter_id):
- self.__delete_perimeter(Action, ActionUnknown, policy_id, perimeter_id)
+ self.__delete_perimeter(Action, exceptions.ActionUnknown, policy_id, perimeter_id)
- def __is_perimeter_data_exist(self, ClassType ,data_id=None, category_id=None):
- logger.info("driver {} {}".format( data_id, category_id))
+ def __is_data_exist(self, ClassType, data_id=None, category_id=None):
+ if not data_id:
+ return False
with self.get_session_for_read() as session:
query = session.query(ClassType)
query = query.filter_by(category_id=category_id)
@@ -558,23 +566,23 @@ class PolicyConnector(BaseConnector, PolicyDriver):
return True
return False
- def __get_perimeter_data(self, ClassType, policy_id, data_id=None, category_id=None):
- logger.info("driver {} {} {}".format(policy_id, data_id, category_id))
+ def __get_data(self, ClassType, policy_id, data_id=None, category_id=None):
with self.get_session_for_read() as session:
query = session.query(ClassType)
- if data_id:
+ if policy_id and data_id and category_id:
query = query.filter_by(policy_id=policy_id, id=data_id, category_id=category_id)
- else:
+ elif policy_id and category_id:
query = query.filter_by(policy_id=policy_id, category_id=category_id)
+ else:
+ query = query.filter_by(category_id=category_id)
ref_list = query.all()
- logger.info("ref_list={}".format(ref_list))
return {
"policy_id": policy_id,
"category_id": category_id,
"data": {_ref.id: _ref.to_dict() for _ref in ref_list}
}
- def __set_perimeter_data(self, ClassType, ClassTypeData, policy_id, data_id=None, category_id=None, value=None):
+ def __set_data(self, ClassType, ClassTypeData, policy_id, data_id=None, category_id=None, value=None):
with self.get_session_for_write() as session:
query = session.query(ClassTypeData)
query = query.filter_by(policy_id=policy_id, id=data_id, category_id=category_id)
@@ -604,7 +612,7 @@ class PolicyConnector(BaseConnector, PolicyDriver):
"data": {ref.id: ref.to_dict()}
}
- def __delete_perimeter_data(self, ClassType, policy_id, data_id):
+ def __delete_data(self, ClassType, policy_id, data_id):
with self.get_session_for_write() as session:
query = session.query(ClassType)
query = query.filter_by(policy_id=policy_id, id=data_id)
@@ -613,49 +621,49 @@ class PolicyConnector(BaseConnector, PolicyDriver):
session.delete(ref)
def is_subject_data_exist(self, data_id=None, category_id=None):
- return self.__is_perimeter_data_exist(SubjectData, data_id=data_id, category_id=category_id)
+ return self.__is_data_exist(SubjectData, data_id=data_id, category_id=category_id)
def get_subject_data(self, policy_id, data_id=None, category_id=None):
- return self.__get_perimeter_data(SubjectData, policy_id, data_id=data_id, category_id=category_id)
+ return self.__get_data(SubjectData, policy_id, data_id=data_id, category_id=category_id)
def set_subject_data(self, policy_id, data_id=None, category_id=None, value=None):
try:
- return self.__set_perimeter_data(Subject, SubjectData, policy_id, data_id=data_id, category_id=category_id, value=value)
+ return self.__set_data(Subject, SubjectData, policy_id, data_id=data_id, category_id=category_id, value=value)
except sqlalchemy.exc.IntegrityError:
- raise SubjectScopeExisting
+ raise exceptions.SubjectScopeExisting
def delete_subject_data(self, policy_id, data_id):
- return self.__delete_perimeter_data(SubjectData, policy_id, data_id)
+ return self.__delete_data(SubjectData, policy_id, data_id)
def is_object_data_exist(self, data_id=None, category_id=None):
- return self.__is_perimeter_data_exist(ObjectData, data_id=data_id, category_id=category_id)
+ return self.__is_data_exist(ObjectData, data_id=data_id, category_id=category_id)
def get_object_data(self, policy_id, data_id=None, category_id=None):
- return self.__get_perimeter_data(ObjectData, policy_id, data_id=data_id, category_id=category_id)
+ return self.__get_data(ObjectData, policy_id, data_id=data_id, category_id=category_id)
def set_object_data(self, policy_id, data_id=None, category_id=None, value=None):
try:
- return self.__set_perimeter_data(Object, ObjectData, policy_id, data_id=data_id, category_id=category_id, value=value)
+ return self.__set_data(Object, ObjectData, policy_id, data_id=data_id, category_id=category_id, value=value)
except sqlalchemy.exc.IntegrityError:
- raise ObjectScopeExisting
+ raise exceptions.ObjectScopeExisting
def delete_object_data(self, policy_id, data_id):
- return self.__delete_perimeter_data(ObjectData, policy_id, data_id)
+ return self.__delete_data(ObjectData, policy_id, data_id)
def is_action_data_exist(self, data_id=None,category_id=None):
- return self.__is_perimeter_data_exist(ActionData, data_id=data_id, category_id=category_id)
+ return self.__is_data_exist(ActionData, data_id=data_id, category_id=category_id)
def get_action_data(self, policy_id, data_id=None, category_id=None):
- return self.__get_perimeter_data(ActionData, policy_id, data_id=data_id, category_id=category_id)
+ return self.__get_data(ActionData, policy_id, data_id=data_id, category_id=category_id)
def set_action_data(self, policy_id, data_id=None, category_id=None, value=None):
try:
- return self.__set_perimeter_data(Action, ActionData, policy_id, data_id=data_id, category_id=category_id, value=value)
+ return self.__set_data(Action, ActionData, policy_id, data_id=data_id, category_id=category_id, value=value)
except sqlalchemy.exc.IntegrityError:
- raise ActionScopeExisting
+ raise exceptions.ActionScopeExisting
def delete_action_data(self, policy_id, data_id):
- return self.__delete_perimeter_data(ActionData, policy_id, data_id)
+ return self.__delete_data(ActionData, policy_id, data_id)
def get_subject_assignments(self, policy_id, subject_id=None, category_id=None):
with self.get_session_for_write() as session:
@@ -682,7 +690,7 @@ class PolicyConnector(BaseConnector, PolicyDriver):
assignments.append(data_id)
setattr(ref, "assignments", assignments)
else:
- raise SubjectAssignmentExisting
+ raise exceptions.SubjectAssignmentExisting
else:
ref = SubjectAssignment.from_dict(
{
@@ -737,7 +745,7 @@ class PolicyConnector(BaseConnector, PolicyDriver):
assignments.append(data_id)
setattr(ref, "assignments", assignments)
else:
- raise ObjectAssignmentExisting
+ raise exceptions.ObjectAssignmentExisting
else:
ref = ObjectAssignment.from_dict(
{
@@ -792,7 +800,7 @@ class PolicyConnector(BaseConnector, PolicyDriver):
assignments.append(data_id)
setattr(ref, "assignments", assignments)
else:
- raise ActionAssignmentExisting
+ raise exceptions.ActionAssignmentExisting
else:
ref = ActionAssignment.from_dict(
{
@@ -847,6 +855,10 @@ class PolicyConnector(BaseConnector, PolicyDriver):
def add_rule(self, policy_id, meta_rule_id, value):
try:
+ rules = self.get_rules(policy_id, meta_rule_id=meta_rule_id)
+ for _rule in map(lambda x: x["rule"], rules["rules"]):
+ if list(value.get('rule')) == list(_rule):
+ raise exceptions.RuleExisting
with self.get_session_for_write() as session:
ref = Rule.from_dict(
{
@@ -859,7 +871,7 @@ class PolicyConnector(BaseConnector, PolicyDriver):
session.add(ref)
return {ref.id: ref.to_dict()}
except sqlalchemy.exc.IntegrityError:
- raise RuleExisting
+ raise exceptions.RuleExisting
def delete_rule(self, policy_id, rule_id):
with self.get_session_for_write() as session:
@@ -905,7 +917,7 @@ class ModelConnector(BaseConnector, ModelDriver):
session.add(new)
return {new.id: new.to_dict()}
except sqlalchemy.exc.IntegrityError as e:
- raise ModelExisting
+ raise exceptions.ModelExisting
def get_models(self, model_id=None):
with self.get_session_for_read() as session:
@@ -939,7 +951,7 @@ class ModelConnector(BaseConnector, ModelDriver):
)
session.add(ref)
except sqlalchemy.exc.IntegrityError as e:
- raise MetaRuleExisting
+ raise exceptions.MetaRuleExisting
else:
query = session.query(MetaRule)
query = query.filter_by(id=meta_rule_id)
@@ -976,6 +988,8 @@ class ModelConnector(BaseConnector, ModelDriver):
return {_ref.id: _ref.to_dict() for _ref in ref_list}
def __add_perimeter_category(self, ClassType, name, description, uuid=None):
+ if not name.strip():
+ raise exceptions.CategoryNameInvalid
with self.get_session_for_write() as session:
ref = ClassType.from_dict(
{
@@ -1002,7 +1016,7 @@ class ModelConnector(BaseConnector, ModelDriver):
try:
return self.__add_perimeter_category(SubjectCategory, name, description, uuid=uuid)
except sql.exc.IntegrityError as e:
- raise SubjectCategoryExisting()
+ raise exceptions.SubjectCategoryExisting()
def delete_subject_category(self, category_id):
self.__delete_perimeter_category(SubjectCategory, category_id)
@@ -1014,7 +1028,7 @@ class ModelConnector(BaseConnector, ModelDriver):
try:
return self.__add_perimeter_category(ObjectCategory, name, description, uuid=uuid)
except sql.exc.IntegrityError as e:
- raise ObjectCategoryExisting()
+ raise exceptions.ObjectCategoryExisting()
def delete_object_category(self, category_id):
self.__delete_perimeter_category(ObjectCategory, category_id)
@@ -1027,7 +1041,7 @@ class ModelConnector(BaseConnector, ModelDriver):
try:
return self.__add_perimeter_category(ActionCategory, name, description, uuid=uuid)
except sql.exc.IntegrityError as e:
- raise ActionCategoryExisting()
+ raise exceptions.ActionCategoryExisting()
def delete_action_category(self, category_id):
self.__delete_perimeter_category(ActionCategory, category_id)
diff --git a/python_moondb/python_moondb/migrate_repo/versions/001_moon.py b/python_moondb/python_moondb/migrate_repo/versions/001_moon.py
index f69d708d..1bfb2ffa 100644
--- a/python_moondb/python_moondb/migrate_repo/versions/001_moon.py
+++ b/python_moondb/python_moondb/migrate_repo/versions/001_moon.py
@@ -3,7 +3,19 @@
# license which can be found in the file 'LICENSE' in this package distribution
# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+import json
import sqlalchemy as sql
+from sqlalchemy import types as sql_types
+
+class JsonBlob(sql_types.TypeDecorator):
+
+ impl = sql.Text
+
+ def process_bind_param(self, value, dialect):
+ return json.dumps(value)
+
+ def process_result_value(self, value, dialect):
+ return json.loads(value)
def upgrade(migrate_engine):
@@ -16,7 +28,7 @@ def upgrade(migrate_engine):
sql.Column('id', sql.String(64), primary_key=True),
sql.Column('name', sql.String(256), nullable=False),
sql.Column('keystone_project_id', sql.String(64), nullable=True, default=""),
- sql.Column('value', sql.Text(), nullable=True),
+ sql.Column('value', JsonBlob(), nullable=True),
sql.UniqueConstraint('name', 'keystone_project_id', name='unique_constraint_models'),
mysql_engine='InnoDB',
mysql_charset='utf8')
@@ -28,7 +40,7 @@ def upgrade(migrate_engine):
sql.Column('id', sql.String(64), primary_key=True),
sql.Column('name', sql.String(256), nullable=False),
sql.Column('model_id', sql.String(64), nullable=True, default=""),
- sql.Column('value', sql.Text(), nullable=True),
+ sql.Column('value', JsonBlob(), nullable=True),
sql.UniqueConstraint('name', 'model_id', name='unique_constraint_models'),
mysql_engine='InnoDB',
mysql_charset='utf8')
@@ -39,7 +51,7 @@ def upgrade(migrate_engine):
meta,
sql.Column('id', sql.String(64), primary_key=True),
sql.Column('name', sql.String(256), nullable=False),
- sql.Column('value', sql.Text(), nullable=True),
+ sql.Column('value', JsonBlob(), nullable=True),
sql.UniqueConstraint('name', name='unique_constraint_models'),
mysql_engine='InnoDB',
mysql_charset='utf8')
@@ -86,7 +98,7 @@ def upgrade(migrate_engine):
meta,
sql.Column('id', sql.String(64), primary_key=True),
sql.Column('name', sql.String(256), nullable=False),
- sql.Column('value', sql.Text(), nullable=True),
+ sql.Column('value', JsonBlob(), nullable=True),
sql.UniqueConstraint('name', name='unique_constraint_subjects'),
mysql_engine='InnoDB',
mysql_charset='utf8')
@@ -97,7 +109,7 @@ def upgrade(migrate_engine):
meta,
sql.Column('id', sql.String(64), primary_key=True),
sql.Column('name', sql.String(256), nullable=False),
- sql.Column('value', sql.Text(), nullable=True),
+ sql.Column('value', JsonBlob(), nullable=True),
sql.UniqueConstraint('name', name='unique_constraint_objects'),
mysql_engine='InnoDB',
mysql_charset='utf8')
@@ -108,7 +120,7 @@ def upgrade(migrate_engine):
meta,
sql.Column('id', sql.String(64), primary_key=True),
sql.Column('name', sql.String(256), nullable=False),
- sql.Column('value', sql.Text(), nullable=True),
+ sql.Column('value', JsonBlob(), nullable=True),
sql.UniqueConstraint('name', name='unique_constraint_actions'),
mysql_engine='InnoDB',
mysql_charset='utf8')
@@ -119,7 +131,7 @@ def upgrade(migrate_engine):
meta,
sql.Column('id', sql.String(64), primary_key=True),
sql.Column('name', sql.String(256), nullable=False),
- sql.Column('value', sql.Text(), nullable=True),
+ sql.Column('value', JsonBlob(), nullable=True),
sql.Column('category_id', sql.ForeignKey("subject_categories.id"), nullable=False),
sql.Column('policy_id', sql.ForeignKey("policies.id"), nullable=False),
sql.UniqueConstraint('name', 'category_id', 'policy_id', name='unique_constraint_subject_data'),
@@ -132,7 +144,7 @@ def upgrade(migrate_engine):
meta,
sql.Column('id', sql.String(64), primary_key=True),
sql.Column('name', sql.String(256), nullable=False),
- sql.Column('value', sql.Text(), nullable=True),
+ sql.Column('value', JsonBlob(), nullable=True),
sql.Column('category_id', sql.ForeignKey("object_categories.id"), nullable=False),
sql.Column('policy_id', sql.ForeignKey("policies.id"), nullable=False),
sql.UniqueConstraint('name', 'category_id', 'policy_id', name='unique_constraint_object_data'),
@@ -145,7 +157,7 @@ def upgrade(migrate_engine):
meta,
sql.Column('id', sql.String(64), primary_key=True),
sql.Column('name', sql.String(256), nullable=False),
- sql.Column('value', sql.Text(), nullable=True),
+ sql.Column('value', JsonBlob(), nullable=True),
sql.Column('category_id', sql.ForeignKey("action_categories.id"), nullable=False),
sql.Column('policy_id', sql.ForeignKey("policies.id"), nullable=False),
sql.UniqueConstraint('name', 'category_id', 'policy_id', name='unique_constraint_action_data'),
@@ -157,7 +169,7 @@ def upgrade(migrate_engine):
'subject_assignments',
meta,
sql.Column('id', sql.String(64), primary_key=True),
- sql.Column('assignments', sql.Text(), nullable=True),
+ sql.Column('assignments', sql.String(256), nullable=True),
sql.Column('policy_id', sql.ForeignKey("policies.id"), nullable=False),
sql.Column('subject_id', sql.ForeignKey("subjects.id"), nullable=False),
sql.Column('category_id', sql.ForeignKey("subject_categories.id"), nullable=False),
@@ -170,7 +182,7 @@ def upgrade(migrate_engine):
'object_assignments',
meta,
sql.Column('id', sql.String(64), primary_key=True),
- sql.Column('assignments', sql.Text(), nullable=True),
+ sql.Column('assignments', sql.String(256), nullable=True),
sql.Column('policy_id', sql.ForeignKey("policies.id"), nullable=False),
sql.Column('object_id', sql.ForeignKey("objects.id"), nullable=False),
sql.Column('category_id', sql.ForeignKey("object_categories.id"), nullable=False),
@@ -183,7 +195,7 @@ def upgrade(migrate_engine):
'action_assignments',
meta,
sql.Column('id', sql.String(64), primary_key=True),
- sql.Column('assignments', sql.Text(), nullable=True),
+ sql.Column('assignments', sql.String(256), nullable=True),
sql.Column('policy_id', sql.ForeignKey("policies.id"), nullable=False),
sql.Column('action_id', sql.ForeignKey("actions.id"), nullable=False),
sql.Column('category_id', sql.ForeignKey("action_categories.id"), nullable=False),
@@ -197,12 +209,12 @@ def upgrade(migrate_engine):
meta,
sql.Column('id', sql.String(64), primary_key=True),
sql.Column('name', sql.String(256), nullable=False),
- sql.Column('subject_categories', sql.Text(), nullable=False),
- sql.Column('object_categories', sql.Text(), nullable=False),
- sql.Column('action_categories', sql.Text(), nullable=False),
- sql.Column('value', sql.Text(), nullable=True),
+ sql.Column('subject_categories', JsonBlob(), nullable=False),
+ sql.Column('object_categories', JsonBlob(), nullable=False),
+ sql.Column('action_categories', JsonBlob(), nullable=False),
+ sql.Column('value', JsonBlob(), nullable=True),
sql.UniqueConstraint('name', name='unique_constraint_meta_rule_name'),
- sql.UniqueConstraint('subject_categories', 'object_categories', 'action_categories', name='unique_constraint_meta_rule_def'),
+ # sql.UniqueConstraint('subject_categories', 'object_categories', 'action_categories', name='unique_constraint_meta_rule_def'),
mysql_engine='InnoDB',
mysql_charset='utf8')
meta_rules_table.create(migrate_engine, checkfirst=True)
@@ -211,10 +223,9 @@ def upgrade(migrate_engine):
'rules',
meta,
sql.Column('id', sql.String(64), primary_key=True),
- sql.Column('rule', sql.Text(), nullable=True),
+ sql.Column('rule', JsonBlob(), nullable=True),
sql.Column('policy_id', sql.ForeignKey("policies.id"), nullable=False),
sql.Column('meta_rule_id', sql.ForeignKey("meta_rules.id"), nullable=False),
- sql.UniqueConstraint('rule', 'policy_id', 'meta_rule_id', name='unique_constraint_rule'),
mysql_engine='InnoDB',
mysql_charset='utf8')
rules_table.create(migrate_engine, checkfirst=True)
diff --git a/python_moondb/tests/unit_python/helpers/__init__.py b/python_moondb/tests/unit_python/helpers/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/python_moondb/tests/unit_python/helpers/__init__.py
diff --git a/python_moondb/tests/unit_python/helpers/assignment_helper.py b/python_moondb/tests/unit_python/helpers/assignment_helper.py
new file mode 100644
index 00000000..22a56e38
--- /dev/null
+++ b/python_moondb/tests/unit_python/helpers/assignment_helper.py
@@ -0,0 +1,49 @@
+# 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'.
+
+def get_action_assignments(policy_id, action_id=None, category_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_action_assignments("", policy_id, action_id, category_id)
+
+
+def add_action_assignment(policy_id, action_id, category_id, data_id):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_action_assignment("", policy_id, action_id, category_id, data_id)
+
+
+def delete_action_assignment(policy_id, action_id, category_id, data_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_action_assignment("", policy_id, action_id, category_id, data_id)
+
+
+def get_object_assignments(policy_id, object_id=None, category_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_object_assignments("", policy_id, object_id, category_id)
+
+
+def add_object_assignment(policy_id, object_id, category_id, data_id):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_object_assignment("", policy_id, object_id, category_id, data_id)
+
+
+def delete_object_assignment(policy_id, object_id, category_id, data_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_object_assignment("", policy_id, object_id, category_id, data_id)
+
+
+def get_subject_assignments(policy_id, subject_id=None, category_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_subject_assignments("", policy_id, subject_id, category_id)
+
+
+def add_subject_assignment(policy_id, subject_id, category_id, data_id):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_subject_assignment("", policy_id, subject_id, category_id, data_id)
+
+
+def delete_subject_assignment(policy_id, subject_id, category_id, data_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_subject_assignment("", policy_id, subject_id, category_id, data_id)
+
diff --git a/python_moondb/tests/unit_python/helpers/category_helper.py b/python_moondb/tests/unit_python/helpers/category_helper.py
new file mode 100644
index 00000000..55e95d91
--- /dev/null
+++ b/python_moondb/tests/unit_python/helpers/category_helper.py
@@ -0,0 +1,54 @@
+# 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'.
+
+def add_subject_category(cat_id=None, value=None):
+ from python_moondb.core import ModelManager
+ category = ModelManager.add_subject_category(user_id=None, category_id=cat_id, value=value)
+ return category
+
+
+def get_subject_category(cat_id=None):
+ from python_moondb.core import ModelManager
+ category = ModelManager.get_subject_categories(user_id=None, category_id=cat_id)
+ return category
+
+
+def add_object_category(cat_id=None, value=None):
+ from python_moondb.core import ModelManager
+ category = ModelManager.add_object_category(user_id=None, category_id=cat_id, value=value)
+ return category
+
+
+def get_object_category(cat_id=None):
+ from python_moondb.core import ModelManager
+ category = ModelManager.get_object_categories(user_id=None, category_id=cat_id)
+ return category
+
+
+def add_action_category(cat_id=None, value=None):
+ from python_moondb.core import ModelManager
+ category = ModelManager.add_action_category(user_id=None, category_id=cat_id, value=value)
+ return category
+
+
+def get_action_category(cat_id=None):
+ from python_moondb.core import ModelManager
+ category = ModelManager.get_action_categories(user_id=None, category_id=cat_id)
+ return category
+
+
+def delete_subject_category(category_id=None):
+ from python_moondb.core import ModelManager
+ return ModelManager.delete_subject_category("", category_id=category_id)
+
+
+def delete_object_category(category_id=None):
+ from python_moondb.core import ModelManager
+ return ModelManager.delete_object_category("", category_id=category_id)
+
+
+def delete_action_category(category_id=None):
+ from python_moondb.core import ModelManager
+ return ModelManager.delete_action_category("", category_id=category_id)
diff --git a/python_moondb/tests/unit_python/helpers/data_helper.py b/python_moondb/tests/unit_python/helpers/data_helper.py
new file mode 100644
index 00000000..20d9ae9a
--- /dev/null
+++ b/python_moondb/tests/unit_python/helpers/data_helper.py
@@ -0,0 +1,98 @@
+# 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'.
+
+def get_action_data(policy_id, data_id=None, category_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_action_data("", policy_id, data_id, category_id)
+
+
+def add_action_data(policy_id, data_id=None, category_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_action_data("", policy_id, data_id, category_id, value)
+
+
+def delete_action_data(policy_id, data_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_action_data("", policy_id, data_id)
+
+
+def get_object_data(policy_id, data_id=None, category_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_object_data("", policy_id, data_id, category_id)
+
+
+def add_object_data(policy_id, data_id=None, category_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_object_data("", policy_id, data_id, category_id, value)
+
+
+def delete_object_data(policy_id, data_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_object_data("", policy_id, data_id)
+
+
+def get_subject_data(policy_id, data_id=None, category_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_subject_data("", policy_id, data_id, category_id)
+
+
+def add_subject_data(policy_id, data_id=None, category_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.set_subject_data("", policy_id, data_id, category_id, value)
+
+
+def delete_subject_data(policy_id, data_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_subject_data("", policy_id, data_id)
+
+
+def get_actions(policy_id, perimeter_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_actions("", policy_id, perimeter_id)
+
+
+def add_action(policy_id, perimeter_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_action("", policy_id, perimeter_id, value)
+
+
+def delete_action(policy_id, perimeter_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_action("", policy_id, perimeter_id)
+
+
+def get_objects(policy_id, perimeter_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_objects("", policy_id, perimeter_id)
+
+
+def add_object(policy_id, perimeter_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_object("", policy_id, perimeter_id, value)
+
+
+def delete_object(policy_id, perimeter_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_object("", policy_id, perimeter_id)
+
+
+def get_subjects(policy_id, perimeter_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_subjects("", policy_id, perimeter_id)
+
+
+def add_subject(policy_id, perimeter_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.add_subject("", policy_id, perimeter_id, value)
+
+
+def delete_subject(policy_id, perimeter_id):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_subject("", policy_id, perimeter_id)
+
+
+def get_available_metadata(policy_id):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_available_metadata("", policy_id)
diff --git a/python_moondb/tests/unit_python/helpers/meta_rule_helper.py b/python_moondb/tests/unit_python/helpers/meta_rule_helper.py
new file mode 100644
index 00000000..80d138c6
--- /dev/null
+++ b/python_moondb/tests/unit_python/helpers/meta_rule_helper.py
@@ -0,0 +1,48 @@
+# 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 helpers import mock_data
+
+
+def set_meta_rule(meta_rule_id, value=None):
+ from python_moondb.core import ModelManager
+ if not value:
+ action_category_id = mock_data.create_action_category("action_category_id1")
+ subject_category_id = mock_data.create_subject_category("subject_category_id1")
+ object_category_id = mock_data.create_object_category("object_category_id1")
+ value = {
+ "name": "MLS_meta_rule",
+ "description": "test",
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
+ }
+ return ModelManager.set_meta_rule(user_id=None, meta_rule_id=meta_rule_id, value=value)
+
+
+def add_meta_rule(meta_rule_id=None, value=None):
+ from python_moondb.core import ModelManager
+ if not value:
+ action_category_id = mock_data.create_action_category("action_category_id1")
+ subject_category_id = mock_data.create_subject_category("subject_category_id1")
+ object_category_id = mock_data.create_object_category("object_category_id1")
+ value = {
+ "name": "MLS_meta_rule",
+ "description": "test",
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
+ }
+ return ModelManager.add_meta_rule(user_id=None, meta_rule_id=meta_rule_id, value=value)
+
+
+def get_meta_rules(meta_rule_id=None):
+ from python_moondb.core import ModelManager
+ return ModelManager.get_meta_rules(user_id=None, meta_rule_id=meta_rule_id)
+
+
+def delete_meta_rules(meta_rule_id=None):
+ from python_moondb.core import ModelManager
+ ModelManager.delete_meta_rule(user_id=None, meta_rule_id=meta_rule_id)
diff --git a/python_moondb/tests/unit_python/helpers/mock_data.py b/python_moondb/tests/unit_python/helpers/mock_data.py
new file mode 100644
index 00000000..82eebe88
--- /dev/null
+++ b/python_moondb/tests/unit_python/helpers/mock_data.py
@@ -0,0 +1,144 @@
+# 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 .category_helper import *
+from .policy_helper import *
+from .data_helper import *
+from .model_helper import *
+from .meta_rule_helper import *
+
+
+def create_subject_category(name):
+ subject_category = add_subject_category(
+ value={"name": name, "description": "description 1"})
+ return list(subject_category.keys())[0]
+
+
+def create_object_category(name):
+ object_category = add_object_category(
+ value={"name": name, "description": "description 1"})
+ return list(object_category.keys())[0]
+
+
+def create_action_category(name):
+ action_category = add_action_category(
+ value={"name": name, "description": "description 1"})
+ return list(action_category.keys())[0]
+
+
+def create_model(meta_rule_id, model_name="test_model"):
+ value = {
+ "name": model_name,
+ "description": "test",
+ "meta_rules": [meta_rule_id]
+
+ }
+ return value
+
+
+def create_policy(model_id, policy_name="policy_1"):
+ value = {
+ "name": policy_name,
+ "model_id": model_id,
+ "genre": "authz",
+ "description": "test",
+ }
+ return value
+
+
+def create_pdp(policies_ids):
+ value = {
+ "name": "test_pdp",
+ "security_pipeline": policies_ids,
+ "keystone_project_id": "keystone_project_id1",
+ "description": "...",
+ }
+ return value
+
+
+def create_new_policy(subject_category_name=None, object_category_name=None, action_category_name=None,
+ model_name="test_model", policy_name="policy_1", meta_rule_name="meta_rule1"):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = create_new_meta_rule(
+ subject_category_name=subject_category_name,
+ object_category_name=object_category_name,
+ action_category_name=action_category_name, meta_rule_name=meta_rule_name)
+ model = add_model(value=create_model(meta_rule_id, model_name))
+ model_id = list(model.keys())[0]
+ value = create_policy(model_id, policy_name)
+ policy = add_policies(value=value)
+ assert policy
+ policy_id = list(policy.keys())[0]
+ return subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id
+
+
+def create_new_meta_rule(subject_category_name=None, object_category_name=None, action_category_name=None,
+ meta_rule_name="meta_rule1"):
+ subject_category_id = create_subject_category(subject_category_name)
+ object_category_id = create_object_category(object_category_name)
+ action_category_id = create_action_category(action_category_name)
+ value = {"name": meta_rule_name,
+ "algorithm": "name of the meta rule algorithm",
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
+ }
+ meta_rule = add_meta_rule(value=value)
+ return subject_category_id, object_category_id, action_category_id, list(meta_rule.keys())[0]
+
+
+def create_subject(policy_id):
+ value = {
+ "name": "testuser",
+ "description": "test",
+ }
+ subject = add_subject(policy_id=policy_id, value=value)
+ return list(subject.keys())[0]
+
+
+def create_object(policy_id):
+ value = {
+ "name": "testobject",
+ "description": "test",
+ }
+ object = add_object(policy_id=policy_id, value=value)
+ return list(object.keys())[0]
+
+
+def create_action(policy_id):
+ value = {
+ "name": "testaction",
+ "description": "test",
+ }
+ action = add_action(policy_id=policy_id, value=value)
+ return list(action.keys())[0]
+
+
+def create_subject_data(policy_id, category_id):
+ value = {
+ "name": "subject-security-level",
+ "description": {"low": "", "medium": "", "high": ""},
+ }
+ subject_data = add_subject_data(policy_id=policy_id, category_id=category_id, value=value).get('data')
+ assert subject_data
+ return list(subject_data.keys())[0]
+
+
+def create_object_data(policy_id, category_id):
+ value = {
+ "name": "object-security-level",
+ "description": {"low": "", "medium": "", "high": ""},
+ }
+ object_data = add_object_data(policy_id=policy_id, category_id=category_id, value=value).get('data')
+ return list(object_data.keys())[0]
+
+
+def create_action_data(policy_id, category_id):
+ value = {
+ "name": "action-type",
+ "description": {"vm-action": "", "storage-action": "", },
+ }
+ action_data = add_action_data(policy_id=policy_id, category_id=category_id, value=value).get('data')
+ return list(action_data.keys())[0]
+
diff --git a/python_moondb/tests/unit_python/helpers/model_helper.py b/python_moondb/tests/unit_python/helpers/model_helper.py
new file mode 100644
index 00000000..58946a99
--- /dev/null
+++ b/python_moondb/tests/unit_python/helpers/model_helper.py
@@ -0,0 +1,50 @@
+# 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 helpers import mock_data
+
+
+def get_models(model_id=None):
+ from python_moondb.core import ModelManager
+ return ModelManager.get_models(user_id=None, model_id=model_id)
+
+
+def add_model(model_id=None, value=None):
+ from python_moondb.core import ModelManager
+ if not value:
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = mock_data.create_new_meta_rule(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1")
+ name = "MLS" if model_id is None else "MLS " + model_id
+ value = {
+ "name": name,
+ "description": "test",
+ "meta_rules": [meta_rule_id]
+ }
+ return ModelManager.add_model(user_id=None, model_id=model_id, value=value)
+
+
+def delete_models(uuid=None, name=None):
+ from python_moondb.core import ModelManager
+ if not uuid:
+ for model_id, model_value in get_models():
+ if name == model_value['name']:
+ uuid = model_id
+ break
+ ModelManager.delete_model(user_id=None, model_id=uuid)
+
+
+def delete_all_models():
+ from python_moondb.core import ModelManager
+ models_values = get_models()
+ print(models_values)
+ for model_id, model_value in models_values.items():
+ ModelManager.delete_model(user_id=None, model_id=model_id)
+
+
+def update_model(model_id=None, value=None):
+ from python_moondb.core import ModelManager
+ return ModelManager.update_model(user_id=None, model_id=model_id, value=value)
diff --git a/python_moondb/tests/unit_python/helpers/pdp_helper.py b/python_moondb/tests/unit_python/helpers/pdp_helper.py
new file mode 100644
index 00000000..3d169b06
--- /dev/null
+++ b/python_moondb/tests/unit_python/helpers/pdp_helper.py
@@ -0,0 +1,23 @@
+# 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'.
+
+def update_pdp(pdp_id, value):
+ from python_moondb.core import PDPManager
+ return PDPManager.update_pdp("", pdp_id, value)
+
+
+def delete_pdp(pdp_id):
+ from python_moondb.core import PDPManager
+ PDPManager.delete_pdp("", pdp_id)
+
+
+def add_pdp(pdp_id=None, value=None):
+ from python_moondb.core import PDPManager
+ return PDPManager.add_pdp("", pdp_id, value)
+
+
+def get_pdp(pdp_id=None):
+ from python_moondb.core import PDPManager
+ return PDPManager.get_pdp("", pdp_id)
diff --git a/python_moondb/tests/unit_python/helpers/policy_helper.py b/python_moondb/tests/unit_python/helpers/policy_helper.py
new file mode 100644
index 00000000..c932ee3a
--- /dev/null
+++ b/python_moondb/tests/unit_python/helpers/policy_helper.py
@@ -0,0 +1,61 @@
+# 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'.
+
+def get_policies():
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_policies("admin")
+
+
+def add_policies(policy_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ if not value:
+ value = {
+ "name": "test_policy",
+ "model_id": "",
+ "genre": "authz",
+ "description": "test",
+ }
+ return PolicyManager.add_policy("admin", policy_id=policy_id, value=value)
+
+
+def delete_policies(uuid=None, name=None):
+ from python_moondb.core import PolicyManager
+ if not uuid:
+ for policy_id, policy_value in get_policies():
+ if name == policy_value['name']:
+ uuid = policy_id
+ break
+ PolicyManager.delete_policy("admin", uuid)
+
+
+def update_policy(policy_id, value):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.update_policy("admin", policy_id, value)
+
+
+def get_policy_from_meta_rules(meta_rule_id):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_policy_from_meta_rules("admin", meta_rule_id)
+
+
+def get_rules(policy_id=None, meta_rule_id=None, rule_id=None):
+ from python_moondb.core import PolicyManager
+ return PolicyManager.get_rules("", policy_id, meta_rule_id, rule_id)
+
+
+def add_rule(policy_id=None, meta_rule_id=None, value=None):
+ from python_moondb.core import PolicyManager
+ if not value:
+ value = {
+ "rule": ("high", "medium", "vm-action"),
+ "instructions": ({"decision": "grant"}),
+ "enabled": "",
+ }
+ return PolicyManager.add_rule("", policy_id, meta_rule_id, value)
+
+
+def delete_rule(policy_id=None, rule_id=None):
+ from python_moondb.core import PolicyManager
+ PolicyManager.delete_rule("", policy_id, rule_id)
diff --git a/python_moondb/tests/unit_python/models/test_categories.py b/python_moondb/tests/unit_python/models/test_categories.py
index 8782f172..f87d0e12 100644
--- a/python_moondb/tests/unit_python/models/test_categories.py
+++ b/python_moondb/tests/unit_python/models/test_categories.py
@@ -1,277 +1,79 @@
-# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors
+# 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 .test_meta_rules import *
-import policies.mock_data as mock_data
-import policies.test_data as test_data
+import pytest
+import logging
+from python_moonutilities.exceptions import *
+from helpers import category_helper
logger = logging.getLogger("moon.db.tests.models.test_categories")
-
-def add_subject_category(cat_id=None, value=None):
- from python_moondb.core import ModelManager
- category = ModelManager.add_subject_category(user_id=None, category_id=cat_id, value=value)
- return category
-
-
def test_add_subject_category_twice():
- category = add_subject_category(value={"name": "category name", "description": "description 1"})
+ category = category_helper.add_subject_category(value={"name": "category name", "description": "description 1"})
category_id = list(category.keys())[0]
assert category is not None
with pytest.raises(SubjectCategoryExisting):
- add_subject_category(category_id, value={"name": "category name", "description": "description 2"})
-
-
-def test_add_subject_category_twice_with_same_name():
- category = add_subject_category(value={"name": "category name", "description": "description 1"})
- assert category is not None
- with pytest.raises(SubjectCategoryExisting):
- add_subject_category(value={"name": "category name", "description": "description 2"})
-
-
-def get_subject_category(cat_id=None):
- from python_moondb.core import ModelManager
- category = ModelManager.get_subject_categories(user_id=None, category_id=cat_id)
- return category
+ category_helper.add_subject_category(category_id,
+ value={"name": "category name", "description": "description 2"})
def test_get_subject_categories():
- added_category = add_subject_category(value={"name": "category name", "description": "description 1"})
+ added_category = category_helper.add_subject_category(
+ value={"name": "category name", "description": "description 1"})
category_id = list(added_category.keys())[0]
- subject_category = get_subject_category(category_id)
+ subject_category = category_helper.get_subject_category(category_id)
assert subject_category == added_category
def test_get_subject_categories_with_invalid_id():
category_id = "invalid_id"
- subject_category = get_subject_category(category_id)
+ subject_category = category_helper.get_subject_category(category_id)
assert len(subject_category) == 0
- category = add_subject_category(value={"name": "category name", "description": "description 1"})
- assert category is not None
- with pytest.raises(SubjectCategoryExisting):
- add_subject_category(value={"name": "category name", "description": "description 2"})
-
-
-def delete_subject_category(cat_id=None):
- from python_moondb.core import ModelManager
- ModelManager.delete_subject_category(user_id=None, category_id=cat_id)
-
-
-def test_delete_subject_category(db):
- category = add_subject_category(value={"name": "category name", "description": "description 1"})
- delete_subject_category(list(category.keys())[0])
-
-
-def test_delete_subject_category_with_invalid_id(db):
- with pytest.raises(SubjectCategoryUnknown) as exception_info:
- delete_subject_category(-1)
-
-
-def test_delete_subject_category_with_meta_rule(db):
- category = add_subject_category(value={"name": "category name", "description": "description 1"})
- subject_category_id = list(category.keys())[0]
- value = {
- "name": "MLS_meta_rule",
- "description": "test",
- "subject_categories": [subject_category_id],
- "object_categories": ["vm_security_level_id_1"],
- "action_categories": ["action_type_id_1"]
- }
- add_meta_rule(value=value)
- with pytest.raises(DeleteCategoryWithMetaRule):
- delete_subject_category(subject_category_id)
-
-
-def test_delete_subject_category_with_data(db):
- category = add_subject_category(value={"name": "category name", "description": "description 1"})
- subject_category_id = list(category.keys())[0]
- policy_id = mock_data.get_policy_id()
- data_id = "data_id_1"
- category_id = subject_category_id
- value = {
- "name": "subject-security-level",
- "description": {"low": "", "medium": "", "high": ""},
- }
- test_data.add_subject_data(policy_id, data_id, category_id, value)
- with pytest.raises(DeleteCategoryWithData):
- delete_subject_category(subject_category_id)
-
-
-def add_object_category(cat_id=None, value=None):
- from python_moondb.core import ModelManager
- category = ModelManager.add_object_category(user_id=None, category_id=cat_id, value=value)
- return category
def test_add_object_category_twice():
- category = add_object_category(value={"name": "category name", "description": "description 1"})
+ category = category_helper.add_object_category(value={"name": "category name", "description": "description 1"})
category_id = list(category.keys())[0]
assert category is not None
with pytest.raises(ObjectCategoryExisting):
- add_object_category(category_id, value={"name": "category name", "description": "description 2"})
-
-
-def test_add_object_category_twice_with_same_name():
- category = add_object_category(value={"name": "category name", "description": "description 1"})
- assert category is not None
- with pytest.raises(ObjectCategoryExisting):
- add_object_category(value={"name": "category name", "description": "description 2"})
-
-
-def get_object_category(cat_id=None):
- from python_moondb.core import ModelManager
- category = ModelManager.get_object_categories(user_id=None, category_id=cat_id)
- return category
+ category_helper.add_object_category(category_id,
+ value={"name": "category name", "description": "description 2"})
def test_get_object_categories():
- added_category = add_object_category(value={"name": "category name", "description": "description 1"})
+ added_category = category_helper.add_object_category(
+ value={"name": "category name", "description": "description 1"})
category_id = list(added_category.keys())[0]
- object_category = get_object_category(category_id)
+ object_category = category_helper.get_object_category(category_id)
assert object_category == added_category
def test_get_object_categories_with_invalid_id():
category_id = "invalid_id"
- object_category = get_object_category(category_id)
+ object_category = category_helper.get_object_category(category_id)
assert len(object_category) == 0
- category = add_object_category(value={"name": "category name", "description": "description 1"})
- assert category is not None
- with pytest.raises(ObjectCategoryExisting):
- add_object_category(value={"name": "category name", "description": "description 2"})
-
-
-def delete_object_category(cat_id=None):
- from python_moondb.core import ModelManager
- ModelManager.delete_object_category(user_id=None, category_id=cat_id)
-
-
-def test_delete_object_category(db):
- category = add_object_category(value={"name": "category name", "description": "description 1"})
- delete_object_category(list(category.keys())[0])
-
-
-def test_delete_object_category_with_invalid_id(db):
- with pytest.raises(ObjectCategoryUnknown) as exception_info:
- delete_object_category(-1)
-
-
-def test_delete_object_category_with_meta_rule(db):
- category = add_object_category(value={"name": "category name", "description": "description 1"})
- object_category_id = list(category.keys())[0]
- value = {
- "name": "MLS_meta_rule",
- "description": "test",
- "subject_categories": ["subject_id_1"],
- "object_categories": [object_category_id],
- "action_categories": ["action_type_id_1"]
- }
- add_meta_rule(value=value)
- with pytest.raises(DeleteCategoryWithMetaRule):
- delete_object_category(object_category_id)
-
-
-def test_delete_object_category_with_data(db):
- policy_id = mock_data.get_policy_id()
- category = add_object_category(value={"name": "category name", "description": "description 1"})
- object_category_id = list(category.keys())[0]
- data_id = "data_id_1"
- category_id = object_category_id
- value = {
- "name": "object-security-level",
- "description": {"low": "", "medium": "", "high": ""},
- }
- test_data.add_object_data(policy_id, data_id, category_id, value)
- with pytest.raises(DeleteCategoryWithData):
- delete_object_category(object_category_id)
-
-
-def add_action_category(cat_id=None, value=None):
- from python_moondb.core import ModelManager
- category = ModelManager.add_action_category(user_id=None, category_id=cat_id, value=value)
- return category
def test_add_action_category_twice():
- category = add_action_category(value={"name": "category name", "description": "description 1"})
+ category = category_helper.add_action_category(value={"name": "category name", "description": "description 1"})
category_id = list(category.keys())[0]
assert category is not None
with pytest.raises(ActionCategoryExisting):
- add_action_category(category_id, value={"name": "category name", "description": "description 2"})
-
-
-def test_add_action_category_twice_with_same_name():
- category = add_action_category(value={"name": "category name", "description": "description 1"})
- assert category is not None
- with pytest.raises(ActionCategoryExisting):
- add_action_category(value={"name": "category name", "description": "description 2"})
-
-
-def get_action_category(cat_id=None):
- from python_moondb.core import ModelManager
- category = ModelManager.get_action_categories(user_id=None, category_id=cat_id)
- return category
+ category_helper.add_action_category(category_id,
+ value={"name": "category name", "description": "description 2"})
def test_get_action_categories():
- added_category = add_action_category(value={"name": "category name", "description": "description 1"})
+ added_category = category_helper.add_action_category(
+ value={"name": "category name", "description": "description 1"})
category_id = list(added_category.keys())[0]
- action_category = get_action_category(category_id)
+ action_category = category_helper.get_action_category(category_id)
assert action_category == added_category
def test_get_action_categories_with_invalid_id():
category_id = "invalid_id"
- action_category = get_action_category(category_id)
+ action_category = category_helper.get_action_category(category_id)
assert len(action_category) == 0
- category = add_action_category(value={"name": "category name", "description": "description 1"})
- assert category is not None
- with pytest.raises(ActionCategoryExisting):
- add_action_category(value={"name": "category name", "description": "description 2"})
-
-
-def delete_action_category(cat_id=None):
- from python_moondb.core import ModelManager
- ModelManager.delete_action_category(user_id=None, category_id=cat_id)
-
-
-def test_delete_action_category(db):
- category = add_action_category(value={"name": "category name", "description": "description 1"})
- delete_action_category(list(category.keys())[0])
-
-
-def test_delete_action_category_with_invalid_id(db):
- with pytest.raises(ActionCategoryUnknown) as exception_info:
- delete_action_category(-1)
-
-
-def test_delete_action_category_with_meta_rule(db):
- category = add_action_category(value={"name": "category name", "description": "description 1"})
- action_category_id = list(category.keys())[0]
- value = {
- "name": "MLS_meta_rule",
- "description": "test",
- "subject_categories": ["subject_id_1"],
- "object_categories": ["vm_security_level_id_1"],
- "action_categories": [action_category_id]
- }
- add_meta_rule(value=value)
- with pytest.raises(DeleteCategoryWithMetaRule):
- delete_action_category(action_category_id)
-
-
-def test_delete_action_category_with_data(db):
- category = add_action_category(value={"name": "category name", "description": "description 1"})
- action_category_id = list(category.keys())[0]
- policy_id = mock_data.get_policy_id()
- data_id = "data_id_1"
- category_id = action_category_id
- value = {
- "name": "action-type",
- "description": {"vm-action": "", "storage-action": "", },
- }
- test_data.add_action_data(policy_id, data_id, category_id, value)
- with pytest.raises(DeleteCategoryWithData):
- delete_action_category(action_category_id)
diff --git a/python_moondb/tests/unit_python/models/test_meta_rules.py b/python_moondb/tests/unit_python/models/test_meta_rules.py
index 4e60e11a..102cd724 100644
--- a/python_moondb/tests/unit_python/models/test_meta_rules.py
+++ b/python_moondb/tests/unit_python/models/test_meta_rules.py
@@ -1,141 +1,113 @@
-# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors
+# 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 .test_models import *
-
-
-def set_meta_rule(meta_rule_id, value=None):
- from python_moondb.core import ModelManager
- if not value:
- value = {
- "name": "MLS_meta_rule",
- "description": "test",
- "subject_categories": ["user_security_level_id_1"],
- "object_categories": ["vm_security_level_id_1"],
- "action_categories": ["action_type_id_1"]
- }
- return ModelManager.set_meta_rule(user_id=None, meta_rule_id=meta_rule_id, value=value)
-
-
-def add_meta_rule(meta_rule_id=None, value=None):
- from python_moondb.core import ModelManager
- if not value:
- value = {
- "name": "MLS_meta_rule",
- "description": "test",
- "subject_categories": ["user_security_level_id_1"],
- "object_categories": ["vm_security_level_id_1"],
- "action_categories": ["action_type_id_1"]
- }
- return ModelManager.add_meta_rule(user_id=None, meta_rule_id=meta_rule_id, value=value)
-
-
-def get_meta_rules(meta_rule_id=None):
- from python_moondb.core import ModelManager
- return ModelManager.get_meta_rules(user_id=None, meta_rule_id=meta_rule_id)
-
-
-def delete_meta_rules(meta_rule_id=None):
- from python_moondb.core import ModelManager
- ModelManager.delete_meta_rule(user_id=None, meta_rule_id=meta_rule_id)
+import pytest
+from helpers import meta_rule_helper
+import helpers.mock_data as mock_data
def test_set_not_exist_meta_rule_error(db):
# set not existing meta rule and expect to raise and error
with pytest.raises(Exception) as exception_info:
- set_meta_rule(meta_rule_id=None)
- assert str(exception_info.value) == '400: Sub Meta Rule Unknown'
+ meta_rule_helper.set_meta_rule(meta_rule_id=None)
+ assert str(exception_info.value) == '400: Meta Rule Unknown'
def test_add_new_meta_rule_success(db):
+ action_category_id = mock_data.create_action_category("action_category_id1")
+ subject_category_id = mock_data.create_subject_category("subject_category_id1")
+ object_category_id = mock_data.create_object_category("object_category_id1")
value = {
"name": "MLS_meta_rule",
"description": "test",
- "subject_categories": ["user_security_level_id_1"],
- "object_categories": ["vm_security_level_id_1"],
- "action_categories": ["action_type_id_1"]
- }
- metaRules = add_meta_rule()
- assert isinstance(metaRules, dict)
- assert metaRules
- assert len(metaRules) is 1
- meta_rule_id = list(metaRules.keys())[0]
- for key in ("name", "description", "subject_categories", "object_categories", "action_categories"):
- assert key in metaRules[meta_rule_id]
- assert metaRules[meta_rule_id][key] == value[key]
-
-
-def test_add_new_meta_rule_with_same_name_twice(db):
- value = {
- "name": "MLS_meta_rule",
- "description": "test",
- "subject_categories": ["user_security_level_id_1"],
- "object_categories": ["vm_security_level_id_1"],
- "action_categories": ["action_type_id_1"]
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
}
- meta_rules = add_meta_rule(value=value)
+ meta_rules = meta_rule_helper.add_meta_rule(value=value)
assert isinstance(meta_rules, dict)
assert meta_rules
- with pytest.raises(Exception) as exc_info:
- add_meta_rule(value=value)
+ assert len(meta_rules) is 1
+ meta_rule_id = list(meta_rules.keys())[0]
+ for key in ("name", "description", "subject_categories", "object_categories", "action_categories"):
+ assert key in meta_rules[meta_rule_id]
+ assert meta_rules[meta_rule_id][key] == value[key]
-def test_set_meta_rule_succes(db):
+def test_set_meta_rule_success(db):
# arrange
- meta_rules = add_meta_rule()
+ meta_rules = meta_rule_helper.add_meta_rule()
meta_rule_id = list(meta_rules.keys())[0]
+ action_category_id = mock_data.create_action_category("action_category_id2")
+ subject_category_id = mock_data.create_subject_category("subject_category_id2")
+ object_category_id = mock_data.create_object_category("object_category_id2")
updated_value = {
"name": "MLS_meta_rule",
"description": "test",
- "subject_categories": ["user_role_id_1"],
- "object_categories": ["vm_security_level_id_1"],
- "action_categories": ["action_type_id_1"]
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
}
# action
- updated_meta_rule = set_meta_rule(meta_rule_id, updated_value)
+ updated_meta_rule = meta_rule_helper.set_meta_rule(meta_rule_id, updated_value)
# assert
updated_meta_rule_id = list(updated_meta_rule.keys())[0]
assert updated_meta_rule_id == meta_rule_id
- assert updated_meta_rule[updated_meta_rule_id]["subject_categories"] == \
- updated_value["subject_categories"]
+ assert updated_meta_rule[updated_meta_rule_id]["subject_categories"] == updated_value["subject_categories"]
def test_add_existing_meta_rule_error(db):
- meta_rules = add_meta_rule()
+ action_category_id = mock_data.create_action_category("action_category_id3")
+ subject_category_id = mock_data.create_subject_category("subject_category_id3")
+ object_category_id = mock_data.create_object_category("object_category_id3")
+ value = {
+ "name": "MLS_meta_rule",
+ "description": "test",
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
+ }
+ meta_rules = meta_rule_helper.add_meta_rule(value=value)
meta_rule_id = list(meta_rules.keys())[0]
with pytest.raises(Exception) as exception_info:
- add_meta_rule(meta_rule_id=meta_rule_id)
+ meta_rule_helper.add_meta_rule(meta_rule_id=meta_rule_id)
assert str(exception_info.value) == '400: Sub Meta Rule Existing'
def test_get_meta_rule_success(db):
# arrange
+ action_category_id = mock_data.create_action_category("action_type")
+ subject_category_id = mock_data.create_subject_category("user_security_level")
+ object_category_id = mock_data.create_object_category("vm_security_level")
values = {}
value1 = {
"name": "MLS_meta_rule",
"description": "test",
- "subject_categories": ["user_security_level_id_1"],
- "object_categories": ["vm_security_level_id_1"],
- "action_categories": ["action_type_id_1"]
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
}
- meta_rules1 = add_meta_rule(value=value1)
+ meta_rules1 = meta_rule_helper.add_meta_rule(value=value1)
meta_rule_id1 = list(meta_rules1.keys())[0]
values[meta_rule_id1] = value1
+ action_category_id = mock_data.create_action_category("action_type2")
+ subject_category_id = mock_data.create_subject_category("user_security_level2")
+ object_category_id = mock_data.create_object_category("vm_security_level2")
value2 = {
"name": "rbac_meta_rule",
"description": "test",
- "subject_categories": ["user_role_id_1"],
- "object_categories": ["vm_id_1"],
- "action_categories": ["action_type_id_1"]
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
}
- meta_rules2 = add_meta_rule(value=value2)
+ meta_rules2 = meta_rule_helper.add_meta_rule(value=value2)
meta_rule_id2 = list(meta_rules2.keys())[0]
values[meta_rule_id2] = value2
# action
- meta_rules = get_meta_rules()
+ meta_rules = meta_rule_helper.get_meta_rules()
# assert
assert isinstance(meta_rules, dict)
assert meta_rules
@@ -148,10 +120,10 @@ def test_get_meta_rule_success(db):
def test_get_specific_meta_rule_success(db):
# arrange
- added_meta_rules = add_meta_rule()
+ added_meta_rules = meta_rule_helper.add_meta_rule()
added_meta_rule_id = list(added_meta_rules.keys())[0]
# action
- meta_rules = get_meta_rules(meta_rule_id=added_meta_rule_id)
+ meta_rules = meta_rule_helper.get_meta_rules(meta_rule_id=added_meta_rule_id)
meta_rule_id = list(meta_rules.keys())[0]
# assert
assert meta_rule_id == added_meta_rule_id
@@ -161,58 +133,28 @@ def test_get_specific_meta_rule_success(db):
def test_delete_meta_rules_success(db):
+ action_category_id = mock_data.create_action_category("action_type")
+ subject_category_id = mock_data.create_subject_category("user_security_level")
+ object_category_id = mock_data.create_object_category("vm_security_level")
# arrange
value1 = {
"name": "MLS_meta_rule",
"description": "test",
- "subject_categories": ["user_security_level_id_1"],
- "object_categories": ["vm_security_level_id_1"],
- "action_categories": ["action_type_id_1"]
+ "subject_categories": [subject_category_id],
+ "object_categories": [object_category_id],
+ "action_categories": [action_category_id]
}
- meta_rules1 = add_meta_rule(value=value1)
+ meta_rules1 = meta_rule_helper.add_meta_rule(value=value1)
meta_rule_id1 = list(meta_rules1.keys())[0]
- value2 = {
- "name": "rbac_meta_rule",
- "description": "test",
- "subject_categories": ["user_role_id_1"],
- "object_categories": ["vm_id_1"],
- "action_categories": ["action_type_id_1"]
- }
- meta_rules2 = add_meta_rule(value=value2)
- meta_rule_id2 = list(meta_rules2.keys())[0]
-
# action
- delete_meta_rules(meta_rule_id1)
+ meta_rule_helper.delete_meta_rules(meta_rule_id1)
# assert
- meta_rules = get_meta_rules()
+ meta_rules = meta_rule_helper.get_meta_rules()
assert meta_rule_id1 not in meta_rules
def test_delete_invalid_meta_rules_error(db):
with pytest.raises(Exception) as exception_info:
- delete_meta_rules("INVALID_META_RULE_ID")
- assert str(exception_info.value) == '400: Sub Meta Rule Unknown'
-
-
-def test_delete_meta_rule_with_assigned_model(db):
- value = {
- "name": "MLS_meta_rule",
- "description": "test",
- "subject_categories": ["user_security_level_id_1"],
- "object_categories": ["vm_security_level_id_1"],
- "action_categories": ["action_type_id_1"]
- }
- metaRules = add_meta_rule()
- assert isinstance(metaRules, dict)
- assert metaRules
- assert len(metaRules) is 1
- meta_rule_id = list(metaRules.keys())[0]
- model_value1 = {
- "name": "MLS",
- "description": "test",
- "meta_rules": meta_rule_id
- }
- add_model(value=model_value1)
- with pytest.raises(DeleteMetaRuleWithModel) as exception_info:
- delete_meta_rules(meta_rule_id)
+ meta_rule_helper.delete_meta_rules("INVALID_META_RULE_ID")
+ assert str(exception_info.value) == '400: Meta Rule Unknown'
diff --git a/python_moondb/tests/unit_python/models/test_models.py b/python_moondb/tests/unit_python/models/test_models.py
index 251792c5..0026345c 100644
--- a/python_moondb/tests/unit_python/models/test_models.py
+++ b/python_moondb/tests/unit_python/models/test_models.py
@@ -1,4 +1,4 @@
-# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors
+# 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'.
@@ -6,54 +6,17 @@
import pytest
from python_moonutilities.exceptions import *
import logging
-import policies.test_policies as test_policies
+import helpers.mock_data as mock_data
+import helpers.model_helper as model_helper
+import helpers.category_helper as category_helper
+import helpers.policy_helper as policy_helper
logger = logging.getLogger("moon.db.tests.test_model")
-def get_models(model_id=None):
- from python_moondb.core import ModelManager
- return ModelManager.get_models(user_id=None, model_id=model_id)
-
-
-def add_model(model_id=None, value=None):
- from python_moondb.core import ModelManager
- if not value:
- name = "MLS" if model_id is None else "MLS " + model_id
- value = {
- "name": name,
- "description": "test",
- "meta_rules": "meta_rule_mls_1"
- }
- return ModelManager.add_model(user_id=None, model_id=model_id, value=value)
-
-
-def delete_models(uuid=None, name=None):
- from python_moondb.core import ModelManager
- if not uuid:
- for model_id, model_value in get_models():
- if name == model_value['name']:
- uuid = model_id
- break
- ModelManager.delete_model(user_id=None, model_id=uuid)
-
-
-def delete_all_models():
- from python_moondb.core import ModelManager
- models_values = get_models()
- print(models_values)
- for model_id, model_value in models_values.items():
- ModelManager.delete_model(user_id=None, model_id=model_id)
-
-
-def update_model(model_id=None, value=None):
- from python_moondb.core import ModelManager
- return ModelManager.update_model(user_id=None, model_id=model_id, value=value)
-
-
def test_get_models_empty(db):
# act
- models = get_models()
+ models = model_helper.get_models()
# assert
assert isinstance(models, dict)
assert not models
@@ -61,75 +24,107 @@ def test_get_models_empty(db):
def test_get_model(db):
# prepare
- add_model(model_id="mls_model_id")
+ model_helper.add_model(model_id="mls_model_id")
# act
- models = get_models()
+ models = model_helper.get_models()
# assert
assert isinstance(models, dict)
assert models # assert model is not empty
assert len(models) is 1
- delete_all_models()
+ model_helper.delete_all_models()
def test_get_specific_model(db):
# prepare
- add_model(model_id="mls_model_id")
- add_model(model_id="rbac_model_id")
+ model_helper.add_model(model_id="mls_model_id")
# act
- models = get_models(model_id="mls_model_id")
+ models = model_helper.get_models(model_id="mls_model_id")
# assert
assert isinstance(models, dict)
assert models # assert model is not empty
assert len(models) is 1
- delete_all_models()
+ model_helper.delete_all_models()
def test_add_model(db):
# act
- model = add_model()
+ model = model_helper.add_model()
# assert
assert isinstance(model, dict)
assert model # assert model is not empty
assert len(model) is 1
- delete_all_models()
+ model_helper.delete_all_models()
def test_add_same_model_twice(db):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = mock_data.create_new_meta_rule(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ value = {
+ "name": "model1",
+ "description": "test",
+ "meta_rules": [meta_rule_id]
+ }
# prepare
- add_model(model_id="model_1") # add model twice
+ model_helper.add_model(model_id="model_1", value=value) # add model twice
# act
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = mock_data.create_new_meta_rule(
+ subject_category_name="subject_category2",
+ object_category_name="object_category2",
+ action_category_name="action_category2",
+ meta_rule_name="meta_rule_2")
+ value = {
+ "name": "model2",
+ "description": "test",
+ "meta_rules": [meta_rule_id]
+ }
with pytest.raises(ModelExisting) as exception_info:
- add_model(model_id="model_1")
- delete_all_models()
+ model_helper.add_model(model_id="model_1", value=value)
+ model_helper.delete_all_models()
# assert str(exception_info.value) == '409: Model Error'
def test_add_model_generate_new_uuid(db):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id1 = mock_data.create_new_meta_rule(
+ subject_category_name="subject_category3",
+ object_category_name="object_category3",
+ action_category_name="action_category3",
+ meta_rule_name="meta_rule_3")
model_value1 = {
"name": "MLS",
"description": "test",
- "meta_rules": "meta_rule_mls_1"
+ "meta_rules": [meta_rule_id1]
}
- model1 = add_model(value=model_value1)
-
+ model1 = model_helper.add_model(value=model_value1)
+ subject_category_id, object_category_id, action_category_id, meta_rule_id2 = mock_data.create_new_meta_rule(
+ subject_category_name="subject_category4",
+ object_category_name="object_category4",
+ action_category_name="action_category4",
+ meta_rule_name="meta_rule_4")
model_value2 = {
"name": "rbac",
"description": "test",
- "meta_rules": "meta_rule_mls_2"
+ "meta_rules": [meta_rule_id2]
}
- model2 = add_model(value=model_value2)
+ model2 = model_helper.add_model(value=model_value2)
assert list(model1)[0] != list(model2)[0]
- delete_all_models()
+ model_helper.delete_all_models()
def test_add_models(db):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = mock_data.create_new_meta_rule(
+ subject_category_name="subject_category5",
+ object_category_name="object_category5",
+ action_category_name="action_category5")
model_value1 = {
"name": "MLS",
"description": "test",
- "meta_rules": "meta_rule_mls_1"
+ "meta_rules": [meta_rule_id]
}
- models = add_model(value=model_value1)
+ models = model_helper.add_model(value=model_value1)
assert isinstance(models, dict)
assert models
assert len(models.keys()) == 1
@@ -137,78 +132,101 @@ def test_add_models(db):
for key in ("name", "meta_rules", "description"):
assert key in models[model_id]
assert models[model_id][key] == model_value1[key]
- delete_all_models()
+ model_helper.delete_all_models()
def test_add_models_with_same_name_twice(db):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id = mock_data.create_new_meta_rule(
+ subject_category_name="subject_category5",
+ object_category_name="object_category5",
+ action_category_name="action_category5")
model_value1 = {
"name": "MLS",
"description": "test",
- "meta_rules": "meta_rule_mls_1"
+ "meta_rules": [meta_rule_id]
}
- models = add_model(value=model_value1)
+ models = model_helper.add_model(value=model_value1)
assert isinstance(models, dict)
assert models
with pytest.raises(Exception) as exc_info:
- add_model(value=model_value1)
- delete_all_models()
+ model_helper.add_model(value=model_value1)
+ model_helper.delete_all_models()
def test_delete_models(db):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id1 = mock_data.create_new_meta_rule(
+ subject_category_name="subject_category6",
+ object_category_name="object_category6",
+ action_category_name="action_category6",
+ meta_rule_name="meta_rule_6")
model_value1 = {
"name": "MLS",
"description": "test",
- "meta_rules": "meta_rule_mls_1"
+ "meta_rules": [meta_rule_id1]
}
- model1 = add_model(value=model_value1)
-
+ model1 = model_helper.add_model(value=model_value1)
+ subject_category_id, object_category_id, action_category_id, meta_rule_id2 = mock_data.create_new_meta_rule(
+ subject_category_name="subject_category7",
+ object_category_name="object_category7",
+ action_category_name="action_category7",
+ meta_rule_name="meta_rule_7")
model_value2 = {
"name": "rbac",
"description": "test",
- "meta_rules": "meta_rule_mls_2"
+ "meta_rules": [meta_rule_id2]
}
- model2 = add_model(value=model_value2)
+ model_helper.add_model(value=model_value2)
id = list(model1)[0]
- delete_models(id)
+ model_helper.delete_models(id)
# assert
- models = get_models()
+ models = model_helper.get_models()
assert id not in models
- delete_all_models()
+ model_helper.delete_all_models()
def test_update_model(db):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id1 = mock_data.create_new_meta_rule(
+ subject_category_name="subject_category8",
+ object_category_name="object_category8",
+ action_category_name="action_category8",
+ meta_rule_name="meta_rule_8")
# prepare
model_value = {
"name": "MLS",
"description": "test",
- "meta_rules": "meta_rule_mls_1"
+ "meta_rules": [meta_rule_id1]
}
- model = add_model(value=model_value)
+ model = model_helper.add_model(value=model_value)
model_id = list(model)[0]
+ subject_category_id, object_category_id, action_category_id, meta_rule_id2 = mock_data.create_new_meta_rule(
+ subject_category_name="subject_category9",
+ object_category_name="object_category9",
+ action_category_name="action_category9",
+ meta_rule_name="meta_rule_9")
new_model_value = {
"name": "MLS2",
"description": "test",
- "meta_rules": "meta_rule_mls_2"
+ "meta_rules": [meta_rule_id2]
}
# act
- update_model(model_id=model_id, value=new_model_value)
+ model_helper.update_model(model_id=model_id, value=new_model_value)
# assert
- model = get_models(model_id)
+ model = model_helper.get_models(model_id)
for key in ("name", "meta_rules", "description"):
assert key in model[model_id]
assert model[model_id][key] == new_model_value[key]
- delete_all_models()
+ model_helper.delete_all_models()
def test_delete_model_assigned_to_policy(db):
model_value1 = {
"name": "MLS",
"description": "test",
- "meta_rules": "meta_rule_mls_1"
+ "meta_rules": []
}
- models = add_model(value=model_value1)
+ models = model_helper.add_model(value=model_value1)
assert isinstance(models, dict)
assert models
assert len(models.keys()) == 1
@@ -219,6 +237,201 @@ def test_delete_model_assigned_to_policy(db):
"genre": "authz",
"description": "test",
}
- test_policies.add_policies(value=value)
+ policy_helper.add_policies(value=value)
with pytest.raises(DeleteModelWithPolicy) as exception_info:
- delete_models(uuid=model_id)
+ model_helper.delete_models(uuid=model_id)
+
+
+def test_add_subject_category(db):
+ category_id = "category_id1"
+ value = {
+ "name": "subject_category",
+ "description": "description subject_category"
+ }
+ subject_category = category_helper.add_subject_category(category_id, value)
+ assert subject_category
+ assert len(subject_category) == 1
+
+
+def test_add_subject_category_with_empty_name(db):
+ category_id = "category_id1"
+ value = {
+ "name": "",
+ "description": "description subject_category"
+ }
+ with pytest.raises(Exception) as exception_info:
+ category_helper.add_subject_category(category_id, value)
+ assert str(exception_info.value) == '400: Category Name Invalid'
+
+
+def test_add_subject_category_with_same_category_id(db):
+ category_id = "category_id1"
+ value = {
+ "name": "subject_category",
+ "description": "description subject_category"
+ }
+ category_helper.add_subject_category(category_id, value)
+ with pytest.raises(Exception) as exception_info:
+ category_helper.add_subject_category(category_id, value)
+ assert str(exception_info.value) == '409: Subject Category Existing'
+
+
+def test_get_subject_category(db):
+ category_id = "category_id1"
+ value = {
+ "name": "subject_category",
+ "description": "description subject_category"
+ }
+ category_helper.add_subject_category(category_id, value)
+ subject_category = category_helper.get_subject_category(category_id)
+ assert subject_category
+ assert len(subject_category) == 1
+
+
+def test_delete_subject_category(db):
+ category_id = "category_id1"
+ value = {
+ "name": "subject_category",
+ "description": "description subject_category"
+ }
+ category_helper.add_subject_category(category_id, value)
+ subject_category = category_helper.delete_subject_category(category_id)
+ assert not subject_category
+
+
+def test_delete_subject_category_with_unkown_category_id(db):
+ category_id = "invalid_category_id"
+
+ with pytest.raises(Exception) as exception_info:
+ category_helper.delete_subject_category(category_id)
+ assert str(exception_info.value) == '400: Subject Category Unknown'
+
+
+def test_add_object_category(db):
+ category_id = "category_id1"
+ value = {
+ "name": "object_category",
+ "description": "description object_category"
+ }
+ object_category = category_helper.add_object_category(category_id, value)
+ assert object_category
+ assert len(object_category) == 1
+
+
+def test_add_object_category_with_same_category_id(db):
+ category_id = "category_id1"
+ value = {
+ "name": "object_category",
+ "description": "description object_category"
+ }
+ category_helper.add_object_category(category_id, value)
+ with pytest.raises(Exception) as exception_info:
+ category_helper.add_object_category(category_id, value)
+ assert str(exception_info.value) == '409: Object Category Existing'
+
+
+def test_add_object_category_with_empty_name(db):
+ category_id = "category_id1"
+ value = {
+ "name": "",
+ "description": "description object_category"
+ }
+ with pytest.raises(Exception) as exception_info:
+ category_helper.add_object_category(category_id, value)
+ assert str(exception_info.value) == '400: Category Name Invalid'
+
+
+def test_get_object_category(db):
+ category_id = "category_id1"
+ value = {
+ "name": "object_category",
+ "description": "description object_category"
+ }
+ category_helper.add_object_category(category_id, value)
+ object_category = category_helper.get_object_category(category_id)
+ assert object_category
+ assert len(object_category) == 1
+
+
+def test_delete_object_category(db):
+ category_id = "category_id1"
+ value = {
+ "name": "object_category",
+ "description": "description object_category"
+ }
+ category_helper.add_object_category(category_id, value)
+ object_category = category_helper.delete_object_category(category_id)
+ assert not object_category
+
+
+def test_delete_object_category_with_unkown_category_id(db):
+ category_id = "invalid_category_id"
+
+ with pytest.raises(Exception) as exception_info:
+ category_helper.delete_object_category(category_id)
+ assert str(exception_info.value) == '400: Object Category Unknown'
+
+
+def test_add_action_category(db):
+ category_id = "category_id1"
+ value = {
+ "name": "action_category",
+ "description": "description action_category"
+ }
+ action_category = category_helper.add_action_category(category_id, value)
+ assert action_category
+ assert len(action_category) == 1
+
+
+def test_add_action_category_with_same_category_id(db):
+ category_id = "category_id1"
+ value = {
+ "name": "action_category",
+ "description": "description action_category"
+ }
+ category_helper.add_action_category(category_id, value)
+ with pytest.raises(Exception) as exception_info:
+ category_helper.add_action_category(category_id, value)
+ assert str(exception_info.value) == '409: Action Category Existing'
+
+
+def test_add_action_category_with_empty_name(db):
+ category_id = "category_id1"
+ value = {
+ "name": "",
+ "description": "description action_category"
+ }
+ with pytest.raises(Exception) as exception_info:
+ category_helper.add_action_category(category_id, value)
+ assert str(exception_info.value) == '400: Category Name Invalid'
+
+
+def test_get_action_category(db):
+ category_id = "category_id1"
+ value = {
+ "name": "action_category",
+ "description": "description action_category"
+ }
+ category_helper.add_action_category(category_id, value)
+ action_category = category_helper.get_action_category(category_id)
+ assert action_category
+ assert len(action_category) == 1
+
+
+def test_delete_action_category(db):
+ category_id = "category_id1"
+ value = {
+ "name": "action_category",
+ "description": "description action_category"
+ }
+ category_helper.add_action_category(category_id, value)
+ action_category = category_helper.delete_action_category(category_id)
+ assert not action_category
+
+
+def test_delete_action_category_with_unkown_category_id(db):
+ category_id = "invalid_category_id"
+
+ with pytest.raises(Exception) as exception_info:
+ category_helper.delete_action_category(category_id)
+ assert str(exception_info.value) == '400: Action Category Unknown'
diff --git a/python_moondb/tests/unit_python/policies/mock_data.py b/python_moondb/tests/unit_python/policies/mock_data.py
index 3e9bea93..47fc9f9e 100644
--- a/python_moondb/tests/unit_python/policies/mock_data.py
+++ b/python_moondb/tests/unit_python/policies/mock_data.py
@@ -1,11 +1,17 @@
+import helpers.model_helper as model_helper
+import helpers.meta_rule_helper as meta_rule_helper
+import helpers.policy_helper as policy_helper
+import helpers.category_helper as category_helper
+
+
def create_meta_rule(meta_rule_name="meta_rule1", category_prefix=""):
meta_rule_value = {
"name": meta_rule_name,
"algorithm": "name of the meta rule algorithm",
"subject_categories": [category_prefix + "subject_category_id1",
category_prefix + "subject_category_id2"],
- "object_categories": [category_prefix +"object_category_id1"],
- "action_categories": [category_prefix +"action_category_id1"]
+ "object_categories": [category_prefix + "object_category_id1"],
+ "action_categories": [category_prefix + "action_category_id1"]
}
return meta_rule_value
@@ -41,15 +47,28 @@ def create_pdp(pdp_ids):
def get_policy_id(model_name="test_model", policy_name="policy_1", meta_rule_name="meta_rule1", category_prefix=""):
- import policies.test_policies as test_policies
- import models.test_models as test_models
- import models.test_meta_rules as test_meta_rules
- meta_rule = test_meta_rules.add_meta_rule(value=create_meta_rule(meta_rule_name, category_prefix))
+ category_helper.add_subject_category(
+ category_prefix + "subject_category_id1",
+ value={"name": category_prefix + "subject_category_id1",
+ "description": "description 1"})
+ category_helper.add_subject_category(
+ category_prefix + "subject_category_id2",
+ value={"name": category_prefix + "subject_category_id2",
+ "description": "description 1"})
+ category_helper.add_object_category(
+ category_prefix + "object_category_id1",
+ value={"name": category_prefix + "object_category_id1",
+ "description": "description 1"})
+ category_helper.add_action_category(
+ category_prefix + "action_category_id1",
+ value={"name": category_prefix + "action_category_id1",
+ "description": "description 1"})
+ meta_rule = meta_rule_helper.add_meta_rule(value=create_meta_rule(meta_rule_name, category_prefix))
meta_rule_id = list(meta_rule.keys())[0]
- model = test_models.add_model(value=create_model(meta_rule_id, model_name))
+ model = model_helper.add_model(value=create_model(meta_rule_id, model_name))
model_id = list(model.keys())[0]
value = create_policy(model_id, policy_name)
- policy = test_policies.add_policies(value=value)
+ policy = policy_helper.add_policies(value=value)
assert policy
policy_id = list(policy.keys())[0]
return policy_id
diff --git a/python_moondb/tests/unit_python/policies/test_assignments.py b/python_moondb/tests/unit_python/policies/test_assignments.py
index 1ca140e6..675c2ff9 100755
--- a/python_moondb/tests/unit_python/policies/test_assignments.py
+++ b/python_moondb/tests/unit_python/policies/test_assignments.py
@@ -1,257 +1,220 @@
-import policies.mock_data as mock_data
+# 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'.
+
+import helpers.mock_data as mock_data
+import helpers.assignment_helper as assignment_helper
from python_moonutilities.exceptions import *
import pytest
-def get_action_assignments(policy_id, action_id=None, category_id=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.get_action_assignments("", policy_id, action_id, category_id)
-
-
-def add_action_assignment(policy_id, action_id, category_id, data_id):
- from python_moondb.core import PolicyManager
- return PolicyManager.add_action_assignment("", policy_id, action_id, category_id, data_id)
-
-
-def delete_action_assignment(policy_id, action_id, category_id, data_id):
- from python_moondb.core import PolicyManager
- PolicyManager.delete_action_assignment("", policy_id, action_id, category_id, data_id)
-
-
-def get_object_assignments(policy_id, object_id=None, category_id=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.get_object_assignments("", policy_id, object_id, category_id)
-
-
-def add_object_assignment(policy_id, object_id, category_id, data_id):
- from python_moondb.core import PolicyManager
- return PolicyManager.add_object_assignment("", policy_id, object_id, category_id, data_id)
-
-
-def delete_object_assignment(policy_id, object_id, category_id, data_id):
- from python_moondb.core import PolicyManager
- PolicyManager.delete_object_assignment("", policy_id, object_id, category_id, data_id)
-
-
-def get_subject_assignments(policy_id, subject_id=None, category_id=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.get_subject_assignments("", policy_id, subject_id, category_id)
-
-
-def add_subject_assignment(policy_id, subject_id, category_id, data_id):
- from python_moondb.core import PolicyManager
- return PolicyManager.add_subject_assignment("", policy_id, subject_id, category_id, data_id)
-
-
-def delete_subject_assignment(policy_id, subject_id, category_id, data_id):
- from python_moondb.core import PolicyManager
- PolicyManager.delete_subject_assignment("", policy_id, subject_id, category_id, data_id)
-
def test_get_action_assignments(db):
- policy_id = mock_data.get_policy_id()
- action_id = "action_id_1"
- category_id = "category_id_1"
- data_id = "data_id_1"
- add_action_assignment(policy_id, action_id, category_id, data_id)
- act_assignments = get_action_assignments(policy_id, action_id, category_id)
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ action_id = mock_data.create_action(policy_id)
+ data_id = mock_data.create_action_data(policy_id=policy_id, category_id=action_category_id)
+
+ assignment_helper.add_action_assignment(policy_id, action_id, action_category_id, data_id)
+ act_assignments = assignment_helper.get_action_assignments(policy_id, action_id, action_category_id)
action_id_1 = list(act_assignments.keys())[0]
assert act_assignments[action_id_1]["policy_id"] == policy_id
assert act_assignments[action_id_1]["action_id"] == action_id
- assert act_assignments[action_id_1]["category_id"] == category_id
+ assert act_assignments[action_id_1]["category_id"] == action_category_id
assert len(act_assignments[action_id_1].get("assignments")) == 1
assert data_id in act_assignments[action_id_1].get("assignments")
-def test_get_action_assignments_by_policy_id(db):
- policy_id = mock_data.get_policy_id()
- action_id = "action_id_1"
- category_id = "category_id_1"
- data_id = "data_id_1"
- add_action_assignment(policy_id, action_id, category_id, data_id)
- data_id = "data_id_2"
- add_action_assignment(policy_id, action_id, category_id, data_id)
- data_id = "data_id_3"
- add_action_assignment(policy_id, action_id, category_id, data_id)
- act_assignments = get_action_assignments(policy_id)
- action_id_1 = list(act_assignments.keys())[0]
- assert act_assignments[action_id_1]["policy_id"] == policy_id
- assert act_assignments[action_id_1]["action_id"] == action_id
- assert act_assignments[action_id_1]["category_id"] == category_id
- assert len(act_assignments[action_id_1].get("assignments")) == 3
-
-
def test_add_action_assignments(db):
- policy_id = mock_data.get_policy_id()
- action_id = "action_id_1"
- category_id = "category_id_1"
- data_id = "data_id_1"
- action_assignments = add_action_assignment(policy_id, action_id, category_id, data_id)
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ action_id = mock_data.create_action(policy_id)
+ data_id = mock_data.create_action_data(policy_id=policy_id, category_id=action_category_id)
+ action_assignments = assignment_helper.add_action_assignment(policy_id, action_id, action_category_id, data_id)
assert action_assignments
action_id_1 = list(action_assignments.keys())[0]
assert action_assignments[action_id_1]["policy_id"] == policy_id
assert action_assignments[action_id_1]["action_id"] == action_id
- assert action_assignments[action_id_1]["category_id"] == category_id
+ assert action_assignments[action_id_1]["category_id"] == action_category_id
assert len(action_assignments[action_id_1].get("assignments")) == 1
assert data_id in action_assignments[action_id_1].get("assignments")
with pytest.raises(ActionAssignmentExisting) as exception_info:
- add_action_assignment(policy_id, action_id, category_id, data_id)
+ assignment_helper.add_action_assignment(policy_id, action_id, action_category_id, data_id)
+
def test_delete_action_assignment(db):
- policy_id = mock_data.get_policy_id()
- add_action_assignment(policy_id, "", "", "")
- policy_id = mock_data.get_policy_id(model_name="test_model2", policy_name="policy_2", meta_rule_name="meta_rule2", category_prefix="_")
- action_id = "action_id_2"
- category_id = "category_id_2"
- data_id = "data_id_2"
- add_action_assignment(policy_id, action_id, category_id, data_id)
- delete_action_assignment(policy_id, "", "", "")
- assignments = get_action_assignments(policy_id, )
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ action_id = mock_data.create_action(policy_id)
+ data_id = mock_data.create_action_data(policy_id=policy_id, category_id=action_category_id)
+ assignment_helper.add_action_assignment(policy_id, action_id, action_category_id, data_id)
+ assignment_helper.delete_action_assignment(policy_id, "", "", "")
+ assignments = assignment_helper.get_action_assignments(policy_id, )
assert len(assignments) == 1
def test_delete_action_assignment_with_invalid_policy_id(db):
policy_id = "invalid_id"
- delete_action_assignment(policy_id, "", "", "")
- assignments = get_action_assignments(policy_id, )
+ assignment_helper.delete_action_assignment(policy_id, "", "", "")
+ assignments = assignment_helper.get_action_assignments(policy_id, )
assert len(assignments) == 0
def test_get_object_assignments(db):
- policy_id = mock_data.get_policy_id()
- object_id = "object_id_1"
- category_id = "category_id_1"
- data_id = "data_id_1"
- add_object_assignment(policy_id, object_id, category_id, data_id)
- obj_assignments = get_object_assignments(policy_id, object_id, category_id)
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ object_id = mock_data.create_object(policy_id)
+ data_id = mock_data.create_object_data(policy_id=policy_id, category_id=object_category_id)
+ assignment_helper.add_object_assignment(policy_id, object_id, object_category_id, data_id)
+ obj_assignments = assignment_helper.get_object_assignments(policy_id, object_id, object_category_id)
object_id_1 = list(obj_assignments.keys())[0]
assert obj_assignments[object_id_1]["policy_id"] == policy_id
assert obj_assignments[object_id_1]["object_id"] == object_id
- assert obj_assignments[object_id_1]["category_id"] == category_id
+ assert obj_assignments[object_id_1]["category_id"] == object_category_id
assert len(obj_assignments[object_id_1].get("assignments")) == 1
assert data_id in obj_assignments[object_id_1].get("assignments")
def test_get_object_assignments_by_policy_id(db):
- policy_id = mock_data.get_policy_id()
- object_id_1 = "object_id_1"
- category_id_1 = "category_id_1"
- data_id = "data_id_1"
- add_action_assignment(policy_id, object_id_1, category_id_1, data_id)
- object_id_2 = "object_id_2"
- category_id_2 = "category_id_2"
- data_id = "data_id_2"
- add_action_assignment(policy_id, object_id_2, category_id_2, data_id)
- object_id_3 = "object_id_3"
- category_id_3 = "category_id_3"
- data_id = "data_id_3"
- add_action_assignment(policy_id, object_id_3, category_id_3, data_id)
- act_assignments = get_action_assignments(policy_id)
- assert len(act_assignments) == 3
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ object_id = mock_data.create_object(policy_id)
+ data_id = mock_data.create_object_data(policy_id=policy_id, category_id=object_category_id)
+ assignment_helper.add_object_assignment(policy_id, object_id, object_category_id, data_id)
+ obj_assignments = assignment_helper.get_object_assignments(policy_id)
+ assert len(obj_assignments) == 1
def test_add_object_assignments(db):
- policy_id = mock_data.get_policy_id()
- object_id = "object_id_1"
- category_id = "category_id_1"
- data_id = "data_id_1"
- object_assignments = add_object_assignment(policy_id, object_id, category_id, data_id)
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ object_id = mock_data.create_object(policy_id)
+ data_id = mock_data.create_object_data(policy_id=policy_id, category_id=object_category_id)
+ object_assignments = assignment_helper.add_object_assignment(policy_id, object_id, object_category_id, data_id)
assert object_assignments
object_id_1 = list(object_assignments.keys())[0]
assert object_assignments[object_id_1]["policy_id"] == policy_id
assert object_assignments[object_id_1]["object_id"] == object_id
- assert object_assignments[object_id_1]["category_id"] == category_id
+ assert object_assignments[object_id_1]["category_id"] == object_category_id
assert len(object_assignments[object_id_1].get("assignments")) == 1
assert data_id in object_assignments[object_id_1].get("assignments")
with pytest.raises(ObjectAssignmentExisting):
- add_object_assignment(policy_id, object_id, category_id, data_id)
+ assignment_helper.add_object_assignment(policy_id, object_id, object_category_id, data_id)
def test_delete_object_assignment(db):
- policy_id = mock_data.get_policy_id()
- add_object_assignment(policy_id, "", "", "")
- object_id = "action_id_2"
- category_id = "category_id_2"
- data_id = "data_id_2"
- add_object_assignment(policy_id, object_id, category_id, data_id)
- delete_object_assignment(policy_id, "", "", "")
- assignments = get_object_assignments(policy_id, )
- assert len(assignments) == 1
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ object_id = mock_data.create_object(policy_id)
+ data_id = mock_data.create_object_data(policy_id=policy_id, category_id=object_category_id)
+ assignment_helper.add_object_assignment(policy_id, object_id, object_category_id, data_id)
+
+ assignment_helper.delete_object_assignment(policy_id, object_id, object_category_id, data_id=data_id)
+ assignments = assignment_helper.get_object_assignments(policy_id)
+ assert len(assignments) == 0
def test_delete_object_assignment_with_invalid_policy_id(db):
policy_id = "invalid_id"
- delete_object_assignment(policy_id, "", "", "")
- assignments = get_object_assignments(policy_id, )
+ assignment_helper.delete_object_assignment(policy_id, "", "", "")
+ assignments = assignment_helper.get_object_assignments(policy_id, )
assert len(assignments) == 0
def test_get_subject_assignments(db):
- policy_id = mock_data.get_policy_id()
- subject_id = "object_id_1"
- category_id = "category_id_1"
- data_id = "data_id_1"
- add_subject_assignment(policy_id, subject_id, category_id, data_id)
- subj_assignments = get_subject_assignments(policy_id, subject_id, category_id)
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ subject_id = mock_data.create_subject(policy_id)
+ data_id = mock_data.create_subject_data(policy_id=policy_id, category_id=subject_category_id)
+
+ assignment_helper.add_subject_assignment(policy_id, subject_id, subject_category_id, data_id)
+ subj_assignments = assignment_helper.get_subject_assignments(policy_id, subject_id, subject_category_id)
subject_id_1 = list(subj_assignments.keys())[0]
assert subj_assignments[subject_id_1]["policy_id"] == policy_id
assert subj_assignments[subject_id_1]["subject_id"] == subject_id
- assert subj_assignments[subject_id_1]["category_id"] == category_id
+ assert subj_assignments[subject_id_1]["category_id"] == subject_category_id
assert len(subj_assignments[subject_id_1].get("assignments")) == 1
assert data_id in subj_assignments[subject_id_1].get("assignments")
def test_get_subject_assignments_by_policy_id(db):
- policy_id = mock_data.get_policy_id()
- subject_id_1 = "subject_id_1"
- category_id_1 = "category_id_1"
- data_id = "data_id_1"
- add_subject_assignment(policy_id, subject_id_1, category_id_1, data_id)
- subject_id_2 = "subject_id_2"
- category_id_2 = "category_id_2"
- data_id = "data_id_2"
- add_subject_assignment(policy_id, subject_id_2, category_id_2, data_id)
- subject_id_3 = "subject_id_3"
- category_id_3 = "category_id_3"
- data_id = "data_id_3"
- add_subject_assignment(policy_id, subject_id_3, category_id_3, data_id)
- subj_assignments = get_subject_assignments(policy_id)
- assert len(subj_assignments) == 3
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ subject_id = mock_data.create_subject(policy_id)
+ data_id = mock_data.create_subject_data(policy_id=policy_id, category_id=subject_category_id)
+
+ assignment_helper.add_subject_assignment(policy_id, subject_id, subject_category_id, data_id)
+ subj_assignments = assignment_helper.get_subject_assignments(policy_id)
+ assert len(subj_assignments) == 1
def test_add_subject_assignments(db):
- policy_id = mock_data.get_policy_id()
- subject_id = "subject_id_1"
- category_id = "category_id_1"
- data_id = "data_id_1"
- subject_assignments = add_subject_assignment(policy_id, subject_id, category_id, data_id)
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ subject_id = mock_data.create_subject(policy_id)
+ data_id = mock_data.create_subject_data(policy_id=policy_id, category_id=subject_category_id)
+
+ subject_assignments = assignment_helper.add_subject_assignment(policy_id, subject_id, subject_category_id, data_id)
assert subject_assignments
subject_id_1 = list(subject_assignments.keys())[0]
assert subject_assignments[subject_id_1]["policy_id"] == policy_id
assert subject_assignments[subject_id_1]["subject_id"] == subject_id
- assert subject_assignments[subject_id_1]["category_id"] == category_id
+ assert subject_assignments[subject_id_1]["category_id"] == subject_category_id
assert len(subject_assignments[subject_id_1].get("assignments")) == 1
assert data_id in subject_assignments[subject_id_1].get("assignments")
with pytest.raises(SubjectAssignmentExisting):
- add_subject_assignment(policy_id, subject_id, category_id, data_id)
+ assignment_helper.add_subject_assignment(policy_id, subject_id, subject_category_id, data_id)
def test_delete_subject_assignment(db):
- policy_id = mock_data.get_policy_id()
- add_subject_assignment(policy_id, "", "", "")
- subject_id = "subject_id_2"
- category_id = "category_id_2"
- data_id = "data_id_2"
- add_subject_assignment(policy_id, subject_id, category_id, data_id)
- delete_subject_assignment(policy_id, "", "", "")
- assignments = get_subject_assignments(policy_id, )
- assert len(assignments) == 1
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ subject_id = mock_data.create_subject(policy_id)
+ data_id = mock_data.create_subject_data(policy_id=policy_id, category_id=subject_category_id)
+ assignment_helper.add_subject_assignment(policy_id, subject_id, subject_category_id, data_id)
+ assignment_helper.delete_subject_assignment(policy_id, subject_id, subject_category_id, data_id)
+ assignments = assignment_helper.get_subject_assignments(policy_id)
+ assert len(assignments) == 0
def test_delete_subject_assignment_with_invalid_policy_id(db):
policy_id = "invalid_id"
- delete_subject_assignment(policy_id, "", "", "")
- assignments = get_subject_assignments(policy_id, )
+ assignment_helper.delete_subject_assignment(policy_id, "", "", "")
+ assignments = assignment_helper.get_subject_assignments(policy_id, )
assert len(assignments) == 0
diff --git a/python_moondb/tests/unit_python/policies/test_data.py b/python_moondb/tests/unit_python/policies/test_data.py
index 5e00fe65..fa3f8c06 100755
--- a/python_moondb/tests/unit_python/policies/test_data.py
+++ b/python_moondb/tests/unit_python/policies/test_data.py
@@ -1,391 +1,269 @@
-# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors
+# 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'.
-import policies.mock_data as mock_data
-from .test_assignments import *
+import helpers.mock_data as mock_data
+import policies.mock_data
+import helpers.data_helper as data_helper
+import pytest
+import logging
+from python_moonutilities.exceptions import *
logger = logging.getLogger("python_moondb.tests.api.test_data")
-def get_action_data(policy_id, data_id=None, category_id=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.get_action_data("", policy_id, data_id, category_id)
-
-
-def add_action_data(policy_id, data_id=None, category_id=None, value=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.add_action_data("", policy_id, data_id, category_id, value)
-
-
-def delete_action_data(policy_id, data_id):
- from python_moondb.core import PolicyManager
- PolicyManager.delete_action_data("", policy_id, data_id)
-
-
-def get_object_data(policy_id, data_id=None, category_id=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.get_object_data("", policy_id, data_id, category_id)
-
-
-def add_object_data(policy_id, data_id=None, category_id=None, value=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.add_object_data("", policy_id, data_id, category_id, value)
-
-
-def delete_object_data(policy_id, data_id):
- from python_moondb.core import PolicyManager
- PolicyManager.delete_object_data("", policy_id, data_id)
-
-
-def get_subject_data(policy_id, data_id=None, category_id=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.get_subject_data("", policy_id, data_id, category_id)
-
-
-def add_subject_data(policy_id, data_id=None, category_id=None, value=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.set_subject_data("", policy_id, data_id, category_id, value)
-
-
-def delete_subject_data(policy_id, data_id):
- from python_moondb.core import PolicyManager
- PolicyManager.delete_subject_data("", policy_id, data_id)
-
-
-def get_actions(policy_id, perimeter_id=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.get_actions("", policy_id, perimeter_id)
-
-
-def add_action(policy_id, perimeter_id=None, value=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.add_action("", policy_id, perimeter_id, value)
-
-
-def delete_action(policy_id, perimeter_id):
- from python_moondb.core import PolicyManager
- PolicyManager.delete_action("", policy_id, perimeter_id)
-
-
-def get_objects(policy_id, perimeter_id=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.get_objects("", policy_id, perimeter_id)
-
-
-def add_object(policy_id, perimeter_id=None, value=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.add_object("", policy_id, perimeter_id, value)
-
-
-def delete_object(policy_id, perimeter_id):
- from python_moondb.core import PolicyManager
- PolicyManager.delete_object("", policy_id, perimeter_id)
-
-
-def get_subjects(policy_id, perimeter_id=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.get_subjects("", policy_id, perimeter_id)
-
-
-def add_subject(policy_id, perimeter_id=None, value=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.add_subject("", policy_id, perimeter_id, value)
-
-
-def delete_subject(policy_id, perimeter_id):
- from python_moondb.core import PolicyManager
- PolicyManager.delete_subject("", policy_id, perimeter_id)
-
-
-def get_available_metadata(policy_id):
- from python_moondb.core import PolicyManager
- return PolicyManager.get_available_metadata("", policy_id)
-
-
def test_get_action_data(db):
- policy_id = mock_data.get_policy_id()
- get_available_metadata(policy_id)
-
- policy_id = policy_id
- data_id = "data_id_1"
- category_id = "action_category_id1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "action-type",
"description": {"vm-action": "", "storage-action": "", },
}
- add_action_data(policy_id, data_id, category_id, value)
- action_data = get_action_data(policy_id, data_id, category_id)
- assert action_data
- assert len(action_data[0]['data']) == 1
+ action_data = data_helper.add_action_data(policy_id=policy_id, category_id=action_category_id, value=value)
+ data_id = list(action_data["data"])[0]
+ found_action_data = data_helper.get_action_data(policy_id=policy_id, data_id=data_id,
+ category_id=action_category_id)
+ assert found_action_data
+ assert len(found_action_data[0]["data"]) == 1
def test_get_action_data_with_invalid_category_id(db):
- policy_id = mock_data.get_policy_id()
- get_available_metadata(policy_id)
- data_id = "data_id_1"
- category_id = "action_category_id1"
- value = {
- "name": "action-type",
- "description": {"vm-action": "", "storage-action": "", },
- }
- add_action_data(policy_id, data_id, category_id, value)
- action_data = get_action_data(policy_id)
- assert action_data
- assert len(action_data[0]['data']) == 1
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ action_data = data_helper.get_action_data(policy_id=policy_id, category_id="invalid")
+ assert len(action_data) == 0
def test_add_action_data(db):
- policy_id = mock_data.get_policy_id()
- data_id = "data_id_1"
- category_id = "category_id_1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "action-type",
"description": {"vm-action": "", "storage-action": "", },
}
- action_data = add_action_data(policy_id, data_id, category_id, value).get('data')
+ action_data = data_helper.add_action_data(policy_id=policy_id, category_id=action_category_id, value=value)
assert action_data
- action_data_id = list(action_data.keys())[0]
- assert action_data[action_data_id].get('policy_id') == policy_id
-
- with pytest.raises(ActionScopeExisting) as exception_info:
- add_action_data(policy_id, category_id=category_id, value=value).get('data')
+ assert len(action_data['data']) == 1
def test_add_action_data_with_invalid_category_id(db):
- policy_id = mock_data.get_policy_id()
- data_id = "data_id_1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "action-type",
"description": {"vm-action": "", "storage-action": "", },
}
with pytest.raises(Exception) as exception_info:
- add_action_data(policy_id=policy_id, data_id=data_id, value=value).get('data')
+ data_helper.add_action_data(policy_id=policy_id, value=value).get('data')
assert str(exception_info.value) == 'Invalid category id'
def test_delete_action_data(db):
- policy_id = mock_data.get_policy_id()
- get_available_metadata(policy_id)
- data_id = "data_id_1"
- category_id = "category_id_1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ data_helper.get_available_metadata(policy_id)
value = {
"name": "action-type",
"description": {"vm-action": "", "storage-action": "", },
}
- action_data = add_action_data(policy_id, data_id, category_id, value).get('data')
- action_data_id = list(action_data.keys())[0]
- delete_action_data(action_data[action_data_id].get('policy_id'), None)
- new_action_data = get_action_data(policy_id)
+ action_data = data_helper.add_action_data(policy_id=policy_id, category_id=action_category_id, value=value)
+ data_id = list(action_data["data"])[0]
+ data_helper.delete_action_data(policy_id, data_id)
+ new_action_data = data_helper.get_action_data(policy_id)
assert len(new_action_data[0]['data']) == 0
-def test_delete_action_data_assigned_to_action_assignment(db):
- policy_id = mock_data.get_policy_id()
- get_available_metadata(policy_id)
- data_id = "data_id_1"
- category_id = "category_id_1"
- value = {
- "name": "action-type",
- "description": {"vm-action": "", "storage-action": "", },
- }
- action_data = add_action_data(policy_id, data_id, category_id, value).get('data')
- action_data_id = list(action_data.keys())[0]
- add_action_assignment(policy_id, "action_id_1", category_id, action_data_id)
- with pytest.raises(DeleteData) as exception_info:
- delete_action_data(action_data[action_data_id].get('policy_id'), None)
-
-
def test_get_object_data(db):
- policy_id = mock_data.get_policy_id()
- get_available_metadata(policy_id)
- data_id = "data_id_1"
- category_id = "object_category_id1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "object-security-level",
"description": {"low": "", "medium": "", "high": ""},
}
- add_object_data(policy_id, data_id, category_id, value)
- object_data = get_object_data(policy_id, data_id, category_id)
- assert object_data
- assert len(object_data[0]['data']) == 1
+ object_data = data_helper.add_object_data(policy_id=policy_id, category_id=object_category_id, value=value)
+ data_id = list(object_data["data"])[0]
+ found_object_data = data_helper.get_object_data(policy_id=policy_id, data_id=data_id,
+ category_id=object_category_id)
+ assert found_object_data
+ assert len(found_object_data[0]['data']) == 1
def test_get_object_data_with_invalid_category_id(db):
- policy_id = mock_data.get_policy_id()
- get_available_metadata(policy_id)
- data_id = "data_id_1"
- category_id = "object_category_id1"
- value = {
- "name": "object-security-level",
- "description": {"low": "", "medium": "", "high": ""},
- }
- add_object_data(policy_id, data_id, category_id, value)
- object_data = get_object_data(policy_id)
- assert object_data
- assert len(object_data[0]['data']) == 1
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ object_data = data_helper.get_object_data(policy_id=policy_id, category_id="invalid")
+ assert len(object_data) == 0
def test_add_object_data(db):
- policy_id = mock_data.get_policy_id()
- data_id = "data_id_1"
- category_id = "object_category_id1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "object-security-level",
"description": {"low": "", "medium": "", "high": ""},
}
- object_data = add_object_data(policy_id, data_id, category_id, value).get('data')
+ object_data = data_helper.add_object_data(policy_id=policy_id, category_id=object_category_id, value=value).get(
+ 'data')
assert object_data
object_data_id = list(object_data.keys())[0]
assert object_data[object_data_id].get('policy_id') == policy_id
- with pytest.raises(ObjectScopeExisting) as exception_info:
- add_object_data(policy_id, category_id=category_id, value=value).get('data')
-
def test_add_object_data_with_invalid_category_id(db):
- policy_id = mock_data.get_policy_id()
- data_id = "data_id_1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "object-security-level",
"description": {"low": "", "medium": "", "high": ""},
}
- with pytest.raises(Exception) as exception_info:
- add_object_data(policy_id=policy_id, data_id=data_id, value=value).get('data')
- assert str(exception_info.value) == 'Invalid category id'
+ with pytest.raises(MetaDataUnknown) as exception_info:
+ data_helper.add_object_data(policy_id=policy_id, category_id="invalid", value=value).get('data')
+ assert str(exception_info.value) == '400: Meta data Unknown'
def test_delete_object_data(db):
- policy_id = mock_data.get_policy_id()
- get_available_metadata(policy_id)
- data_id = "data_id_1"
- category_id = "object_category_id1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "object-security-level",
"description": {"low": "", "medium": "", "high": ""},
}
- object_data = add_object_data(policy_id, data_id, category_id, value).get('data')
+ object_data = data_helper.add_object_data(policy_id=policy_id, category_id=object_category_id, value=value).get(
+ 'data')
object_data_id = list(object_data.keys())[0]
- delete_object_data(object_data[object_data_id].get('policy_id'), data_id)
- new_object_data = get_object_data(policy_id)
+ data_helper.delete_object_data(policy_id=object_data[object_data_id].get('policy_id'), data_id=object_data_id)
+ new_object_data = data_helper.get_object_data(policy_id)
assert len(new_object_data[0]['data']) == 0
-def test_delete_object_data_assigned_to_object_assignment(db):
- policy_id = mock_data.get_policy_id()
- get_available_metadata(policy_id)
- data_id = "data_id_1"
- category_id = "category_id_1"
- value = {
- "name": "object-type",
- "description": {"vm-action": "", "storage-action": "", },
- }
- object_data = add_object_data(policy_id, data_id, category_id, value).get('data')
- object_data_id = list(object_data.keys())[0]
- add_object_assignment(policy_id, "object_id_1", category_id, object_data_id)
- with pytest.raises(DeleteData) as exception_info:
- delete_object_data(object_data[object_data_id].get('policy_id'), None)
-
-
def test_get_subject_data(db):
- policy_id = mock_data.get_policy_id()
- get_available_metadata(policy_id)
- data_id = "data_id_1"
- category_id = "subject_category_id1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "subject-security-level",
"description": {"low": "", "medium": "", "high": ""},
}
- add_subject_data(policy_id, data_id, category_id, value)
- subject_data = get_subject_data(policy_id, data_id, category_id)
+ subject_data = data_helper.add_subject_data(policy_id=policy_id, category_id=subject_category_id, value=value).get(
+ 'data')
+ subject_data_id = list(subject_data.keys())[0]
+ subject_data = data_helper.get_subject_data(policy_id, subject_data_id, subject_category_id)
assert subject_data
assert len(subject_data[0]['data']) == 1
def test_get_subject_data_with_invalid_category_id(db):
- policy_id = mock_data.get_policy_id()
- get_available_metadata(policy_id)
- data_id = "data_id_1"
- category_id = "subject_category_id1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "subject-security-level",
"description": {"low": "", "medium": "", "high": ""},
}
- add_subject_data(policy_id, data_id, category_id, value)
- subject_data = get_subject_data(policy_id)
- assert subject_data
- assert len(subject_data[0]['data']) == 1
+ subject_data = data_helper.add_subject_data(policy_id=policy_id, category_id=subject_category_id, value=value).get(
+ 'data')
+ subject_data_id = list(subject_data.keys())[0]
+ found_subject_data = data_helper.get_subject_data(policy_id, subject_data_id, "invalid")
+ assert len(found_subject_data) == 0
def test_add_subject_data(db):
- policy_id = mock_data.get_policy_id()
- data_id = "data_id_1"
- category_id = "subject_category_id1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "subject-security-level",
"description": {"low": "", "medium": "", "high": ""},
}
- subject_data = add_subject_data(policy_id, data_id, category_id, value).get('data')
+ subject_data = data_helper.add_subject_data(policy_id=policy_id, category_id=subject_category_id, value=value).get(
+ 'data')
assert subject_data
subject_data_id = list(subject_data.keys())[0]
assert subject_data[subject_data_id].get('policy_id') == policy_id
- with pytest.raises(SubjectScopeExisting):
- add_subject_data(policy_id, category_id=category_id, value=value).get('data')
def test_add_subject_data_with_no_category_id(db):
- policy_id = mock_data.get_policy_id()
- data_id = "data_id_1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "subject-security-level",
"description": {"low": "", "medium": "", "high": ""},
}
with pytest.raises(Exception) as exception_info:
- add_subject_data(policy_id=policy_id, data_id=data_id, value=value).get('data')
+ data_helper.add_subject_data(policy_id=policy_id, data_id=subject_category_id, value=value).get('data')
assert str(exception_info.value) == 'Invalid category id'
def test_delete_subject_data(db):
- policy_id = mock_data.get_policy_id()
- get_available_metadata(policy_id)
- data_id = "data_id_1"
- category_id = "subject_category_id1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "subject-security-level",
"description": {"low": "", "medium": "", "high": ""},
}
- subject_data = add_subject_data(policy_id, data_id, category_id, value).get('data')
+ subject_data = data_helper.add_subject_data(policy_id=policy_id, category_id=subject_category_id, value=value).get(
+ 'data')
subject_data_id = list(subject_data.keys())[0]
- delete_subject_data(subject_data[subject_data_id].get('policy_id'), data_id)
- new_subject_data = get_subject_data(policy_id)
+ data_helper.delete_subject_data(subject_data[subject_data_id].get('policy_id'), subject_data_id)
+ new_subject_data = data_helper.get_subject_data(policy_id)
assert len(new_subject_data[0]['data']) == 0
-def test_delete_subject_data_assigned_to_subject_assignment(db):
- policy_id = mock_data.get_policy_id()
- get_available_metadata(policy_id)
- data_id = "data_id_1"
- category_id = "category_id_1"
- value = {
- "name": "subject-type",
- "description": {"vm-action": "", "storage-action": "", },
- }
- subject_data = add_subject_data(policy_id, data_id, category_id, value).get('data')
- subject_data_id = list(subject_data.keys())[0]
- add_subject_assignment(policy_id, "object_id_1", category_id, subject_data_id)
- with pytest.raises(DeleteData) as exception_info:
- delete_subject_data(subject_data[subject_data_id].get('policy_id'), None)
-
-
def test_get_actions(db):
- policy_id = mock_data.get_policy_id()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "test_action",
"description": "test",
}
- add_action(policy_id=policy_id, value=value)
- actions = get_actions(policy_id, )
+ data_helper.add_action(policy_id=policy_id, value=value)
+ actions = data_helper.get_actions(policy_id, )
assert actions
assert len(actions) == 1
action_id = list(actions.keys())[0]
@@ -393,27 +271,70 @@ def test_get_actions(db):
def test_add_action(db):
- policy_id = mock_data.get_policy_id()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "test_action",
"description": "test",
}
- action = add_action(policy_id=policy_id, value=value)
+ action = data_helper.add_action(policy_id=policy_id, value=value)
assert action
action_id = list(action.keys())[0]
assert len(action[action_id].get('policy_list')) == 1
+
+def test_add_action_twice(db):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ value = {
+ "name": "test_action",
+ "description": "test",
+ }
+ data_helper.add_action(policy_id=policy_id, value=value)
with pytest.raises(ActionExisting):
- add_action(policy_id=policy_id, value=value)
+ data_helper.add_action(policy_id=policy_id, value=value)
+
+
+def test_add_action_blank_name(db):
+ policy_id = policies.mock_data.get_policy_id()
+ value = {
+ "name": "",
+ "description": "test",
+ }
+ with pytest.raises(Exception) as exception_info:
+ data_helper.add_action(policy_id=policy_id, value=value)
+ assert str(exception_info.value) == '400: Perimeter Name is Invalid'
+
+
+def test_add_action_with_name_space(db):
+ policy_id = policies.mock_data.get_policy_id()
+ value = {
+ "name": " ",
+ "description": "test",
+ }
+ with pytest.raises(Exception) as exception_info:
+ data_helper.add_action(policy_id=policy_id, value=value)
+ assert str(exception_info.value) == '400: Perimeter Name is Invalid'
def test_add_action_multiple_times(db):
- policy_id = mock_data.get_policy_id()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id1 = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1",
+ model_name="model1")
value = {
"name": "test_action",
"description": "test",
}
- action = add_action(policy_id=policy_id, value=value)
+ action = data_helper.add_action(policy_id=policy_id1, value=value)
logger.info("action : {}".format(action))
action_id = list(action.keys())[0]
perimeter_id = action[action_id].get('id')
@@ -423,9 +344,13 @@ def test_add_action_multiple_times(db):
"description": "test",
"policy_list": ['policy_id_3', 'policy_id_4']
}
- action = add_action(
- mock_data.get_policy_id(model_name="test_model2", policy_name="policy_2", meta_rule_name="meta_rule2",
- category_prefix="_"), perimeter_id, value)
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id2 = mock_data.create_new_policy(
+ subject_category_name="subject_category2",
+ object_category_name="object_category2",
+ action_category_name="action_category2",
+ meta_rule_name="meta_rule_2",
+ model_name="model2")
+ action = data_helper.add_action(policy_id=policy_id2, perimeter_id=perimeter_id, value=value)
logger.info("action : {}".format(action))
assert action
action_id = list(action.keys())[0]
@@ -433,15 +358,19 @@ def test_add_action_multiple_times(db):
def test_delete_action(db):
- policy_id = mock_data.get_policy_id()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "test_action",
"description": "test",
}
- action = add_action(policy_id=policy_id, value=value)
+ action = data_helper.add_action(policy_id=policy_id, value=value)
action_id = list(action.keys())[0]
- delete_action(policy_id, action_id)
- actions = get_actions(policy_id, )
+ data_helper.delete_action(policy_id, action_id)
+ actions = data_helper.get_actions(policy_id, )
assert not actions
@@ -449,18 +378,22 @@ def test_delete_action_with_invalid_perimeter_id(db):
policy_id = "invalid"
perimeter_id = "invalid"
with pytest.raises(Exception) as exception_info:
- delete_action(policy_id, perimeter_id)
- assert str(exception_info.value) == '400: Action Unknown'
+ data_helper.delete_action(policy_id, perimeter_id)
+ assert str(exception_info.value) == '400: Policy Unknown'
def test_get_objects(db):
- policy_id = mock_data.get_policy_id()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "test_object",
"description": "test",
}
- add_object(policy_id=policy_id, value=value)
- objects = get_objects(policy_id, )
+ data_helper.add_object(policy_id=policy_id, value=value)
+ objects = data_helper.get_objects(policy_id, )
assert objects
assert len(objects) == 1
object_id = list(objects.keys())[0]
@@ -468,53 +401,69 @@ def test_get_objects(db):
def test_add_object(db):
- policy_id = mock_data.get_policy_id()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "test_object",
"description": "test",
}
- added_object = add_object(policy_id=policy_id, value=value)
+ added_object = data_helper.add_object(policy_id=policy_id, value=value)
assert added_object
object_id = list(added_object.keys())[0]
assert len(added_object[object_id].get('policy_list')) == 1
with pytest.raises(ObjectExisting):
- add_object(policy_id=policy_id, value=value)
+ data_helper.add_object(policy_id=policy_id, value=value)
def test_add_objects_multiple_times(db):
- policy_id = mock_data.get_policy_id()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1",
+ model_name="model1")
value = {
"name": "test_object",
"description": "test",
}
- added_object = add_object(policy_id=policy_id, value=value)
+ added_object = data_helper.add_object(policy_id=policy_id, value=value)
object_id = list(added_object.keys())[0]
perimeter_id = added_object[object_id].get('id')
assert added_object
value = {
"name": "test_object",
"description": "test",
- "policy_list": ['policy_id_3', 'policy_id_4']
}
- added_object = add_object(
- mock_data.get_policy_id(model_name="test_model2", policy_name="policy_2", meta_rule_name="meta_rule2",
- category_prefix="_"), perimeter_id, value)
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category2",
+ object_category_name="object_category2",
+ action_category_name="action_category2",
+ meta_rule_name="meta_rule_2",
+ model_name="model2")
+ added_object = data_helper.add_object(policy_id=policy_id, perimeter_id=perimeter_id, value=value)
assert added_object
object_id = list(added_object.keys())[0]
assert len(added_object[object_id].get('policy_list')) == 2
def test_delete_object(db):
- policy_id = mock_data.get_policy_id()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "test_object",
"description": "test",
}
- added_object = add_object(policy_id=policy_id, value=value)
+ added_object = data_helper.add_object(policy_id=policy_id, value=value)
object_id = list(added_object.keys())[0]
- delete_object(policy_id, object_id)
- objects = get_objects(policy_id, )
+ data_helper.delete_object(policy_id, object_id)
+ objects = data_helper.get_objects(policy_id, )
assert not objects
@@ -522,72 +471,107 @@ def test_delete_object_with_invalid_perimeter_id(db):
policy_id = "invalid"
perimeter_id = "invalid"
with pytest.raises(Exception) as exception_info:
- delete_object(policy_id, perimeter_id)
- assert str(exception_info.value) == '400: Object Unknown'
+ data_helper.delete_object(policy_id, perimeter_id)
+ assert str(exception_info.value) == '400: Policy Unknown'
def test_get_subjects(db):
- policy_id = mock_data.get_policy_id()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "testuser",
"description": "test",
}
- add_subject(policy_id=policy_id, value=value)
- subjects = get_subjects(policy_id, )
+ data_helper.add_subject(policy_id=policy_id, value=value)
+ subjects = data_helper.get_subjects(policy_id=policy_id)
assert subjects
assert len(subjects) == 1
subject_id = list(subjects.keys())[0]
assert subjects[subject_id].get('policy_list')[0] == policy_id
+def test_get_subjects_with_invalid_policy_id(db):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ value = {
+ "name": "testuser",
+ "description": "test",
+ }
+ data_helper.add_subject(policy_id=policy_id, value=value)
+ with pytest.raises(PolicyUnknown):
+ data_helper.get_subjects(policy_id="invalid")
+
+
def test_add_subject(db):
- policy_id = mock_data.get_policy_id()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "testuser",
"description": "test",
}
- subject = add_subject(policy_id=policy_id, value=value)
+ subject = data_helper.add_subject(policy_id=policy_id, value=value)
assert subject
subject_id = list(subject.keys())[0]
assert len(subject[subject_id].get('policy_list')) == 1
-
- with pytest.raises(SubjectExisting):
- add_subject(policy_id=policy_id, value=value)
+ with pytest.raises(SubjectExisting) as exception_info:
+ data_helper.add_subject(policy_id=policy_id, value=value)
+ assert str(exception_info.value) == '409: Subject Existing'
def test_add_subjects_multiple_times(db):
- policy_id = mock_data.get_policy_id()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1",
+ model_name="model1")
value = {
"name": "testuser",
"description": "test",
}
- subject = add_subject(policy_id=policy_id, value=value)
+ subject = data_helper.add_subject(policy_id=policy_id, value=value)
subject_id = list(subject.keys())[0]
perimeter_id = subject[subject_id].get('id')
assert subject
value = {
"name": "testuser",
"description": "test",
- "policy_list": ['policy_id_3', 'policy_id_4']
}
- subject = add_subject(
- mock_data.get_policy_id(model_name="test_model2", policy_name="policy_2", meta_rule_name="meta_rule2",
- category_prefix="_"), perimeter_id, value)
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category2",
+ object_category_name="object_category2",
+ action_category_name="action_category2",
+ meta_rule_name="meta_rule_2",
+ model_name="model2")
+ subject = data_helper.add_subject(policy_id=policy_id, perimeter_id=perimeter_id, value=value)
assert subject
subject_id = list(subject.keys())[0]
assert len(subject[subject_id].get('policy_list')) == 2
def test_delete_subject(db):
- policy_id = mock_data.get_policy_id()
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
value = {
"name": "testuser",
"description": "test",
}
- subject = add_subject(policy_id=policy_id, value=value)
+ subject = data_helper.add_subject(policy_id=policy_id, value=value)
subject_id = list(subject.keys())[0]
- delete_subject(policy_id, subject_id)
- subjects = get_subjects(policy_id, )
+ data_helper.delete_subject(policy_id, subject_id)
+ subjects = data_helper.get_subjects(policy_id, )
assert not subjects
@@ -595,30 +579,24 @@ def test_delete_subject_with_invalid_perimeter_id(db):
policy_id = "invalid"
perimeter_id = "invalid"
with pytest.raises(Exception) as exception_info:
- delete_subject(policy_id, perimeter_id)
- assert str(exception_info.value) == '400: Subject Unknown'
+ data_helper.delete_subject(policy_id, perimeter_id)
+ assert str(exception_info.value) == '400: Policy Unknown'
def test_get_available_metadata(db):
- policy_id = mock_data.get_policy_id()
- metadata = get_available_metadata(policy_id=policy_id)
- assert metadata
- assert metadata['object'][0] == "object_category_id1"
- assert metadata['subject'][0] == "subject_category_id1"
- assert metadata['subject'][1] == "subject_category_id2"
-
-
-def test_get_available_metadata_empty_model(db):
- import policies.test_policies as test_policies
- value = mock_data.create_policy("invalid")
- policy = test_policies.add_policies(value=value)
- assert policy
- policy_id = list(policy.keys())[0]
- metadata = get_available_metadata(policy_id=policy_id)
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1")
+ metadata = data_helper.get_available_metadata(policy_id=policy_id)
assert metadata
+ assert metadata['object'][0] == object_category_id
+ assert metadata['subject'][0] == subject_category_id
+ assert metadata['action'][0] == action_category_id
def test_get_available_metadata_with_invalid_policy_id(db):
with pytest.raises(Exception) as exception_info:
- get_available_metadata(policy_id='invalid')
+ data_helper.get_available_metadata(policy_id='invalid')
assert '400: Policy Unknown' == str(exception_info.value)
diff --git a/python_moondb/tests/unit_python/policies/test_policies.py b/python_moondb/tests/unit_python/policies/test_policies.py
index f1dd258f..07ee87fd 100755
--- a/python_moondb/tests/unit_python/policies/test_policies.py
+++ b/python_moondb/tests/unit_python/policies/test_policies.py
@@ -4,70 +4,14 @@
# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
import pytest
-import policies.mock_data as mock_data
+import helpers.mock_data as mock_data
+import helpers.policy_helper as policy_helper
from python_moonutilities.exceptions import *
-
-
-def get_policies():
- from python_moondb.core import PolicyManager
- return PolicyManager.get_policies("admin")
-
-
-def add_policies(policy_id=None, value=None):
- from python_moondb.core import PolicyManager
- if not value:
- value = {
- "name": "test_policiy",
- "model_id": "",
- "genre": "authz",
- "description": "test",
- }
- return PolicyManager.add_policy("admin", policy_id=policy_id, value=value)
-
-
-def delete_policies(uuid=None, name=None):
- from python_moondb.core import PolicyManager
- if not uuid:
- for policy_id, policy_value in get_policies():
- if name == policy_value['name']:
- uuid = policy_id
- break
- PolicyManager.delete_policy("admin", uuid)
-
-
-def update_policy(policy_id, value):
- from python_moondb.core import PolicyManager
- return PolicyManager.update_policy("admin", policy_id, value)
-
-
-def get_policy_from_meta_rules(meta_rule_id):
- from python_moondb.core import PolicyManager
- return PolicyManager.get_policy_from_meta_rules("admin", meta_rule_id)
-
-
-def get_rules(policy_id=None, meta_rule_id=None, rule_id=None):
- from python_moondb.core import PolicyManager
- return PolicyManager.get_rules("", policy_id, meta_rule_id, rule_id)
-
-
-def add_rule(policy_id=None, meta_rule_id=None, value=None):
- from python_moondb.core import PolicyManager
- if not value:
- value = {
- "rule": ("high", "medium", "vm-action"),
- "instructions": ({"decision": "grant"}),
- "enabled": "",
- }
- return PolicyManager.add_rule("", policy_id, meta_rule_id, value)
-
-
-def delete_rule(policy_id=None, rule_id=None):
- from python_moondb.core import PolicyManager
- PolicyManager.delete_rule("", policy_id, rule_id)
+import helpers.pdp_helper as pdp_helper
def test_get_policies(db):
- policies = get_policies()
+ policies = policy_helper.get_policies()
assert isinstance(policies, dict)
assert not policies
@@ -79,7 +23,7 @@ def test_add_policies(db):
"genre": "authz",
"description": "test",
}
- policies = add_policies(value=value)
+ policies = policy_helper.add_policies(value=value)
assert isinstance(policies, dict)
assert policies
assert len(policies.keys()) == 1
@@ -97,9 +41,9 @@ def test_add_policies_twice_with_same_id(db):
"genre": "authz",
"description": "test",
}
- add_policies(policy_id, value)
+ policy_helper.add_policies(policy_id, value)
with pytest.raises(PolicyExisting) as exception_info:
- add_policies(policy_id, value)
+ policy_helper.add_policies(policy_id, value)
# assert str(exception_info.value) == '409: Policy Error'
@@ -110,9 +54,9 @@ def test_add_policies_twice_with_same_name(db):
"genre": "authz",
"description": "test",
}
- add_policies(value=value)
+ policy_helper.add_policies(value=value)
with pytest.raises(Exception) as exception_info:
- add_policies(value=value)
+ policy_helper.add_policies(value=value)
# assert str(exception_info.value) == '409: Policy Error'
@@ -123,7 +67,7 @@ def test_delete_policies(db):
"genre": "authz",
"description": "test",
}
- policies = add_policies(value=value)
+ policies = policy_helper.add_policies(value=value)
policy_id1 = list(policies.keys())[0]
value = {
"name": "test_policy2",
@@ -131,45 +75,23 @@ def test_delete_policies(db):
"genre": "authz",
"description": "test",
}
- policies = add_policies(value=value)
+ policies = policy_helper.add_policies(value=value)
policy_id2 = list(policies.keys())[0]
assert policy_id1 != policy_id2
- delete_policies(policy_id1)
- policies = get_policies()
+ policy_helper.delete_policies(policy_id1)
+ policies = policy_helper.get_policies()
assert policy_id1 not in policies
def test_delete_policies_with_invalid_id(db):
policy_id = 'policy_id_1'
with pytest.raises(PolicyUnknown) as exception_info:
- delete_policies(policy_id)
+ policy_helper.delete_policies(policy_id)
# assert str(exception_info.value) == '400: Policy Unknown'
-def test_delete_policies_with_pdp(db):
- from python_moondb.core import PDPManager
- value = {
- "name": "test_policy1",
- "model_id": "",
- "genre": "authz",
- "description": "test",
- }
- policies = add_policies(value=value)
- policy_id1 = list(policies.keys())[0]
- pdp_id = "pdp_id1"
- value = {
- "name": "test_pdp",
- "security_pipeline": [policy_id1],
- "keystone_project_id": "keystone_project_id1",
- "description": "...",
- }
- PDPManager.add_pdp(user_id="admin" ,pdp_id=pdp_id, value=value)
- with pytest.raises(DeletePolicyWithPdp) as exception_info:
- delete_policies(policy_id1)
-
-
def test_update_policy(db):
- policies = add_policies()
+ policies = policy_helper.add_policies()
policy_id = list(policies.keys())[0]
value = {
"name": "test_policy4",
@@ -177,7 +99,7 @@ def test_update_policy(db):
"genre": "authz",
"description": "test-3",
}
- updated_policy = update_policy(policy_id, value)
+ updated_policy = policy_helper.update_policy(policy_id, value)
assert updated_policy
for key in ("genre", "name", "model_id", "description"):
assert key in updated_policy[policy_id]
@@ -193,32 +115,26 @@ def test_update_policy_with_invalid_id(db):
"description": "test-3",
}
with pytest.raises(PolicyUnknown) as exception_info:
- update_policy(policy_id, value)
+ policy_helper.update_policy(policy_id, value)
# assert str(exception_info.value) == '400: Policy Unknown'
def test_get_policy_from_meta_rules(db):
- import models.test_models as test_models
- import models.test_meta_rules as test_meta_rules
- import test_pdp as test_pdp
- meta_rule = test_meta_rules.add_meta_rule(value=mock_data.create_meta_rule())
- meta_rule_id = list(meta_rule.keys())[0]
- model = test_models.add_model(value=mock_data.create_model(meta_rule_id))
- model_id = list(model.keys())[0]
- value = mock_data.create_policy(model_id)
- policy = add_policies(value=value)
- assert policy
- policy_id = list(policy.keys())[0]
- pdp_ids = [policy_id, ]
- pdp_obj = mock_data.create_pdp(pdp_ids)
- test_pdp.add_pdp(value=pdp_obj)
- matched_policy_id = get_policy_from_meta_rules(meta_rule_id)
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1",
+ model_name="model1")
+ security_pipeline = [policy_id]
+ pdp_obj = mock_data.create_pdp(security_pipeline)
+ pdp_helper.add_pdp(value=pdp_obj)
+ matched_policy_id = policy_helper.get_policy_from_meta_rules(meta_rule_id)
assert matched_policy_id
assert policy_id == matched_policy_id
def test_get_policy_from_meta_rules_with_no_policy_ids(db):
- import test_pdp as test_pdp
meta_rule_id = 'meta_rule_id'
value = {
"name": "test_pdp",
@@ -226,58 +142,31 @@ def test_get_policy_from_meta_rules_with_no_policy_ids(db):
"keystone_project_id": "keystone_project_id1",
"description": "...",
}
- test_pdp.add_pdp(value=value)
- matched_policy_id = get_policy_from_meta_rules(meta_rule_id)
+ pdp_helper.add_pdp(value=value)
+ matched_policy_id = policy_helper.get_policy_from_meta_rules(meta_rule_id)
assert not matched_policy_id
-def test_get_policy_from_meta_rules_with_no_policies(db):
- import test_pdp as test_pdp
- meta_rule_id = 'meta_rule_id'
- policy_id = 'invalid'
- pdp_ids = [policy_id, ]
- pdp_obj = mock_data.create_pdp(pdp_ids)
- test_pdp.add_pdp(value=pdp_obj)
- with pytest.raises(Exception) as exception_info:
- get_policy_from_meta_rules(meta_rule_id)
- assert str(exception_info.value) == '400: Policy Unknown'
-
-
-def test_get_policy_from_meta_rules_with_no_models(db):
- import models.test_meta_rules as test_meta_rules
- import test_pdp as test_pdp
- meta_rule = test_meta_rules.add_meta_rule(value=mock_data.create_meta_rule())
- meta_rule_id = list(meta_rule.keys())[0]
- model_id = 'invalid'
- value = mock_data.create_policy(model_id)
- policy = add_policies(value=value)
- assert policy
- policy_id = list(policy.keys())[0]
- pdp_ids = [policy_id, ]
- pdp_obj = mock_data.create_pdp(pdp_ids)
- test_pdp.add_pdp(value=pdp_obj)
- with pytest.raises(Exception) as exception_info:
- get_policy_from_meta_rules(meta_rule_id)
- assert str(exception_info.value) == '400: Model Unknown'
-
-
def test_get_rules(db):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category12",
+ object_category_name="object_category12",
+ action_category_name="action_category12",
+ meta_rule_name="meta_rule_12",
+ model_name="model12")
value = {
"rule": ("low", "medium", "vm-action"),
"instructions": ({"decision": "grant"}),
"enabled": "",
}
- policy_id = mock_data.get_policy_id()
- meta_rule_id = "1"
- add_rule(policy_id, meta_rule_id, value)
+ policy_helper.add_rule(policy_id=policy_id, meta_rule_id=meta_rule_id, value=value)
value = {
"rule": ("low", "low", "vm-action"),
"instructions": ({"decision": "grant"}),
"enabled": "",
}
- meta_rule_id = "1"
- add_rule(policy_id, meta_rule_id, value)
- rules = get_rules(policy_id, meta_rule_id)
+ policy_helper.add_rule(policy_id=policy_id, meta_rule_id=meta_rule_id, value=value)
+ rules = policy_helper.get_rules(policy_id=policy_id, meta_rule_id=meta_rule_id)
assert isinstance(rules, dict)
assert rules
obj = rules.get('rules')
@@ -285,20 +174,25 @@ def test_get_rules(db):
def test_get_rules_with_invalid_policy_id_failure(db):
- rules = get_rules("invalid_policy_id", "meta_rule_id")
+ rules = policy_helper.get_rules("invalid_policy_id", "meta_rule_id")
assert not rules.get('meta_rule-id')
assert len(rules.get('rules')) == 0
def test_add_rule(db):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1",
+ model_name="model1")
value = {
"rule": ("high", "medium", "vm-action"),
"instructions": ({"decision": "grant"}),
"enabled": "",
}
- policy_id = mock_data.get_policy_id()
- meta_rule_id = "1"
- rules = add_rule(policy_id, meta_rule_id, value)
+
+ rules = policy_helper.add_rule(policy_id=policy_id, meta_rule_id=meta_rule_id, value=value)
assert rules
assert len(rules) == 1
assert isinstance(rules, dict)
@@ -308,19 +202,44 @@ def test_add_rule(db):
assert rules[rule_id][key] == value[key]
with pytest.raises(RuleExisting):
- add_rule(policy_id, meta_rule_id, value)
+ policy_helper.add_rule(policy_id=policy_id, meta_rule_id=meta_rule_id, value=value)
def test_delete_rule(db):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category14",
+ object_category_name="object_category14",
+ action_category_name="action_category14",
+ meta_rule_name="meta_rule_14",
+ model_name="model14")
value = {
"rule": ("low", "low", "vm-action"),
"instructions": ({"decision": "grant"}),
"enabled": "",
}
- policy_id = mock_data.get_policy_id()
- meta_rule_id = "2"
- rules = add_rule(policy_id, meta_rule_id, value)
+ rules = policy_helper.add_rule(policy_id, meta_rule_id, value)
rule_id = list(rules.keys())[0]
- delete_rule(policy_id, rule_id)
- rules = get_rules(policy_id, meta_rule_id)
+ policy_helper.delete_rule(policy_id, rule_id)
+ rules = policy_helper.get_rules(policy_id, meta_rule_id)
assert not rules.get('rules')
+
+
+def test_delete_policies_with_pdp(db):
+ value = {
+ "name": "test_policy1",
+ "model_id": "",
+ "genre": "authz",
+ "description": "test",
+ }
+ policies = policy_helper.add_policies(value=value)
+ policy_id1 = list(policies.keys())[0]
+ pdp_id = "pdp_id1"
+ value = {
+ "name": "test_pdp",
+ "security_pipeline": [policy_id1],
+ "keystone_project_id": "keystone_project_id1",
+ "description": "...",
+ }
+ pdp_helper.add_pdp(pdp_id=pdp_id, value=value)
+ with pytest.raises(DeletePolicyWithPdp) as exception_info:
+ policy_helper.delete_policies(policy_id1)
diff --git a/python_moondb/tests/unit_python/requirements.txt b/python_moondb/tests/unit_python/requirements.txt
index 5f507ff7..ff727723 100644
--- a/python_moondb/tests/unit_python/requirements.txt
+++ b/python_moondb/tests/unit_python/requirements.txt
@@ -1,5 +1,4 @@
sqlalchemy
pymysql
-pytest
requests_mock
python_moonutilities \ No newline at end of file
diff --git a/python_moondb/tests/unit_python/test_pdp.py b/python_moondb/tests/unit_python/test_pdp.py
index 942d98a3..4d245e4d 100755
--- a/python_moondb/tests/unit_python/test_pdp.py
+++ b/python_moondb/tests/unit_python/test_pdp.py
@@ -1,125 +1,149 @@
import pytest
-
-
-def update_pdp(pdp_id, value):
- from python_moondb.core import PDPManager
- return PDPManager.update_pdp("", pdp_id, value)
-
-
-def delete_pdp(pdp_id):
- from python_moondb.core import PDPManager
- PDPManager.delete_pdp("", pdp_id)
-
-
-def add_pdp(pdp_id=None, value=None):
- from python_moondb.core import PDPManager
- return PDPManager.add_pdp("", pdp_id, value)
-
-
-def get_pdp(pdp_id=None):
- from python_moondb.core import PDPManager
- return PDPManager.get_pdp("", pdp_id)
+import helpers.mock_data as mock_data
+import helpers.pdp_helper as pdp_helper
def test_update_pdp(db):
pdp_id = "pdp_id1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1",
+ model_name="model1")
value = {
"name": "test_pdp",
- "security_pipeline": ["policy_id_1", "policy_id_2"],
+ "security_pipeline": [policy_id],
"keystone_project_id": "keystone_project_id1",
"description": "...",
}
- add_pdp(pdp_id, value)
- pdp = update_pdp(pdp_id, value)
+ pdp_helper.add_pdp(pdp_id, value)
+ pdp = pdp_helper.update_pdp(pdp_id, value)
assert pdp
def test_update_pdp_with_invalid_id(db):
pdp_id = "pdp_id1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1",
+ model_name="model1")
value = {
"name": "test_pdp",
- "security_pipeline": ["policy_id_1", "policy_id_2"],
+ "security_pipeline": [policy_id],
"keystone_project_id": "keystone_project_id1",
"description": "...",
}
with pytest.raises(Exception) as exception_info:
- update_pdp(pdp_id, value)
+ pdp_helper.update_pdp(pdp_id, value)
assert str(exception_info.value) == '400: Pdp Unknown'
def test_delete_pdp(db):
pdp_id = "pdp_id1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1",
+ model_name="model1")
value = {
"name": "test_pdp",
- "security_pipeline": ["policy_id_1", "policy_id_2"],
+ "security_pipeline": [policy_id],
"keystone_project_id": "keystone_project_id1",
"description": "...",
}
- add_pdp(pdp_id, value)
- delete_pdp(pdp_id)
- assert len(get_pdp(pdp_id)) == 0
+ pdp_helper.add_pdp(pdp_id, value)
+ pdp_helper.delete_pdp(pdp_id)
+ assert len(pdp_helper.get_pdp(pdp_id)) == 0
def test_delete_pdp_with_invalid_id(db):
pdp_id = "pdp_id1"
with pytest.raises(Exception) as exception_info:
- delete_pdp(pdp_id)
+ pdp_helper.delete_pdp(pdp_id)
assert str(exception_info.value) == '400: Pdp Unknown'
def test_add_pdp(db):
pdp_id = "pdp_id1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1",
+ model_name="model1")
value = {
"name": "test_pdp",
- "security_pipeline": ["policy_id_1", "policy_id_2"],
+ "security_pipeline": [policy_id],
"keystone_project_id": "keystone_project_id1",
"description": "...",
}
- pdp = add_pdp(pdp_id, value)
+ pdp = pdp_helper.add_pdp(pdp_id, value)
assert pdp
def test_add_pdp_twice_with_same_id(db):
pdp_id = "pdp_id1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1",
+ model_name="model1")
value = {
"name": "test_pdp",
- "security_pipeline": ["policy_id_1", "policy_id_2"],
+ "security_pipeline": [policy_id],
"keystone_project_id": "keystone_project_id1",
"description": "...",
}
- add_pdp(pdp_id, value)
+ pdp_helper.add_pdp(pdp_id, value)
with pytest.raises(Exception) as exception_info:
- add_pdp(pdp_id, value)
+ pdp_helper.add_pdp(pdp_id, value)
assert str(exception_info.value) == '409: Pdp Error'
def test_add_pdp_twice_with_same_name(db):
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1",
+ model_name="model1")
value = {
"name": "test_pdp",
- "security_pipeline": ["policy_id_1", "policy_id_2"],
+ "security_pipeline": [policy_id],
"keystone_project_id": "keystone_project_id1",
"description": "...",
}
- add_pdp(value=value)
+ pdp_helper.add_pdp(value=value)
with pytest.raises(Exception) as exception_info:
- add_pdp(value=value)
+ pdp_helper.add_pdp(value=value)
assert str(exception_info.value) == '409: Pdp Error'
def test_get_pdp(db):
pdp_id = "pdp_id1"
+ subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = mock_data.create_new_policy(
+ subject_category_name="subject_category1",
+ object_category_name="object_category1",
+ action_category_name="action_category1",
+ meta_rule_name="meta_rule_1",
+ model_name="model1")
value = {
"name": "test_pdp",
- "security_pipeline": ["policy_id_1", "policy_id_2"],
+ "security_pipeline": [policy_id],
"keystone_project_id": "keystone_project_id1",
"description": "...",
}
- add_pdp(pdp_id, value)
- pdp = get_pdp(pdp_id)
+ pdp_helper.add_pdp(pdp_id, value)
+ pdp = pdp_helper.get_pdp(pdp_id)
assert len(pdp) == 1
def test_get_pdp_with_invalid_id(db):
pdp_id = "invalid"
- pdp = get_pdp(pdp_id)
+ pdp = pdp_helper.get_pdp(pdp_id)
assert len(pdp) == 0
diff --git a/python_moonutilities/Changelog b/python_moonutilities/Changelog
index 61225b2b..ae7f352f 100644
--- a/python_moonutilities/Changelog
+++ b/python_moonutilities/Changelog
@@ -94,3 +94,7 @@ CHANGES
1.4.9
-----
- Add some exceptions when deletion of elements is impossible
+
+1.4.10
+-----
+- Add CategoryNameInvalid and PerimeterNameInvalid exceptions
diff --git a/python_moonutilities/python_moonutilities/__init__.py b/python_moonutilities/python_moonutilities/__init__.py
index d313ecc3..6b30dedc 100644
--- a/python_moonutilities/python_moonutilities/__init__.py
+++ b/python_moonutilities/python_moonutilities/__init__.py
@@ -3,6 +3,6 @@
# 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.9"
+__version__ = "1.4.10"
diff --git a/python_moonutilities/python_moonutilities/exceptions.py b/python_moonutilities/python_moonutilities/exceptions.py
index bb2d35b7..a43ac89f 100644
--- a/python_moonutilities/python_moonutilities/exceptions.py
+++ b/python_moonutilities/python_moonutilities/exceptions.py
@@ -197,6 +197,11 @@ class AdminRule(AdminException):
code = 400
title = 'Rule Exception'
+class CategoryNameInvalid(AdminMetaData):
+ description = _("The given category name is invalid.")
+ code = 409
+ title = 'Category Name Invalid'
+ logger = "ERROR"
class SubjectCategoryNameExisting(AdminMetaData):
description = _("The given subject category name already exists.")
@@ -261,6 +266,12 @@ class ActionCategoryUnknown(AdminMetaData):
logger = "ERROR"
+class PerimeterNameInvalid(AdminPerimeter):
+ description = _("The given name is not valid.")
+ code = 400
+ title = 'Perimeter Name is Invalid'
+ logger = "ERROR"
+
class SubjectUnknown(AdminPerimeter):
description = _("The given subject is unknown.")
code = 400
@@ -674,13 +685,6 @@ class DeleteCategoryWithMetaRule(MoonError):
logger = "Error"
-class DeleteCategoryWithData(MoonError):
- description = _("Cannot delete category with data")
- code = 400
- title = 'Category Error'
- logger = "Error"
-
-
class DeleteModelWithPolicy(MoonError):
description = _("Cannot delete model with policy")
code = 400
diff --git a/python_moonutilities/python_moonutilities/security_functions.py b/python_moonutilities/python_moonutilities/security_functions.py
index 84e9ab7d..5d5275ee 100644
--- a/python_moonutilities/python_moonutilities/security_functions.py
+++ b/python_moonutilities/python_moonutilities/security_functions.py
@@ -120,7 +120,7 @@ def validate_data(data):
raise ValueError('Value is Not String or Container or Dictionary')
-def validate_input(type, args_state=[], kwargs_state=[], body_state=[]):
+def validate_input(type='get', args_state=[], kwargs_state=[], body_state=[]):
"""
this fucntion works only on List or tuple or dictionary of Strings ,and String direct
Check if input of function is Valid or not, Valid if not has spaces and values is not None or empty.